// build to order V2.00 jQuery - Leon Paul build - includes support for Tabber V2
// 21-01-12 includes support for Engraving on BTO items

var btopprices = new Object();

function setBTOPanes(Id) {	// Tabber V2 with Built to Order
	if ( $('#cont_' + Id).length == 0) return;	// skip if no tabs
	// find a tab-container
	// set up the panes array with named pane
	// find the max height, set tab-panes to that height
	// save height and width - use old values if defined
	var containerId = 'cont_' + Id;
	panes[containerId] = new Object();
	var maxHeight = 0; var maxWidth = 0;
	var container = document.getElementById(containerId);
	var paneContainer = container.getElementsByTagName("div")[0];
	var paneList = paneContainer.childNodes;
	for (var i=0; i < paneList.length; i++ ) 
		{
		var pane = paneList[i];
		if (pane.nodeType != 1) continue;
		if (pane.offsetHeight > maxHeight) maxHeight = pane.offsetHeight;
		if (pane.offsetWidth  > maxWidth ) maxWidth  = pane.offsetWidth;
		panes[containerId][pane.id] = pane;
		pane.style.display = "none";
		}
	if ( panewidths[Id] )					// BTO - use prior computed values
		{
		maxWidth = panewidths[Id];
		maxHeight = paneheights[Id];
		} 
	paneContainer.style.height = maxHeight + "px";
	paneContainer.style.width  = maxWidth + "px";
	panewidths[Id] = maxWidth;				// BTO save size 
	paneheights[Id] = maxHeight;				// BTO  save size
	// activate first tab
	swaptabs(Id, 0);
}

function btoCommaFormatted(num){		// format a number into a £n,nnn.nn price
	var sep = ',';
	var curr = '£';
	num = num.toFixed(2).split('').reverse().join('');		// reverse number
	num = num.replace(/(\d\d\d)(?=\d)(?!\d*\.)/g,'$1' + sep);	// add commas
	return curr + num.split('').reverse().join('');			// reverse number back and add currency;
}

function toggleinfo(link, id){		// when More... info link clicked
	if ( link.innerHTML == btomoretext )
		{
		$('#pdetail_' + id).show(btoinfoanimate, function(){setBTOPanes(id)});	// show and check for any tabs when done
		link.innerHTML = btolesstext;
		}
	else	
		{
		$('#pdetail_' + id).hide(btoinfoanimate);
		link.innerHTML = btomoretext;
		}
	return false;	
}

function expandcomponent(pid, idx){		// display hidden permutations within component
		$('#btocomp_' + pid + '_' + idx + ' .rdconsize').each(function()	// our pseudo radios for the size select drop downs
			{$('#compitem_' + this.name.replace(/csize_/, '') + '_' + ((this.value - 0) + 1)).show(btochoiceanimate);});			
		$('#btocomp_' + pid + '_' + idx + ' .rdentry').each(function()	// normal radios that need to be shown
			{if ($(this).attr('show') == '1' ) $('#compitem_' + this.name + '_' + this.value).show(btochoiceanimate);});			
}

function btoreview(btn, pid, idx){		// reopen component and show all choices
	if ( btn.innerHTML == btoexpandtext)
		{
		expandcomponent(pid, idx);	// WAS $("#btotbl_" + idx + ' .btoitem').show(btochoiceanimate);
		btn.innerHTML = btocontracttext;
		if (btoinactiveopacity) $('#btocomp_' + pid + '_' + idx).animate({opacity: 1});
		}
	else
		{
		$("#btotbl_" + idx + ' .btoitem').each(function()
			{if( $('input:radio:checked', this).length == 0 ) $(this).hide(btochoiceanimate);});
		btn.innerHTML = btoexpandtext;
		if (btoinactiveopacity) $('#btocomp_' + pid + '_' + idx).animate({opacity: btoinactiveopacity});
		}
	return false;
}

function btomoveon(btn, pid, idx){		// this components Next... button clicked.  
	// Hide all but current selection and display next component (or Cart button).
	var thiscomp = $('#btocomp_' + pid + '_' + idx);

	// before doing anything check for any engraving options
	var engravingerror = false;
	$('input.rdentry', thiscomp).each(function()		// normal (usually visible) radios
		{
		if ( ($(this).attr('show') == 1) && $('#engraveditem_' + this.name + '_' + this.value).length )	// normal radios only and we have engraving
			{
			var info0 = $('#inf0_' + pid);			// the engraving field that determines if we have any lines
			if( this.checked ) 				// we want engraving so check that some text has been entered
				{
				if ( countallchars(pid) < 1 ) 		// call function within Engraving add-on code
					{
					alert('You must enter some engraving text or deselect Engraving');
					engravingerror = true;
					}
				info0.removeAttr('disabled');		// allow engraving data submit	
				}
			else 
				{
				info0.attr('disabled', 'disabled');	//disable engraving data submit	
				}
			}	
		});
	if ( engravingerror ) return false;

	// fade down the item
	if (btoinactiveopacity) thiscomp.animate({opacity: btoinactiveopacity});
	// hide all but selected item
	$('input.rdconsize', thiscomp).each(function()		// pseudo radios for drop-downs
		{if(! this.checked) $('#compitem_' + this.name.replace(/csize_/, '') + '_' + ((this.value - 0) + 1)).hide(btochoiceanimate);});
	$('input.rdentry', thiscomp).each(function()		// normal (usually visible) radios
		{if( (! this.checked) && ($(this).attr('show') == 1) ) $('#compitem_' + this.name + '_' + this.value).hide(btochoiceanimate);});
	// enable the Expand link
	$('#btoexpand_' + idx).show();
	$('#btoexpand_' + idx)[0].innerHTML = btoexpandtext;
	// display the progress tick
	$('#btotick_' + idx)[0].className = 'btotick';
	// now display next option	
	var nextcomp = $('#btocomp_' + pid + '_' + (idx + 1));
	if ( nextcomp.length )	// hide the previous set of buttons as we don't need them anymore
		{
		$('#btns_' + pid + '_' + idx).hide();
		// display next component
		nextcomp.show(btocompanimate);
		// indicate this component is now visible (for the price calc routine)
		nextcomp.attr('btovis', 1);			
		}
		
	else	// all must be done so enable Qty and Cart
		{
		// hide the previous sets Next button as we don't need it anymore
		if ( $('#nxtbtn_' + pid + '_' + idx).length ) $('#nxtbtn_' + pid + '_' + idx).hide();
		// enable the back button just in case it's a single Component product
		if ( $('#backbtn_' + pid + '_' + idx) ) $('#backbtn_' + pid + '_' + idx).show();
		// enable Qty and Cart button
		var qtycart =  document.getElementById('qtycart_' + pid);
		if ( qtycart ) qtycart.className = 'btoshow';
		}
	// update calculated total
	calctot(pid);
	return false;
}

function btomoveback(btn, pid, idx){		// Back... button clicked.  
	// Hide current selection and reopen previous
	var qtycart =  document.getElementById('qtycart_' + pid);
	if ( qtycart.className == 'btohide' )
		{
		// normal progress (we're not showing the cart) - hide current
		var thiscomp = $('#btocomp_' + pid + '_' + idx);
		thiscomp.hide(btocompanimate)
		thiscomp.attr('btovis', 0);	
		// reopen previous
		if (btoinactiveopacity) $('#btocomp_' + pid + '_' + (idx - 1)).animate({opacity: 1});
		expandcomponent(pid, idx - 1);
		// hide the Expand link
		$('#btoexpand_' + (idx - 1)).hide();
		// show the buttons for previous
		if ( $('#btns_' + pid + '_' + (idx - 1)).length ) $('#btns_' + pid + '_' + (idx - 1)).show();
		}
	else	// special case if we're on last selection
		{
		qtycart.className = 'btohide';		// hide the qty and cart
		// reopen current selection at full opacity
		if (btoinactiveopacity) $('#btocomp_' + pid + '_' + idx).animate({opacity: 1});
		expandcomponent(pid, idx);
		// hide the Expand link
		$('#btoexpand_' + (idx)).hide();
		// and reenable buttons
		var thisbtns = $('#btns_' + pid + '_' + idx);
		if ( thisbtns.length )thisbtns.show();
		var nxtbtns = $('#nxtbtn_' + pid + '_' + idx);
		if ( nxtbtns.length ) nxtbtns.show();
		// hide the back button if we're on the first item
		if ( (idx == 1) && $('#backbtn_' + pid + '_' + idx).length ) $('#backbtn_' + pid + '_' + idx).hide();
		}
	calctot(pid);
	return false;
}	

function calctot(pid){		// calculate total for all visible Components
	var rtot = btopprices[pid] - 0;		// possible product price
	// all divs with id starting btocomp_<pid>_
	$("div[id^='btocomp_" + pid + "_']").each(function(){
		if ( this.getAttribute('btovis') == 1) 
			{
			rtot += $("input.rdentry:checked", this).attr('ppraw').replace(/[^\d\.]/g,'') - 0;	// perm price
			}
		});
		// display the price
		if ( $('#stot_' + pid).length ) $('#stot_' + pid).html('<h2 class="btototal">Price: ' + btoCommaFormatted(rtot) + '</h2>');
}

function btosetup(pid,ppraw){	// called when product being laid out - save product price
	btopprices[pid] = ppraw;
}

function initallbtos(){			// called when DOM loaded - display all running totals
	$(".rdentry[checked='checked']").attr('checked','checked');	// make sure all radios are in fact checked
	$("div[id^='btocomp_']").each(function(){$('.rdconsize:first', this).attr('checked', 'checked')});	// make sure first size related radios are checked
	$(".selconsize").each(function(){this.selectedIndex = 0;});	// make sure that all drop-downs are set to inital values
	for (var pid in btopprices) calctot(pid);
}

function compactsizes(attid, groupby){	// reduce exhaustive list of radio buttons to use drop-down for sub-sizes
	if ( groupby == '' ) groupby = 'skizziks';				// set unlikely value to disable
	var pid = attid.replace(/v_(.*)_.*/, "$1");
	var compdiv = $("div[id^='compitem_" + attid + "_']");
	var comps = new Object();
	var currentname = '';
	var curridx;
	compdiv.each(								// each radio item
		function(cidx){
			var prodspan = $(this).find('span.btoprodname');	// contains the Product Name	
			var nbits = prodspan.text().split(groupby);		// see if Product name comntains e.g. "Size"
			comps[cidx] = new Object();				// one per item
			comps[cidx].nfield = prodspan;				// the Associated product name SPAN object
			comps[cidx].shortname = nbits[0];			// truncated Associated product name text
			comps[cidx].selcode = '';
			if ( nbits[0] != currentname )				// first or different item than previous
				{
				comps[cidx].show = true;			// we always show first item with new name
				curridx = cidx;					// remember first item index
				currentname = nbits[0];				// save current items name
				}
			if ( nbits[1] )						// item has a Size value
				{
				comps[curridx].selcode += '<option>' + nbits[1] + '</option>';	// save size option
				}				
		}
	);
	var chkd = ' checked';
	var disabled = '';
	compdiv.each(								// rescan each radio item
		function(curridx){
			if ( comps[curridx].selcode ) 				// if size range was used
				{
				$(this).find('input:radio').hide();		// hide unwanted Actinic radio buttons
				var radionew = '<input type="radio" class="rdconsize" onclick="compsizeradiochange(this, ' + curridx + ')"'	// create a radio button to select this group
					+ ' name="csize_'+ attid + '" value="' + curridx + '"' + chkd + ' />';
				chkd = '';
				comps[curridx].nfield.html(radionew + comps[curridx].shortname);	// add in radio and remove size info from 1st of all groups of similar items
				$(this).find('span.btooption').html(groupby + '&nbsp;<select class="selconsize" onchange="setcompsize(this, ' + curridx + ')"'	// insert the size drop-down 
					+ disabled
					+ ' id="' + curridx + '_compsize_' + attid + '">'
					+ comps[curridx].selcode + '</select>');
				disabled = ' disabled';
				}
			else
				{
				if ( comps[curridx].show ) 
					{
					$(this).find('input:radio').attr('show', '1');	// flag this item as wanted
					}
				else
					{
					$(this).hide();				// hide unwanted size related items
					}
				}
		}
	);	
}

function setcompsize(sizesel, curridx){			// size selector drop-down has changed
	var attid = sizesel.id.replace(/.*_compsize_/, '');
	var actradio = $("input[name='" + attid + "']:radio")[sizesel.selectedIndex + curridx];	// the appropriate Actinic radio button
	$("#permprice_" + attid + "_" + (curridx + 1)).html($(actradio).attr('ppraw'));		// update current item price
	$(actradio).attr('checked', 'checked');							// set Actinic radio
	var pid = attid.replace(/v_(.*)_.*/, "$1");						// extract Product ID
	calctot(pid);
}

function compsizeradiochange(radsel, curridx){		// pseudo radio button for drop-down size groups
	var attid = radsel.name.replace(/csize_/, '');					// extract attrib id
	var selid = curridx + radsel.name.replace(/csize_/, '_compsize_');		// determine related drop-down id
	$("select[id$='compsize_" + attid + "']").attr('disabled', 'disabled');		// disable all drop-downs
	$('#' + selid).removeAttr('disabled');						// and enable only this
	$('#' + selid)[0].onchange();							// fire drop down to recalculate price
	
}

function radiochange(radio, pid){			// standard Actinic radio button clicked
	var attid = radio.name.replace(/csize_/, '');					// extract attrib id
	$("input[name$='csize_" + attid + "']").attr('checked', '');			// uncheck any drop-down radios
	$("select[id$='compsize_" + attid + "']").attr('disabled', 'disabled');		// disable all drop-downs
	calctot(pid);
}		

$(document).ready(function(){initallbtos();});

/*
 * Image preview script - tweaked drillpine for unique namespace and repositioning
 * written by Alen Grakalic (http://cssglobe.com)
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 */
 this.btoImagePreview = function(){	
	xOffset = btotooltipy;	// NB back to front
	yOffset = btotooltipx;

	$("a.btopreview").click(function(e){return false;});	// inhibit click
	$("a.btopreview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='btopreview'><img id='btopopimg' src='"+ this.href +"' alt='Image preview' />"+ c + "</p>");								 
		$("#btopreview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn(btotooltipfade);						
    },
	function(){
		this.title = this.t;	
		$("#btopreview").remove();
    });	
	$("a.btopreview").mousemove(function(e){
		pw = $("#btopopimg").width();
		$("#btopreview").width(pw);
		var border_top = $(window).scrollTop();
		var ttheight = $("#btopreview").height();
		top_pos = (border_top+(xOffset*2)>=(e.pageY - ttheight)) ? border_top + xOffset : e.pageY - ttheight - xOffset;
		$("#btopreview")
			.css("top", top_pos + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

// starting the script on page load
$(document).ready(function(){
	btoImagePreview();
});

