// 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 cartShipping;
	var objectScope;
	var instanceName;
	var updateTotals;
	var checkoutLoader;
	var windowWidth;
	var windowheight;
	var lgoID;
	var urlPreFix;
	var rowCounter;
	
	// 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.addNewCartItem = addNewCartItem;
	this.addNewitemComplete = addNewitemComplete;
	this.removeCheckoutStatusUpdating = removeCheckoutStatusUpdating;
	this.makeCheckoutStatusUpdating = makeCheckoutStatusUpdating;
	this.closeCartAddedConfirm = closeCartAddedConfirm;
	this.openCartAddedConfirmation = openCartAddedConfirmation;
	this.getWindowDimentions = getWindowDimentions;
	this.getlgoID = getlgoID;
	this.completeOrder = completeOrder;
	this.finaliseCart = finaliseCart;
	
	// set the scope and other defaults
	this.objectScope = this;
	this.instanceName = instanceName;
	
	this.cartShipping = 10.00;
	
	this.cartTotal = 0;
	this.checkoutLoader = 0;
	this.windowWidth = 0;
	this.windowheight = 0;
	this.urlPreFix = "http://www.LgoConsulting.co.uk/";
	//this.urlPreFix = "https://www.lgogroup.net/www.twfoam.co.uk/";

	//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("items")[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()
	
	}
	
	//////////////////////////////////////////////////////////////////////////////////////
	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-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
				
		// 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('remove'));
		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('Add 1') );
		plusOneCell.appendChild(linkNode);
		
		// total
		var totalCell = document.createElement("div");
		totalCell.className = "totalCell";
		newItemRow.appendChild(totalCell);
		totalCell.appendChild(document.createTextNode('\u00A3' + itemTotal.toFixed(2)));
		
		// price
		var priceCell = document.createElement("div");
		priceCell.className = "priceCell";
		newItemRow.appendChild(priceCell);
		priceCell.appendChild(document.createTextNode('\u00A3' + itemCost));
		
		// 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));		
		
		// 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
		
		// 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 row total Node
		var rowItemValue = priceNode.firstChild.nodeValue.split('\u00A3');	
		totalNode.firstChild.nodeValue = '\u00A3' + 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
		
		// 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 row total Node
		var rowItemValue = priceNode.firstChild.nodeValue.split('\u00A3');	
		totalNode.firstChild.nodeValue = '\u00A3' + 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
		
		// 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('\u00A3');	
		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);	
		
		// 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(){


		// 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;
		
		// 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 = "\u00A3" + discountAmount.toFixed(2);
		
		var totalCell = document.getElementById("total");
		
		var displayTotal = this.cartTotal;
		// quick check for -0.00
		if (this.cartTotalWithDiscount.toFixed(2) == -0.00) displayTotal = 0.00;
		totalCell.firstChild.nodeValue = "\u00A3" + displayTotal.toFixed(2);
				
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	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;
			}
		}
		
				
	}	
	//////////////////////////////////////////////////////////////////////////////////////
	function makeCheckoutStatusUpdating(){
		
		// check if a loader is present
		if (this.checkoutLoader == -1){
			// Add Loader to check out button
			var checkoutLinks = document.getElementById("registration");
			// 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);
		}

		// 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);
		}
		
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function addNewCartItem(itemCode,additionEventObj) {
			
		// 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){
	

	}
	//////////////////////////////////////////////////////////////////////////////////////
	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.7});
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function closeCartAddedConfirm(){
	
		Effect.Fade('cartAdded', {duration:0.1})
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function roundToTwoDecimals(value){
		return value.toFixed(2);
	}
	//////////////////////////////////////////////////////////////////////////////////////
	function updateCartDBComplete(value){
	
		
		// 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
		this.lgoID = false;
		this.getCartStats();

	}
	//////////////////////////////////////////////////////////////////////////////////////
	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.');
		}
		
  	}
		  	//////////////////////////////////////////////////////////////////////////////////////

}
