// 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;
	var supplierPostageArray;
	
	// 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.setPostageDetails = setPostageDetails;
	this.calculatePostage = calculatePostage;
	this.completeOrder = completeOrder;
	this.cartItemCount = cartItemCount;
	this.removePostageDetails = removePostageDetails;
	this.localPostage = localPostage;
	
	// set the scope and other defaults
	this.objectScope = this;
	this.instanceName = instanceName;
	
	this.cartShipping = 0.00;
	this.cartShippingVat = 0.00
	this.postageFlag = 1; // set to free postage to start
	this.supplierPostageArray = new Array()  // Create 1 Big Array

	
	this.cartTotal = 0;
	this.checkoutLoader = 0;
	this.windowWidth = 0;
	this.windowheight = 0;
	this.urlPreFix = "https://secure.lgoconsulting.net/www.happyhomefurnishers.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
	
		//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;
				// change data in ItemName/Desc
				//itemName = itemName.replace(/1/gi,"<br>");
			}
			
			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-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;
			}
			
			if(xmlItemData.childNodes[i].nodeName == 'item-supplier'){
				if (xmlItemData.childNodes[i].firstChild) var itemSupplier = 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
		itemCost = itemCost * 1; // do this so we can round the number;

		
		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
		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
		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
		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);
		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);
		itemNameCell.appendChild(document.createTextNode(itemName));
		
		// HH Cust.
		
		// Add Postage to a hidden Span.
		var itemPostageSpan = document.createElement("span");
		itemPostageSpan.setAttribute("id","itemPostage");
		itemPostageSpan.appendChild(document.createTextNode(itemPostage));
		// add the Postage SPAN to the description box.
		newItemRow.appendChild(itemPostageSpan);
		
		// Add Supplier to a hidden Span.
		var itemSupplierSpan = document.createElement("span");
		itemSupplierSpan.setAttribute("id","itemSupplier");
		itemSupplierSpan.appendChild(document.createTextNode(itemSupplier));
		// add the Supplier SPAN to the description box.
		newItemRow.appendChild(itemSupplierSpan);
				
		// set the postage flag do it once for every qty the item has
		var i = 1;
		while (i <= itemQty){
			this.setPostageDetails(itemPostage,itemSupplier);
			i++;
		}
		
		// 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",itemName);  // 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);
		
		// Add a blank at the end of the row i.e <div class="clearAll"> </div>
		var clearAllCell = document.createElement("div");
		clearAllCell.className = "clearAll";
		itemRows.appendChild(clearAllCell);
		clearAllCell.appendChild(document.createTextNode(" "));
		
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	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];
			}
			if (selectedRow.childNodes[i].id == "itemPostage"){
				var postageNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].id == "itemSupplier"){
				var supplierNode = 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]));
		
		// HH cust.
		// Add the new item to the Postage arrays
		var itemPostage = postageNode.firstChild.nodeValue;
		var itemSupplier = supplierNode.firstChild.nodeValue;
		
		this.setPostageDetails(itemPostage,itemSupplier);
		
		// 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];
			}
			if (selectedRow.childNodes[i].id == "itemPostage"){
				var postageNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].id == "itemSupplier"){
				var supplierNode = 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) {
		
			// HH cust.
			// Remove the postage from the postage amount array
			var itemPostage = postageNode.firstChild.nodeValue;
			var itemSupplier = supplierNode.firstChild.nodeValue;
			this.removePostageDetails(itemPostage,itemSupplier);
		
			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];
			}
			if (selectedRow.childNodes[i].id == "itemPostage"){
				var postageNode = selectedRow.childNodes[i];
			}
			if (selectedRow.childNodes[i].id == "itemSupplier"){
				var supplierNode = 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;
		
		// HH cust.
		// Remove the postage from the postage amount array
		var itemPostage = postageNode.firstChild.nodeValue;
		var itemSupplier = supplierNode.firstChild.nodeValue;
		
		var i = 1;
		while (i <= currentQtyValue){
			this.removePostageDetails(itemPostage,itemSupplier);
			i++;
		}

		// 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);
		}
		
		this.supplierPostageArray = new Array()  // Create 1 Big Array

		// 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(){
	
	
		var postageCell = document.getElementById("postage");
		this.calculatePostage(); // Calculate postage
		postageCell.firstChild.nodeValue = "£" + this.cartShipping.toFixed(2);
		
		// add postage to cart total
		var displayTotal = this.cartTotal + this.cartShipping;
		
		var totalCell = document.getElementById("total");
		// quick check for -0.00
		if (this.cartTotal.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;
			var var1 = itemForm.qty.var1;
			var var2 = itemForm.qty.var2;
			
			// Add the extra details to send in the URL
			var requestURLExtra = '&qty=' + qty + '&var1=' + var1 + '&var2=' + var2;
		
		// 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=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 setPostageDetails(itemPostage,itemSupplier){ // Set Postage Rates
						
			//Check if supplier postage array exist, if not create it
			if(!this.supplierPostageArray[itemSupplier]){
				this.supplierPostageArray[itemSupplier] = new Array()  // Create an array for the supplier
				//this.supplierPostageArray[itemSupplier] = itemSupplier; // set the element to the supplier id
			}
			
			this.supplierPostageArray[itemSupplier].push(itemPostage);  // Push the item's postage into the array for the supplier.
			
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function removePostageDetails(itemPostage,itemSupplier){ // Remove Postage Rates
			
			var i = 0;
						
			while(i < this.supplierPostageArray[itemSupplier].length){
				
				if (this.supplierPostageArray[itemSupplier][i] == itemPostage){
					this.supplierPostageArray[itemSupplier][i] = "";  // wipe the postage
					i = 99999999999999  // Set the count to a huge value so end the test
				}
				i ++;
			}
						
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function calculatePostage(){ // if free postage change cost to 0
	
		var postageAmount = 0;
		var i = 0;
		
		while(i < this.supplierPostageArray.length){  // For Every Suppier
			
			if (this.supplierPostageArray[i]){

				var si = 0;
				var supplierPostageAmount = 0;
				var supplierItemCount = 0;
				
				while(si < this.supplierPostageArray[i].length){  // For every item of that supplier
				
					if (this.supplierPostageArray[i][si]){ // If Value is set add it to the postage total
						supplierPostageAmount = supplierPostageAmount + parseFloat(this.supplierPostageArray[i][si]); 
						supplierItemCount ++; // count of items per supplier
					}
					
					if (i == 1){ // if Claxtons is the supplier WHERE IS REPRESENTS SUPPLIER ID
					
						if (supplierItemCount == 2 && supplierPostageAmount > 56) supplierPostageAmount = 56;
						if (supplierItemCount == 3 && supplierPostageAmount > 75) supplierPostageAmount = 75;
						if (supplierItemCount > 3 && supplierPostageAmount > 75) supplierPostageAmount = 75;				
						
					}
					
					if (i == 9){ // if Kingstown is the supplier WHERE IS REPRESENTS SUPPLIER ID
						if (this.cartTotal > 299)  supplierPostageAmount = 0;
					}
					si ++;
				}
				
				postageAmount = postageAmount + supplierPostageAmount;
			}

			i++;
		}
		//Set the cap of £90 to he postage
		if (postageAmount > 90) postageAmount = 90;
		
		this.cartShipping = postageAmount;

		this.localPostage(1); // run local postage to check incase we need to account for that.
	
	}
	//////////////////////////////////////////////////////////////////////////////////////
	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 localPostage(updateTotalsCall){ // Checkf or local postage and update postage amount
		
		var postageCheckBox = document.getElementById("localPostage");
	
		if(postageCheckBox.checked){
			var postageAmount = 29;
			this.cartShipping = postageAmount;
		}
		
		if (!updateTotalsCall){
			this.updateTotals();
		}
		
		
	}	
	//////////////////////////////////////////////////////////////////////////////////////
	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;
	  	}
  	}
  	//////////////////////////////////////////////////////////////////////////////////////
}
