
// ############ don't edit below this line ############### //

// JavaScript Document
var searchString = window.location.search.substring(1);
var Parameters = new Object();
var nameValuePairs = searchString.split(/&/);
var nameValuePair;
var name;
var value;
var pi = 0;
var pickReference = new Array();
var pickColour = new Array();
var pickLocation = new Array();
var pickQty = new Array();
var dontDoShip = false;

for (var i = 0; i < nameValuePairs.length; i++) {
  nameValuePair = nameValuePairs[i].split(/=/);

  name = nameValuePair[0];
  value = nameValuePair[1];

    name = name.toLowerCase();

    if (name == "adnetwork"){
      if (typeof(value)!="undefined"){
        value = value.toLowerCase();
        pathname = location.pathname;
        myDomain = pathname.substring(0,pathname.lastIndexOf('/')) +'/';
        // set expiry date to 30 days from now.
        var largeExpDate = new Date ();
        largeExpDate.setTime(largeExpDate.getTime() + (30 * 24 * 3600 * 1000));
        SetCookie(name,value,largeExpDate,myDomain);
      }
   }
}

//////////////////functions////////////////////////////////////////////////
function onLoad () {
	document.formOCC.submit();
	}
function toCash(p, c, t, d) {
    var s = (0 > p) ? "-" : "";
    var m = String(Math.round(Math.abs(p)));
    var j, k = "", f;
    c = c || "";
    t = t || "";
    d = d || ".";
    while (m.length < 3) {
        m = "0" + m;
    }
    f = m.substring((j = m.length - 2));
    while (j > 3) {
        k = t + m.substring(j - 3, j) + k;
        j -= 3;
    }
    k = m.substring(0, j) + k;
    return s + c + k + d + f;
}

function TryCash(S) {
    var T = S.split(/\s+/);
    return toCash(+ T[0], T[1], T[2], T[3]);
}

function tocash(X) {
    return toCash(X * 100);
}
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function SetCookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function GetCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
function setPackingSlip () {
	//find the hidden field;
	var myFieldTwo = document.getElementById("GENERALUSERDEFINEDTWO");
	var myFieldThree = document.getElementById("GENERALUSERDEFINEDTHREE"); 
	//find the rows that we need to hide
	var myTextTwo = "";
	var myTextThree = "";
	var lineTextTwo = "";
	var lineTextThree = "";
	var doTwo = false;
	var doThree = false;
		//the loops are counted by pi
		for (var i = 0; i < pickReference.length; i++) 
		{	//now build the text to be inserted
			lineTextTwo = lineTextTwo + pickColour[i] + "; "+ pickLocation[i] + "; Qty:" + pickQty[i] + ";\n";
			if(doThree)
			{
				lineTextThree = lineTextTwo + pickColour[i] + "; "+ pickLocation[i] + "; Qty:" + pickQty[i] + ";\n";
				if(lineTextThree.length < 253)
				{	myTextThree = lineTextThree;
				}
			}
			if(lineTextTwo.length < 253)
			{ 	
				myTextTwo = lineTextTwo;				
			}
			else
			{	doThree = true;
			}

		}
		//myFieldTwo.value=myTextTwo;
		$("#userDefinedRowTwo").html("<tr><td colspan=\"2\"><textarea name='GENERALWHYBUY' id='GENERALUSERDEFINEDTWO'>"+myTextTwo+"</textarea></td></tr>");
		if(doThree)
		{	//steal userdefined two
			//myFieldThree.value=myTextThree;
			$("#userDefinedRowThree").html("<tr><td colspan=\"2\"><textarea name='GENERALHOWFOUND' id='GENERALUSERDEFINEDTHREE'>"+myTextTwo+"</textarea></td></tr>");
			//hide the whole thing
		}
		$("#generalInfo").addClass('hide');
	}
function setReferenceCookie()
{	//find the p that the Class has been applied to and then find the dropdown
	var myJDrop = $('#associateProductDrop');
	//work out which index has been selected
	var mySelected = myJDrop.attr("value");
	//find the corresponding javascript array
	var prodRef = productReference[mySelected];
	//save the product into the cookie
	var prodStock = stockLevel[mySelected];
	//save the stock level into a cookie
	SetCookie(prodRef,prodStock,30,"/");
}
function setReferenceCookieClick(prodRef,prodStock){
	SetCookie(prodRef,prodStock,30,"/");
	}
function setTotalsRow(nPoundPence, nEuroCent)
{
					//find the subtotal
				var subTotal = $("#subCostCol").html();
				var poundTot = subTotal.replace(/£(\d*\.\d\d) \/ €\d*\.\d\d/mg, "$1");
				var euroTot = subTotal.replace(/£\d*\.\d\d \/ €(\d*\.\d\d)/mg, "$1");		
				
				//cast it to a number and turn it to pence
				poundTot = poundTot*100;
				euroTot = euroTot*100;
								
				//add the shipping
				poundTot = poundTot+nPoundPence;
				euroTot=euroTot+nEuroCent;
				
				//work out the vat
				var vatSubTotal=poundTot*0.15;
				var varEuroTot=euroTot*0.15;
				//turn it back to pounds
				//work out the total
				poundTot = poundTot+vatSubTotal;
				euroTot = euroTot+varEuroTot;
				
				vatSubTotal=toCash(vatSubTotal,"£",",",".");
				varEuroTot=toCash(varEuroTot,"€",",",".");
				poundTot=toCash(poundTot,"£",",",".");
				euroTot=toCash(euroTot,"€",",",".");
				
				
				//correct the vat row
				$("#vatCostCol").html(vatSubTotal+" / "+varEuroTot);
				//correct the total row
				$("#totalCostCol").html(poundTot+" / "+euroTot);

	}
function setShippingTime()
{	
	//convert to pence
	nthreeToSixDayDelivery=nthreeToSixDayDelivery*100;
	nextDayDelivery=nextDayDelivery*100;
	nextDayBeforeOne=nextDayBeforeOne*100;
	saturdayDelivery=saturdayDelivery*100;
	sevenToFourteenInStock=sevenToFourteenInStock*100;
	SevenToFourteenOutStock=SevenToFourteenOutStock*100;
	nonUKoutOfStock=nonUKoutOfStock*100;
	nonUKinStock=nonUKinStock*100;
	
	//convert the prices into currency
	var PnthreeToSixDayDelivery=toCash(nthreeToSixDayDelivery,"£",",",".");
	var PnextDayDelivery=toCash(nextDayDelivery,"£",",",".");
	var PnextDayBeforeOne=toCash(nextDayBeforeOne,"£",",",".");
	var PsaturdayDelivery=toCash(saturdayDelivery,"£",",",".");
	var PsevenToFourteenInStock=toCash(sevenToFourteenInStock,"£",",",".");
	var PSevenToFourteenOutStock=toCash(SevenToFourteenOutStock,"£",",",".");
	var PnonUKoutOfStock=toCash(nonUKoutOfStock,"£",",",".");
	var PnonUKinStock=toCash(nonUKinStock,"£",",",".");
	
	//convert the shipping into euro currency
	var EnthreeToSixDayDelivery=toCash((nthreeToSixDayDelivery*euroExchangeRate),"€",",",".");
	var EnextDayDelivery=toCash((nextDayDelivery*euroExchangeRate),"€",",",".");
	var EnextDayBeforeOne=toCash((nextDayBeforeOne*euroExchangeRate),"€",",",".");
	var EsaturdayDelivery=toCash((saturdayDelivery*euroExchangeRate),"€",",",".");
	var EsevenToFourteenInStock=toCash((sevenToFourteenInStock*euroExchangeRate),"€",",",".");
	var ESevenToFourteenOutStock=toCash((SevenToFourteenOutStock*euroExchangeRate),"€",",",".");
	var EnonUKinStock=toCash((nonUKinStock*euroExchangeRate),"€",",",".");
	var EnonUKoutOfStock=toCash((nonUKoutOfStock*euroExchangeRate),"€",",",".");

	//are we controlling image only
	//find the product reference
	var myProdRef = "";
	var myStock = "";
	var banShip = false;
	$(".productReference").each(function(){
										 myProdRef = $(this).html();
											 if(trim(myProdRef)!="&nbsp;")
											 {    	//now get the stock
											 		
													myStock = GetCookie(trim(myProdRef));
													//now test if below 1 - if it's null there is a problem so allow full shipping
													if(myStock!=null)
													{
													 if(myStock<1){//find where we are goint to inject HMTL
														 banShip = true;
													 }
													}
											 }
										 });
	var picRow = $("#subPicRow").html();

	//if it's above zero then inject the photo
	if(banShip == false){
		if($("input[name='INVOICECOUNTRY']").attr('value')=="United Kingdom"||$("input[name='INVOICECOUNTRY']").attr('value')==null){
				if(dontDoShip==false)
				{	picRow = "<img src='nextDay.gif' border=0 alt='' id='shipPic'>"+picRow;	
			//build the injection text
						
			var injectionText = "<select id='lstClass' name='ShippingClass'><option selected='selected' value='10'>" + threeSixDayText + " ("+PnthreeToSixDayDelivery+" / "+EnthreeToSixDayDelivery+")</option>";
			if(allowNextDay)
			{
			 injectionText = injectionText + "<option value='6'>"+nextDayText+" ("+PnextDayDelivery+" / "+EnextDayDelivery+")</option><option value='7'>" + nextDayBeforeOneText + " ("+PnextDayBeforeOne+" / "+EnextDayBeforeOne+")</option>";
			}			
			injectionText = injectionText + "<option value='8'>saturday delivery ("+PsaturdayDelivery+" / "+EsaturdayDelivery+")</option><option value='11'>7-14 day delivery ("+PsevenToFourteenInStock+" / "+EsevenToFourteenInStock+")</option></select>"
			$("#shippingSelect").html(injectionText);
			
			$("#subPicRow").html(picRow);
					//don't do this if we are in the second page of the checkout
				var headingRow = "<b>shipping (3-6 Days)</b>";
				$("#shipHeadCol").html(headingRow);
				var costRow = PnthreeToSixDayDelivery+"&nbsp;/&nbsp;"+EnthreeToSixDayDelivery;
				$("#shipCostCol").html(costRow);
			
				//if we are adding the shipping row
				if($("#shipHeadCol").html())
				{	
					setTotalsRow(nthreeToSixDayDelivery,(nthreeToSixDayDelivery*euroExchangeRate));
				}	
			}
	}
	else{	//don't do this if 2nd page of the checkout
			if(dontDoShip==false){
					//do the non uk out of stock
					$("#shippingSelect").html("<select id='lstClass' name='ShippingClass'><option selected='selected' value='9'>non-uk delivery (£19.99 / €23.99)</option></select>");
					//set the totals row
					//don't do this if we are in the second page of the checkout
					var costRow = PnonUKinStock+"&nbsp;/&nbsp;"+EnonUKinStock;
					$("#shipCostCol").html(costRow);
					//if we are adding the shipping row
					if($("#shipHeadCol").html())
					{	//make sure we are using the right maths
						setTotalsRow(nonUKinStock,(nonUKinStock*euroExchangeRate));
					}				
					}
		}
		}else{
			if($("input[name='INVOICECOUNTRY']").attr('value')=="United Kingdom"||$("input[name='INVOICECOUNTRY']").attr('value')==null){
					
			//don't do this if 2nd page of the checkout
			if(dontDoShip==false)
				{	
				//if below then inject picture
				picRow = "<img src='7-14Day.gif' border=0 alt='' id='shipPic'>"+picRow;
				//so find the shipping select
				$("#shippingSelect").html("<select id='lstClass' name='ShippingClass'><option selected='selected' value='12'>7-14 days delivery ("+PSevenToFourteenOutStock+" / "+ESevenToFourteenOutStock+")</option></select>");
				$("#subPicRow").html(picRow);	
			
				var costRow = PSevenToFourteenOutStock+"&nbsp;/&nbsp;"+ESevenToFourteenOutStock;
				$("#shipCostCol").html(costRow);
						
				//if we are adding the shipping row
				if($("#shipHeadCol").html())
				{	
					setTotalsRow(SevenToFourteenOutStock,(SevenToFourteenOutStock*euroExchangeRate));
				}
			}
		}else
		{
			//don't do this if 2nd page of the checkout
			if(dontDoShip==false)
				{	//we don't need to do picture row
					//do the non uk out of stock
					$("#shippingSelect").html("<select id='lstClass' name='ShippingClass'><option value='13' selected='selected'>Non-UK Deliveries (£19.98 / €23.98)</option></select>");
					//set the totals row
					//don't do this if we are in the second page of the checkout
					var costRow = PnonUKoutOfStock+"&nbsp;/&nbsp;"+EnonUKoutOfStock;
					$("#shipCostCol").html(costRow);
					//if we are adding the shipping row
					if($("#shipHeadCol").html())
					{	//make sure we are using the right maths
						setTotalsRow(nonUKoutOfStock,(nonUKoutOfStock*euroExchangeRate));
					}
				}
		}
			//find payPal span and hide it
			$("#payPalLogo").removeClass().addClass('hide');		
		}
}
function hideCards()
{	$('.showCards').each(function(){
							  $(this).removeClass('showCards');
							  $(this).addClass('hideCards');
							  });
	}
function showCards()
{	//right 
		if($('select[name]').attr('value')==10005)
		{		
		$('.hideCards').each(function(){
							  $(this).removeClass('hideCards');
							  $(this).addClass('showCards');
							  });
		}
		else
		{	hideCards();
			}
	}

//////////////////functions///////////////
$(document).ready(
				  function(){$('.addToCart').bind('click',setReferenceCookie);//find the button and bind the click to it
				});
$(document).ready(
				  function(){$('select[name]').bind('change',showCards);
				});
$(document).ready(setShippingTime);
$(document).ready(hideCards);
$(document).ready(setPackingSlip);
////////////////////////////////



