var xmlHttp = createXmlHttpRequest();
var serverAddress = "validate.php";
var showErrors = true;
var cache = new Array();

function createXmlHttpRequest()
{
	var xmlHttp;
	
	try
	{
		xmlHttp = new XMLHttpRequest();
	}
	catch(e)
	{
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");
		
		for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
		{
			try
			{
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e)
			{}
		}
	}
	
	if (!xmlHttp) {alert("Error creating the XMLHttpRequest object.");}
	else {return xmlHttp;}
}

function displayErrors($message)
{
	if(showErrors)
	{
		showErrors = false;
		alert("Error encountered: \n" + $message);
		
		setTimeout("validate();", 100000);
	}
}

function validate(inputValue, fieldID)
{
	if(xmlHttp)
	{
		if(fieldID)
		{
			inputValue = encodeURIComponent(inputValue);
			fieldID = encodeURIComponent(fieldID);
			
			cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);
		}
		
		try
		{
			if((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0)
			{
				var cacheEntry = cache.shift();
				
				xmlHttp.open("POST", serverAddress, true);
				xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = handleRequestStateChange;
				xmlHttp.send(cacheEntry);
			}
		}
		catch(e)
		{
			displayErrors(e.toString());
		}
	}
}

function handleRequestStateChange()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			try
			{
				readResponse();
			}
			catch(e)
			{
				displayErrors(e.toString());
			}
		}
		else
		{
			displayErrors(xmlHttp.statusText);
		}
	}
}

function readResponse()
{
	var response = xmlHttp.responseText;
	
	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);
}