// prepares the contact form
addLoadEvent(prepareContact);
addLoadEvent(prepareTellAFriend);

// can add multiple functions to the onload event handler
function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function()
		{
			if (oldonload) {
			oldonload();
			}
		func();
		}
	}
}

// prepares the contact form and sends the data
function prepareContact()
{
	// test for dom elements
	if(!document.getElementById) {
		return;
	}
	if(!document.getElementById("contactform")) {
		return;
	} 
	
	// hijack onsubmit and loop through values and send data
	document.getElementById("contactform").onsubmit = function() {
		var data = "";
		for (var i=0; i<this.elements.length; i++) {
				data+= this.elements[i].name;
				data+= "=";
				data+= escape(this.elements[i].value);
				data+= "&";
		}
	return !sendData(data, "includes/contact_form.inc.php");
	};
}

// prepares the tell a friend form and sends the data
function prepareTellAFriend()
{
	// test for dom elements
	if(!document.getElementById) { return; }
	if(!document.getElementById("tellafriendform")) { return; } 
	
	// hijack onsubmit and loop through values and send data
	document.getElementById("tellafriendform").onsubmit = function() {
		var data = "";
		for (var i=0; i<this.elements.length; i++) {
				data+= this.elements[i].name;
				data+= "=";
				data+= escape(this.elements[i].value);
				data+= "&";
		}
	return !sendData(data, "includes/tellafriend.inc.php");
	};
}

// sends the form data to the php script
function sendData(data, dest)
{
	var request = getHTTPObject();
	if (request)
	{
		request.onreadystatechange = function() {
			parseResponse(request);
    	};
	request.open("POST", dest, true );
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	request.send(data);
	return true;
	}
	else {
		return false;
	}
}

// parses the response from the ajax request
function parseResponse(request)
{
	if (request.readyState == 4)
	{
		if (request.status == 200 || request.status == 304)
		{
			var container = document.getElementById("contact_form");
			container.innerHTML = request.responseText;
			
			// repeat preparation
			prepareContact();
			prepareTellAFriend();
		}
	}
}

// returns a http object for ajax
function getHTTPObject()
{
	var xhr = false;
	if (window.XMLHttpRequest)
	{
		xhr = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
    	try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
    	} catch(e) {
			try {
        		xhr = new ActiveXObject("Microsoft.XMLHTTP");
      		} catch(e) {
        		xhr = false;
      		}
    	}
	}
return xhr;
}