// 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();
	} 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 returned 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, asynchronousRequest) {
	// First create our request object
	var currentRequest = createGenericXMLRequest();
	// Check asynchronousRequest is a suitable value otherwise set it to default [true]
	if (asynchronousRequest!=true||asynchronousRequest!=false) { 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;
					// Here we work out where the section we want starts and return 
					// an integer marking its beginning.
					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'
						var myNewSection = resultingDocument.substring(startPosition,endPosition);
					} else {
						var myNewSection = resultingDocument.substring(startPosition);
					}
					if (document.getElementById) {
						var documentContentElement = document.getElementById('maincontent');
					} else {
						var documentContentElement = document.all['maincontent'];
					}
					documentContentElement.innerHTML = myNewSection;
				} 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('<!-- main content start -->');
}

// 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('<!-- main content end -->');
}

// 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 {
					document.getElementById('error').innerHTML = currentRequest.status;
				}
			} else {
				document.getElementById('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);
}
