// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address 
var serverAddress = "rbajax_validate.php";
// when set to true, display detailed error messages
var showErrors = true;
// initialize the validation requests cache 
var cache = new Array();
var select_ID ="";
// 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 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) {} // ignore potential error
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
	{
		displayError("Error creating the XMLHttpRequest object.");
	}
	else 
	{
		return xmlHttp;
	}
}

// function that displays an error message
function displayError($message)
{
	// ignore errors if showErrors is false
	if (showErrors)
	{
		// turn error displaying Off
		showErrors = false;
		// display error message
 
		alert("Error encountered: \n" + $message);
		// retry validation after 10 seconds
		setTimeout("ajax_validate();", 10000);
	}
}

// the function handles the validation for any form field
function ajax_validate(inputValue, fieldID,inputValue2, fieldID2)
{
	inputValue = trim(inputValue);
	fieldID = trim(fieldID);

	inputValue2 = trim(inputValue2);
	fieldID2 = trim(fieldID2);

		 // alert("inputValue=" + inputValue + "&fieldID=" + fieldID);
	// only continue if xmlHttp isn't void
	if (xmlHttp)
	{
		// if we received 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 != undefined && inputValue != undefined && inputValue != "")
		{
		  // encode values for safely adding them to an HTTP request query string
		  inputValue = encodeURIComponent(inputValue);
		  fieldID = encodeURIComponent(fieldID);
		  // add the values to the queue
		  
		  //alert("inputValue=" + inputValue + "&fieldID=" + fieldID + "&inputValue2=" + inputValue2 + "&fieldID2=" + fieldID2);
		  cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID + "&inputValue2=" + inputValue2 + "&fieldID2=" + fieldID2);
		}
		// try to connect to the server
		try
		{
		  // continue only if the XMLHttpRequest object isn't busy
		  // and the cache is not empty
		  if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) 
		     && cache.length > 0)
		  {
		    // get a new set of parameters from the cache
		    var cacheEntry = cache.shift();
		    //alert(cacheEntry);
		    // make a server request to validate the extracted data
		    xmlHttp.open("POST", serverAddress, true);
		    xmlHttp.setRequestHeader("Content-Type", 
		                             "application/x-www-form-urlencoded");
		    xmlHttp.onreadystatechange = handleRequestStateChange;
		    xmlHttp.send(cacheEntry);
		  }
		}
		catch (e)
		{
		  // display an error when failing to connect to the server
		  displayError(e.toString());
		}
		select_ID = fieldID2;
	}
}

// function that handles the HTTP response
function handleRequestStateChange() 
{
	// when readyState is 4, we read the server response
	if (xmlHttp.readyState == 4) 
	{
		// continue only if HTTP status is "OK"
		if (xmlHttp.status == 200) 
		{
		  try
		  {
		    // read the response from the server
		    readResponse();
		  }
		  catch(e)
 
		  {
		    // display error message
		    displayError(e.toString());
		  }
		}
		else
		{
		  // display error message
		  displayError(xmlHttp.statusText);
		}
	}
}

// read server's response 
function readResponse()
{
	// retrieve the server's response 
	var response = xmlHttp.responseText;
	//alert(response);
	var key;
	// server error?
	if (response.indexOf("ERRNO") >= 0 
		  || response.indexOf("error:") >= 0
		  || response.length == 0)
		throw(response.length == 0 ? "Server error." : response);
	// get response in XML format (assume the response is valid XML)
	responseXml = xmlHttp.responseXML;
	// get the document element
	xmlDoc = responseXml.documentElement;
	//fieldID = xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;
	key = "fieldid";
	fieldID = get_from_XML(xmlDoc,key);
	var fieldID2 = fieldID ;
	fieldID2 = fieldID2.replace("PostKey","Postcode");
	//alert(fieldID + " " + fieldID2);

	key="postcode";
	postcode = get_from_XML(xmlDoc,key)
	Set_Value(fieldID2,postcode);

//	address = xmlDoc.getElementsByTagName("address")[0].firstChild.data;
	key="message";
	//server_message = xmlDoc.getElementsByTagName("message")[0].firstChild.data;
	//alert(key);
	server_message = get_from_XML(xmlDoc,key);
	//alert(server_message);
	//result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
	key="result";
	result = get_from_XML(xmlDoc,key)
	if (xmlDoc.getElementsByTagName("addresses")[0].firstChild != undefined)
	{
		//addresses = xmlDoc.getElementsByTagName("addresses")[0].firstChild.data;
		//alert(addresses);
		//addresses = xmlDoc.getElementsByTagName("addresses")[0].childNodes[0].data;
		//alert(addresses);
		
		addresses = "";
		myAdds = xmlDoc.getElementsByTagName("addresses")[0].childNodes;
		
		for(i = 0; i < myAdds.length; i++) {
			addresses = addresses + myAdds[i].data;
		}
		//alert(addresses);
		Populate_Property_Selector(addresses)
	}
	else
	{
		Clear_Property_Selector(true,true);
	}
	if (xmlDoc.getElementsByTagName("postkey")[0].firstChild != undefined)
	{
		postkey = xmlDoc.getElementsByTagName("postkey")[0].firstChild.data;
	}
	//alert ("result:" + result.toString + ":");

	// find the HTML element that displays the error
	message = document.getElementById(fieldID2 + "Response");
	// show the error or hide the error
	message.className = (result == "0") ? "error" : "hidden";
//	alert(server_message);
//	server_message = server_message.replace("'","");
	message.innerHTML = server_message;
	message.className = "";
	//message.focus();
	//alert(message.className);
	// call validate() again, in case there are values left in the cache
	setTimeout("ajax_validate();", 500);
}

// sets focus on the first field of the form
function setFocus()    
{
	document.getElementById("txtUsername").focus();
}

function Populate_Property_Selector(addresses_input)
{
if (select_ID != "" && select_ID != undefined)
{
	//alert(addresses_input);
	//alert(select_ID);
	var sel = document.getElementById(select_ID);
	var addresses = new Array();
	addresses = addresses_input.split(";;");
	var addr = new Array();
	var postkey;
	var postaddress;
	var opt;
	var i;

// first remove any existing options (except the first)

	if (addresses.length == 1) // only one address returned  for the postcode
	{
		Clear_Property_Selector(false);
	}
	else
	{
		Clear_Property_Selector(true);
	}

	for (i=0;i<addresses.length;i++)
	{
		addr = addresses[i]
		if (addr.length > 5)
		{
			addr = addr.split("::");
			postkey = addr[0];
			postaddress = addr[1];
			postaddress = postaddress.replace("'","&apos;");
			//alert(postkey + ":" + postaddress);
			opt = document.createElement("OPTION");
			opt.text=postaddress;
			opt.value=postkey;
//			sel.options.add(opt);
			sel.options[sel.length] = opt;
		}
	}
	sel.disabled = false;
	sel.size  = sel.length ;

}
}
function Error_Property_Selector()
{
if (select_ID != "" && select_ID != undefined)
{
	//alert(select_ID);
	var sel = document.getElementById(select_ID);

// first remove any existing options
	Clear_Property_Selector(false);

	opt = document.createElement("OPTION");
	opt.text="________That postcode is not on our database, please try again_________";
	opt.value="";
//	sel.options.add(opt);
	sel.options[sel.length] = opt;

}
}

function Clear_Property_Selector(Addtop,error)
{
if (select_ID != "" && select_ID != undefined)
{
	var sel = document.getElementById(select_ID);
	sel.disabled = true;
// remove any existing options (except the first)
	var len = sel.options.length;
	for (i=0;i<len;i++)
	{
		sel.options[0] = null;
	}
	if (Addtop == true)
	{
		opt = document.createElement("OPTION");
		if (error == true)
		{
			opt.text="_____________________Please enter your postcode above._____________________";
		}
		else
		{
			opt.text="________________________Please select your property_________________________";
		}
		opt.value="";
//		sel.options.add(opt);
		sel.options[sel.length] = opt;

	}
}
}



function get_from_XML(xmlDoc,key)
{
	var rv = "";
	if (xmlDoc.getElementsByTagName(key)[0].firstChild != undefined)
	{
		rv = xmlDoc.getElementsByTagName(key)[0].firstChild.data;
	}
	return rv;
}

function Get_Value (id)
{
//alert(id + " " + value);
var sel = document.getElementById(id);
return sel.value;
}


function Set_Value (id, value)
{
//alert(id + " " + value);
var sel = document.getElementById(id);
sel.value = value;
}


