// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address
var serverAddress = ""; // Set via a hidden field from the form (Its different depending on live or test server
// when set to true, display detailed error messages
var showErrors = false;
// initialize the validation requests cache
var cache = new Array();
// Global indicate if there are any errors (If so the button will be disabled)
var anyErrors = false;

// 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("validate();", 10000);
	}
}

// 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;
}


// the function handles the validation for any form field
function validate(inputValue, fieldID, formname, inputValue2)
{
	// 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)
		{
			// Show loading gif
			iconShowLoading(fieldID);
			
			// encode values for safely adding them to an HTTP request query string
			inputValue 		= encodeURIComponent(inputValue);
			fieldID 		= encodeURIComponent(fieldID);
			formname 		= encodeURIComponent(formname);
			inputValue2		= encodeURIComponent(inputValue2);	// InputValue2 is to compare fore example two passwords that need to be the same
			
			// add the values to the queue
			cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID + "&form=" + formname + "&inputValue2=" + inputValue2);
		}
		// 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();
				// Get server address from hidden field (Instead of using constants)
				serverAddress = document.getElementById('ServerAddress').value;

				// make a server request to validate the extracted data
				xmlHttp.open("POST", serverAddress + "/validate.php", true);
				
				xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp.onreadystatechange = handleRequestStateChange;
				// Send post data (inputValue, fieldid etc)
				xmlHttp.send(cacheEntry);
			}
		}
		catch (e)
		{
			iconHide(fieldID);
			// display an error when failing to connect to the server
			displayError(e.toString());
		}
	}
}

// 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); // Uncomment this to see critical data for debugging!
	
	// 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;

	result 		= xmlDoc.getElementsByTagName("result")[0].firstChild.data;
	msg		 	= xmlDoc.getElementsByTagName("msg")[0].firstChild.data;
	fieldID 	= xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;
	
	// Set global error variable (To enable/disable submit button)
	// Not using this yet
	//anyErrors   = anyErrors & result == '0'; 
	
	// Update submit button
	//updateSubmitButton(anyErrors);
	
	// find the HTML element that displays the error
	label = document.getElementById(fieldID + "Failed");
	// show the error or hide the error
	label.className = (result == "0") ? "formFieldError" : "formFieldHidden";
	label.innerHTML = msg;
	
	// Find the input field and change the background color
	field = document.getElementById(fieldID);
	//field.style.background = (result == "0") ? "#fff6bf" : "";
	field.style.background = (result == "0") ? "#fff6bf" : "#FFFFFF";
	
	// Show status gif
	if (result == "0")
		iconShowFail(fieldID);
	else
		iconShowOk(fieldID);

	// call validate() again, in case there are values left in the cache
	setTimeout("validate();", 500);
}

// Change status icon to hidden
function iconHide(fieldID)
{
	loadinggif = document.getElementById(fieldID + "Loading");
	loadinggif.className = 'AJAXIconHide';	
}

// Show loading icon
function iconShowLoading(fieldID)
{
	loadinggif = document.getElementById(fieldID + "Loading");
	loadinggif.src = serverAddress + "/pics/ajax-loader-small.gif";
	loadinggif.className = 'AJAXIconShow';	
}

// Show okay icon
function iconShowOk(fieldID)
{
	loadinggif = document.getElementById(fieldID + "Loading");
	loadinggif.src = serverAddress + "/pics/checked-yes.gif";
	loadinggif.title	= "Information is valid.";
	loadinggif.className = 'AJAXIconShow';	
}

// Show okay icon
function iconShowFail(fieldID)
{
	loadinggif = document.getElementById(fieldID + "Loading");
	loadinggif.src 		= serverAddress + "/pics/checked-no.gif";
	loadinggif.title	= "Invalid entry. Please check information on the right to correct";
	loadinggif.className = 'AJAXIconShow';	
}

// Clean up zipcode
function cleanUpZip(fieldID)
{
	field = document.getElementById(fieldID);
	field.value = field.value.replace(" ", "");
	field.value = field.value.replace("-", "");
	field.value = field.value.toUpperCase();
}

// Enable/Disable submit button
function updateSubmitButton(state)
{
	field = document.getElementById("SubmitBtn");
	
	if (state)
	{
		field.src = serverAddress + "/pics/submit-small.gif";
	}
	else
	{
		field.src = serverAddress + "/pics/submit-small-disabled.gif";
	}
}

// Other javascript methods ------------------------------------------------------------
// Is used for the loginform to force submit on enter in password field
function logonOnEnter(myfield,e)
{
	var keycode;
	if (window.event) 
		keycode = window.event.keyCode;
	else 
	if (e) 
		keycode = e.which;
	else 
		return true;

	if (keycode == 13)
   	{
   		myfield.form.submit();
   		return false;
   	}
	else
   		return true;
}

// Validate find listing per id
function validateFindListingPerId()
{
	/*
	error = '';
	
	if (document.FindListingPerId.Apt.value == "" || !isNaN(document.FindListingPerId.Apt.value))
		error = "Listing can only be a number";

	if (error)
		alert(error)
	else
	{
		//document.findListingPerId.submit();
		window.location = "../../apartment/index.php?apt=" + FindListingPerId.Apt.value;
	}
	*/
	window.location = "../../apartment/index.php?apt=" + FindListingPerId.Apt.value;
}

// Marks a hidden field that any of the address fields (Address, City, ZipCode, Province) has been modifying to indicate the we need to get the new lat/long from GMaps
function addressModified()
{
	document.ManagerApartment.Addressupdated.value = 1
}

// Confirms if user wants to delete apartment
function deleteApartment(redirectLink) 
{
	if (window.confirm("This will delete your apartment and listing.\n\nIf you found a tenant it is enough to unlist your apartment so that you have your information for next time its vacant\n\nAre you sure you wish to delete this?"))
	{
		 window.location=redirectLink;
	}
}

// Confirms if user wants to delete tenant
function deleteTenant(redirectLink) 
{
	if (window.confirm("This will delete your tenant.\n\nAre you sure you wish to do this?"))
	{
		 window.location=redirectLink;
	}
}
// sets focus on the first field of the form
/*
function setFocus()
{
	document.getElementById("txtUsername").focus();
}
*/