// lgoCart DOM/AJAX Class © 2007 Gareth watson
//////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////
// Requires :
// lgoAJAXClass.js
// scriptaculous.js
// prototype.js
//
//////////////////////////////////////////////////////////////////////////////////////
/* the Cart Class loads an immutable XML document of the servers current contents, Then updates are added to the server
Object Vars. to update the XML Document, the cart has to be rebuilt/reloaded
*/
//////////////////////////////////////////////////////////////////////////////////////
var cart = new cartClass("cart"); // Make a new instance of the cart and pass the instance name

//////////////////////////////////////////////////////////////////////////////////////
// Cart Class 
//////////////////////////////////////////////////////////////////////////////////////
function cartClass(instanceName){ 
	// define class vars
	var cartTotal;
	var cartVat;
	var cartShipping;
	var objectScope;
	var instanceName;
	var updateTotals;
	var checkoutLoader;
	var windowWidth;
	var windowheight;
	var lgoID;
	var urlPreFix;
	var rowCounter;
	var postageFlag;
	
	// Define arrays
	var AJAXRequest;
	this.AJAXRequest = new Array();
	
	// define class methods
	this.fetchTheMakeCart = fetchTheMakeCart;
	this.makeCart = makeCart;
	this.newItemRow = newItemRow;
	this.copyRow = copyRow;
	this.plusOne = plusOne;
	this.minusOne = minusOne;
	this.removeRow = removeRow;
	this.updateTotals = updateTotals;
	this.roundToTwoDecimals = roundToTwoDecimals;
	this.eraseWholeCart = eraseWholeCart;
	this.getCartStats = getCartStats;
	this.handleCartStatus = handleCartStatus;
	this.updateCartDBComplete = updateCartDBComplete;
	this.makeSmallCartStausLoading = makeSmallCartStausLoading;
	this.addNewCartItem = addNewCartItem;
	this.addNewitemComplete = addNewitemComplete;
	this.removeCheckoutStatusUpdating = removeCheckoutStatusUpdating;
	this.makeCheckoutStatusUpdating = makeCheckoutStatusUpdating;
	this.closeCartAddedConfirm = closeCartAddedConfirm;
	this.openCartAddedConfirmation = openCartAddedConfirmation;
	this.getWindowDimentions = getWindowDimentions;
	this.getlgoID = getlgoID;
	this.setPostageFlag = setPostageFlag;
	this.calculatePostage = calculatePostage;
	this.completeOrder = completeOrder;
	this.cartItemCount = cartItemCount;
	this.finaliseCart = finaliseCart;
	
	// set the scope and other defaults
	this.objectScope = this;
	this.instanceName = instanceName;
	
	this.cartShipping = 10.00;
	this.postageFlag = 1; // set to postage to 1
	
	this.cartTotal = 0;
	this.checkoutLoader = 0;
	this.windowWidth = 0;
	this.windowheight = 0;
	this.urlPreFix = "https://secure.lgo.co.uk/www.sportouring.com/";

	//this.urlPreFix = "";
	this.rowCounter = 0;
		
	//////////////////////////////////////////////////////////////////////////////////////
	function fetchTheMakeCart(){
		// Create a new AJAX Object and get the a cart row as XML
		var fetchTheMakeCart_ajaxObject = new ajaxClass();
		
		// To load a previous order check if orderID_Load input is valid.
		var orderID_Load = document.getElementById('orderID_Load');
				
		if(orderID_Load.value){
			fetchTheMakeCart_ajaxObject.generateRequest(
									"cartCalls.php?do=completeCartXML&orderID_Load="+orderID_Load.value,		// The URL of the request
									"GET",				// The Method of the request
									true,	 			// freeze the browser t/f
									"makeCart",	 		// successfully function
									"xml",	 			// expected format xml/text
									this.objectScope	// Scope of the call
									 );
			
			fetchTheMakeCart_ajaxObject.sendRequest(); // use the object to send the request
		}
		else{
					fetchTheMakeCart_ajaxObject.generateRequest(
									"cartCalls.php?do=completeCartXML",		// The URL of the request
									"GET",				// The Method of the request
									true,	 			// freeze the browser t/f
									"makeCart",	 		// successfully function
									"xml",	 			// expected format xml/text
									this.objectScope	// Scope of the call
									 );
			
			fetchTheMakeCart_ajaxObject.sendRequest(); // use the object to send the request
		}
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function makeCart(returnObject){ // This is the method that recieved the sucessfull result and builds cart
	
		var xmlItems = returnObject.xmlDoc.getElementsByTagName("cart")[0];
		
		for (var i=0; i< xmlItems.childNodes.length; i++){
			if(xmlItems.childNodes[i].nodeName == 'item'){
				// for each item in the cart produce a row
				this.newItemRow(xmlItems.childNodes[i]);
			}
		}
		
		// Update Totals
		this.updateTotals();
		
		// Set the erase scope
		var eraseLink = document.getElementById("eraseLink");
		eraseLink.setAttribute("href","javascript:"+this.instanceName+"."+"eraseWholeCart();");  // set link attributes for
		
		// Remove the loading row
		var loadingRow = document.getElementById("cartLoader");
		var loadingRowParent = loadingRow.parentNode;
		loadingRowParent.removeChild(loadingRow);
		
		// update checkout loader
		this.removeCheckoutStatusUpdating()
		
		// output the row count
		this.cartItemCount();
	
	}
	
	//////////////////////////////////////////////////////////////////////////////////////
	function newItemRow(xmlItemData){ // add a row to the cart
		
		// Get hidden var from page to find out if we are showing the cart tools or not.
		var showCartToolsElement = document.getElementById("showCartTools");
		var showCartTools = showCartToolsElement.value;
				
		//increment the this.rowCounter
		this.rowCounter++;
		
	
		// assign xml data to variables
		for (var i=0; i< xmlItemData.childNodes.length; i++){
		
			if(xmlItemData.childNodes[i].nodeName == 'item-rowID'){
				if (xmlItemData.childNodes[i].firstChild) var itemRowID = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-productCode'){
				if (xmlItemData.childNodes[i].firstChild) var itemProductCode = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-name'){
				if (xmlItemData.childNodes[i].firstChild) var itemName = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-var1'){
				if (xmlItemData.childNodes[i].firstChild) var itemVar1 = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-var2'){
				if (xmlItemData.childNodes[i].firstChild) var itemVar2 = xmlItemData.childNodes[i].firstChild.nodeValue;
			}

			if(xmlItemData.childNodes[i].nodeName == 'item-var2'){
				if (xmlItemData.childNodes[i].firstChild) var itemVar2 = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-var3'){
				if (xmlItemData.childNodes[i].firstChild) var itemVar3 = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-var4'){
				if (xmlItemData.childNodes[i].firstChild) var itemVar4 = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-var5'){
				if (xmlItemData.childNodes[i].firstChild) var itemVar5 = xmlItemData.childNodes[i].firstChild.nodeValue;
			}

			if(xmlItemData.childNodes[i].nodeName == 'item-qty'){
				if (xmlItemData.childNodes[i].firstChild) var itemQty = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-cost'){
				if (xmlItemData.childNodes[i].firstChild) var itemCost = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-vat'){
				if (xmlItemData.childNodes[i].firstChild) var itemVat = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-postage'){
				if (xmlItemData.childNodes[i].firstChild) var itemPostage = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-total'){
				if (xmlItemData.childNodes[i].firstChild) var itemTotal = xmlItemData.childNodes[i].firstChild.nodeValue;
			}
		
		}
		
		// Preform the Math that is needed.
		var itemTotal = itemCost * itemQty; // set the row total
		this.cartTotal = this.cartTotal + itemTotal;	// Add total to cart total
		
		this.cartVat = this.cartVat;	 // Not Implemented yet
		this.cartShipping = this.cartShipping;	 // Not Implemented yet
		
		
		// Locate the item rows container to insert into
		var itemRows = document.getElementById("itemRows");
		
		// Create the row Container
		var newItemRow = document.createElement("div");
		newItemRow.className = "item";
		// Set the row ID using the data from the XML Doc
		newItemRow.id = itemRowID;
		
		// Create Cells
		// For each Cell the code does the follow:
		// Create a Div Elementment
		// Assign a the class
		// Append to the row
		// Append data to div in a text node
		// do it backwards for the row streach

		// Add the tool cells
		var removeRowCell = document.createElement("div");
		removeRowCell.className = "toolsRemove";
		newItemRow.appendChild(removeRowCell);
		var linkNode = document.createElement("a"); // Add an <a> element for link
		linkNode.setAttribute("href","javascript:"+this.instanceName+"."+"removeRow("+itemRowID+");");  // set link attributes for
		if (showCartTools != 0) linkNode.appendChild( document.createTextNode('x'));
		removeRowCell.appendChild(linkNode);	
		
		var minusOneCell = document.createElement("div");
		minusOneCell.className = "tools";
		newItemRow.appendChild(minusOneCell);
		var linkNode = document.createElement("a"); // Add an <a> element for link
		linkNode.setAttribute("href","javascript:"+this.instanceName+"."+"minusOne("+itemRowID+");");  // set link attributes for
		if (showCartTools != 0) linkNode.appendChild( document.createTextNode('-1'));
		minusOneCell.appendChild(linkNode);
		
		var plusOneCell = document.createElement("div");
		plusOneCell.className = "tools";
		newItemRow.appendChild(plusOneCell);
		var linkNode = document.createElement("a"); // Add an <a> element for link
		linkNode.setAttribute("href","javascript:"+this.instanceName+"."+"plusOne("+itemRowID+");");  // set link attributes for
		if (showCartTools  != 0) linkNode.appendChild( document.createTextNode('+1') );
		plusOneCell.appendChild(linkNode);
		
		// total
		var totalCell = document.createElement("div");
		totalCell.className = "totalCell";
		newItemRow.appendChild(totalCell);
		totalCell.appendChild(document.createTextNode('£' + itemTotal.toFixed(2)));
		
		// price
		var priceCell = document.createElement("div");
		priceCell.className = "priceCell";
		newItemRow.appendChild(priceCell);
		var itemCost = itemCost * 1; // Turn the var into an interger
		priceCell.appendChild(document.createTextNode('£' + itemCost.toFixed(2)));
		
		// qty
		var qtyCell = document.createElement("div");
		qtyCell.className = "qtyCell";
		newItemRow.appendChild(qtyCell);
		qtyCell.appendChild(document.createTextNode(itemQty));	
		
		// Name
		var itemNameCell = document.createElement("div");
		itemNameCell.className = "itemCell";
		newItemRow.appendChild(itemNameCell);
		
		// Using tools generate a string to send to checkout
		var itemNameForCheckOut = itemName;

			// Generate a Readable cart row
			
				// Make it clickable
				var linkNodeSpan = document.createElement("span"); // Add an <a> element for link
				linkNodeSpan.setAttribute("class","cartRowDataTitle");

				var linkNode = document.createElement("a"); // Add an <a> element for link
				var linkUrl = "item.php?productcode=" +itemProductCode;
				linkNode.setAttribute("href",linkUrl);  // set link attributes for
				
				// Add text <a>
				linkNodeSpan.appendChild(linkNode);
				linkNode.appendChild(document.createTextNode(itemName));
				linkNode.appendChild(document.createElement("br"));
				
				itemNameCell.appendChild(linkNodeSpan);
				
				// Create Product code line:
					var productDescNode = document.createElement("span");
					productDescNode.setAttribute("class","cartRowData");
					
					// Add Label
					var nodeLabel = document.createElement("label");
					nodeLabel.appendChild(document.createTextNode("Code: "));
					productDescNode.appendChild(nodeLabel);
					// Add Data
					productDescNode.appendChild(document.createTextNode(itemProductCode));
					
					// Append to main display
					itemNameCell.appendChild(productDescNode);
					itemNameCell.appendChild(document.createElement("br"));
				
			
					var productDescNode = document.createElement("span");
					productDescNode.setAttribute("class","cartRowDataAdditional");
					
					// Add Label
					var nodeLabel = document.createElement("label");
					nodeLabel.appendChild(document.createTextNode("Additional Information: "));
					productDescNode.appendChild(nodeLabel);
					
					// Add Data
					if(itemVar1 != "undefined"){
						productDescNode.appendChild(document.createElement("br"));
						productDescNode.appendChild(document.createTextNode(itemVar1));
						itemNameForCheckOut = itemNameForCheckOut + ", " + itemVar1;
					}
					if(itemVar2 != "undefined"){
						productDescNode.appendChild(document.createElement("br"));
						productDescNode.appendChild(document.createTextNode(itemVar2));
						itemNameForCheckOut = itemNameForCheckOut + ", " + itemVar2;

					}
					if(itemVar3 != "undefined"){
						productDescNode.appendChild(document.createElement("br"));
						productDescNode.appendChild(document.createTextNode(itemVar3));
						itemNameForCheckOut = itemNameForCheckOut + ", " + itemVar3;

					}
					if(itemVar4 != "undefined"){
						productDescNode.appendChild(document.createElement("br"));
						productDescNode.appendChild(document.createTextNode(itemVar4));
						itemNameForCheckOut = itemNameForCheckOut + ", " + itemVar4;

					}
					if(itemVar5 != "undefined"){
						productDescNode.appendChild(document.createElement("br"));
						productDescNode.appendChild(document.createTextNode(itemVar5));
						itemNameForCheckOut = itemNameForCheckOut + ", " + itemVar5;
					}
					// Append to main display
					itemNameCell.appendChild(productDescNode);
					itemNameCell.appendChild(document.createElement("br"));
							
		
		// set the postage flag
		this.setPostageFlag(itemPostage);
		
		// in the name cell insert 4 hidden form feild for LGO cart
		var hiddenLGOitem = document.createElement("input");
		hiddenLGOitem.setAttribute("name","LGOitem"+this.rowCounter);  // set attributes for hidden feild
		hiddenLGOitem.setAttribute("type","hidden");  // set attributes for hidden feild
		hiddenLGOitem.setAttribute("value",itemNameForCheckOut);  // set attributes for hidden feild
		itemNameCell.appendChild(hiddenLGOitem); // append to the child row
		
		var hiddenLGOqty = document.createElement("input");
		hiddenLGOqty.setAttribute("name","LGOqty"+this.rowCounter);  // set attributes for hidden feild
		hiddenLGOqty.setAttribute("type","hidden");  // set attributes for hidden feild
		hiddenLGOqty.setAttribute("value",itemQty);  // set attributes for hidden feild
		hiddenLGOqty.setAttribute("id","itemQty_"+itemRowID);  // set a custom id to find the qty feild of the row
		itemNameCell.appendChild(hiddenLGOqty); // append to the child row

		var hiddenLGOprice = document.createElement("input");
		hiddenLGOprice.setAttribute("name","LGOprice"+this.rowCounter);  // set attributes for hidden feild
		hiddenLGOprice.setAttribute("type","hidden");  // set attributes for hidden feild
		hiddenLGOprice.setAttribute("value",itemCost.toFixed(2));  // set attributes for hidden feild
		itemNameCell.appendChild(hiddenLGOprice); // append to the child row

		var hiddenLGOcode= document.createElement("input");
		hiddenLGOcode.setAttribute("name","LGOcode"+this.rowCounter);  // set attributes for hidden feild
		hiddenLGOcode.setAttribute("type","hidden");  // set attributes for hidden feild
		hiddenLGOcode.setAttribute("value",itemProductCode);  // set attributes for hidden feild
		itemNameCell.appendChild(hiddenLGOcode); // append to the child row
		
		
		// Insert the new row into the itemRows div
		itemRows.appendChild(newItemRow);
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function copyRow(target){
		// Add a new item row to the items
		
		// Identify the target row
		var selectedRow = target;	
		var targetRow = target.parentNode;
		
		// Clone the selected rows
		var cloned = targetRow.cloneNode(true);
		cloned.setAttribute('id', 'blah')
		
		// Get the item Area and add the cloned div Row
		var itemArea = document.getElementById('itemRows');
		itemArea.appendChild(cloned);
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function plusOne(target){
		// Add one more to the row quantity
		
		// Make the loader appear on the small cart.
		this.makeSmallCartStausLoading();
		// Update checkout loader
		this.makeCheckoutStatusUpdating();
		
		// Identify the target row
		var selectedRow = document.getElementById(target);	
		
		// Locate the Div with the data that is needed using the cell class
		for (var i=0; i<selectedRow.childNodes.length; i++){
			if (selectedRow.childNodes[i].className == "qtyCell"){
				var qtyNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].className == "priceCell"){
				var priceNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].className == "totalCell"){
				var totalNode = selectedRow.childNodes[i];
			}
		}
		// once we get the correct DIV, text is there stored in the first Child
		
		// Update the Qty in DOM
		var currentQtyValue = qtyNode.firstChild.nodeValue;
		currentQtyValue++;
		qtyNode.firstChild.nodeValue = currentQtyValue;
		
		// Update the LGO Hidden QTY Feild
		var lgoQtyFeild = document.getElementById("itemQty_"+target);
		lgoQtyFeild.setAttribute("value", currentQtyValue);
		
		// Update row total Node
		var rowItemValue = priceNode.firstChild.nodeValue.split('£');	
		totalNode.firstChild.nodeValue = '£' + this.roundToTwoDecimals((currentQtyValue * rowItemValue[1]));
		
		// Update the final total node
		this.cartTotal = this.cartTotal + (1 * rowItemValue[1]);
		this.updateTotals();

		// Update the Qty in DB	
		
		//Generate a new AJAX Reqeust and store in using a Unique name in the AJAXRequest Array
		var unique = new Date().getTime();
		this.AJAXRequest[unique] = new ajaxClass();
				  
		this.AJAXRequest[unique].generateRequest(
												"cartCalls.php?do=plusOne&item="+target,		// The URL of the request
												"GET",				// The Method of the request
												true,	 			// freeze the browser t/f
												"updateCartDBComplete",	// successfully function
												"text",	 			// expected format xml/text
												this.objectScope	// Scope of the call
												 );
		
		this.AJAXRequest[unique].sendRequest(); // use the object to send the request
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function minusOne(target){
		// Remove one from the row quantity
		
		// Make the loader appear on the small cart.
		this.makeSmallCartStausLoading();
		// Update checkout loader
		this.makeCheckoutStatusUpdating();
		
		// Identify the target row
		var selectedRow = document.getElementById(target);	
		
		// Locate the Div with the data that is needed using the cell class
		for (var i=0; i<selectedRow.childNodes.length; i++){
			if (selectedRow.childNodes[i].className == "qtyCell"){
				var qtyNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].className == "priceCell"){
				var priceNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].className == "totalCell"){
				var totalNode = selectedRow.childNodes[i];
			}
		}
		// once we get the correct DIV, text is there stored in the first Child
		
		// Update the Qty in DOM
		var currentQtyValue = qtyNode.firstChild.nodeValue;
		currentQtyValue--;
		
		// check if the value is below 0 if so rest to 0
		if (currentQtyValue < 0) { 
			currentQtyValue = 0;
			// set a flag for updating totals
			var totalZeroFlag = 1;
		}
		qtyNode.firstChild.nodeValue = currentQtyValue;
		
		
		// Update the LGO Hidden QTY Feild
		var lgoQtyFeild = document.getElementById("itemQty_"+target);
		lgoQtyFeild.setAttribute("value", currentQtyValue);


		// Update row total Node
		var rowItemValue = priceNode.firstChild.nodeValue.split('£');	
		totalNode.firstChild.nodeValue = '£' + this.roundToTwoDecimals((currentQtyValue * rowItemValue[1])) ;
		
		// Update the final total node
		if (totalZeroFlag != 1) {
			this.cartTotal = this.cartTotal - (1 * rowItemValue[1]);
			this.updateTotals();
		}
		
		// Update the Qty in DB
		
		//Generate a new AJAX Reqeust and store in using a Unique name in the AJAXRequest Array
		var unique = new Date().getTime();
		this.AJAXRequest[unique] = new ajaxClass();
				  
		this.AJAXRequest[unique].generateRequest(
												"cartCalls.php?do=minusOne&item="+target,		// The URL of the request
												"GET",				// The Method of the request
												true,	 			// freeze the browser t/f
												"updateCartDBComplete",	// successfully function
												"text",	 			// expected format xml/text
												this.objectScope	// Scope of the call
												 );
		
		this.AJAXRequest[unique].sendRequest(); // use the object to send the request
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function removeRow(target){
		// Remove a row from the items
		
		// Make the loader appear on the small cart.
		this.makeSmallCartStausLoading();
		// Update checkout loader
		this.makeCheckoutStatusUpdating();
		
		// Identify the target row
		var selectedRow = document.getElementById(target);	
		
		// Locate the Div with the data that is needed using the cell class
		for (var i=0; i<selectedRow.childNodes.length; i++){
			if (selectedRow.childNodes[i].className == "qtyCell"){
				var qtyNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].className == "priceCell"){
				var priceNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].className == "totalCell"){
				var totalNode = selectedRow.childNodes[i];
			}
		}
		// once we get the correct DIV, text is there stored in the first Child
		
		// Get the Values needed
		var rowItemValue = priceNode.firstChild.nodeValue.split('£');	
		var currentQtyValue = qtyNode.firstChild.nodeValue;
		
		// Update the final total node
		this.cartTotal = this.cartTotal - (currentQtyValue * rowItemValue[1]);
		this.updateTotals();
		
		// Remove the row
		var itemArea = document.getElementById('itemRows');
		itemArea.removeChild(selectedRow);
		
		// Reduce the row count
		this.rowCounter = this.rowCounter - 1;
		var cartItemCount = document.getElementById("cartItemCount");
		cartItemCount.setAttribute("value",this.rowCounter);  // set attributes for hidden feild
	
		
		// Update the DB
		//Generate a new AJAX Reqeust and store in using a Unique name in the AJAXRequest Array
		var unique = new Date().getTime();
		this.AJAXRequest[unique] = new ajaxClass();
				  
		this.AJAXRequest[unique].generateRequest(
												"cartCalls.php?do=removeRow&item="+target,		// The URL of the request
												"GET",				// The Method of the request
												true,	 			// freeze the browser t/f
												"updateCartDBComplete",	// successfully function
												"text",	 			// expected format xml/text
												this.objectScope	// Scope of the call
												 );
		
		this.AJAXRequest[unique].sendRequest(); // use the object to send the request
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function eraseWholeCart(){
	
		// Make the loader appear on the small cart.
		this.makeSmallCartStausLoading();
		// Update checkout loader
		this.makeCheckoutStatusUpdating();
	
		// Locate the item rows container
		var itemRows = document.getElementById("itemRows");
		
		while (itemRows.lastChild){
		itemRows.removeChild(itemRows.lastChild);
		}
		
		// Reset the totals etc
		this.cartTotal = 0.00;
		this.updateTotals();
		
		// Update the DB
		//Generate a new AJAX Reqeust and store in using a Unique name in the AJAXRequest Array
		var unique = new Date().getTime();
		this.AJAXRequest[unique] = new ajaxClass();
				  
		this.AJAXRequest[unique].generateRequest(
												"cartCalls.php?do=eraseWholeCart",		// The URL of the request
												"GET",				// The Method of the request
												true,	 			// freeze the browser t/f
												"updateCartDBComplete",	// successfully function
												"text",	 			// expected format xml/text
												this.objectScope	// Scope of the call
												 );
		
		this.AJAXRequest[unique].sendRequest(); // use the object to send the request
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function updateTotals(){
	
		// Check for order discount
		var orderDiscount = 0;
		
		if (this.cartTotal > 9999999999999999999.99) {
			var orderDiscount = 10
		}
		
		if (this.cartTotal > 19999999999999999999999.99) {
			var orderDiscount = 20;
		}
		
		// populate discount feild
		var discountCell = document.getElementById("discount");
		var discountSpan = document.getElementById("discountSpan");
		//discountSpan.firstChild.nodeValue = orderDiscount + "% ";
		
		var discountAmount = (this.cartTotal * (orderDiscount/100));
		this.cartTotalWithDiscount = this.cartTotal - discountAmount;
		
		//if (discountAmount.toFixed(2) == -0.00) discountAmount = 0.00
		//discountCell.firstChild.nodeValue = "£" + discountAmount.toFixed(2);

		var postageCell = document.getElementById("postage");
		this.calculatePostage(); // Calculate postage
		postageCell.firstChild.nodeValue = "£" + this.cartShipping.toFixed(2);
		
		// add postage to cart total
		var displayTotal = this.cartTotalWithDiscount + this.cartShipping;
		
		var totalCell = document.getElementById("total");
		// quick check for -0.00
		if (this.cartTotalWithDiscount.toFixed(2) == -0.00) displayTotal = 0.00;
		totalCell.firstChild.nodeValue = "£" + displayTotal.toFixed(2);
		
		var vatCell = document.getElementById("vat");
		//vatCell.firstChild.nodeValue = "£" + this.cartVat;
		
		// Update Checkout Total
		var cartTotal = document.getElementById("cartTotal");
		cartTotal.setAttribute("value",displayTotal.toFixed(2));  // set attributes for hidden total

		var cartHTMLTotal = document.getElementById("cartHTMLTotal");
		cartHTMLTotal.firstChild.nodeValue = "£" + displayTotal.toFixed(2);
		
		// Update checkout postage
		var cartPostage = document.getElementById("cartPostage");
		cartPostage.setAttribute("value",this.cartShipping.toFixed(2));  // set attributes for hidden total
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function getCartStats(){
	
	// check for lgoID if false save it
	if (!this.lgoID) this.getlgoID();
	
	// Create a new AJAX Object and get the a cart row as XML
	var getCartStats_ajaxObject = new ajaxClass();
	  
	getCartStats_ajaxObject.generateRequest(
												"cartCalls.php?do=cartStatsXML",	// The URL of the request
												"GET",					// The Method of the request
												true,	 				// freeze the browser t/f
												"handleCartStatus",	 	// successfully function
												"xml",	 				// expected format xml/text
												this.objectScope		// Scope of the call
	 											);
	
	getCartStats_ajaxObject.sendRequest(); // use the object to send the request
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function handleCartStatus(returnObject){ // Handles the cart stats
		
		// Handle results
		var xmldata = returnObject.xmlDoc.getElementsByTagName("cartStats")[0];
		
		for (var i=0; i< xmldata.childNodes.length; i++){
		
			// assign xml data to variables
			if(xmldata.childNodes[i].nodeName == 'numItems'){
				if(xmldata.childNodes[i].firstChild) {
					var numItems = xmldata.childNodes[i].firstChild.nodeValue;
				} else numItems = 0;
			}
			
			if(xmldata.childNodes[i].nodeName == 'totalValue'){
				if(xmldata.childNodes[i].firstChild) {
					var totalValue = xmldata.childNodes[i].firstChild.nodeValue;
				} else totalValue = 0.00;
			}
		}
		
		// Update Page
		
		// Locate the Div that contains the small cart
		//var smallCartContents = document.getElementById("cartData");
		
		// remove the loader
		//while (smallCartContents.lastChild){
			//smallCartContents.removeChild(smallCartContents.lastChild)
		//}
		
		// Create the number of items
		var headerSpan = document.createElement("span");
		headerSpan.className = "cartContentsHeading";
		headerSpan.appendChild(document.createTextNode("Items: "));
		
		//smallCartContents.appendChild(headerSpan);
		//smallCartContents.appendChild(document.createTextNode(numItems));
		
			// Add some space between the data
			//smallCartContents.appendChild(document.createTextNode('\u00a0 \u00a0'));
		
		// Create the value of items
		var headerSpan = document.createElement("span");
		headerSpan.className = "cartContentsHeading";
		headerSpan.appendChild(document.createTextNode("Total: "));
		
		//smallCartContents.appendChild(headerSpan);
		//smallCartContents.appendChild(document.createTextNode('£' + totalValue));
		
			// Add some space between the data
			//smallCartContents.appendChild(document.createTextNode('\u00a0 \u00a0 \u00a0 \u00a0'));
			
		var viewCart = document.createElement("span");
		viewCart.className = "cartLink";
		
		var viewCartLink = document.createElement("a"); // Add an <a> element for link
		viewCartLink.setAttribute("href",this.urlPreFix+"cart.php?lgoID="+this.lgoID);  // set link attributes for
		viewCartLink.appendChild(document.createTextNode("View Cart"));

		viewCart.appendChild(viewCartLink);
		//smallCartContents.appendChild(viewCart);
			
	}	
	//////////////////////////////////////////////////////////////////////////////////////
	function makeSmallCartStausLoading(){
		// remove any nodes in the smallcart
		
		/*
		// remove the Current contents
		var smallCartContents = document.getElementById("cartData");
		
		while (smallCartContents.lastChild){
			smallCartContents.removeChild(smallCartContents.lastChild)
		}
		
		// Load the loader		
		var loaderTag = document.createElement("img"); // Add an <img> element for link
		loaderTag.setAttribute("src","images/loading.gif");  // set link attributes for
		
		smallCartContents.appendChild(loaderTag);
		*/

	}
	//////////////////////////////////////////////////////////////////////////////////////
	function makeCheckoutStatusUpdating(){
		
		// check if a loader is present
		if (this.checkoutLoader == -1){
			// Add Loader to check out button
			var checkoutLinks = document.getElementById("checkoutLinks");
			// Find the first child  to insert before
			var firstChild = checkoutLinks.firstChild;
				
			var checkoutStatus = document.createElement("img"); // Add an <img> element for link
			checkoutStatus.setAttribute("src","images/checkoutLoader.gif");  // set link attributes for
			checkoutStatus.setAttribute("id","checkoutLoader");  // set link attributes for
			checkoutStatus.setAttribute("alt","Updating cart before checkout");  // set link attributes for
			
			checkoutLinks.insertBefore(checkoutStatus,firstChild);
			
			// Make checout button inactive - using prototype
			$('checkOutButton').disable();
		}

		// Increment the counter of the of the loader
		this.checkoutLoader++;

	}
	//////////////////////////////////////////////////////////////////////////////////////
	function removeCheckoutStatusUpdating(){
		
		// Decrease  the counter of the of the loader
		this.checkoutLoader--;
		
		// check if a loader should be removed
		if (this.checkoutLoader < 0){
			// Remove Loader to check out button
			var checkoutStatus = document.getElementById("checkoutLoader");
			var checkoutStatusParent = checkoutStatus.parentNode;
			checkoutStatusParent.removeChild(checkoutStatus);
			
			// Make checout button active  - using prototype
			$('checkOutButton').enable();
			
		}
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function addNewCartItem(itemCode,additionEventObj) {
		// Make the loader appear on the small cart.
		this.makeSmallCartStausLoading();
		
		// Turn on the Confirmation panel
		this.openCartAddedConfirmation(additionEventObj);
		
		// Use a delay to remove the confirmation
		var _this = this;
		window.setTimeout(function(){
									_this.closeCartAddedConfirm();
								 	} ,2500); // 2.5 secs
		
		// Add a new item to the shopping cart
		
			// Get the variables qty, var1, var2, etc
			var itemForm = document.getElementById("item_"+itemCode);
			
			var qty = itemForm.qty.value;
			if(itemForm.var1) var var1 = itemForm.var1.value;
			if(itemForm.var2) var var2 = itemForm.var2.value;
			if(itemForm.var3) var var3 = itemForm.var3.value;
			if(itemForm.var4) var var4 = itemForm.var4.value;
			if(itemForm.var5) var var5 = itemForm.var5.value;
						
			// Add the extra details to send in the URL
			var requestURLExtra = '&qty=' + qty + '&var1=' + var1 + '&var2=' + var2 + '&var3=' + var3 + '&var4=' + var4 + '&var5=' + var5;
			
		// Generate a new AJAX Reqeust and store in using a Unique name in the AJAXRequest Array
		var unique = new Date().getTime();
		this.AJAXRequest[unique] = new ajaxClass();
		
		//alert("cartCalls.php?do=addNewItem&item="+itemCode+requestURLExtra);
		
		this.AJAXRequest[unique].generateRequest(
												"cartCalls.php?do=addNewItem&item="+itemCode+requestURLExtra,		// The URL of the request
												"GET",					// The Method of the request
												true,	 				// freeze the browser t/f
												"addNewitemComplete",	// successfully function
												"text",	 				// expected format xml/text
												this.objectScope		// Scope of the call
												 );
		
		this.AJAXRequest[unique].sendRequest(); // use the object to send the request
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function addNewitemComplete(value){
	
		// Force small cart to update
		this.getCartStats();	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function openCartAddedConfirmation(additionEventObj){
		
		// Get the position of the click using prototype.js
		var x = Event.pointerX(additionEventObj)
		var y = Event.pointerY(additionEventObj)
		
		// check window size for extreme right disappear
		this.getWindowDimentions();
		var testValue = x + 150;
		
		if (testValue > this.windowWidth) x = this.windowWidth - 200;
							
		// using prototype.js
		$('cartAdded').setStyle({ 
							left: x+'px',
							top: y+'px'
							});
		
		// use a scriptaculous effect to show confirmation			
		Effect.Appear('cartAdded', {duration:0.5});
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function closeCartAddedConfirm(){
	
		Effect.Fade('cartAdded', {duration:0.25})
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function roundToTwoDecimals(value){
		return value.toFixed(2);
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function updateCartDBComplete(value){
	
		// Force small cart to update
		this.getCartStats();
		
		// Update the checkout loader
		this.removeCheckoutStatusUpdating();
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function getlgoID(){ // get the lgoID from the hidden feild on the page
	
		this.lgoID = document.getElementById("lgoID").getAttribute("value");
				
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function completeOrder(){
	
		// Set new lgoID
		document.getElementById("lgoID").setAttribute("value", "");
		
		// Reload the Small cart
		this.lgoID = false;
		this.getCartStats();

	}
	//////////////////////////////////////////////////////////////////////////////////////
	function setPostageFlag(itemPostageFlag){ // check and set postage flag(s)
		
			// If postage flag is higher, change flag.
			if (this.postageFlag < itemPostageFlag){
				this.postageFlag = itemPostageFlag;
			}
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function calculatePostage(){ 
		
		if (this.postageFlag == 0)  	this.cartShipping = 0.0;  
		if (this.postageFlag == 1)  	this.cartShipping = 1.49;  
		if (this.postageFlag == 1.3) 	this.cartShipping = 1.99;  
		if (this.postageFlag == 2)  	this.cartShipping = 3.49;  
		if (this.postageFlag == 3)  	this.cartShipping = 4.99;  
		if (this.postageFlag == 3.2)  	this.cartShipping = 5.99;  
		if (this.postageFlag == 3.3)  	this.cartShipping = 6.99;  
		if (this.postageFlag == 3.4)  	this.cartShipping = 7.49;  
		if (this.postageFlag == 4)  	this.cartShipping = 9.99;  
		if (this.postageFlag == 4.2)  	this.cartShipping = 12.99;  
		if (this.postageFlag == 5)  	this.cartShipping = 14.99;
		if (this.postageFlag == 5.2) 	this.cartShipping = 17.99;  
		if (this.postageFlag == 5.4) 	this.cartShipping = 19.99;  
		if (this.postageFlag == 6)  	this.cartShipping = 21.00;  
		if (this.postageFlag == 7)  	this.cartShipping = 24.99;  
		if (this.postageFlag == 8)  	this.cartShipping = 34.80;  
		if (this.postageFlag == 9)  	this.cartShipping = 44.95; 
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function cartItemCount(){ // add an item count hidden feild to the cart out put.
	
		var checkOutRow = document.getElementById("checkoutLinks");
	
		var cartItemCount= document.createElement("input");
		cartItemCount.setAttribute("name","Number_Of_Items");  // set attributes for hidden feild
		cartItemCount.setAttribute("type","hidden");  // set attributes for hidden feild
		cartItemCount.setAttribute("value",this.rowCounter);  // set attributes for hidden feild
		cartItemCount.setAttribute("id","cartItemCount");  // set attributes for hidden feild
		checkOutRow.appendChild(cartItemCount); // append to the child row

	
	}	
	//////////////////////////////////////////////////////////////////////////////////////
	function getWindowDimentions(){ // get window dimentions and save in object
	
		this.windowWidth = 0;
		this.windowheight = 0;
		
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			this.windowWidth = window.innerWidth;
			this.windowheight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			this.windowWidth = document.documentElement.clientWidth;
			this.windowheight = document.documentElement.clientHeight;
	  	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			this.windowWidth = document.body.clientWidth;
			this.windowheight = document.body.clientHeight;
	  	}
  	}
  	//////////////////////////////////////////////////////////////////////////////////////
  	function finaliseCart(){
  	
  		// Reset the flag
  		var flag = true;
  	
  		// Disable order button, and change name
  		document.getElementById("orderButton").setAttribute("value", "Please Wait.........");
  		document.getElementById("orderButton").setAttribute("disabled", "disabled");

  		// Check Card info
		var element = document.getElementById('nameoncard');
		element.style.backgroundColor = '#FFFFFF';
		
		var element = document.getElementById('cardno');
		element.style.backgroundColor = '#FFFFFF';
				
		var element = document.getElementById('endmonth');
		element.style.backgroundColor = '#FFFFFF';
		
		var element = document.getElementById('endyear');
		element.style.backgroundColor = '#FFFFFF';

		var element = document.getElementById('securitycode');
		element.style.backgroundColor = '#FFFFFF';

		// Card Payment
		if (!window.document.lgoCartForm.nameoncard.value) {
			var element = document.getElementById('nameoncard');
			element.style.backgroundColor = '#FF3333';
			flag = false;
		}
		if (!window.document.lgoCartForm.cardno.value) {
			var element = document.getElementById('cardno');
			element.style.backgroundColor = '#FF3333';
			flag = false;
		}
		if (!window.document.lgoCartForm.endmonth.value) {
			var element = document.getElementById('endmonth');
			element.style.backgroundColor = '#FF3333';
			flag = false;
		}
		if (!window.document.lgoCartForm.endyear.value) {
			var element = document.getElementById('endyear');
			element.style.backgroundColor = '#FF3333';
			flag = false;
		}
		if (!window.document.lgoCartForm.securitycode.value) {
			var element = document.getElementById('securitycode');
			element.style.backgroundColor = '#FF3333';
			flag = false;
		}

		
		if (!document.getElementById("shippingAddress") || !document.getElementById("billingAddress")) {
			var addressFlag = true;
			flag = false;
			alert("You have not saved any addresses. Please check the address section");			
		} 
				
		
		// Sumbit the form
		if (flag) {
		
				// set the Form Location
		  		window.document.lgoCartForm.action = window.document.lgoCartForm.formLocationFinal.value;
		
				//Wipe the feilds not needed.
				document.getElementById("formLocationFinal").setAttribute("name", "");	  	
				document.getElementById("formLocationUpdate").setAttribute("name", "");
				document.getElementById("appAction").setAttribute("name", "");
				document.getElementById("firstname").setAttribute("name", "");
				document.getElementById("lastname").setAttribute("name", "");
				document.getElementById("phonemob").setAttribute("name", "");
				document.getElementById("rowID").setAttribute("name", "");
				document.getElementById("objectArea").setAttribute("name", "");
				document.getElementById("billingAddress").setAttribute("name", "");
				document.getElementById("shippingAddress").setAttribute("name", "")
				document.getElementById("typeFlag").setAttribute("name", "");
				document.getElementById("new1").setAttribute("name", "");
				document.getElementById("new2").setAttribute("name", "");
				document.getElementById("new3").setAttribute("name", "");
				document.getElementById("new_postcode").setAttribute("name", "");
				document.getElementById("new_country").setAttribute("name", "");		
				
				// Move mobile phone to correct form feild
				window.document.lgoCartForm.mobilephone.value = document.getElementById("phonemob").value;
				// Move Name feilds
				window.document.lgoCartForm.name.value = document.getElementById("firstname").value;
				window.document.lgoCartForm.sname.value = document.getElementById("lastname").value;
				
				// Move the addresses to the hidden feilds
				// Billing
				if (document.getElementById("billingAddress")) {
					var addressString = document.getElementById("billingAddress").value;
					addressArray = addressString.split(',  ');
			
					window.document.lgoCartForm.ch_address1.value = addressArray[0];
					window.document.lgoCartForm.ch_address2.value = addressArray[1];
					window.document.lgoCartForm.ch_address3.value = addressArray[2];
					window.document.lgoCartForm.ch_postcode.value = addressArray[3];
					window.document.lgoCartForm.ch_country.value = addressArray[4];
				}
				
				// Shipping
				if (document.getElementById("shippingAddress")){
					var addressString = document.getElementById("shippingAddress").value;
					addressArray = addressString.split(',  ');
		
					window.document.lgoCartForm.sh_address1.value = addressArray[0];
					window.document.lgoCartForm.sh_address2.value = addressArray[1];
					window.document.lgoCartForm.sh_address3.value = addressArray[2];
					window.document.lgoCartForm.sh_postcode.value = addressArray[3];
					window.document.lgoCartForm.sh_country.value = addressArray[4];
				}

				window.document.lgoCartForm.submit();
		}
		
		if (!flag) {
			// Make button active  - using prototype
			document.getElementById("orderButton").setAttribute("value", "Place Order");
		//	$('orderButton').enable();
			
			alert('Please check the fields in red, and that you have entered expiry date for your card.');
		}
		
  	}
		  	//////////////////////////////////////////////////////////////////////////////////////

}

