// This is to create a generic request object that will most if
// not all browsers. It does this by simply testing request objects
// beginning with the most popular browser. Essentially this is not
// the best method as it relies on the code failing if the user is
// not using the first browser being tested for. Thus it can take a 
// little longer than anticipated.
function createGenericXMLRequest() {
	try {
		// Test for FireFox / Mozilla Browsers First
		myRequest = new XMLHttpRequest();
		if (myRequest.overrideMimeType) {
			// set type accordingly to anticipated content type
		//http_request.overrideMimeType('text/xml');
			myRequest.overrideMimeType('text/html');
		}
	} catch (err_ff) {
		try {
			// Then new versions of IE
			myRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (err_ie1) {
			try {
				// And finally older versions of IE
				myRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err_ie2) {
				// We dont know what browser this is and no request
				// objects have been successfull as of yet. We will
				// return false and fall back here and have to use 
				// HTML functions to complete the request.
				myRequest = false;
			}	
		}
	}
	// Finally return the request that has been generated
	return myRequest;
}

// This function is used to make an AJAX call for a page and input the result into the element with
// the id='four', currently the main content section.
// Due to the way in which the shopping cart functions it is much simpler to simply request a whole page
// and then trip out the correct section of the reELECT * FROM SecureSession_200709turned page to include in our current page.
// It expects two variables, the first is the URL being requested, and the second whether or not the
// the request shoudl be made synchronously or not. This defaults to true.
function ajaxRequest(urlBeingRequested) {
	// First create our request object
	var currentRequest = createGenericXMLRequest();
	// Check asynchronousRequest is a suitable value otherwise set it to default [true]
	asynchronousRequest = true;
	// Open a connection for the request so that it can be sent when ready
	currentRequest.open('GET', urlBeingRequested, asynchronousRequest);
	// Set a function to handle the response from the server.
	currentRequest.onreadystatechange = function() 
		{
			// Check the state of the request object. When the response has been recieved the 
			// state will be increased to four. Any state other than four we handle by simply
			// displaying `loading` for the user. It is not essential to handle any other state
			// however, that is entirely optional.
			if (currentRequest.readyState == 4) {
				// Here we check the status of the request. This is the HTML standard status
				// so 200 is the desired outcome as it means the request is ok. Examples of
				// states include 404 page not found ect..
				if (currentRequest.status == 200) {
					// Now we fetch the reponse as text and store it in a variable
					var resultingDocument = currentRequest.responseText;
					alert(resultingDocument);
				} else {
					// Here the response was not correct thus we fall over to the server side
					// protection. This will occur only if the HTML status is not ok and in
					// many situations will result in the user being taken to an error page.
					window.location(urlBeingRequested);
				}
			} else {
				// Here the request is still being processed so we will simply display 'loading'
				// To the user to that they know what is happening.
				//document.getElementById('four').innerHTML = 'Loading . . . ';
			}
		};
	// With the function defined we can proceed to sending the request and waiting for the response.
	//ajaxLog('2', 'POST', 'pageurl=' + urlBeingRequested);
	currentRequest.send(null)
}

function logForm(formNameToGet, eventID) {
	var variablesToPass = 'formname=' + formNameToGet;
	myForm = document.forms[formNameToGet];
	myFormElements = myForm.elements;
	numberOfElements = myFormElements.length -1;
	
	for (var i = 0; i < numberOfElements; i++) {
		variablesToPass += "&" + myFormElements[i].name + "=" + myFormElements[i].value;
	}
	if (!eventID) { eventID='3'; }

	ajaxLog(eventID, 'POST', variablesToPass, formNameToGet);
}

function ajaxLog(eventID, methodOfRequest, variablesToPass, formToSubmit) {
	var logRequest = createGenericXMLRequest();

	var urlToRequest = '/ajaxScripts/ajaxLogging.php';

	variablesToPass += "&eventid=" + eventID;
	if (methodOfRequest=='GET') {
		urlToRequest += "?" + variablesToPass;
		logRequest.open(methodOfRequest, urlToRequest, true);
	} else {
		logRequest.open(methodOfRequest, urlToRequest, true);
		logRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		logRequest.setRequestHeader("Content-length", variablesToPass.length);
		logRequest.setRequestHeader("Connection", "close");
	}

	logRequest.onreadystatechange = function() 
		{
			if (logRequest.readyState == 4) {
				if (logRequest.status == 200) {
					//alert(logRequest.responseText);
					if (formToSubmit) {
						document.forms[formToSubmit].submit();
					}
				} else {
					alert(logRequest.status);
				}
			}
		};
	if (methodOfRequest=='POST') {
		logRequest.send(variablesToPass);	
	} else {
		logRequest.send();
	}
}

// This function finds the start of the section we are interested in and returns its index as an integer
function findStartSection(resultingDocument) {
	return resultingDocument.indexOf("<!-- START TOTAL AREA -->");
}

// This function finds the end of the section we are interested in and returns its index as an integer
function findEndSection(resultingDocument) {
	return resultingDocument.indexOf("<!-- END TOTAL AREA -->");
}

// This function is called to check the users shopping cart before they are allowed to proceed to the
// billing and order completion. This is used to ensure that the user does not cheat the system by
// opening other tabs to continue shopping.
function checkCart(urlBeingRequested) {
	// First we get the number of items by reading a hidden field on the document
	var numberOfItems = document.getElementsByName('item_count').length;
	// Next we set the post variables that will be sent with the request. This includes the action
	// we want to take (checkCart) as well as all of the information about the items in the cart.
	var postVariables = "action=checkCart";
	postVariables += "&count=" + numberOfItems;
	for (itemCount=1;itemCount<=numberOfItems;itemCount++) {
		// Populate the post variables with the informaiton we want about the items
		postVariables += "&item" + itemCount + "=" + document.getElementsByName('sku' + itemCount)[0].value + ":" + document.getElementsByName('unit_price' + itemCount)[0].value + ":" + document.getElementsByName('qty' + itemCount)[0].value;
	}

	// First create our request object
	var currentRequest = createGenericXMLRequest();

	// Open the request so that we can get ready to use it
	currentRequest.open('POST', '/ajaxScripts/ajaxCheckCart.php', true);

	//Send the proper header information along with the request
	currentRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	currentRequest.setRequestHeader("Content-length", postVariables.length);
	currentRequest.setRequestHeader("Connection", "close");

	// Create the function that will handle the response to the request
	currentRequest.onreadystatechange = function() 
		{
			// When the requests state has been updated to complete (four) we can proceed to handle the
			// event with the response. Until we get ready state four we display an info message
			// that informs the user that the request is being processed.
			if (currentRequest.readyState == 4) {
				// We can now check the status of the request and if it is ok (200) we can 
				// proceed with its response. If we get anything other than 200 we have encountered
				// and error and need to act accordingly
				if (currentRequest.status == 200) {
					// First we store the response in a variable
					var resultingDocument = currentRequest.responseText;
					// Next we check to see if it is simply success
					if (resultingDocument=='Success') {
						// It was a success so we can now send the user on their way to
						// the checkout.
						ajaxLog('10', 'POST', "None=Post");
						window.location = urlBeingRequested;
					} else {
						// Here the response did not indicate success thus we need to
						// refresh the cart so that the correct information is being shown
						// and alert the user as to the problem.
						ajaxRequest('index.php?mode=show_cart', true);
						ajaxLog('1', 'POST', postVariables);
						alert(resultingDocument);
					}
				} else {
					if (document.getElementById) {
						document.getElementById('error').innerHTML = currentRequest.status;
					} else {
						document.all['error'].innerHTML = currentRequest.status;
					}
				}
			} else {
				if (document.getElementById) {
					document.getElementById('error').innerHTML = 'Checking Cart Details ...';
				} else {
					document.all['error'].innerHTML = 'Checking Cart Details ...';
				}
			}
		};
//	alert(postVariables);
	// And finally send the request with the post variables that were defined.
	ajaxLog('0', 'POST', postVariables);
	currentRequest.send(postVariables);
}

function updateShoppingCart() {
	urlToRequest = '/cart/';

	var allMyElements = document.showcart.elements;
	var numberOfItems = allMyElements.length;
	postVariables = "mode=mod_cart";
	for (itemCount=1;itemCount<=numberOfItems-1;itemCount++) {
		// Populate the post variables with the informaiton we want about the items
		if (allMyElements[itemCount].name!='mode') {
			postVariables += "&" + allMyElements[itemCount].name + "=" + allMyElements[itemCount].value;
		}
	}
	//urlToRequest += "?" + postVariables;
	var currentRequest = createGenericXMLRequest();
	// Check asynchronousRequest is a suitable value otherwise set it to default [true]
	asynchronousRequest = true;
	// Open a connection for the request so that it can be sent when ready
	currentRequest.open('POST', urlToRequest, asynchronousRequest);
   	currentRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	// Set a function to handle the response from the server.
	currentRequest.onreadystatechange = function() 
		{
			// Check the state of the request object. When the response has been recieved the 
			// state will be increased to four. Any state other than four we handle by simply
			// displaying `loading` for the user. It is not essential to handle any other state
			// however, that is entirely optional.
			if (currentRequest.readyState == 4) {
				// Here we check the status of the request. This is the HTML standard status
				// so 200 is the desired outcome as it means the request is ok. Examples of
				// states include 404 page not found ect..
				if (currentRequest.status == 200) {
					resultingDocument = currentRequest.responseText;
					var startPosition = findStartSection(resultingDocument);
					// And then the same for the finishing point.
					var endPosition = findEndSection(resultingDocument);
					// We check to see whether an end position was found and act accordingly
					if (endPosition!=-1) { 
						// Insert the section of the response we want into the element
						// with an id='4'
						resultingDocument = resultingDocument.substring(startPosition,endPosition);
					} else {
						resultingDocument = resultingDocument.substring(startPosition);
					}
					updateCartLineIds(resultingDocument);
					if (document.getElementById) {
						document.getElementById('test').innerHTML = resultingDocument;
					} else {
						document.all['test'].innerHTML = resultingDocument;
					}
					//refreshButtons();
				} else {
					alert("Error: " + currentRequest.status);
				}
			}
		};
	// With the function defined we can proceed to sending the request and waiting for the response.
	//ajaxLog('2', 'POST', 'pageurl=' + urlBeingRequested);
	currentRequest.send(postVariables)
}

function updateCartLineIds(newDocument) {
	numberOfItems = document.getElementsByName('count').length;
	for (itemsInShop=1;itemsInShop<=numberOfItems;itemsInShop++) {
		startText = "<!-- cartlineid" + itemsInShop;
		endText = "cartlineid" + itemsInShop + " -->";
		startPos = newDocument.indexOf(startText) + 18;
		endPos = newDocument.indexOf(endText) -1;
		if (endPos!=-2 && startPos!=17) {
			myValue = newDocument.substring(startPos,endPos);
			document.forms[0].elements['cartlineid' + itemsInShop].value = myValue;
		}
	}
}

function updateOnChange() {
	updateShoppingCart();
	productInformation = '';
	totalCostOverall = 0;
	myElementCount = document.getElementsByName('count').length;
	for (itemCount=1;itemCount<=myElementCount;itemCount++) {
		myNewTotalPrice = document.getElementsByName('qty' + itemCount)[0].value * document.getElementsByName('price' + itemCount)[0].value;
		totalCostOverall += myNewTotalPrice;
		myNewTotalPrice = document.getElementById('currency').value + roundNumber(myNewTotalPrice, 2);
		document.getElementById('totalPrice' + itemCount).innerHTML = myNewTotalPrice;
		if (document.getElementsByName('qty' + itemCount)[0].value>=1) {
			productInformation += "<p class='miniTitle'>" + document.getElementsByName('product' + itemCount)[0].value + "</p><p>";
			productInformation += "Quantity: " + document.getElementsByName('qty' + itemCount)[0].value + "<br />";
			productInformation += "Cost: " + myNewTotalPrice + "</p>";
		}
	}
	//document.getElementById('miniProduct').innerHTML = productInformation + "<hr />";
	//document.getElementById('miniSubTotal').innerHTML = '<p style="text-align: center;"><b>Sub Total: $' + roundNumber(totalCostOverall, 2) + "</b></p>";
}

function showMiniCart(idToHeight, enabled) {
	//document.getElementById('minicart').style.height = 'Auto';
	//document.getElementById('showMini').style.height = '0px';
}

function hideMiniCart(idToHeight, enabled) {
	//document.getElementById('minicart').style.height = '0px';
	//document.getElementById('showMini').style.height = 'Auto';
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	var myParts = String(result).split('.');
	if (myParts.length==1) {
		return result + '.00';
	} else {
		var myDecimals = String(myParts[1]);
		if (myDecimals.length==1) {
			return result + "0";
		} else {
			return result;
		}
	}
}

function refreshButtons() {
	urlToRequest = '/cart/';
	var allMyElements = document.showcart.elements;
	var numberOfItems = allMyElements.length;
	postVariables = "mode=show_cart";
	for (itemCount=1;itemCount<=numberOfItems-1;itemCount++) {
		// Populate the post variables with the informaiton we want about the items
		if (allMyElements[itemCount].type == 'select-one') {
			postVariables += "&" + allMyElements[itemCount].name + "=" + allMyElements[itemCount].value;
		} else {
			postVariables += "&" + allMyElements[itemCount].name + "=" + allMyElements[itemCount].value;
		}
	}
	//urlToRequest += "?" + postVariables;
	var currentRequest = createGenericXMLRequest();
	// Check asynchronousRequest is a suitable value otherwise set it to default [true]
	asynchronousRequest = true;
	// Open a connection for the request so that it can be sent when ready
	currentRequest.open('POST', urlToRequest, asynchronousRequest);
   	currentRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	// Set a function to handle the response from the server.
	currentRequest.onreadystatechange = function() 
		{
			// Check the state of the request object. When the response has been recieved the 
			// state will be increased to four. Any state other than four we handle by simply
			// displaying `loading` for the user. It is not essential to handle any other state
			// however, that is entirely optional.
			if (currentRequest.readyState == 4) {
				// Here we check the status of the request. This is the HTML standard status
				// so 200 is the desired outcome as it means the request is ok. Examples of
				// states include 404 page not found ect..
				if (currentRequest.status == 200) {
					resultingDocument = currentRequest.responseText;
					var startPosition = resultingDocument.indexOf('<!-- START OF BUTTONS -->');
					// And then the same for the finishing point.
					var endPosition = resultingDocument.indexOf('<!-- END OF BUTTONS -->');
					// We check to see whether an end position was found and act accordingly
					if (endPosition!=-1) { 
						// Insert the section of the response we want into the element
						// with an id='4'
						var myNewSection = resultingDocument.substring(startPosition,endPosition);
					} else {
						var myNewSection = resultingDocument.substring(startPosition);
					}
					if (document.getElementById) {
						var documentContentElement = document.getElementById('buttons');
					} else {
						var documentContentElement = document.all['buttons'];
					}
					documentContentElement.innerHTML = myNewSection;
				} else {
					alert("Error: " + currentRequest.status);
				}
			}
		};
	// With the function defined we can proceed to sending the request and waiting for the response.
	//ajaxLog('2', 'POST', 'pageurl=' + urlBeingRequested);
	currentRequest.send(postVariables)
	puffProductColumns()
}

function roundMoney(numberToRound, dec) {
	numberToRound += "";
	try {
		var mySplitResult = numberToRound.split(".");
	} catch (err_ie1) {
		return false;
	}
	alert(mySplitResult[1].length);
	if (mySplitResult.length==1) {
		numberToRound += ".00";
		return numberToRound;
	} else {
		if (mySplitResult[1].length=1) {
			numberToRound += "0";
			return numberToRound;
		} else {
			return Math.round(numberToRound*Math.pow(10,dec))/Math.pow(10,dec);
		}
	}
}

function puffProductColumns() {
	var myRequiredHeight = 0;
	var numberOfItems = document.getElementsByName('tot_i')[0].length;
	for (itemCount=1;itemCount<=numberOfItems;itemCount++) {
		myHeight = document.getElementsByName('productrow' + itemCount).offsetHeight;
		if (myHeight>myRequiredHeight) {
			myRequiredHeight = myHeight;
		}
	}
	//alert(myRequiredHeight);
	for (itemCount=1;itemCount<=numberOfItems;itemCount++) {
		document.getElementsByName('productrow' + itemCount).style.height = myRequiredHeight + 'px';
	}
}

function enlargeImage(imageSrc) {
		
}

function displayExtraInformation(informationToDisplay) {
	
}
