//  Original Metal Box 
//  products40js.js		17 Jul 11   new version for Promo Discount Code 
//  products50js.js		14 Oct 11	no change from v40, but this version now used for home page (Flash and non-flash)
//  products47js.js		 8 Nov 11   new delivery rules (adding rc, ubs etc). Note version num (50 was premature and same as 40)
//  products50js.js		 4 Jan 12 	add EVERYONE and ALLPRODUCTS features to Promo Discount Code


// 'constants'
var MAX_ORDER_LINES = 10;		// max number of orderline cookies that I allow line0..line9 
								// because I suspect there is an IE limit of 20, and need to leave a few for addresses
// global variables
var pageName = '';				// name of meta tag page-name (eg 'home' or 'cart'). Used to tell if on home (flash) page
var aCartCode = new Array();	// array to hold item product codes for each row of shopping cart (max 10)
								// only reason is for quick calc of shipping cost without having to get every cookie again
var numOrderLines = 0;			// number of orderline cookies (created, or found and read)
var shippingArea = "UK";        // UK or EUR or ROW, default is UK

// these two new, for beta organisation 20 dec 09
var iTotalItems = 0;			// total items in shop cart (not lines) (ie if 2 of one item and 1 of another, total  = 3)
var nTotalValue = 0.0;			// total value in ShopCart Summary (NOT incl shipping, 19may10)

var oldDescrip = '';			// to hold previous content of Descripdiv
var bCartOnDisplay = false;		// used in GoHome to see whether to close cart

// for Discount Code feature
var bDCrunning = false;			// is there a discount scheme running
var bDCcorrect = false;			// is the user entered discount code correct ?
var sDCproduct = "";			// eg pi-royal
var nDCratenum = 0.0;			// discount rate (parsefloat)
var sDCratetype = "";			// eg percent (or pound)
var nDCtotal = 0.0;				// total discount on order


// content of descrip when Shopping Cart on view
var shopCartPara = '<p class="textclass">In the shopping cart, you can change quantities or delete whole lines, or close it and view more products via the main menu.<br />Please be sure to select your delivery area to see the correct delivery charge. </p>';
	
	
var prevMenuLine = -1;			// current 'page' (actually index of <li> in menudiv)
var $prevMenuObject = null;		// used to reactivate previous menuline
												   

// ********************** functions called from Flash ***********************************************

// to display the product text in the description area
function jDisplayDescription(descrip) {
	descrip = "<p class='textclass'>" + descrip + "</p>";  // but I should be able to change text and still keep the style ??
	$('#descripdiv').html(descrip);
	$('#descripdiv p').hide();
	$('#descripdiv p').slideDown('slow');
}

// called from Flash
// save cookie with this product (qty  always 1 from Flash)
function jAddToCart(cookieString) {
	//alert("AddToCart : " + cookieString);
	var cookieNum;
	var iSuccess;
		
		//alert("jAddToCart");
		
		if (numOrderLines < MAX_ORDER_LINES) {
			cookieNum = checkCookieExists(cookieString);
			if (cookieNum > -1) {
				changeCookieQty(cookieNum, 1, true);		// qty always 1 from Flash
			} else {
				cookieNum = numOrderLines;
				createCookie(cookieNum, cookieString);		// create new cookie
				if (cookieNum == 0) {
					setDeliveryAreaCookie();				// and if first orderline, then also create deliv area cookie, 
															// in case area left as UK, and no reason to ever set it
				}
				numOrderLines++;
			}
			doSummary();										// recalc and display Summary
			iSuccess = numOrderLines;
		} else {
			// shopping cart full
			// Need to improve this !! JS or Flash ?
			alert ("Your Shopping Cart is full. You can't add any more items. Please proceed to CheckOut.")
			iSuccess = -1;
		}
		return iSuccess;
}

// funcs to pass shop cart summary back to Flash
// total num of items in cart (eg if 2 x Frog and 1 x Hoodie = 3, not same as num of lines)
function jGetCartTotalItems() {
	return iTotalItems;
}

// total value (NOT incl shipping, 19may10)
function jGetCartTotalValue() {
	return nTotalValue;
}

// called from View Cart button in Flash product page
function jViewCart() {
	window.location.href = "cart.htm";		// cart40.htm while testing v40
	return 1; 		 // unnecessary ?
}

// called from Checkout button in Flash product page
function jCheckout() {
	window.location.href = "checkout.htm";
	return 1; 		 // unnecessary ?
}

// ********************   menu button functions *************************************

// this code modified from Atlanta Jones (much better than my old arrays etc!)

$(document).ready(function() {
		
		// Preload all rollovers
		$("#menudiv img").each(function() {
			// Set the original src
			rollsrc = $(this).attr("src");
			rollON = rollsrc.replace('_up', '_over');
			newImg = new Image(); // create new image obj
			$(newImg).attr("src", rollON); // set new obj's src, ie cache it
			rollDown = rollsrc.replace('_up', '_down');
			downImg = new Image(); // create new image obj
			$(downImg).attr("src", rollDown); // set new obj's src, ie cache it
		});

		
		// Navigation rollovers
		$("#menudiv a").mouseover(function(){
			imgsrc = $(this).children("img").attr("src");
			if (typeof(imgsrc) != 'undefined') {
				imgsrcOVER = imgsrc.replace('_up', '_over');
				$(this).children("img").attr("src", imgsrcOVER);
			}
		});
		
		// on mouse down
		$("#menudiv a").mousedown(function(){
			if (typeof(imgsrc) != 'undefined') {
				imgsrcDOWN = imgsrc.replace('_up', '_down');
				$(this).children("img").attr("src", imgsrcDOWN);
			}
		});
		
		// Handle mouseout
		$("#menudiv a").mouseout(function(){
			if (typeof(imgsrc) != 'undefined') {
				$(this).children("img").attr("src", imgsrc);
			}
		});
		
		
});

// *************** to handle secondary menu buttons  **********************************

$(document).ready(function() {
		
		// Preload all rollovers
		$("#menu2div img").each(function() {
			// Set the original src
			rollsrc = $(this).attr("src");
			rollON = rollsrc.replace('_up', '_over');
			newImg = new Image(); // create new image obj
			$(newImg).attr("src", rollON); // set new obj's src, ie cache it
			rollDown = rollsrc.replace('_up', '_down');
			downImg = new Image(); // create new image obj
			$(downImg).attr("src", rollDown); // set new obj's src, ie cache it
		});

		
		// Navigation rollovers
		$("#menu2div a").mouseover(function(){
			imgsrc = $(this).children("img").attr("src");
			if (typeof(imgsrc) != 'undefined') {
				imgsrcOVER = imgsrc.replace('_up', '_over');
				$(this).children("img").attr("src", imgsrcOVER);
			}
		});
		
		// on mouse down
		$("#menu2div a").mousedown(function(){
			if (typeof(imgsrc) != 'undefined') {
				imgsrcDOWN = imgsrc.replace('_up', '_down');
				$(this).children("img").attr("src", imgsrcDOWN);
			}
		});
		
		// Handle mouseout
		$("#menu2div a").mouseout(function(){
			if (typeof(imgsrc) != 'undefined') {
				$(this).children("img").attr("src", imgsrc);
			}
		});
		
});

// ************* functions that call Actionscript ********************************

/*var flashPlayer;
// but can't get this to work with SWFObject
function detectFlashPlayer() {
	if (navigator.appName.indexOf("Microsoft") != -1 ) {
		flashPlayer = window.objectId;
	} else {
		flashPlayer = window.document.embedName;
	}
}
*/

// called from Home button, 
// ensure flashdiv up, and then tell Flash to get back to Home page
// (Flash checks its state to see what it has to do)
// problems ref status of View Cart/Products button and description
function goHome() {
	if (bCartOnDisplay) {
		closeCart(); 
	}
	var swf = document.getElementById("flashdiv");  // pipwerks solution for SWFObject
	swf.fromHTMLGoHome();	// this displays Home descrip (I think)
}





// *********************** doc.ready functions **************************************

// on doc ready, initialise ShopCartSummary, 
// but first have to read DeliveryArea cookie (if it exists)
// I assume that this is first time shippingArea is required, so this is the only point where this cookie is read
// also (4sep09) initialise numOrderLines
$(document).ready(function() {
	var cookieline;
	// get the DeliveryArea cookie (if it exists, otherwise leave as UK), values UK, EUR or ROW
	cookieline = $.cookie('DeliveryArea'); 
	if (cookieline) {
		shippingArea = cookieline;
	}
	
	doSummary();
	
	// also initialise numOrderLines (bit of duplication with doSummary) 
	// so could put it inside doSummary (if speed req'd) , but that's not very obvious, so leave it here for now
	for (var i = 0;  i < MAX_ORDER_LINES; i++) {
		cookieline = $.cookie('line' + i);  // cookies are line0 .. line9
		if (cookieline == null) {
			break;		// assumes cookies will always be contiguous eg 1..2..3, ie first one not found = stop
		} 
	}
	numOrderLines = i;
});

// to see what page we are on (used to differentiate between home and cart)
// both can show shopcart, but on home it is overlaid above the flash div
$(document).ready(function() {
	pageName = $('meta[name=page-name]').attr("content");
});


// on doc ready, slide HTMLDiv up, in readiness for subsequent slideDowns on View cart, to get into right sequence
// HOWEVER this isn't clever as Flash may not load etc,in which case we'll need htmlDiv. Need to be cleverer
// could do it on a message from Flash after first load of all home pics ??
// 2sep09 don't do this on Cart page, cos cart already visible
$(document).ready(function() {
	if (pageName == 'home') {
		$('#htmldiv').slideUp('slow');
	}
});

// **************** check whether Promo Discount campaign running *********
// needs to be before ShowCart








//  ************** called from ViewCart page, *********************************************
// most of the time will be to close the cart view and see the alternative Flash product/collection' view
// ie slideUp htmldiv to make flashdiv visible
// but what if previous page was not flash, eg terms&conditions ?? (need to solve this later)

// ****************************************************************************************
// nb. note (20jul09) that we have to use *visibility* (not fadeOut, slideDown etc) ...      *
//  ... because in FF hide() etc seem to reset the Flash Movie (OK in IE)                 *
// ... maybe could get away with it if Flash within an inner div ??? (need to experiment) *
// ... no inner div doesn't help (27jul09) I think this is because of swf being-on-top problem (solved by wmode opaque ?)
// ****************************************************************************************
function closeCart() {
	
	// reset page ht if shopcart extended it
	var oldHt = 580;
	$('#outerdiv').height(oldHt);
	
	if (pageName == 'home') {
		$('#htmldiv').slideUp('slow');
	} else {
		history.back();
	}
	bCartOnDisplay = false;
	
	// change Hide Cart button back to View Cart
	$('#viewCartButton').html('<a href="javascript:viewCart()"><img src="images/buttons/btn_viewcart03_up.gif" width="200" height="25" alt="" border="0"></a>');
		// and add rollover back to 'new' button
		$("#viewCartButton a").mouseover(function(){
			imgsrc = $(this).children("img").attr("src");
			if (typeof(imgsrc) != 'undefined') {
				imgsrcON = imgsrc.replace('_up', '_over');
				$(this).children("img").attr("src", imgsrcON);
			}
		});
		// and on mouse down
		$("#viewCartButton a").mousedown(function(){
			if (typeof(imgsrc) != 'undefined') {
				imgsrcDOWN = imgsrc.replace('_up', '_down');
				$(this).children("img").attr("src", imgsrcDOWN);
			}
		});
		// and mouseout
		$("#viewCartButton a").mouseout(function(){
			if (typeof(imgsrc) != 'undefined') {
				$(this).children("img").attr("src", imgsrc);
			}
		});
	
	// display old descrip para, whatever it was
	$('#descripdiv p').hide();
	$('#descripdiv p').html(oldDescrip);
	$('#descripdiv p').slideDown('slow');
}

function showCart() {
	// extend page ht if shopcart needs it
	// ensure htmldiv (contains shopcart) is always at least min (420px), to fully cover flashdiv
	// but mustn't SET ht of htmldiv, or else can't read real ht ever again, so pad it out to reqd ht
	// outerdiv ht might have been reduced (eg if deleted line), but ensure never less than min (580px)
	var minHtmldivHt = 420;
	var minOuterdivHt = 580;
	var paddingValue;
	//alert("htmldiv ht and innerHeight on entry : "  + $('#htmldiv').height() + ", " + $('#htmldiv').innerHeight() );
	if ($('#htmldiv').innerHeight() < minHtmldivHt) {	
		paddingValue = minHtmldivHt - $('#htmldiv').innerHeight();
		$('#htmldiv').css("padding-bottom", paddingValue);
		//alert("paddingValue and htmldiv innerHeight after padding : " + paddingValue + ", " + $('#htmldiv').innerHeight() );
	}
	var newPageHt = minOuterdivHt + ($('#htmldiv').innerHeight() - $('#contentdiv').height());
	//alert("contentdiv & htmldiv heights : " + $('#contentdiv').height() + ", " + $('#htmldiv').innerHeight() );
	if (newPageHt < minOuterdivHt) {
		newPageHt = minOuterdivHt;
	}
	$('#outerdiv').height(newPageHt);
	
	// display shopcart
	$('#htmldiv').slideDown('slow');
	bCartOnDisplay = true;
		
	// change View Cart button to Hide Cart
	$('#viewCartButton').html('<a href="javascript:closeCart()"><img src="images/buttons/btn_hidecart03_up.gif" width="200" height="25" alt="" border="0"></a>');
		// and add rollover back to 'new' button
		$("#viewCartButton a").mouseover(function(){
			imgsrc = $(this).children("img").attr("src");
			if (typeof(imgsrc) != 'undefined') {
				imgsrcON = imgsrc.replace('_up', '_over');
				$(this).children("img").attr("src", imgsrcON);
			}
		});
		// and on mouse down
		$("#viewCartButton a").mousedown(function(){
			if (typeof(imgsrc) != 'undefined') {
				imgsrcDOWN = imgsrc.replace('_up', '_down');
				$(this).children("img").attr("src", imgsrcDOWN);
			}
		});
		// and mouseout
		$("#viewCartButton a").mouseout(function(){
			if (typeof(imgsrc) != 'undefined') {
				$(this).children("img").attr("src", imgsrc);
			}
		});
}




// to read cookies and display shopping cart
function viewCart() {
	
	// remove prev contents of display panel 
	$('#htmldiv').css("padding-bottom", 0);
	$('#htmldiv').empty();
	var html = '<h3>Your Shopping Cart</h3>';
	
	// get orderline cookies
	var cookieline;
	var cookiearray;
	var imgsource;
	var lineTotal = 0;
	var subTotal = 0;
	var DCTotal = 0;	// total discount
	var Total = 0;
	
	numOrderLines = 0;			// number of orderline cookies found (and read)
	for (var i = 0;  i < MAX_ORDER_LINES; i++) {
		cookieline = $.cookie('line' + numOrderLines);  // cookies are line0 .. line9
		//alert( cookieline);
		if (cookieline == null) {
			if (numOrderLines == 0) {
				html += '<h4>is empty</h4>';   // if cookieline 0 is empty, then there ain't none 
			} else {
				html += '</tbody></table>';  // close 
			}
			break;		// assumes cookies will always be contiguous eg 1..2..3, ie first one not found = stop
		} else {
			if (numOrderLines == 0) {
				html += '<table class="carttable">';
				html += '<thead><tr><th width="70" class="carthdr">&nbsp;</th><th width="180" class="carthdr">Product</th><th width="80" class="carthdr">Price</th><th width="50" class="carthdr">Qty</th><th width="80" class="carthdr">Line Total</th><th width="40" class="carthdr">Cancel</th></thead>';
				html += '<tfoot><tr><td>Subtotal</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td id="subtotal">&nbsp;</td><td>&nbsp;</td></tr>';
				html += '<tr class="discountrow"><td>Discount</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td id="discountcell">&nbsp;</td><td>&nbsp;</td></tr>';
				html += '<tr><td>Delivery</td><td id="shippingdescrip">( UK )</td><td>&nbsp;</td><td>&nbsp;</td><td id="shippingcost">&nbsp;</td><td>&nbsp;</td></tr>';
				html += '<tr><td>TOTAL</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td id="total"><strong>&nbsp;</strong></td><td>&nbsp;</td></tr></tfoot>';
				html += '<tbody>';
			}
						
			// parse cookie
			// format is code|name|option|price|qty|  
			// eg ph_red|Red Hoodie|with address panel|160.00|1|
			cookiearray = cookieline.split("|");   
			// save product codes, for shipping recalcs
			aCartCode[numOrderLines] = cookiearray[0];   
			// build up the shopping cart table  (set widths here for now, tidy into css later ?)
			// trying to force slideUp to work correctly on <tr>s
			
			// various options need a different cart image  ******************
			if (cookiearray[0] == "ps_openers") {
				// 15sep10  bottle openers need a different image depending on the option eg : ps_openers-cameron_cart.gif
				imgsource = "images/cart/" + cookiearray[0] + cookiearray[2].toLowerCase() + "_cart.gif";
			} else if (cookiearray[0] == "gi_staff") {
				// if staffordshire, option is '-Left facing' or '-Right facing', so cut this to 'gi_staff-left_cart.gif' etc
				var sOption;
				if ( cookiearray[2].indexOf("Right") == -1) {
					sOption = "-left";
				} else {
					sOption = "-right";
				}
				imgsource = "images/cart/" + cookiearray[0] + sOption + "_cart.gif";
				//alert(imgsource);
			} else if (cookiearray[0] == "gi_dearmats") {
				// if Dearmats, check if this is Tube of dearmats 'gi_dearmats-tube_cart.gif' etc
				var sOption;
				if ( cookiearray[2].indexOf("Tube") != -1) {
					sOption = "-tube";
				} else {
					sOption = "";
				}
				imgsource = "images/cart/" + cookiearray[0] + sOption + "_cart.gif";
			} else {
				// if not a special option then just normal cart image
				imgsource = "images/cart/" + cookiearray[0] + "_cart.gif";
			}
			// end of cart images  *************************
			
			html += '<tr class="cartrow" width="70"><td class="cartimgcell"><img src="' + imgsource +'">'+ '</td>';
			html += '<td class="cartcell"  width="180">' + cookiearray[1] + '<br />' + cookiearray[2]+ '</td>';  // name (+option)
			html += '<td class="pricecell" width="80">' + '&pound; ' + parseFloat(cookiearray[3]).toFixed(2) + '</td>';  // price
			// quantity
			html += '<td class="quantitycell" width="50">' + '<input type="text" value=' + cookiearray[4] + ' maxlength="3" size="4" />' + '</td>';
			lineTotal = cookiearray[3] * cookiearray[4];
			html += '<td class="linetotalcell" width="80">' + '&pound; ' + lineTotal.toFixed(2) + '</td>';
			html += '<td class="deletecell" width="40">' + '<img src="images/buttons/cross.gif" width="16" height = "16" alt="remove from cart" title="remove from cart" class="clickable" />' + '</td>';
			html += '</tr>';
			
			numOrderLines++;
		}
	}
	
	// create cart table and actually display shopping cart contents ****************************
	$('#htmldiv').append($(html));
	//alert("NumOrderLines = " + numOrderLines);
	showCart();
	
	// ******************** add behaviours to the html carttable **************************
	
	// set up recalc behaviour if change qty - recalc num items (for deliv cost) line totals and subtotal
	var $quantities = $('td.quantitycell input');
	$quantities.change(function() {
		//alert("Qtys changed");
		var rowNum = $("td.quantitycell input").index(this);  // remember current row
		// calc and display new subtotal, shipping and total
		displayTotals();	
		// and update Cookie with changed qty
		var quantity = parseInt($(this).val(), 10);
		quantity = isNaN(quantity) ? 0 : quantity; 
		//alert("Change qty in Cookie " + rowNum + " qty = " + quantity);
		changeCookieQty(rowNum, quantity, false);               // false = replace with this qty, don't increment
		doSummary();
	});
	
	
	// limit input to numeric only for Qty boxes
	$('.quantitycell input').keypress(function(event) {
	// only allow 0-9, backspace, tab, cr, delete
		var asc = event.which;
		//alert("asc = " + asc);
		if (asc && (asc < 48 || asc > 57) && (asc != 8) && (asc != 13)) {
			event.preventDefault();
		}
		// trigger 'change' if user presses Enter, needed by IE
		if (asc == 13) {
			$(this).change();
		}
  	});
	
	// Behaviour of Delete button
	$('td.deletecell').click(function() {
		//$(this).parents('tr').find('td.quantitycell input').val(0).trigger('change').end().fadeOut("slow");
		
		// do I need to confirm user meant to delete ?, do it later - if so then remove and change cookies
		var rowNum = $(".deletecell").index(this);
		//alert("Delete Cookienum = " + rownum + " ? ");   // for now
		// delete this cookie
		deleteCookie(rowNum);
		
		// now fade the row and *then* read cart afresh from cookies, and therefore recalc totals etc
		// do it in callback, else too quick visually
		// can't slideUp a table row unfortunately, cos of known(?) problem in jQuery & FF with sliding table rows
		// $(this).parents('tr').slideUp(2000);
		// $(this).parents('tr').fadeTo('slow', 0.2).slideUp('slow', function() {
		$(this).parents('tr').fadeOut('slow', function() {
			viewCart();
		});
		
		// recalc summary
		doSummary();
	});
	
	// delivery area form behaviour (recalc shipping cost if radio button clicked)
	$("form input:radio").click(function() {
		shippingArea = $(".radioclass:checked").val();  // UK or EUR or ROW
		doShipping();
		doSummary();
		setDeliveryAreaCookie();
	});
	
	// internal function to calculate and display Cart subtotal, shipping and Total
	function displayTotals() {
		var totalQuantity = 0;
		var totalCost = 0;
		
		$('.carttable tbody tr').each(function() {
			  var price = parseFloat($('.pricecell', this).text().replace(/^[^\d.]*/, ''));
			  price = isNaN(price) ? 0 : price;
			  var quantity = parseInt($('.quantitycell input', this).val(), 10);
			  quantity = isNaN(quantity) ? 0 : quantity;         
			  var cost = quantity * price;
			  $('.linetotalcell', this).text("£ " + cost.toFixed(2));
			  totalQuantity += quantity;
			  totalCost += cost;
		});
    	$('#subtotal').text("£ " + totalCost.toFixed(2));
		// calc and display shipping cost and grand total
		doShipping();
	}
	
	
	// **** now actually display  the shipping options and the totals *******************
	
	// select the right area button
	if (shippingArea == "EUR") {
		$('#eurbutton').attr("checked", true); 
	} else if (shippingArea == "ROW") {
		$('#rowbutton').attr("checked", true); 
	} else  {
		$('#ukbutton').attr("checked", true); 
	}
	
	// and calc total etc first time (can't use trigger('change') because causes unnecessary rewrites of cookies every time
	displayTotals();
	
}       // end of ViewCart


	
// *********** Order cookie functions *******************************

// create an order cookie, from cookieString passed from Flash  :  prodcode | name | option | unitprice | qty |
// expiry duration : this session only
// I had originally set it to 1 day to allow to reorder if an internet problem,  etc (sort of wish-list)
// but that meant they expired at different times, and therefore might not be contiguous, as the code expects
// So I reverted to session only for now. 
// (if 1 day is really needed, then must check for all cookies, and not just stop at first non-existent one)
function createCookie(cookieNum, cookieString) {
	var cookieName = 'line' + cookieNum;
	$.cookie(cookieName, cookieString);  //duration = session only
	//$.cookie(cookieName, cookieString, {expires:1});  // duration = 1 day
}

// change the quantity in a cookie
// (if bIncrement = true, then add qty, else replace qty)
function changeCookieQty(cookieNum, qty, bIncrement) {
	var cookieName = 'line' + cookieNum;
	var cookieLine = $.cookie(cookieName);  // get cookie, cookies are line0 .. line9
	var cookieArray = cookieLine.split("|");
	var cookieString = cookieArray[0]+"|"+cookieArray[1]+"|"+cookieArray[2]+"|"+cookieArray[3]+"|";
	if (bIncrement) {
		cookieString += parseInt(cookieArray[4]) + parseInt(qty) + "|";   // add new qty
	} else {
		cookieString += qty + "|";   // replace with new qty
	}
	//$.cookie(cookieName, cookieString, {expires:1});
	$.cookie(cookieName, cookieString);
	
}



// delete a cookie, and slide any others down
function deleteCookie(cookieNum) {
	var cookieName = 'line' + cookieNum;
	$.cookie(cookieName, null);						// delete cookie
	//alert("Deleting cookie " + cookieNum);
	// need to shuffle others down ?
	var cookieString;
	for (var i = cookieNum; i < MAX_ORDER_LINES; i++) {
		cookieName = 'line' + (i+1);
		cookieString = $.cookie(cookieName);    	// read cookie i+1
		if (cookieString != null) {
			//$.cookie('line' + i, cookieString, {expires:1});		// save as cookie i, expiry 1 day
			$.cookie('line' + i, cookieString);		// save as cookie i, session only
			$.cookie(cookieName, null);				// delete cookie i+1
			//alert("New cookie " + i);
		} else {
			break;									// if not found, then stop
		}
	}
}



// check to see if a cookie already exists for this product (and option)
// compare 'prodcode|prodname|option' from each
// if exists return cookieNum, else -1
function checkCookieExists(newCookieStr) {
	var subLen;
	var prodStr;   // product and option string eg "ph_red|Red Hoodie|with address panel|"
	
	var cookieName;
	var cookieString;
	var cookieNum = -1;
	// find end of 3rd 'element'
	subLen = newCookieStr.indexOf("|",0);
	subLen = newCookieStr.indexOf("|",subLen+1);
	subLen = newCookieStr.indexOf("|",subLen+1);
	subLen = subLen+1;										// to get trailing |
	prodStr = newCookieStr.substr(0,subLen); 
	//alert("checkCookieExists : " + prodStr);
	for (var i = 0; i < numOrderLines; i++) {
		cookieName = 'line' + (i);
		cookieString = $.cookie(cookieName);    	// read cookie i
		if (cookieString.length > subLen) {
			if (prodStr == cookieString.substr(0,subLen)) {
				cookieNum = i;
				//alert("Cookie Found " + i + " " + prodStr);
				break;
			}
		}
	}
	return cookieNum;
}

function getDeliveryAreaCookie () {
   	 var cookieLine;
	 cookieLine = $.cookie('DeliveryArea');  
     if (cookieLine) {
		 shippingArea = cookieLine;
	 }
}

function setDeliveryAreaCookie (){
   var expiryDays =  365;
   $.cookie('DeliveryArea', shippingArea, {expires: expiryDays});
}


// ***************** Shipping and Delivery functions *****************************

// shippingArea (global) has already been set in 'change radio etc'
// doShipping is the high level func, to recalc and display
// logic changed 21 Dec 09 (UK is now per shipment)
// and updated 26 May 10, 22 Nov 10
function doShipping() {
	var shippingString;
	var shippingTotal;
	
	if (shippingArea == "UK") {
		shippingString = "( UK )";
		var rate1 = 12.0;
		var rate2 = 3.5;
		shippingTotal = calcShipping(rate1, rate2);
	} else if (shippingArea == "EUR") {
		shippingString = "(Europe)";
		var rate1 = 30.0;
		var rate2 = 9.50;
		shippingTotal = calcShipping(rate1, rate2);
	} else if (shippingArea == "ROW") {
		shippingString = "(Rest of World)";
		var rate1 = 60.0;
		var rate2 = 15.0;
		shippingTotal = calcShipping(rate1, rate2);
	} 
	displayShipping(shippingString, shippingTotal);
}

// logic is 
// for each line in shopping cart :
// 		is item a lowrate (small) item (eg so (robot clocks), or gift (gi) ?), if so use rate 2, else normal rate 1
// 		multiply number of items by rate
//		but for UK (26may10), if one or more big items, then cost of whole shipment is £12 (rate1)
//                            if no big, and 1 or 2 small £3.50 (rate2), 3 or more small £7 (2 x rate2)
//
// 13sep10, add 2020 and kbs boxes to small
// also remove shipping calcs from doSummary, but do note that if I have to reinstate them in doSummary I can't use this func because carttable may not exist (if from flash)
// 8 Nov 11, add rc, ubs, sbs, eg_box_small to Small items category

function calcShipping(rate1, rate2) {
	var shippingCost = 0.0;
	var collectioncode;
	var rate;
	var qty;
	var nBigItems;   // used for UK calcs (26may10)
	var nSmallItems;
	var cost;
	var cartRow = 0;
	var underscorePos;	// position of first underscore in product code
	
	nBigItems = 0;
	nSmallItems = 0;
	// for each line of shopping cart
	$('.carttable tbody tr').each(function() {
			// get qty
			qty = parseInt($('.quantitycell input', this).val(), 10);
			qty = isNaN(qty) ? 0 : qty; 
			
			// get collection code for this item (cookiearray0), use aCartCode array, created just for this purpose
			// cartcode examples : ph_splat, ubs_dog, eg_box_large, kbl_smile etc
			underscorePos = aCartCode[cartRow].indexOf("_"); 
			collectioncode = aCartCode[cartRow].substr(0,underscorePos);
			if (collectioncode == "eg"){
				// 8nov11, need to get eg_rack_large, eg_rack_small, eg_box_small but not eg_box_large
				collectioncode = aCartCode[cartRow].substr(0,8);
			}
			// and decide which rate to use (rate2 for small items), rate 1 for others
			// small items (8nov11): robot clocks, gifts, public servants, nightlights
			// 		small useful boxes, small keyboxes,small seedboxes, egg racks, small egg box
			if ( (collectioncode == "rc") || 
				 (collectioncode == "gi") || 
				 (collectioncode == "ps") || 
				 (collectioncode == "nn") ||
				 (collectioncode == "ubs") || 
				 (collectioncode == "kbs") 	||
				 (collectioncode == "sbs") 	||
				 (collectioncode == "eg_rack_") || (collectioncode == "eg_box_s")
			   )	{	
				rate = rate2;
				nSmallItems += qty;
			} else {
				rate = rate1;
				nBigItems += qty;
			}
			        
			//alert("calcShipping " + rate + " x " + qty);
			// calc shipping for this line
			cost = qty * rate;
			shippingCost += cost;
			
			cartRow++;
	});
	
	// for UK only, (26may10)  if one or more big items, whole shipment is  large amount
	//              if all small items, then 1 or 2 is small amount, 3 or more is 2 x small amount
	if (shippingArea == "UK") {
		shippingCost = 0.0;
		if (nBigItems > 0) {
			shippingCost = rate1;
		} else if (nSmallItems > 2) {
			shippingCost = 2 * rate2;
		} else if (nSmallItems > 0){
			shippingCost = rate2;
		}
	}
	
    return shippingCost;
}

// display subtotal, calculate discount if any, shipping text (eg (Europe)) cost and Total
function displayShipping(shippingString, shippingTotal) {
	$('#shippingdescrip').text(shippingString);
	// get subtotal (strip any non-numeric off front)
	var subTotal = parseFloat($('#subtotal').text().replace(/^[^\d.]*/, ''));
	subTotal = isNaN(subTotal) ? 0 : subTotal;
	$('#subtotal').text("£ " + subTotal.toFixed(2));
	// if user's discount code is good (only true if there is a running scheme) calc discount and add it in, and display
	if (bDCcorrect) {
		nDCtotal = calcDiscount();
		$('#discountcell').text("-£ " + nDCtotal.toFixed(2));
		$('tr.discountrow').show();
	} else {
		nDCtotal = 0.0;
		$('tr.discountrow').hide();
		// can't slideUp a table row unfortunately, cos of known(?) problem in jQuery & FF with sliding table rows
	}
	
	$('#shippingcost').text("£ " + shippingTotal.toFixed(2));
	var totalCost = subTotal - nDCtotal + shippingTotal;
	$('#total').text("£ " + totalCost.toFixed(2));	
}

// calc discount (only called if there is a scheme and code is valid)
function calcDiscount() {
	var dtotal = 0.0;
	var i = 0;
	var drate = 0.0;
	var lineprice;
	
	// for now only handle percent type calc
	if (sDCratetype == "percent") {
		drate = nDCratenum / 100;
	}
	
	// check if any discount products (assume 1 discount product (sDCproduct) only for now, or ALLPRODUCTS)
	// need to increment aCartCode array in line with cart table
	i = 0;
	$('.carttable tbody tr').each(function() {
		  if (sDCproduct == "ALLPRODUCTS" || sDCproduct == aCartCode[i]) {
				lineprice = parseFloat($('.linetotalcell', this).text().replace(/^[^\d.]*/, ''));
				lineprice = isNaN(lineprice) ? 0 : lineprice;
				dtotal += lineprice * drate;
		  }
		  i++;
			  
	});
	
	return dtotal;
}

// ************ Cart Summary functions *********************
// can't assume cart table exists, so have to work from cookies, so can't use calcShipping() above

// 13sep10 remove shipping calcs from doSummary, because they have kept to that since 19May10
// but do note that if I have to reinstate them in doSummary I can't use calcShipping() above
// because carttable may not exist (if from flash)  
// See products21js.js for required code
function doSummary() {
	var numItems = 0;
	var totalValue = 0.0;
	var shipCost = 0.0;
	
	var cookieline;
	var cookiearray;
	var collectioncode;
	var qty;
	var price;
	
	
	for (var i = 0;  i < MAX_ORDER_LINES; i++) {
		cookieline = $.cookie('line' + i);  // cookies are line0 .. line9
		if (cookieline == null) {
			break;		// assumes cookies will always be contiguous eg 1..2..3, ie first one not found = stop
		} else {	
			// parse cookie
			// format is code|name|option|price|qty  
			// eg ph_red|Red Hoodie|with address panel|160.00|1
			cookiearray = cookieline.split("|");   
			collectioncode = cookiearray[0].substr(0,2);
			price = parseFloat(cookiearray[3]);
			price = isNaN(price) ? 0.0 : price; 
			qty = parseInt(cookiearray[4]);
			qty = isNaN(qty) ? 0 : qty; 
			numItems += qty;
			totalValue += (qty * price);
			
		}
	}
	
	// new 20dec09, save value and items in global variables (so they can be read without recalc everytime)
	iTotalItems = numItems;
	nTotalValue = totalValue;
	
}
	
// Promotional Discount Code functions ***********************************
// this code for cart page only (not products page)
$(document).ready(function() {
	
	if (pageName == "cart") {
		// on page (re)load/ready check to see if there is a Discount cookie
		// if so that means there is a promo campaign running AND the user has already entered a valid code 
		//      and has now re-entered the Shopcart page (could do this many times)
		// in which case we want to get back to previous state as efficiently as poss
		// (nb Discount cookie lifetime is just for the session)
		//var discountcookiepresent = false;  // just testing
		if (getDiscountCookie()) {
			// yes there is a Discount cookie, so user must have already entered correct code
			// getDisc..cookie sets sDCproduct, nDCratenum, sDCratetype
			bDCrunning = true;
			bDCcorrect = true;
			//sDCproduct = 'pi_royal'; // just testing
			//nDCratenum = 25;
			//sDCratetype = "percent";
			doShipping();	// calc discount (and shipping and Total) and display
			//$("#usercode").val(" Cookie !");
			$('#codeform').hide();
			//$("#message").html("<p class='rightclass'>You have a valid Discount code</p>").show();  // normal
			$('#message').html("<p class='redbold'>January Sale - 30% off everything !</p>").show();  // open scheme
		} else {
			// if no discount cookie then check to see whether there is a discount campaign running
			bDCrunning = false;
			bDCcorrect = false;
			//$("#message").html("<p class='rightclass'>&nbsp;</p>").hide();
			$.ajax({
				type: "POST",
				url: 'lpromo02.php',
				data: {usercode: "onoffer?", is_ajax: 1},
				success: function(response)
				{
					if (response == "false") {
						//No discount scheme
						$('#codeform').hide(); // unnecessary ? it's now hidden by default
						bDCrunning = false;
						bDCcorrect = false;
					} else {
						// there is a current scheme
						// if it's an open scheme (code=EVERYONE) then response contains 'productcode, discount rate' 
						// if it's a closed scheme (ie requiring user to enter a discount code) then it contains 'true'
						bDCrunning = true;
						if ( response == "true") {
							// user must enter their discount code
							$('#codeform').show();
						} else {
							// scheme open to everyone so no need for discount code
							bDCcorrect = true;
							sDCproduct = response.substring(0, response.indexOf(','));
							var rate = response.substring(response.indexOf(',')+1);
							nDCratenum = parseFloat(rate);
							sDCratetype = "pounds";
							if (rate.indexOf("percent") != -1) {
								sDCratetype = "percent";
							}
							doShipping(); 			//recalc and display with discount
							$('#codeform').hide();	// unnecessary ? it's now hidden by default
							setDiscountCookie();	// contains details, and shows user has entered correct code
							$('#message').html("<p class='redbold'>January Sale - 30% off everything !</p>").show();
						}
					} 
				}
			});		
		}
		
		
		
		
		
		
		// add method to Discount button (ie 'Check my discount code')
		$("#discount").click(function() {
	
			var form_data = {
					usercode: $("#usercode").val(),
					is_ajax: 1
				};
	
			$.ajax({
				type: "POST",
				url: 'lpromo02.php',
				data: form_data,
				success: function(response)
				{
					if(response == 'fail') {
						$("#usercode").val("Invalid code");
						$("#message").html("<p class='rightclass'>&nbsp;</p>").hide();
						bDCcorrect = false;
						nDCtotal = 0;
						doShipping(); 	// re-show, in case it was valid before
						clearDiscountCookie();
					} else  {
						$('#codeform').hide();
						$("#message").html("<p class='rightclass'>You have a valid Discount code</p>").show();
						bDCcorrect = true;
						var scheme = response;
						sDCproduct = scheme.substring(0,scheme.indexOf(','));
						var rate = scheme.substring(scheme.indexOf(',')+1);
						nDCratenum = parseFloat(rate);
						sDCratetype = "pounds";
						if (rate.indexOf("percent") != -1) {
							sDCratetype = "percent";
						}
						doShipping(); 	//recalc and display with discount
						setDiscountCookie();	// shows user has entered correct code
					}
				}
			});
	
			return false;
		});
		
	}	// end of 'if cartpage...'
});

// not finished yet
function getDiscountCookie () {
   	 var cookieLine;
	 cookieLine = $.cookie('Discount');  
	 //alert("getDiscountCookie: " + cookieLine);
     if (cookieLine) {
		// parse cookie
		// format is productcode|rate|ratetype 
		// eg pi_royal|25|percent
		var cookiearray = cookieLine.split("|");   
		sDCproduct = cookiearray[0];
		nDCratenum = parseFloat(cookiearray[1]);
		nDCratenum = isNaN(nDCratenum) ? 0.0 : nDCratenum; 
		sDCratetype = cookiearray[2];
		//alert("getDiscountCookie: " + sDCproduct);
		return true;
	 } else {
		return false;
	 }
}

function setDiscountCookie (){
	// expires at end of session
	var cookieLine;
	cookieLine = sDCproduct + "|" + nDCratenum + "|" + sDCratetype;
	$.cookie('Discount', cookieLine);
}

function clearDiscountCookie() {
	$.cookie('Discount', null);	
}
// ************ end of Promo code ******************************


