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

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

var timer;

// This function is called on mouse down (The % will then update more rapidly)
function mouseDownUpdatePct(action)
{
	timer = setInterval("updatePctMouseDown('" + action + "')",250);
	//timer = setInterval("updatePctMouseDown('Plus')",100);
	//setInterval("alert('hep hey')",300);
}

function updatePctMouseDown(action)
{
	updatePct(document.ManagerFormRentIncrease.RentIncreasePct.value,document.ManagerFormRentIncrease.RentFrom.value, action, document.ManagerFormRentIncrease.RentRoundDown.checked);
}
// This function is called on mouse up (The % will then update more rapidly)
function mouseUpRelease()
{
	window.clearInterval(timer);
	//setInterval("alert('hep hey')",300);
}

// The function shows the new Pct (based on action (+/-) and recalculates the Rent Increase and New Rent)
function updatePct(pct, rent, action, roundDown)
{
	
	// only continue if formRentIncreaseXmlHttp isn't void
	if (formRentIncreaseXmlHttp)
	{
		//alert("Updating");

		// 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 (pct && rent && action)
		{
			// Show loading gif
			//formIconShowLoading();
			iconShowLoading("RentTo");

			// encode values for safely adding them to an HTTP request query string
			pct			= encodeURIComponent(pct);				// Current Pct
			action 		= encodeURIComponent(action);			// Plus / Minus
			rent 		= encodeURIComponent(rent);				// Current Rent
			roundDown	= encodeURIComponent(roundDown);		// Round Down

			// add the values to the queue
			cacheRentIncrease.push("pct=" + pct + "&action=" + action + "&rent=" + rent + "&rounddown=" + roundDown);
		}
		// try to connect to the server
		try
		{
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((formRentIncreaseXmlHttp.readyState == 4 || formRentIncreaseXmlHttp.readyState == 0) && cacheRentIncrease.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheRentIncreaseEntry = cacheRentIncrease.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
				formRentIncreaseXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerFormRentIncrease.php?mode=updatePct", true);

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

// The function shows the new Rent when a Rent Increase is manually entered
function updateRentIncrease(rent, rentIncrease, roundDown)
{
	//	alert("Updating");
	// only continue if formRentIncreaseXmlHttp isn't void
	if (formRentIncreaseXmlHttp)
	{
		// 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 (rent && rentIncrease)
		{
			// Show loading gif
			//formIconShowLoading();
			showLoading("RentToLoading");

			// encode values for safely adding them to an HTTP request query string
			rent			= encodeURIComponent(rent);				// Current Rent
			rentIncrease 	= encodeURIComponent(rentIncrease);		// Rent Increase
			roundDown		= encodeURIComponent(roundDown);		// Round Down

			// add the values to the queue
			cacheRentIncrease.push("rent=" + rent + "&rentincrease=" + rentIncrease + "&rounddown=" + roundDown);
		}
		// try to connect to the server
		try
		{
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((formRentIncreaseXmlHttp.readyState == 4 || formRentIncreaseXmlHttp.readyState == 0) && cacheRentIncrease.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheRentIncreaseEntry = cacheRentIncrease.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
				formRentIncreaseXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerFormRentIncrease.php?mode=updateRentIncrease", true);

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

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

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

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

	if (xmlDoc.getElementsByTagName("mode")[0].firstChild.data == 'updatePct')
	{
		pct				= xmlDoc.getElementsByTagName("pct")[0].firstChild.data;
		rentincrease	= xmlDoc.getElementsByTagName("rentincrease")[0].firstChild.data;
		newrent			= xmlDoc.getElementsByTagName("newrent")[0].firstChild.data;

		document.getElementById("RentIncreasePct").value		= pct;
		document.getElementById("RentIncreasePctTxt").innerHTML = pct + "%";
		document.getElementById("RentIncrease").value			= rentincrease;
		document.getElementById("RentTo").value					= newrent;
	}
	else
	if (xmlDoc.getElementsByTagName("mode")[0].firstChild.data == 'updateRentIncrease')
	{
		newrent			= xmlDoc.getElementsByTagName("newrent")[0].firstChild.data;
		pct				= xmlDoc.getElementsByTagName("pct")[0].firstChild.data;
		rentincrease	= xmlDoc.getElementsByTagName("rentincrease")[0].firstChild.data;

		document.getElementById("RentTo").value					= newrent;
		document.getElementById("RentIncrease").value			= rentincrease;
		document.getElementById("RentIncreasePct").value		= pct;
		document.getElementById("RentIncreasePctTxt").innerHTML = pct + "%";
	}
	hideLoading("RentToLoading");

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