// holds an instance of XMLHttpRequest
var valXmlHttp = createValXmlHttpRequestObject();
// 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 createValXmlHttpRequestObject()
{
	// will store the reference to the XMLHttpRequest object
	var valXmlHttp;
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		valXmlHttp = 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 && !valXmlHttp; i++)
		{
			try
			{
				// try to create XMLHttpRequest object
				valXmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}
			catch (e) {} // ignore potential error
		}
	}

	// return the created object or display an error message
	if (!valXmlHttp)
		displayError("Error creating the XMLHttpRequest object.");
	else
		return valXmlHttp;
}


// the function handles the validation for any form field
function validate(inputValue, fieldID, formname, inputValue2)
{
	// only continue if valXmlHttp isn't void
	if (valXmlHttp)
	{
		// 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 ((valXmlHttp.readyState == 4 || valXmlHttp.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
				valXmlHttp.open("POST", serverAddress + "/includes/AJAXValidate.php", true);
				
				valXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				valXmlHttp.onreadystatechange = valHandleRequestStateChange;
				// Send post data (inputValue, fieldid etc)
				valXmlHttp.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 valHandleRequestStateChange()
{
	// when readyState is 4, we read the server response
	if (valXmlHttp.readyState == 4)
	{
		// continue only if HTTP status is "OK"
		if (valXmlHttp.status == 200)
		{
			try
			{
				// read the response from the server
				readResponse();
			}
			catch(e)
			{
				// display error message
				displayError(e.toString());
			}
		}
		else
		{
			// display error message
			displayError(valXmlHttp.statusText);
		}
	}
}

// read server's response
function readResponse()
{
	// retrieve the server's response
	var response = valXmlHttp.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 = valXmlHttp.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 findListingPerId()
{
	aptId = document.getElementById("AptId");
	
	window.location = "/apartment/" + aptId.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 a recurring billing
function deleteRecurrentBilling(redirectLink) 
{
	if (window.confirm("This will delete your recurring billing\n\nAre you sure you wish to delete this?"))
	{
		 window.location=redirectLink;
	}
}


// Confirms if user wants to delete apartment finder
function deleteApartmentFinder(redirectLink) 
{
	if (window.confirm("This will delete your Apartment Finder.\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;
	}
}

// Submit Complete Order 
// This will submit the form and disable the submit button
function completeManagerOrder()
{
	field = document.getElementById('CompleteOrderBtn');
	
	field.src = '/pics/complete-order-disabled.gif';
	field.setAttribute("onclick","alert('Please wait while we process your payment')");
	
	document.ManagerBilling.submit();
}

// Submit Complete Order for Plans 
// This will submit the form and disable the submit button
function completeManagerPlanOrder()
{
	field = document.getElementById('CompleteOrderBtn');
	
	field.src = '/pics/complete-order-disabled.gif';
	field.setAttribute("onclick","alert('Please wait while we process your payment')");
	
	document.ManagerUpdatePlan.submit();
}

function completeTenantOrder()
{
	field = document.getElementById('CompleteOrderBtn');
	
	field.src = '/pics/complete-order-disabled.gif';
	//field.setAttribute("onclick","alert('Please wait while we process your payment')");
	field.onclick = new Function("alert('Please wait while we process your payment')");
	
	document.TenantBilling.submit();
}

function acceptTOS()
{
	field = document.getElementById('SubmitBtn');
	
	//field.src = '/pics/complete-order-disabled.gif';
	//field.setAttribute("onclick","alert('Please wait while we process your payment')");
	field.onclick = new Function("document.AffiliateSignUp.submit()");
}

// Shows a Appear effect on the two logoes
function frontPageAppear()
{
	new Effect.Appear('welcome',{duration:0.3})
}

function SlideDown(id)
{
	field = document.getElementById(id);
	//field.setAttribute("onclick", "SlideUp('" + id + "')");
	
	Effect.BlindDown(id + "_text");
	field.onclick = new Function("SlideUp('" + id + "')");
	
	return false; // To not execute the a href
}

function SlideUp(id)
{
	field = document.getElementById(id);
	
	//field.setAttribute("onclick", "SlideDown('" + id + "')");
	field.onclick = new Function("SlideDown('" + id + "')");
	
	Effect.BlindUp(id + "_text");

	return false; // To not execute the a href
}

// Used to call OutsideCanadaFieldsToogle if there's multiple province fields in the form
function LandlordOutsideCanadaFieldsToogle(value)
{
	OutsideCanadaFieldsToogle(value,'Landlord')
}

// Used to call OutsideCanadaFieldsToogle if there's one province field in the form
function UserOutsideCanadaFieldsToogle(value)
{
	OutsideCanadaFieldsToogle(value,'')
}

// Used to call OutsideCanadaFieldsToogle if there's multiple province fields in the form
function RentalOutsideCanadaFieldsToogle(value)
{
	OutsideCanadaFieldsToogle(value,'Rental')
}

// Used to enable fields (State & Country) if the purchaser/user is outside Canada
function OutsideCanadaFieldsToogle(value, type)
{
	if (value == 'Outside of Canada')
	{
		Effect.BlindDown(type + "OutsideCanadaInfo");
		
		document.getElementById(type + "OutsideCanadaInfoShown").value		= 'true';

		// Purpose of this: IE6.0 fucks up the blinddown so if the client is a IE6.0 it will fold it out, but then hide it.
		// To catch this error there's a timeout of 1 second that will then force it to be shown
		setTimeout("document.getElementById('" + type + "OutsideCanadaInfo').style.display	= 'block';",1000);
	}
	else
	{
		// Is this already being shown? If so then don't do the blind since it looks silly
		//loadinggif = document.getElementById("OutsideCanadaInfoShown");
		
		if (document.getElementById(type + "OutsideCanadaInfoShown").value != 'false')
		{
			Effect.BlindUp(type + "OutsideCanadaInfo");
			
			document.getElementById(type + "OutsideCanadaInfoShown").value = 'false';
		}
	}
}

/*
function MODALDeleteApartmentFinder(id)
{
	Modalbox.hide(); 
	window.location = "/apartmentfinder/index.php?mode=delete&sId=" + id + "';
}
							
function MODALIgnoreApartmentFinder()
{
	Modalbox.hide();
}
*/

// sets focus on the first field of the form
/*
function setFocus()
{
	document.getElementById("txtUsername").focus();
}
*/