// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address and parameters
var serverAddress = "validate.php";
var showErrors = true; // display detailed error messages
var cache = new Array();

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
	// will store the reference to the XMLHttpRequest object
	var xmlHttp;
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		// assume IE6 or older
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
										"MSXML2.XMLHTTP.5.0",
										"MSXML2.XMLHTTP.4.0",
										"MSXML2.XMLHTTP.3.0",
										"MSXML2.XMLHTTP",
										"Microsoft.XMLHTTP");
		// try every prog id until one works
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
		{
			try
			{
				// try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e) {}
		}
	}
	if (!xmlHttp)
		displayError("Error creating the XMLHttpRequest object");
	else
		return xmlHttp;
}

//function that displays an error message
function displayError($message)
{
	// display error message, with more technical details if showErrors is true
	if (showErrors)
	{
		showErrors = false;
		alert("Error encountered: \n" + $message);
		setTimeout("validate();", 10000);
	}
}

// function that handles validation for any form field
function validate(inputValue, fieldID)
{
	// only continue if xmlHttp isn't void
	if (xmlHttp)
	{
		// if we receive non-null parameters we add them to cache in the form of the query string to be sent to the server for validation
		if (fieldID)
		{
			// encode values for safely adding them to an http request query string
			inputValue = encodeURIComponent(inputValue);
			fieldID = encodeURIComponent(fieldID);
			// add the values to the queue
			cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);
		}

		// try to connect to the server
		try
		{
			if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheEntry = cache.shift();
				// make a server request to validate the data
				xmlHttp.open("POST", serverAddress, true);
				xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = handleRequestStateChange;
				xmlHttp.send(cacheEntry);
			}
		}
		catch (e)
		{
			displayError('a ' + e.toString());
		}
	}
}

// function called when the state of the HTTP request changes
function handleRequestStateChange()
{
	// when readyState is 4, we are ready to read the server response
	if (xmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (xmlHttp.status == 200)
		{
			try
			{
				// do something with the response from the server
				readResponse();
			}
			catch (e)
			{
				// display error message
				displayError('b-' + e.toString())
			}
		}
		else
		{
			// display status message
			displayError('c-' + xmlHttp.statusText);
		}
	}
}
function readResponse()
{
	// retrieve the server's response 
	var response = xmlHttp.responseText;
	// if the response is too long, or is void, assume it's an error report
	if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)
		throw(response.length == 0 ? "Server error" : response);
	responseXml = xmlHttp.responseXML;
	xmlDoc = responseXml.documentElement;
	result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
	fieldID = xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;
	message = document.getElementById(fieldID + "Failed");
	message.className = (result == "0") ? "error" : "hidden";
	setTimeout("validate();", 500);
}
function setFocus()
{
	document.getElementById("txtEmail").focus();
}