// lgjs.js  last changed 27 Oct 07
// lghsbcjs.js  26 Oct 07 insert code for Shift+Checkout sends to lgcheckhsbc.htm (for postage and hsbc testing)
//  9 Oct 09 	lgcoal01js.js	for coal and Logs trial (replace patio tabs with coallogs tabs)

if (document.images){  
	//precache images
	var offImgArray = new Array();
	offImgArray["button1"] = new Image (94,40);
	offImgArray["button2"] = new Image (104,40);
	offImgArray["button3"] = new Image (119,40);
	offImgArray["button4"] = new Image (145,40);
	offImgArray["button5"] = new Image (155,40);
	offImgArray["button6"] = new Image (74,40);
	offImgArray["button7"] = new Image (200,40);
	offImgArray["button8"] = new Image (135,40);
	offImgArray["button1"].src = "img/tab/tab_home1.gif";
	offImgArray["button2"].src = "img/tab/tab_beer1.gif";
	offImgArray["button3"].src = "img/tab/tab_calor1.gif";
	offImgArray["button4"].src = "img/tab/tab_coallogs1.gif";
	offImgArray["button5"].src = "img/tab/tab_mobile1.gif";  
	offImgArray["button6"].src = "img/tab/tab_bbq1.gif";
	offImgArray["button7"].src = "img/tab/tab_ppack1.gif";
	offImgArray["button8"].src = "img/tab/tab_helium1.gif";

	var overImgArray = new Array();
	overImgArray["button1"] = new Image (94,40);
	overImgArray["button2"] = new Image (104,40);
	overImgArray["button3"] = new Image (119,40);
	overImgArray["button4"] = new Image (145,40);
	overImgArray["button5"] = new Image (155,40);
	overImgArray["button6"] = new Image (74,40);
	overImgArray["button7"] = new Image (200,40);
	overImgArray["button8"] = new Image (135,40);
	overImgArray["button1"].src = "img/tab/tab_home2.gif";
	overImgArray["button2"].src = "img/tab/tab_beer2.gif";
	overImgArray["button3"].src = "img/tab/tab_calor2.gif";
	overImgArray["button4"].src = "img/tab/tab_coallogs2.gif";
	overImgArray["button5"].src = "img/tab/tab_mobile2.gif";
	overImgArray["button6"].src = "img/tab/tab_bbq2.gif";
	overImgArray["button7"].src = "img/tab/tab_ppack2.gif";
	overImgArray["button8"].src = "img/tab/tab_helium2.gif";
	
	var downImgArray = new Array();
	downImgArray["button1"] = new Image (94,40);
	downImgArray["button2"] = new Image (104,40);
	downImgArray["button3"] = new Image (119,40);
	downImgArray["button4"] = new Image (145,40);
	downImgArray["button5"] = new Image (155,40);
	downImgArray["button6"] = new Image (74,40);
	downImgArray["button7"] = new Image (200,40);
	downImgArray["button8"] = new Image (135,40);
	downImgArray["button1"].src = "img/tab/tab_home3.gif";
	downImgArray["button2"].src = "img/tab/tab_beer3.gif";
	downImgArray["button3"].src = "img/tab/tab_calor3.gif";
	downImgArray["button4"].src = "img/tab/tab_coallogs3.gif";
	downImgArray["button5"].src = "img/tab/tab_mobile3.gif";
	downImgArray["button6"].src = "img/tab/tab_bbq3.gif";
	downImgArray["button7"].src = "img/tab/tab_ppack3.gif";
	downImgArray["button8"].src = "img/tab/tab_helium3.gif";
}

/* functions for Tab buttons */
function mOver (imgName) {   // highlight tab when mouse over (current tab is not active), and hide Focus for later
	document.images[imgName].src = overImgArray[imgName].src;
	document.images[imgName].parentNode.hideFocus = true;
	return true;
}
	
function mOut (imgName) {    // normal when mouse out,
	document.images[imgName].src = offImgArray[imgName].src;
	return true;
}

function mDown (imgName) {   // highlight tab and bring to front - then page changes
	document.images[imgName].src = downImgArray[imgName].src;
	window.document.getElementById(imgName+"div").style.zIndex = "31";
	return true;
}

function emailOver (imgName) {   
	document.images[imgName].src = "img/emailup.gif";
	document.images[imgName].parentNode.hideFocus = true;
	return true;
}
	
function emailOut (imgName) {    // normal when mouse out,
	document.images[imgName].src = "img/emaildown.gif";
	return true;
}

var bBasketShut = true;    // shopping list starts in shut mode (used in Green Arrow functions also)

/* functions for Add and Remove buttons on product pages */
var overAdd = new Image (32,17);
var offAdd = new Image (32,17);
overAdd.src = "img/btn/btnaddover.gif";
offAdd.src = "img/btn/btnadd.gif";

function addOver (imgRef) {   // highlight Add button when mouse over
	imgRef.src  = overAdd.src;
	return true;
}
	
function addOut (imgRef) {    // revert Add button when mouse out
	imgRef.src = offAdd.src;
	return true;
}

var overRemove = new Image (57,17);
var offRemove = new Image (57,17);
overRemove.src = "img/btn/btnremoveover.gif";
offRemove.src = "img/btn/btnremove.gif";

function removeOver (imgRef) {  
	imgRef.src  = overRemove.src;
	return true;
}
	
function removeOut (imgRef) { 
	imgRef.src = offRemove.src;
	return true;
}

/* functions for GreenArrow buttons on product pages */
var overLeftArrowGreen = new Image (10,30);
var offLeftArrowGreen = new Image (10,30);
var overRightArrowGreen = new Image (10,30);
var offRightArrowGreen = new Image (10,30);
overLeftArrowGreen.src = "img/btn/ltarrowgreenover.gif";
offLeftArrowGreen.src = "img/btn/ltarrowgreen.gif";
overRightArrowGreen.src = "img/btn/rtarrowgreenover.gif";
offRightArrowGreen.src = "img/btn/rtarrowgreen.gif";

function greenArrowOver (imgRef) {   // highlight Green arrow when mouse over
	if (bBasketShut) {               //if shut then left
		imgRef.src  = overLeftArrowGreen.src;
	} else {
		imgRef.src  = overRightArrowGreen.src;
	}
	return true;
}
	
function greenArrowOut (imgRef) {            // revertGreen arrow when mouse out
	if (bBasketShut) {                      //is this left or right arrow ?
		imgRef.src  = offLeftArrowGreen.src;
	} else {
		imgRef.src  = offRightArrowGreen.src;
	}
	return true;
}

/* functions for Checkout buttons on product pages */
var overCheckout = new Image (73,17);
var offCheckout = new Image (73,17);
overCheckout.src = "img/btn/btncheckoutover.gif";
offCheckout.src = "img/btn/btncheckout.gif";

function checkoutOver (imgRef) {   // highlight Checkout button when mouse over
	imgRef.src  = overCheckout.src;
	return true;
}
	
function checkoutOut (imgRef) {    // revert Checkout button when mouse out
	imgRef.src = offCheckout.src;
	return true;
}
 
function checkoutClick (evt) {
// submit to normal checkout (Checkout Button) or Trial HSBC checkout (Shift and Checkout button)
	evt = (evt) ? evt : ((window.event) ? window.event: null);
	if (evt) {
		var elem = (evt.target) ? evt.target : evt.srcElement;
		if (evt.shiftKey) {
			//alert("Checkout + Shift");
			location.href = "lgcheckhsbc.htm";  // hsbc trial
		}
		else {
			//alert("Checkout with no shift");
			location.href = "lgcheckout.htm"; // normal 
		}
	}
	return true;
}


function myTest() {
	//alert("myTest in lgjs.js");
}


// used for Change Quantity, so that Return acts like Tab (though it doesn't advance to next field)
function checkReturn(thisfield, myevt) {
var charCode = (myevt.charCode) ? myevt.charCode : ((myevt.which) ? myevt.which : myevt.keyCode);
var bResult = true;
	if (charCode == 13) {
		// alert("checkReturn : " + thisfield.type);  
		thisfield.blur();  // to trigger onchange().  27oct07 - this gives an unspecified error in IE, but seems to work.  OK in FF. Why ?
		bResult = false;
	}
	return bResult;
}

// ******************** Functions to slide Shopping List open and shut - Conor  May 07 

var slideIntervalId = null;

function getSubtotalRowNumber() {
		var i, nRows, nSubtotalRow;
		var cartTable = window.document.getElementById("shopListTable");
		nRows = cartTable.rows.length;
		i = nRows -1;
		nSubtotalRow = 0;
		while ((i > 0) && (nSubtotalRow == 0)) {
			if (cartTable.rows[i].cells.length > 1) {
				if (cartTable.rows[i].cells[1].id == "shopcellsubtotal") { // is this subtotal row
					nSubtotalRow = i;
				}
			}
			i--;
		}
		return nSubtotalRow
}

//---------------------------------------------------------------------||
// FUNCTION:    deleteShopListRows 
// PARAMETERS:  itemnumber to be removed, number of items (before removal)
// RETURNS:     nothing 
// PURPOSE:     removes both the rows of this item 
//   but have to do it by cell id, or else get muddled, slower but necessary. And can't change cell id's unfortunately
//   first, move contents of later cells 'back' one, have to keep cell numbers sync'd with ItemNo,
//   Basket will always be open, ie Change and Remove buttons on view
//         have to reset Change button (newqty, but old ordernum )
//         leave Remove button untouched (it contains correct OrderNumber),
//   Then recalc subtotal  (and if on checkout page, postage and total)
//---------------------------------------------------------------------||
function deleteShopListRows ( itemNo, numberOfItems ) {
	var i, j, cellId, nextCellId;
	var cartTable, myCell, nSubtotalRow;
	var totalPrice, linePrice, sChange;
	
	// move content of later items (if any) back one
	for (i = itemNo; i < numberOfItems; i++) {
		cellId = "shopcell" + i;
		nextCellId = "shopcell" + (i+1);
		for (j = 0; j < 4; j++) {    // name, line2, qty and price cells
			if (myCell = window.document.getElementById(cellId + j)) {
				myCell.innerHTML = window.document.getElementById(nextCellId + j).innerHTML;
			}
		}
		if (myCell = window.document.getElementById(cellId + "4")) {   // change qty cell				
				sChange = " <input type='text' class='shopnewqty' size='2' maxlength='3' value='";
				sChange += window.document.getElementById(cellId + "2").innerHTML + "' onkeypress='checkReturn(this, event)'";
				sChange += " onChange = 'ChangeQuantity(" + i + ", this.value, this)'/>";
				myCell.innerHTML = sChange;
		}
	}

	// now delete last two item rows (leave Subtotal rows/ Checkout / Postage rows intact)
	cartTable = window.document.getElementById("shopListTable");
	// find subtotal row
	nSubtotalRow = getSubtotalRowNumber();
	cartTable.deleteRow(nSubtotalRow - 1);
	cartTable.deleteRow(nSubtotalRow - 2);
	
    // recalc subtotal price. the IDs of the price cells are shopcell13, shopcell23 ...shopcell123 
   var totalPrice = 0;
   for (var i = 1; i < numberOfItems ; i++ ) {
	   if (window.document.getElementById("shopcell"+i+"3")) {
		   linePrice = parseFloat(window.document.getElementById("shopcell"+i+"3").innerHTML); 
		   if (!isNaN(linePrice)) {
			   totalPrice += linePrice;
		   }
	   }
   }
   window.document.getElementById("shopcellsubtotal").innerHTML = totalPrice.toFixed(2);
   
   if (window.document.getElementById("shopcellpostage")) {  // if postage row exists
   		calcPostageAndTotal(totalPrice, true);  // and display  (nb this func is in lgcheckout...js)
   }
	   
}



//---------------------------------------------------------------------||
// FUNCTION:    addShopListColumns
// PARAMETERS:  none 
// RETURNS:     nothing
// PURPOSE:     Adds  extra columns, after shopping basket slides out 
//              to allow Change qty and Remove line  
//---------------------------------------------------------------------||
function addShopListColumns() {
  		var myRow, newCell, sChange, sRemove, orderNum, myQty, numRows;
	  	var bTotals = false;   // is this a Totals row (subtotal, checkout, postage, total ) ?
		var cartTable = window.document.getElementById("shopListTable");
		
		numRows = cartTable.rows.length;
		var i =0;
		if (numRows > 1) {    // only insert new cols if shop instructions not there 
			while ( i < numRows ) {
				myRow = cartTable.rows[i];
				if (myRow.cells.length > 1) {
					bTotals = (bTotals || (myRow.cells[1].id == "shopcellsubtotal")); // is this subtotal row, or after?
				}
				if (i==0)  {                        // for header , add Change Qty and filler
					newCell = myRow.insertCell(-1);                 
					newCell.className = "shoppingcellcentered";
					newCell.innerHTML = " Change Qty ?";
					newCell.width = 100;
					newCell = myRow.insertCell(-1);
					newCell.className = "shoppingcell";
					newCell.innerHTML = "&nbsp;";
					newCell.width = 80;
					i = i + 1;
				} else if (bTotals) {  // for subtotal row and after (subtotal, checkout, postage etc)                     
					newCell = myRow.insertCell(-1);
					newCell.colSpan = 2;                 // just add filler, but no underline
					newCell.className = "shoppingname";
					newCell.innerHTML = "&nbsp;";
					newCell.width = 180;
					i = i + 1;
				} else {  							// ie product name rows, add changeQty & Removebutton (rowspan=2)
					myQty = cartTable.rows[i+1].cells[1].innerHTML;  // get it from second cell in the next row
					orderNum = Math.round((i+1) / 2);  // assumes we will be on rows 1,3,5 etc (starting from 0)
					newCell = myRow.insertCell(-1);
					newCell.id = "shopcell"+ orderNum + "4";       // needed when removing rows
					newCell.className = "shoppingcellcentered";
					newCell.rowSpan = 2;
					sChange = " <input type='text' class='shopnewqty' size='2' maxlength='3' value='";
					sChange += myQty + "' onkeypress='checkReturn(this, event)' onChange = 'ChangeQuantity(";
					sChange += orderNum + ", this.value, this)'/>";
					newCell.innerHTML = sChange;
					newCell.width = 100;
					newCell = myRow.insertCell(-1);
					newCell.className = "shoppingcell";
					newCell.rowSpan = 2;
					sRemove = "<img src='img/btn/btnremove.gif' width='57' height='17' border='0' onClick='RemoveFromCart(";
					sRemove += orderNum + ")'  onmouseover='removeOver(this)' onmouseout='removeOut(this)' />";																	
					newCell.innerHTML = sRemove;
					newCell.width = 80;
					i = i + 2;
				} 
			}
			cartTable.width = 350;
		}
}




function slideLeft() {
   var col5 = document.getElementById("col5div");
   var leftpos = parseInt(col5.style.left);
   var newwidth = parseInt(col5.style.width);
   leftpos -= 10;
   newwidth += 10;
   col5.style.left = leftpos + "px";
   col5.style.width = newwidth + "px";
   if (leftpos <  576) {
   	  col5.style.left = 576 + "px";
	  col5.style.width = 359 + "px";  // 172 + 15 + 172
      clearInterval(slideIntervalId);
	  slideIntervalId = null;
	  bBasketShut = false;
	  addShopListColumns();
   }
}

function removeShopListColumns() {  // remove 'Change Qty' and 'Remove ?' columns but be careful with titles and total etc
  		var myRow, newCell;
		var bTotals = false;  // subtotal row or below ?
	  	var cartTable = window.document.getElementById("shopListTable");
		
		if (cartTable.rows[0].cells[0].id != "shopinstructions") {  // if instr, do nothing
			for (var i = 0; i < cartTable.rows.length; i++) {
				myRow = cartTable.rows[i];
				if (myRow.cells.length > 1) {
					bTotals = (bTotals || (myRow.cells[1].id == "shopcellsubtotal")); // is this subtotal row, or after?
				}
				if (i == 0) {  				 				// header 
					myRow.deleteCell(4);                     // delete Change Qty and Remove hdr cells
					myRow.deleteCell(3);
				} else if (bTotals) {                        // subtotal or later
					myRow.deleteCell(myRow.cells.length-1);  // just remove last cell (filler)
				} else if (i % 2 != 0) {                     // on odd rows only, because these cells are rowspan=2
					myRow.deleteCell(2);                     // delete change and remove cells
					myRow.deleteCell(1);
				} 
			}
		}
		cartTable.width = 170;
}

function slideRight() {
   var col5 = document.getElementById("col5div");
   var leftpos = parseInt(col5.style.left);
   var newwidth = parseInt(col5.style.width);
   leftpos += 10;
   newwidth -= 10;
   col5.style.left = leftpos + "px";
   col5.style.width = newwidth + "px";
   if (leftpos > 763) {
   	  col5.style.left = 763 + "px";
	  col5.style.width = 172 + "px"; 
      clearInterval(slideIntervalId);
	  slideIntervalId = null;
	  bBasketShut = true;
   }
}
   
function openBasket () {   // slide open expanded basket (col 5), or if already open, shut it. Ensure slide completes.
	if (bBasketShut) {
		if (slideIntervalId == null) {
			document.getElementById("col5div").style.left = 763+"px"; // note MUST set it first time, or else undefined !
			document.getElementById("col5div").style.width = 172 + "px";  // same with width
			slideIntervalId = setInterval("slideLeft()", 10);
			document.images["shoparrow"].src = overRightArrowGreen.src;
		}
	} else {
		if (slideIntervalId == null) {
			slideIntervalId = setInterval("slideRight()", 10);  // assumes style.left and width set from opening it 	
			removeShopListColumns();
			document.images["shoparrow"].src = overLeftArrowGreen.src;
		}
	}
}

// ********************* end of Slide shop cart functions * **************************** 

//=====================================================================||
//               NOP Design JavaScript Shopping Cart                   ||
//                                                                     ||
// For more information on SmartSystems, or how NOPDesign can help you ||
// Please visit us on the WWW at http://www.nopdesign.com              ||
//                                                                     ||
// Javascript portions of this shopping cart software are available as ||
// freeware from NOP Design.  You must keep this comment unchanged in  ||
// your code.  For more information contact FreeCart@NopDesign.com.    ||
//                                                                     ||
// JavaScript Shop Module, V.4.4.0                                     ||
//=====================================================================||
//
// 21 May 06  Conor Maxwell  nopcart3.js  new functions added for Planet Balloon :
//                                         cookies for addresses and comment
// 05 Jun 06  Conor Maxwell  nopcart4.js  add shipping row, for postage etc
// 
// 14 May 07  Conor Maxwell  lgnopcart6x.js  for londongases project
//         									 longer cookies, displayCartLine etc
// 17 May 07  Conor Maxwell  lgcartjs_01x.js 





//Options for Everyone:
MonetarySymbol        = '£';
DisplayNotice         = false;   // v6 true for testing only
DisplayShippingColumn = false;
DisplayShippingRow    = true;   // v4
DisplayTaxRow         = false;
TaxRate               = 0.00;
TaxByRegion           = false;
TaxPrompt             = 'For tax purposes, please select if you are an Arizona resident before continuing';
TaxablePrompt         = 'Arizona Residents';
NonTaxablePrompt      = 'Other States';
MinimumOrder          = 0.00;
MinimumOrderPrompt    = 'Your order is below our minimum order, please order more before checking out.';



// Order Cookies expiry time (nopcart)
exp = new Date();
exp.setTime(exp.getTime() + (1*24*60*60*1000));  // (24 hrs)

//=====================================================================||
//---------------------------------------------------------------------||
//    YOU DO NOT NEED TO MAKE ANY MODIFICATIONS BELOW THIS LINE        ||
//---------------------------------------------------------------------||
//=====================================================================||

   strSorry  = "I'm Sorry, your basket is full, please proceed to checkout.";
   strAdded  = " added to your shopping basket.";
   strRemove = "Click 'Ok' to remove this product from your shopping basket.";
   strILabel = "ref";
   strDLabel = "Item";
   strQLabel = "Quantity";
   strPLabel = "Price";
   strSLabel = "Postage";
   strRLabel = " ";
   strRButton= "Remove";
   strSUB    = "Subtotal:";
   strSHIP   = "Postage:";
   strTAX    = "TAX";
   strTOT    = "Total:";
   strErrQty = "Invalid Quantity.";
   strNewQty = 'Please enter new quantity:';
   bLanguageDefined = true;



//---------------------------------------------------------------------||
// FUNCTION:    createShopList                                         ||
// PARAMETERS:  bProductPage   (true for normal page - add Checkout row and button,
//                              false on Checkout page, add postage and Total)   
// RETURNS:     nothing                                                ||
// PURPOSE:     Removes shopping instructions from Shopping List       ||
//              create Header and Subtotal rows only                      ||
//              but only do it if shop instructions are really on display,
//              cos can come here with an empty list (header and total already there) - after 'Item Removes'
//---------------------------------------------------------------------||
function createShopList(bProductPage) {
	  	var cartTable = window.document.getElementById("shopListTable");
		if (cartTable.rows[0].cells[0].id == "shopinstructions") {
			cartTable.deleteRow(0);  // remove shopping instructions
			
			var newRow = cartTable.insertRow(-1);
			var newCell = newRow.insertCell(0);  // add col hdrs
			newCell.className = "shoppingcell";
			newCell.innerHTML = "Name";
			newCell = newRow.insertCell(1);
			newCell.className = "shoppingcell";
			newCell.innerHTML = "Qty";
			newCell = newRow.insertCell(2);
			newCell.className = "shoppingcell";
			newCell.innerHTML = "&pound;";
			newCell.width = 40;
			
			newRow = cartTable.insertRow(-1);   // add Subtotal row
			newCell = newRow.insertCell(0);  
			newCell.className = "shoppingtotal";
			newCell.colSpan = 2;
			newCell.innerHTML = "Subtotal (excl p&amp;p)";
			newCell = newRow.insertCell(1);
			newCell.id = "shopcellsubtotal";
			newCell.className = "shoppingcell";
			newCell.innerHTML = "&nbsp;";
			
			if (bProductPage) {
				newRow = cartTable.insertRow(-1);   // add Checkout button row
				newCell = newRow.insertCell(0);  
				newCell.colSpan = 3;
				newCell.innerHTML = "<img id='checkout' src='img/btncheckout.gif' width='73' height='17' border = '0' onClick='checkoutClick(event)' onmouseover='checkoutOver(this)' onMouseout='checkoutOut(this)' align='left'/>";
			} 
			
			// ****  for now (24 may 07) comment out creation of Postage and Total row (cos logic not decided)
			else {
				newRow = cartTable.insertRow(-1);   // add Postage/Shipping row
				newCell = newRow.insertCell(0);  
				newCell.id = "shopcellpostagedesc";
				newCell.className = "shoppingtotal";
				newCell.colSpan = 2;
				newCell.innerHTML = "Postage";
				newCell = newRow.insertCell(1);
				newCell.id = "shopcellpostage";
				newCell.className = "shoppingcell";
				newCell.innerHTML = "&nbsp;";
				
				newRow = cartTable.insertRow(-1);   // add Total row
				newCell = newRow.insertCell(0);  
				newCell.className = "shoppingtotal";
				newCell.colSpan = 2;
				newCell.innerHTML = "TOTAL";
				newCell = newRow.insertCell(1);
				newCell.id = "shopcelltotal";
				newCell.className = "shoppingcell";
				newCell.innerHTML = "&nbsp;";
			}  //**** */
				
		}
}



//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {
   var strNewQuantity = "";
   var ch;
   for ( var i = 0; i < checkString.length; i++ ) {
      ch = checkString.substring(i, i+1);
      if (ch >= "0" && ch <= "9")
         strNewQuantity += ch;
   }
   if ( strNewQuantity.length < 1 )
      strNewQuantity = "1";
   return(strNewQuantity);
}


//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {
   var iNumberOrdered = 0;
   var bAlreadyInCart = false;
   var notice = "";
   
   // parse info from form, esp radiobuttons  (new v6 jcm 11may07)
   var buttonGroup;  // either packsize (latex) or colours(megaloons)
   var buttonNumber = 0;
   var extraDesc = " ";
   var extraCode = "";
  
  // any radio button options in this form? if so set appropriate fields (shop cart desc, and productcode addition)
  if (thisForm.packsize) {       // if packsize (latex balloons etc) set unit size,price,product-code from selected radio button
  	   buttonGroup = thisForm.packsize;
	   while (!buttonGroup[buttonNumber].checked  && buttonNumber < buttonGroup.length) {
			buttonNumber++;
		}
		thisForm.PRICE.value = buttonGroup[buttonNumber].value;
		switch (buttonNumber) {
			case 0 : extraDesc = " (pk30)"; extraCode = "30"; break;
			case 1 : extraDesc = " (pk50)"; extraCode = "50"; break;
			case 2 : extraDesc = " (pk100)"; extraCode = "100"; break;
			default :  extraDesc = " "; extraCode = "";
		} 
   } else if (thisForm.colours) {       // if 'colours' (megaloons)  then set colour, product code from selected radio button
  	   buttonGroup = thisForm.colours;
	   while (!buttonGroup[buttonNumber].checked  && buttonNumber < buttonGroup.length) {
			buttonNumber++;
		}
		thisForm.PRICE.value = buttonGroup[buttonNumber].value;
		switch (buttonNumber) {
			case 0 : extraDesc = " - red"; extraCode = "R"; break;
			case 1 : extraDesc = " - silver"; extraCode = "S"; break;
			case 2 : extraDesc = " - gold"; extraCode = "GO"; break;
			default :  extraDesc = " "; extraCode = "";
		} 
   } else if (thisForm.calor) {       // if 'calor' then set refill type, price and product code
  	   buttonGroup = thisForm.calor;
	   while (!buttonGroup[buttonNumber].checked  && buttonNumber < buttonGroup.length) {
			buttonNumber++;
		}
		thisForm.PRICE.value = buttonGroup[buttonNumber].value;
		switch (buttonNumber) {
			case 0 : extraDesc = "- refill"; extraCode = "R"; break;
			case 1 : extraDesc = "- new   "; extraCode = "N"; break;
			default :  extraDesc = " "; extraCode = "";
		} 
   }

   // put info into cookies for shopping cart
   
   iNumberOrdered = GetCookie("NumberOrdered");
  
   if ( iNumberOrdered == null )
      iNumberOrdered = 0;

   if ( thisForm.PRODCODE == null )
      strPRODCODE    = "";
   else
      strPRODCODE    = thisForm.PRODCODE.value + extraCode;    // eg LPL-R30

   if ( thisForm.QUANTITY == null )
      strQUANTITY  = "1";
   else
      strQUANTITY  = thisForm.QUANTITY.value;

   if ( thisForm.PRICE == null )
      strPRICE     = "0.00";
   else
      strPRICE     = thisForm.PRICE.value;

   if ( thisForm.NAME == null )
      strNAME      = "";
   else
      strNAME      = thisForm.NAME.value;
	  
   if ( thisForm.SHIPPING == null )
      strSHIPPING  = "0.00";
   else
      strSHIPPING  = thisForm.SHIPPING.value;

   if ( thisForm.ADDITIONALINFO == null ) {
      strADDTLINFO = "";
   } else {
      strADDTLINFO = thisForm.ADDITIONALINFO[thisForm.ADDITIONALINFO.selectedIndex].value;
   }
   if ( thisForm.ADDITIONALINFO2 != null ) {
      strADDTLINFO += "; " + thisForm.ADDITIONALINFO2[thisForm.ADDITIONALINFO2.selectedIndex].value;
   }
   if ( thisForm.ADDITIONALINFO3 != null ) {
      strADDTLINFO += "; " + thisForm.ADDITIONALINFO3[thisForm.ADDITIONALINFO3.selectedIndex].value;
   }
   if ( thisForm.ADDITIONALINFO4 != null ) {
      strADDTLINFO += "; " + thisForm.ADDITIONALINFO4[thisForm.ADDITIONALINFO4.selectedIndex].value;
   }

   // NOTE 24May07  we pass LINE3 text to shopcart (not LINE2, which is only used in main product cells)
   if ( thisForm.LINE2 == null )                 // v6  
      strLINE2      = "";
   else
      strLINE2      = thisForm.LINE3.value + extraDesc;  
	  
   if ( thisForm.VATRATE == null )                 // v6  
      strVATRATE      = "";
   else
      strVATRATE      = thisForm.VATRATE.value;
	  
   if ( thisForm.SPECIAL == null )                 // v6  =Y for specials which can't be handled by HSBC
      strSPECIAL      = "";
   else
      strSPECIAL      = thisForm.SPECIAL.value;
	
   // if first item, remove shopping instructions, create list inc CheckoutRow
   if (iNumberOrdered == 0) {
	   createShopList(true);
   }

   //Is this product already in the cart?  If so, increment quantity instead of adding another.
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
	  Token5 = database.indexOf("|", Token4+1);
	  Token6 = database.indexOf("|", Token5+1);
	  Token7 = database.indexOf("|", Token6+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );                 // prodcode
      fields[1] = database.substring( Token0+1, Token1 );          // qty
      fields[2] = database.substring( Token1+1, Token2 );          // unit price
      fields[3] = database.substring( Token2+1, Token3 );          // Line1, name
      fields[4] = database.substring( Token3+1, Token4 );          // shipping, postage cost
	  fields[5] = database.substring( Token4+1, Token5 );          // addtnl info, not used
	  fields[6] = database.substring( Token5+1, Token6 );          // Line2
	  fields[7] = database.substring( Token6+1, Token7 );          // VATrate
      fields[8] = database.substring( Token7+1, database.length ); // Special item ? if so can't use HSBC

      if ( fields[0] == strPRODCODE &&
           fields[2] == strPRICE  &&
           fields[3] == strNAME   &&
		   fields[6] == strLINE2
         ) {
         bAlreadyInCart = true;
         dbUpdatedOrder = strPRODCODE    + "|" +
                          (parseInt(strQUANTITY)+parseInt(fields[1]))  + "|" +
                          strPRICE     + "|" +
                          strNAME      + "|" +
                          strSHIPPING  + "|" +
						  strADDTLINFO + "|" +
						  strLINE2     + "|" +
						  strVATRATE   + "|" +
                          strSPECIAL;
         strNewOrder = "Order." + i;
         DeleteCookie(strNewOrder, "/");
         SetCookie(strNewOrder, dbUpdatedOrder, exp, "/");
         notice = strQUANTITY + " " + strNAME + strAdded;
		 displayCartLine(i, strNAME, strLINE2, parseInt(strQUANTITY)+parseInt(fields[1]), strPRICE);   // v6
         break;
      }
   }

   if ( !bAlreadyInCart ) {
      iNumberOrdered++;
    
	  if ( iNumberOrdered > 12 )
         alert( strSorry );
      else {
         dbUpdatedOrder = strPRODCODE    + "|" + 
                          strQUANTITY  + "|" +
                          strPRICE     + "|" +
                          strNAME      + "|" +
                          strSHIPPING  + "|" +
                          strADDTLINFO + "|" +
						  strLINE2     + "|" +
						  strVATRATE   + "|" +
                          strSPECIAL;

         strNewOrder = "Order." + iNumberOrdered;
         SetCookie(strNewOrder, dbUpdatedOrder, exp, "/");
         SetCookie("NumberOrdered", iNumberOrdered, null, "/");
         notice = strQUANTITY + " " + strNAME + strAdded;
		 displayCartLine(iNumberOrdered, strNAME, strLINE2, strQUANTITY, strPRICE);   // v6
      }
   }
   
   if ( DisplayNotice )
      alert(notice);
}


//---------------------------------------------------------------------||
// FUNCTION:    displayCartLine                                        ||
// PARAMETERS:  Item number (1..12), Name, Line2, Qty, Price           ||
// RETURNS:     nothing                                                ||
// PURPOSE:     Display the new item in the shopping list
//              create table row if necessary
//              this is a new function for LondonGases jcm 11may 07    ||
//              see end of func for overloaded 6th param  (27oct07)  ||
//---------------------------------------------------------------------||
function displayCartLine (iNum, prodName, prodLine2, prodQty, prodPrice ) {
   var i, nSubtotalRow, nRows, numCells, linePrice, changeQtyText, removeText;
   var cellId = "shopcell" + iNum;
   var cell = window.document.getElementById(cellId+"0");
   if (cell) {
	    cell.innerHTML = prodName;
   		window.document.getElementById(cellId +"1").innerHTML = prodLine2;
		window.document.getElementById(cellId +"2").innerHTML = prodQty;
		if (isNaN(prodPrice)) {
			window.document.getElementById(cellId +"3").innerHTML = prodPrice;
		} else {
			linePrice =  parseInt(prodQty) * parseFloat(prodPrice);
			window.document.getElementById(cellId +"3").innerHTML = linePrice.toFixed(2);
		}
		if (cell = window.document.getElementById(cellId +"4")) {  // if chg qty cell exists,then update it too
			changeQtyText = " <input type='text' class='shopnewqty' size='2' maxlength='3' value='";
       		changeQtyText += prodQty + "' onkeypress='checkReturn(this, event)' onChange = 'ChangeQuantity(";
	   		changeQtyText += iNum + ", this.value, this)'/>";
			cell.innerHTML = changeQtyText;
		}
   } else {   // have to insert new row, at end
   	    var cartTable = window.document.getElementById("shopListTable");
		if (cartTable) {
			nRows = cartTable.rows.length;                          // inc Header, Subtotal and Checkout etc
			var bBasketOpen = cartTable.rows[0].cells.length > 3;  // is basket slid open? Header row has 4 cells, if it is.
			nSubtotalRow = getSubtotalRowNumber();
						
			var nameRow = cartTable.insertRow(nSubtotalRow);     // before subtotal row
			var newCell = nameRow.insertCell(0);
			newCell.id = cellId + "0";
			newCell.className = "shoppingname";
			newCell.colSpan = 3;
			newCell.innerHTML = prodName;
			
			nSubtotalRow++;
			var newRow = cartTable.insertRow(nSubtotalRow);   // before subtotal again, add 2nd row : Line2, qty, price
			for (i = 0; i < 3; i++) {
				newCell = newRow.insertCell(i);
				newCell.id = cellId + (i+1);
				newCell.className = "shoppingcell";
				switch (i) {
				case 0 : newCell.innerHTML = prodLine2; break;
				case 1 : newCell.innerHTML = prodQty; break;
				case 2 : if (isNaN(prodPrice)) {
							newCell.innerHTML = prodPrice;
						 } else {
							linePrice =  parseInt(prodQty) * parseFloat(prodPrice);
					    	newCell.innerHTML = linePrice.toFixed(2);
						 }
						 break;
				}
			}
			if (bBasketOpen) {
				newCell = nameRow.insertCell(1);
				newCell.id = cellId + "4";       // needed when removing rows
				newCell.className = "shoppingcellcentered";
				newCell.rowSpan = 2;
				changeQtyText = " <input type='text' class='shopnewqty' size='2' maxlength='3' value='";
       			changeQtyText += prodQty + "' onkeypress='checkReturn(this, event)'  onChange = 'ChangeQuantity(";
	   			changeQtyText += iNum + ", this.value, this)'/>";
				newCell.innerHTML = changeQtyText;
				newCell.width = 100;
				newCell = nameRow.insertCell(2);
				newCell.className = "shoppingcell";
				newCell.rowSpan = 2;
				removeText = "<img src='img/btn/btnremove.gif' width='57' height='17' border='0' onClick='RemoveFromCart(";
				removeText += iNum + ")'  onmouseover='removeOver(this)' onmouseout='removeOut(this)' />";	
				newCell.innerHTML = removeText;
				newCell.width = 80;
			}
		}
   }	
   
   // extend col5div if shopping list too long  (and extend outerdiv also if needed)
	var nTableHeight = window.document.getElementById("shopListTable").offsetHeight + 36; // 36 for header
	var nDiv5Height = window.document.getElementById("col5div").offsetHeight;
	if (nTableHeight > nDiv5Height) {
		window.document.getElementById("col5div").style.height = nTableHeight +"px";
	}
	var nOuterDivHeight = window.document.getElementById("outerdiv").offsetHeight;
	nTableHeight += 161 + 15;                       // 161 for ht above div5, 15 for bottom border
	if (nTableHeight > nOuterDivHeight) {
		window.document.getElementById("outerdiv").style.height = nTableHeight +"px";
	} 
   
   // recalc subtotal. the IDs of the price cells are cell13, cell23 ...cell123 
   var subtotalPrice = 0;
   for (i = 1; i <= 12 ; i++ ) {     // how to stop search at end, quickly ?
	   if (window.document.getElementById("shopcell"+i+"3")) {
		   linePrice = parseFloat(window.document.getElementById("shopcell"+i+"3").innerHTML); 
		   if (!isNaN(linePrice)) {
			   subtotalPrice += linePrice;
		   }
	   }
   }
   window.document.getElementById("shopcellsubtotal").innerHTML = subtotalPrice.toFixed(2);	
   
   // 27oct07 new bit ref overloaded param bCalcPostage (to disallow calcs on each row from displayCart2) 
   var bCalculatePostage = true;  // default
   if (displayCartLine.arguments.length > 5) {
	   bCalculatePostage = displayCartLine.arguments[5];
   }
   if (window.document.getElementById("shopcellpostage")) {  // if postage row exists
   		if (bCalculatePostage) {                             // AND request not prevented from displayCart2()
			calcPostageAndTotal(subtotalPrice, true);  		// calc and display  (nb this func is in lgcheckout...js)
		}
   }
}



//---------------------------------------------------------------------||
// FUNCTION:    displayCart                                            ||
// PARAMETERS:  none         										   ||
// RETURNS:     nothing                                                ||
// PURPOSE:     Display all items in the shopping list jcm 13 May 07
//              has to read all Order.x cookies
//              typically called on loading new page                   ||
//---------------------------------------------------------------------||
function displayCart () {
	var LineQty;
	var UnitPrice;
	var ProdName;
	var ProdLine2;
	
	var iNumberOrdered = GetCookie("NumberOrdered");
	if ( iNumberOrdered == null )
      iNumberOrdered = 0;
	  
	if (iNumberOrdered > 0) {    // remove shopping instructions, replace with Header and Subtotal rows
	  	createShopList(true);    // with Checkout row
	}
		
	for ( var iNum = 1; iNum <= iNumberOrdered; iNum++ ) {
		  NewOrder = "Order." + iNum;
		  database = "";
		  database = GetCookie(NewOrder);
		  
		  Token0 = database.indexOf("|", 0);
		  Token1 = database.indexOf("|", Token0+1);
		  Token2 = database.indexOf("|", Token1+1);
		  Token3 = database.indexOf("|", Token2+1);
		  Token4 = database.indexOf("|", Token3+1);
		  Token5 = database.indexOf("|", Token4+1);
		  Token6 = database.indexOf("|", Token5+1);
		  Token7 = database.indexOf("|", Token6+1);
		  
		  LineQty = database.substring( Token0+1, Token1 ); 
		  UnitPrice = database.substring( Token1+1, Token2 ); 
		  ProdName = database.substring( Token2+1, Token3 ); 
		  ProdLine2 = database.substring( Token5+1, Token6 ); 
	
		  displayCartLine (iNum, ProdName, ProdLine2, LineQty, UnitPrice );
	}
	  
}


//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
   var base = new Date(0);
   var skew = base.getTime();

   date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;

   while ( i < clen ) {
      var j = i + alen;
      if ( document.cookie.substring(i, j) == arg ) return(getCookieVal (j));
      i = document.cookie.indexOf(" ", i) + 1;
      if ( i == 0 ) break;
   }

   return(null);
}



//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
   document.cookie = name + "=" + escape (value) +
                     ((expires) ? "; expires=" + expires.toGMTString() : "") +
                     ((path) ? "; path=" + path : "") +
                     ((domain) ? "; domain=" + domain : "") +
                     ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ) {
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number (or original string if Not number)    ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
// 09 Jul 07    Conor : insert isNaN check for 'tba' prices of BeerGas
//---------------------------------------------------------------------||
function moneyFormat(input) {
   if (isNaN(input)) {
	   return input;
   } else {
	   var dollars = Math.floor(input);
	   var tmp = new String(input);
	   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
		  if ( tmp.charAt(decimalAt)=="." )
			 break;
	   }
	   var cents  = "" + Math.round(input * 100);
	   cents = cents.substring(cents.length-2, cents.length);
	   dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;
	   if ( cents == "0" )
		  cents = "00";
	   return(dollars + "." + cents);
	}
}

//---------------------------------------------------------------------||
// FUNCTION:    my_parseFloat  
// PARAMETERS:  Number, but could be a string (esp BeerGas price of 'tba')
// RETURNS:     Float Number (or 0 if param was string)
// 09 Jul 07    Conor : insert isNaN check for 'tba' prices of BeerGas
//---------------------------------------------------------------------||
function my_parseFloat(param) {
	if (isNaN(param)) {
		return 0;
	} else {
		return parseFloat(param);
	}
}

//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
   if ( confirm( strRemove ) ) {
      NumberOrdered = GetCookie("NumberOrdered");
      for ( i=RemOrder; i < NumberOrdered; i++ ) {
         NewOrder1 = "Order." + (i+1);
         NewOrder2 = "Order." + (i);
         database = GetCookie(NewOrder1);
         SetCookie (NewOrder2, database, null, "/");
      }
      NewOrder = "Order." + NumberOrdered;
      SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
      DeleteCookie(NewOrder, "/");
	  
      deleteShopListRows(RemOrder, NumberOrdered);   // v6  (it was href.location = href.location)
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    ChangeQuantity                                         ||
// PARAMETERS:  Order Number to Change Quantity                        ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Changes quantity of an item in the shopping cart       ||
//---------------------------------------------------------------------||
function ChangeQuantity(OrderItem, newValue, thisfield) {
	
   	  var NewQuantity = CKquantity(newValue);  // ensure it's integer; if not, set to 1
      thisfield.value = NewQuantity;
	  
	  NewOrder = "Order." + OrderItem;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
	  Token5 = database.indexOf("|", Token4+1);
      Token6 = database.indexOf("|", Token5+1);
      Token7 = database.indexOf("|", Token6+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );
      fields[1] = database.substring( Token0+1, Token1 );
      fields[2] = database.substring( Token1+1, Token2 );
      fields[3] = database.substring( Token2+1, Token3 );
      fields[4] = database.substring( Token3+1, Token4 );
	  fields[5] = database.substring( Token4+1, Token5 );
	  fields[6] = database.substring( Token5+1, Token6 );
	  fields[7] = database.substring( Token6+1, Token7 );
      fields[8] = database.substring( Token7+1, database.length );

      dbUpdatedOrder = fields[0] + "|" +
                       NewQuantity + "|" +
                       fields[2] + "|" +
                       fields[3] + "|" +
                       fields[4] + "|" +
					   fields[5] + "|" +
					   fields[6] + "|" +
					   fields[7] + "|" +
                       fields[8];
      strNewOrder = "Order." + OrderItem;
      DeleteCookie(strNewOrder, "/");
      SetCookie(strNewOrder, dbUpdatedOrder, exp, "/");
      // location.href=location.href;    (old code to redisplay whole page)
	  displayCartLine (OrderItem, fields[3], fields[6], NewQuantity, fields[2] )  // just redisplay affected line. Good !
}

