// holds an instance of XMLHttpRequest
var rentXmlHttp = createRentXmlHttpRequestObject();
// 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 cacheRent = 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 createRentXmlHttpRequestObject()
{
	// will store the reference to the XMLHttpRequest object
	var rentXmlHttp;
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		rentXmlHttp = 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 && !rentXmlHttp; i++)
		{
			try
			{
				// try to create XMLHttpRequest object
				rentXmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e) {} // ignore potential error
		}
	}

	// return the created object or display an error message
	if (!rentXmlHttp)
		displayError("Error creating the XMLHttpRequest object.");
	else
		return rentXmlHttp;
}


// The function handles the retrieval of Tenants names based on the Apartment
function updateNames(apartmentid, includeEmpty)
{
	// only continue if rentXmlHttp isn't void
	if (rentXmlHttp)
	{
		// 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
			//rentIconShowLoading();
			showLoading("ApartmentIdLoading");
			
			// encode values for safely adding them to an HTTP request query string
			apartmentid	= encodeURIComponent(apartmentid);
			
			// add the values to the queue
			cacheRent.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 ((rentXmlHttp.readyState == 4 || rentXmlHttp.readyState == 0) && cacheRent.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheRentEntry = cacheRent.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
				rentXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerRent.php?mode=updatenames&includeEmpty=" + includeEmpty, true);
				
				rentXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				rentXmlHttp.onreadystatechange = handleUpdateNames;
				// Send post data (inputValue, fieldid etc)
				rentXmlHttp.send(cacheRentEntry);
			}
		}
		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 (rentXmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (rentXmlHttp.status == 200)
		{
			try
			{
				// read the response from the server
				readUpdateNamesResponse();
			}
			catch(e)
			{
				// display error message
				displayError(e.toString());
			}
		}
		else
		{
			// display error message
			displayError(rentXmlHttp.statusText);
		}
	}
}

// read server's response
function readUpdateNamesResponse()
{
	// retrieve the server's response
	var response = rentXmlHttp.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 = rentXmlHttp.responseXML;

	// get the document element
	xmlDoc = responseXml.documentElement;
	
	nameArray = new Array();
	
	if (xmlDoc.childNodes.length)
	{
		nameArray = xmlToArray(xmlDoc.getElementsByTagName('tenant'));
	}

	updateSelectField(nameArray);
	
	// Set rent
	document.getElementById("Amount").value = xmlDoc.getElementsByTagName("rent")[0].firstChild.data;
	// Set Payment Type
	$paymentType = xmlDoc.getElementsByTagName("paymenttype")[0].firstChild.data;
	$eRent		 = document.getElementById("eRent").value;
	
	switch ($paymentType)
	{
		case "eRent"		:	document.getElementById("PaymentType").selectedIndex = 0;
								break;

		case "Check"		:	document.getElementById("PaymentType").selectedIndex = $eRent == '1' ? 1 : 0;
								break;

		case "Money Order"	:	document.getElementById("PaymentType").selectedIndex = $eRent == '1' ? 2 : 1;
								break;
								
		case "Cash"			:	document.getElementById("PaymentType").selectedIndex = $eRent == '1' ? 3 : 2;
								break;


	}
		
	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');
	// 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-arround
    	try
    	{
    		field.add(newElement,oldElement); // Standard compliant. Doesn't work in IE
    	}
    	catch (ex)
    	{
    		field.add(newElement,field.selectedIndex);
    	}
	}
	// 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>.";
}

// 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;
}

/* ------------------------------------------ Calculate Next Payment Date ------------------------------------------------------------------*/
// Shows next payment based on the form fields
function showNextPayment()
{
	nextPaymentInfo 	= document.getElementById("NextPaymentInfo");
	rentFrequency		= document.getElementById("RentFrequency").value;
	rentDay			= document.getElementById("RentDay").value;
	
	firstPaymentMonth	= document.getElementById("FirstPaymentMonth").value;
	firstPaymentYear	= document.getElementById("FirstPaymentYear").value;
	
	// Set Day to 1st if its Bi-Monthly and change help text based on that as well
	document.getElementById("RentDay").disabled 			= rentFrequency == 'Bi-Monthly';
	document.getElementById("RentDay").options.selectedIndex 	= rentFrequency == 'Bi-Monthly' ? 0 : document.getElementById("RentDay").options.selectedIndex;
	document.getElementById("RentFrequencyHelp").innerHTML		= rentFrequency == 'Bi-Monthly' ? "Bi-Monthly means the tenants pays the 1<sup>st</sup>, and the 15<sup>th</sup> of each month" : "Please select the rent frequency";
	
	// only continue if rentXmlHttp isn't void
	if (rentXmlHttp)
	{
		// 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 (nextPaymentInfo && rentFrequency && rentDay && firstPaymentMonth && firstPaymentYear)
		{
			// Show loading gif
			showLoading("NextPaymentInfoLoading");
			
			// encode values for safely adding them to an HTTP request query string
			rentFrequency		= encodeURIComponent(rentFrequency);
			rentDay			= encodeURIComponent(rentDay);
			firstPaymentMonth	= encodeURIComponent(firstPaymentMonth);
			firstPaymentYear	= encodeURIComponent(firstPaymentYear);
			
			// add the values to the queue
			cacheRent.push("RentFrequency=" + rentFrequency + "&RentDay=" + rentDay + "&FirstPaymentMonth=" + firstPaymentMonth + "&FirstPaymentYear=" + firstPaymentYear);
		}
		// try to connect to the server
		try
		{
			// continue only if the XMLHttpRequest object isn't busy
			// and the cache is not empty
			if ((rentXmlHttp.readyState == 4 || rentXmlHttp.readyState == 0) && cacheRent.length > 0)
			{
				// get a new set of parameters from the cache
				var cacheRentEntry = cacheRent.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
				rentXmlHttp.open("POST", serverAddress + "/includes/AJAXManagerRent.php?mode=nextpayment&", true);
				
				rentXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				rentXmlHttp.onreadystatechange = handleNextPayment;
				// Send post data (inputValue, fieldid etc)
				rentXmlHttp.send(cacheRentEntry);
			}
		}
		catch (e)
		{
			rentIconHide(fieldID);
			// display an error when failing to connect to the server
			displayError(e.toString());
		}
		document.getElementById("ApartmentId").focus();
	}
}

// function that handles the HTTP response
function handleNextPayment()
{
	// when readyState is 4, we read the server response
	if (rentXmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (rentXmlHttp.status == 200)
		{
			try
			{
				// read the response from the server
				readNextPaymentResponse();
			}
			catch(e)
			{
				// display error message
				displayError(e.toString());
			}
		}
		else
		{
			// display error message
			displayError(rentXmlHttp.statusText);
		}
	}
}

// read server's response
function readNextPaymentResponse()
{
	// retrieve the server's response
	var response = rentXmlHttp.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 = rentXmlHttp.responseXML;

	// get response in XML format (assume the response is valid XML)
	responseXml = rentXmlHttp.responseXML;

	// get the document element
	xmlDoc = responseXml.documentElement;

	//nextpayment 		= 

	document.getElementById("NextPaymentInfo").innerHTML = xmlDoc.getElementsByTagName("nextpayment")[0].firstChild.data;
	
	hideLoading("NextPaymentInfoLoading");
	
	// call recalc() again, in case there are values left in the cache
	//setTimeout("updateFields();", 500);
}



// 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";
}

/*
// Change status icon to hidden
function rentIconHide()
{
	loadinggif = document.getElementById("ApartmentIdLoading");
	loadinggif.src = serverAddress + "/pics/ajax-loader-small-blank.gif";
}

// Show loading icon
function rentIconShowLoading()
{
	loadinggif = document.getElementById("ApartmentIdLoading");
	loadinggif.src = serverAddress + "/pics/ajax-loader-small.gif";
}
*/

// Disables Account information etc if Manual Entry
function toggleeRentAccess(set)
{
	if (set)
	{
		Effect.BlindUp("eRentAccess");
		
		// Enable Payment type and remove eRent since thats not available in manual transactions.
		paymenttype = document.getElementById('PaymentType');
		paymenttype.remove(0);
		paymenttype.disabled = false;
		
		// Enable EFT fields (Only needed for IE)
		document.getElementById('AccountType').disabled = true;
		document.getElementById('TransitNum').disabled 	= true;
		document.getElementById('BankNum').disabled 	= true;
		document.getElementById('AccountNum').disabled 	= true;
	}
	else
	{
		Effect.BlindDown("eRentAccess");
		
		// Enable Payment type
		paymenttype = document.getElementById('PaymentType');
		
		
		// Add Online Rent Collection to list box, select it and disable the box
		var newElement = document.createElement('option');
		var oldElement = paymenttype.options[0];
		
		newElement.text = "eRent";
    	newElement.value = "eRent";
    		
    		// IE sucks as usual. This is a work-arround
    		try
    		{
    			paymenttype.add(newElement,oldElement); // Standard compliant. Doesn't work in IE
    		}
    		catch (ex)
    		{
    			paymenttype.add(newElement,paymenttype.selectedIndex);
    		}
    		
		paymenttype.selectedIndex = 0;
		paymenttype.disabled = true;
		
		// Enable EFT fields (Only needed for IE)
		document.getElementById('AccountType').disabled = false;
		document.getElementById('TransitNum').disabled 	= false;
		document.getElementById('BankNum').disabled 	= false;
		document.getElementById('AccountNum').disabled 	= false;


	}
}