// holds an instance of XMLHttpRequest
var formXmlHttp = createFormXmlHttpRequestObject();
// 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 cacheForm = 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("recalc();", 10000);
	}
}

// creates an XMLHttpRequest instance
function createFormXmlHttpRequestObject()
{
	// will store the reference to the XMLHttpRequest object
	var formXmlHttp;
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		formXmlHttp = 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 && !formXmlHttp; i++)
		{
			try
			{
				// try to create XMLHttpRequest object
				formXmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e) {} // ignore potential error
		}
	}

	// return the created object or display an error message
	if (!formXmlHttp)
		displayError("Error creating the XMLHttpRequest object.");
	else
		return formXmlHttp;
}


// The function handles the retrieval of Tenants names based on the Apartment
function updateNames(apartmentid, includeEmpty)
{
	//alert(apartmentId);
	// only continue if formXmlHttp isn't void
	if (formXmlHttp)
	{
		// 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 (apartmentid)
		{
			// Show loading gif
			//formIconShowLoading();
			showLoading("ApartmentIdLoading");

			// encode values for safely adding them to an HTTP request query string
			apartmentid	= encodeURIComponent(apartmentid);

			// add the values to the queue
			cacheForm.push("ApartmentId=" + apartmentid);
		}
		// try to connect to the server
		try
		{
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((formXmlHttp.readyState == 4 || formXmlHttp.readyState == 0) && cacheForm.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheFormEntry = cacheForm.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
				formXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerForm.php?mode=updatenames&includeEmpty=" + includeEmpty, true);

				formXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				formXmlHttp.onreadystatechange = handleUpdateNames;
				// Send post data (inputValue, fieldid etc)
				formXmlHttp.send(cacheFormEntry);
			}
		}
		catch (e)
		{
			hideLoading("ApartmentIdLoading");
			// display an error when failing to connect to the server
			displayError(e.toString());
		}
		document.getElementById("ApartmentId").focus();
	}
}

// function that handles the HTTP response
function handleUpdateNames()
{
	// when readyState is 4, we read the server response
	if (formXmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (formXmlHttp.status == 200)
		{
			try
			{
				// read the response from the server
				readUpdateNamesResponse();
			}
			catch(e)
			{
				// display error message
				displayError(e.toString());
			}
		}
		else
		{
			// display error message
			displayError(formXmlHttp.statusText);
		}
	}
}

// read server's response
function readUpdateNamesResponse()
{
	// retrieve the server's response
	var response = formXmlHttp.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 = formXmlHttp.responseXML;

	// get the document element
	xmlDoc = responseXml.documentElement;

	nameArray = new Array();

	if (xmlDoc.childNodes.length)
	{
		nameArray = xmlToArray(xmlDoc.getElementsByTagName('tenant'));
	}

	updateSelectField(nameArray);

	// Set Address field
	document.getElementById("RentalAddress").value = xmlDoc.getElementsByTagName("address")[0].firstChild.data;
	document.getElementById("RentalCity").value = xmlDoc.getElementsByTagName("city")[0].firstChild.data;
	document.getElementById("RentalZipCode").value = xmlDoc.getElementsByTagName("zipcode")[0].firstChild.data;
	document.getElementById("RentalProvince").value = xmlDoc.getElementsByTagName("province")[0].firstChild.data;

	// Set tenant name as well (The first one in the TenantName select field is auto-selected
	document.getElementById("TenantName").value = xmlDoc.getElementsByTagName("name")[0].firstChild.data;

	// Set Rent (If the field exists)
	if (document.getElementById("RentFrom"))
	{
		document.getElementById("RentFrom").value = xmlDoc.getElementsByTagName("rent")[0].firstChild.data;

		// Force the OnChange event to update other rent fields (If any)
		document.getElementById("RentFrom").onchange();
	}

	hideLoading("ApartmentIdLoading");

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

// Updates fields
function updateSelectField(tenants)
{
	// Get select field
	field = document.getElementById('TenantId');

	if (field)
	{
		// Remove all existing elements
		for (i = 0; i <= field.options.length; i++)
		{
			field.remove(i);
		}
		field.options.length = 0;

		for (i = 0; i < tenants.length; i++)
		{
			var newElement = document.createElement('option');
			var oldElement = field.options[i];

			// The data is in the format: [tenantid]|[Name]. Split it up.
			// This doesn't work in IE so I'm replacing it with an Array instead which works
			//[key,value] = tenants[i].split("/");
			//newElement.text = value;
			//newElement.value = key;
			aArray = tenants[i].split("/");
			newElement.text = aArray[1];
			newElement.value = aArray[0];

			// IE sucks as usual. This is a work-around
			try
			{
				field.add(newElement,oldElement); // Standard compliant. Doesn't work in IE
			}
			catch (ex)
			{
				field.add(newElement,field.selectedIndex);
			}

			// If its the first then update the other information as well since it will be the one selected per default
			if (i == 0)
			{
				selectedTenant = aArray[0];
			}
		}
		// Update help text
		helpfield = document.getElementById('NoTenantHelp');
		helpfield.innerHTML = tenants.length > 0 ? "Please select a tenant" : "There's no current tenant assigned to this apartment. You can <a href='/manager/tenant/add/'>create one here</a>.";
	} // if (field)
}

// This is used for the AJAX Get Tenant Call. It will convert the xml into an array of Tenants
function xmlToArray(resultsXml)
{
	// Initiate the resultsArray
	var resultsArray = new Array();
	// Iterate through the xml nodes retrieving the data
	for (i = 0; i < resultsXml.length; i++)
	{
		resultsArray[i] = resultsXml.item(i).firstChild.data;
	}
	return resultsArray;
}

// The function handles the retrieval of Tenants names based on the Tenant
function updateTenant(tenantId)
{
	// only continue if formXmlHttp isn't void
	if (formXmlHttp)
	{
		// 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 (tenantId)
		{
			// Show loading gif
			//formIconShowLoading();
			showLoading("TenantIdLoading");

			// encode values for safely adding them to an HTTP request query string
			tenantId	= encodeURIComponent(tenantId);

			// add the values to the queue
			cacheForm.push("TenantId=" + tenantId);
		}
		// try to connect to the server
		try
		{
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((formXmlHttp.readyState == 4 || formXmlHttp.readyState == 0) && cacheForm.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheFormEntry = cacheForm.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
				formXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerForm.php?mode=updatetenant", true);

				formXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				formXmlHttp.onreadystatechange = handleUpdateTenant;
				// Send post data (inputValue, fieldid etc)
				formXmlHttp.send(cacheFormEntry);
			}
		}
		catch (e)
		{
			hideLoading("TenantIdLoading");
			// display an error when failing to connect to the server
			displayError(e.toString());
		}
		document.getElementById("TenantId").focus();
	}
}

// function that handles the HTTP response
function handleUpdateTenant()
{
	// when readyState is 4, we read the server response
	if (formXmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (formXmlHttp.status == 200)
		{
			try
			{
				// read the response from the server
				readUpdateTenantResponse();
			}
			catch(e)
			{
				// display error message
				displayError(e.toString());
			}
		}
		else
		{
			// display error message
			displayError(formXmlHttp.statusText);
		}
	}
}

// read server's response
function readUpdateTenantResponse()
{
	// retrieve the server's response
	var response = formXmlHttp.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 = formXmlHttp.responseXML;

	// get the document element
	xmlDoc = responseXml.documentElement;

	nameArray = new Array();

	// Set Tenant fields
	document.getElementById("TenantName").value = xmlDoc.getElementsByTagName("name")[0].firstChild.data;

	hideLoading("TenantIdLoading");

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

// function that handles the HTTP response
function handleUpdateGoverningLaw()
{
	// when readyState is 4, we read the server response
	if (formXmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (formXmlHttp.status == 200)
		{
			try
			{
				// read the response from the server
				readUpdateGoverningLaw();
			}
			catch(e)
			{
				// display error message
				displayError(e.toString());
			}
		}
		else
		{
			// display error message
			displayError(formXmlHttp.statusText);
		}
	}
}

// read server's response
function readUpdateGoverningLaw()
{
	// retrieve the server's response
	var response = formXmlHttp.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 = formXmlHttp.responseXML;

	// get the document element
	xmlDoc = responseXml.documentElement;

	// Set Governing Law description
	document.getElementById("GoverningLaw").innerHTML = xmlDoc.getElementsByTagName("description")[0].firstChild.data;

	hideLoading("RentalProvinceLoading");

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

// Updates the law description based on the province --------------------------------------
function updateGoverningLawDescription(province)
{
	// only continue if formXmlHttp isn't void
	if (formXmlHttp)
	{
		// 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 (province)
		{
			// Show loading gif
			//formIconShowLoading();
			showLoading("RentalProvinceLoading");

			// encode values for safely adding them to an HTTP request query string
			province	= encodeURIComponent(province);

			// add the values to the queue
			cacheForm.push("RentalProvince=" + province);
		}
		// try to connect to the server
		try
		{
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((formXmlHttp.readyState == 4 || formXmlHttp.readyState == 0) && cacheForm.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheFormEntry = cacheForm.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
				formXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerForm.php?mode=updateGoverningLaw", true);

				formXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				formXmlHttp.onreadystatechange = handleUpdateGoverningLaw;
				// Send post data (inputValue, fieldid etc)
				formXmlHttp.send(cacheFormEntry);
			}
		}
		catch (e)
		{
			hideLoading("RentalProvinceLoading");
			// display an error when failing to connect to the server
			displayError(e.toString());
		}
		//document.getElementById("TenantId").focus();
	}
}

/* ------------------------- Updating Pct, Rent Increase Field and New Rent (Used by Rent Increase) ---------------------------------- */

// Shows Loading
function showLoading(field)
{
	loadinggif = document.getElementById(field);
	loadinggif.src = serverAddress + "/pics/ajax-loader-small-blank.gif";
}

// Hide Loading
function hideLoading(field)
{
	loadinggif = document.getElementById(field);
	loadinggif.src = serverAddress + "/pics/ajax-loader-small-blank.gif";
}
