//HOlds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();

//Display error messages (true) or degrade to non-AJAX behavoir (false)
var showErrors = true;

//Contains the link or form clicked or submitted by the cisitor 
var actionObject ='';

//this is true when the place order button is clicked, false otherwise
var placingOrder = false;

//Creates the XMLHttpRequest instance
function createXmlHttpRequestObject()
{
	//will store the zmlhttprequest object
	var xmlHttp;

	//Create the XMLHttpRequest object
	try
	{
		// Try to create native XMLHttpRequest();
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		//Assume IE6 or older
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0","MSXML2.HTTP.5.0","MSXML2.HTTP.4.0","MSXML2.HTTP.3.0","MSXML2.HTTP","Microsoft.XMLHTTP");

		//try every id until one works
		for (i = 0; i < XmlHttpVersions.length && !xmlHttp; i++ )
		{
			try
			{
				//try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e)
			{
				//Ignore potential errors
			}
		}
	}

	// if the XMLHttpRequest object was created successfully, return it
	if(xmlHttp)
	{
		return xmlHttp;
	}
	else
	{
		//If an error happend, pass it to the handler
		handleError("Error creating the XMLHttpRequest object");
	}
}

//Displays the error message or degrades to non-AJAX behavior

function handleError($message) 
{
	//Ignore errors if showErrors is false
	if (showErrors)
	{
		//Display error message
		alert("Error Encountered: \n" + $message);
		return false;
	}
	//fall back to non-AJAX behavior
	else if(!actionObject.tagName) 
	{
		return true;
	}
	else if (actionObject.tagName == 'A')
	{
		window.location = actionObject.href;
	}
	else if (actionObject.tagName == 'FORM')
	{
		actionObject.submit();
	}
}

//adds song to cart
function addProductToCart (form)
{
	//display "updating" Message
	document.getElementById('Updating').style.visibility = 'visible';

	//degrade to classical form submit 
	if (!xmlHttp)
	{
		return true;
	}

	//Create the URL we open asynchronously
	request = form.action + '&AjaxRequest';
	params = '';

	// obtain selected attributes
	formSelects = form.getElementsByTagName('select');

	if (formSelects)
	{
			params += '&' + form.Format.name + '=' + form.Format.value;
	}

	//try to connect to the server
	try
	{
		//continue only if the xmlhttprequest object isnt busy
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
		{
		//Make a server request to validate the extracted data
		xmlHttp.open("POST", request, true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.onreadystatechange = addToCartStateChange;
		xmlHttp.send(params);
		}
	}
	catch (e)
	{
		//handle error
		handleError(e.toString());
	}

	//Stop slassical form submit if AJAX action succeded
	return false;
}

//function that retrieves the HTTP response
function addToCartStateChange()
{
	//when readyState is 4, we also read the server response
	if (xmlHttp.readyState == 4)
	{
		//continue if status is OK
		if (xmlHttp.status == 200)
		{
			try
			{
				updateCartSummary();
			}
			catch (e)
			{
				handleError(e.toString());
			}
		}
		else 
		{
			handleError(xmlHttp.statusText);
		}
	}
}

//process servers response
function updateCartSummary()
{

	//Read response 
	response = xmlHttp.responseText;

	//server error?
	if (response.indexOf("ERRNO") >= 0 || response.indexOf("error") >= 0)
	{
		handleError(response);
	}
	else
	{
		//Extract the contents of the cart_summary div element
		var cartSummaryRegEx = /^<div class="box" id="cart-summary">([\s\S]*)<\/div>$/m;
		matches = cartSummaryRegEx.exec(response);
		response = matches[1];

		//Update the cart summary box and hide the loading message
		document.getElementById("cart-summary").innerHTML = response;
		//Hide Updating
		document.getElementById("Updating").style.visibility = 'hidden';
	}
}

//Called on shopping cart update actions 
function executeCartAction(obj) {

	//degrade to classical form submit for place order action 
	if(placingOrder) return true;
	
	//Display "Updating" 
	document.getElementById('Updating').style.visibility = 'visible';

	//Degrade to classical form is AJAX not there
	if(!xmlHttp) return true;

	//save object ref
	actionObject = obj;

	//initalize response and parameters
	response ='';
	params = '';

	//if a link was clicked we get its href attribute
	if(obj.tagName == 'A')
	{
		url = obj.href + '&AjaxRequest';
	}
	else
	{
		url = obj.action + '&AjaxRequest';

		formElements = obj.getElementsByTagName('INPUT');

		if(formElements)
		{
			for (i=0;i<formElements.length ;i++ )
			{
				if(formElements[i].name != 'place_order')
				{
				params += '&' + formElements[i].name + '=';
				params += encodeURIComponent(formElements[i].value);
				}
			}
		}
	}


	// try and connect to the server
	try
	{
		//make server request only if the object isnt busy
		if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
		{
		//Make a server request to validate the extracted data
		xmlHttp.open("POST", url, true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.onreadystatechange = cartActionStateChange;
		xmlHttp.send(params);
		}
	}
	catch (e)
	{
		handleError(e.toString());
	}

	//Stop classical form submit if AJAX works
	return false;
}

function cartActionStateChange() {
	//When readyState is 4, we also read the server response
	if (xmlHttp.readyState == 4)
	{
		//continue if status is OK
		if (xmlHttp.status == 200)
		{
			try
			{
				//read the response
				response = xmlHttp.responseText;

				//server error?
				if (response.indexOf("ERRNO") >=0 || response.indexOf("error") >= 0)
				{
					handleError(response);
				}
				else
				{
					//update the cart 
					document.getElementById("songs").innerHTML = response;

					//hide updating
					document.getElementById("Updating").style.visibility = 'hidden';
				}
			}
			catch (e)
			{
				handleError(xmlHttp.statusText);
			}
		}
		else
		{
			handleError(xmlHttp.statusText);
		}
	}
}