//**********************************************************************************//
//* AJAX Communication Methods		
//* By Darryn van der Walt (www.ventureflow.co.za)																        															           	
//* Last Updated : 25 April 2006    
//**********************************************************************************//

var LOGIN_PREFIX    = '/AJAX/AJAX.aspx?';
var http;
var toPost          = '';

addEvent(window, 'load', AddDelayToFormSubmission);

//**********************************************************************************//
// Add delay to form submission to allow object to be fully updated
//**********************************************************************************//
function AddDelayToFormSubmission()
{
	if(document.forms.length > 0)
	{
		mainForm = document.forms[0];
		addEvent(mainForm, 'load', FormSubmissionDelayer);
	}
	return true;
}

function FormSubmissionDelayer() {
	setTimeout("TheDelay()",100);
	return true;
}

function TheDelay() { return true; }

//**********************************************************************************//
// Handle different types of controls and obtaining their values
//**********************************************************************************//
function GetValueOfControl(thisControl, useBitProperty) {
	switch(thisControl.type) {
		case 'hidden'			 : newValue = CleanUpValue(thisControl.value); break;
		case 'radio'			 : newValue = CleanUpValue(thisControl.value); break;
		case 'password'			 : newValue = CleanUpValue(thisControl.value); break;
		case 'textarea'          : newValue = CleanUpValue(thisControl.value); break;
		case 'text'              : newValue = CleanUpValue(thisControl.value); break;
		case 'checkbox'          :	if(useBitProperty == 'true') {
										newValue = thisControl.checked; break;
									}
									else {
										newValue = retrieveCheckedValuesList(thisControl.id); break;
									}
		case 'select-one'        : newValue = CleanUpValue(thisControl.options[thisControl.selectedIndex].value); break;
		default                  : newValue = 'UnknownControlType';
	}
	
	return newValue;
}

//**********************************************************************************//
// Clean up value of control so that AJAX doesn't break
//**********************************************************************************//
function CleanUpValue(stringToClean) {
	stringToClean = stringToClean.replace(new RegExp(/&/g),"and");
	stringToClean = stringToClean.replace(new RegExp(/\|/g),"");
	stringToClean = stringToClean.replace(new RegExp(/\^/g),"");
	stringToClean = stringToClean.replace(new RegExp(/\~/g),"");
	return stringToClean;
}

//**********************************************************************************//
// Function to display errors for a certain field
//**********************************************************************************//
function displayPropertyErrors(thisControlID, errStr) {
	if(DOMGetElement(thisControlID) != null) {	
		currentControl = DOMGetElement(thisControlID);
		currentControl.title = errStr;
		currentControl.style.borderColor = "black"; 
		currentControl.style.backgroundColor = "#BFE4FF"; 
		currentControl.style.borderWidth = "2px"
		currentControl.style.color = "black"; 
		currentControl.style.fontWeight = "bold"; 
	}
	if(DOMGetElement("AJAX_Errors") != null) {
		ajaxerrorsControl = DOMGetElement("AJAX_Errors");
		if(ajaxerrorsControl.innerHTML.indexOf(errStr) == -1) {
			if(ajaxerrorsControl.innerHTML != errStr)
				ajaxerrorsControl.innerHTML = ajaxerrorsControl.innerHTML + " " + errStr;
		}
		ajaxerrorsControl.style.display = ""; 
	}
}

//**********************************************************************************//
// Function to clear errors for a certain field
//**********************************************************************************//
function hidePropertyErrors(thisControlID){
	if(DOMGetElement(thisControlID) != null){
		currentControl = DOMGetElement(thisControlID);
		currentControl.title = "";
		currentControl.style.borderColor = ""; 
		currentControl.style.backgroundColor = ""; 
		currentControl.style.borderWidth = ""
		currentControl.style.color = ""; 
		currentControl.style.fontWeight = ""; 
	}
}

//**********************************************************************************//
// Attaching event that checks for existing errors in the viewstate, and then 
// populates the error DIV
//**********************************************************************************//
addEvent(window, 'load', AJAX_CheckErrorsInViewstate);

//**********************************************************************************//
// Function which checks for existing errors in the viewstate, and then populates
// the error DIV
//**********************************************************************************//
function AJAX_CheckErrorsInViewstate() {
	clearAJAXErrorsDiv();
	if(DOMGetElement("masterPage__PageTemplate_innerHolder_AJAX_Errors_Viewstate") != null) {
		currentViewState = DOMGetElement("masterPage__PageTemplate_innerHolder_AJAX_Errors_Viewstate");
		if(currentViewState.value != "") {
			if(DOMGetElement("AJAX_Errors") != null) {
				ajaxerrorsControl = DOMGetElement("AJAX_Errors");
				if(ajaxerrorsControl.innerHTML != currentViewState.value) {
					ajaxerrorsControl.innerHTML = currentViewState.value;
				}
				ajaxerrorsControl.style.display = ""; 
			}
		} 
	}
}

//**********************************************************************************//
// Function which saves errors to the viewstate
//**********************************************************************************//
function AJAX_SaveErrorsToViewState() {
	if(DOMGetElement("masterPage__PageTemplate_innerHolder_AJAX_Errors_Viewstate") != null) {
		currentViewState = DOMGetElement("masterPage__PageTemplate_innerHolder_AJAX_Errors_Viewstate");
		if(DOMGetElement("AJAX_Errors") != null) {
			ajaxerrorsControl = DOMGetElement("AJAX_Errors");
			if(currentViewState.value != ajaxerrorsControl.innerHTML) {
				currentViewState.value = ajaxerrorsControl.innerHTML;
			}
		} 
	}
}

//**********************************************************************************//
// Function which clears the error DIV
//**********************************************************************************//
function clearAJAXErrorsDiv() {
	if(DOMGetElement("AJAX_Errors") != null) {
		ajaxerrorsControl = DOMGetElement("AJAX_Errors");
		ajaxerrorsControl.innerHTML = "";
		ajaxerrorsControl.style.display = "none"; 
	}
}

//**********************************************************************************//
// Function which displays the results from the session save
//**********************************************************************************//
var previousFailedError = '';
function displaySaveSessionResults(retStr) {
	if(DOMGetElement(retStr[3]) != null) {
		buttonInCharge = DOMGetElement(retStr[3]);
		buttonInCharge.value = "Save";
		buttonInCharge.disabled = false;
	}
	if(DOMGetElement("AJAX_Errors") != null) {
		ajaxerrorsControl = DOMGetElement("AJAX_Errors");
		fontColor = '';
		if(retStr[0] == 'true') {
			fontColor = 'green';
		}
		else {
			fontColor = 'red';
		}
		stringToDisplay = "<font color=" + fontColor + "> " + retStr[2] + " </font>";
		ajaxerrorsControl.innerHTML = stringToDisplay;
		ajaxerrorsControl.style.display = ""; 
		
		//Redirect to the specified location
		if(retStr[0] == 'true') {
			if(retStr[4] != '') {
				window.location = retStr[4];
			}
		}
	}
}

//**********************************************************************************//
// Called when the validation results are returned from the server
//**********************************************************************************//
function handleResponse(retStr) {
	if(retStr[0] != 'true' && retStr[0] != 'false')
		alert("The server returned an unrecognised response. Please try your request again.");
	else {
		if(retStr[1] == 'savesessionresults')
			displaySaveSessionResults(retStr);
		else {
			if(retStr[2] != '') {
				clearAJAXErrorsDiv();
				ErrorAndID = retStr[2].split("^");
				for (i=0; i<ErrorAndID.length; i++) {
					currentPair = ErrorAndID[i].split("~");
					if(currentPair[0] != '') {
						displayPropertyErrors(currentPair[1], currentPair[0]);
					} else {
						hidePropertyErrors(currentPair[1]);
					}
				} 
			}
			AJAX_SaveErrorsToViewState();
		}
	}
}

//**********************************************************************************//
// Function which handles the response from the server
//**********************************************************************************//
function handleHttp() {
	if( http.readyState == 1 ) {
		OnLoading();
	}
	else if( http.readyState == 2 )	{
	    OnLoaded();
	}
	else if( http.readyState == 3 )	{
	    OnInteractive();
	}
	else if( http.readyState == 4 )	{
	    if( http.status == 0 )
			OnAbort();
		else if( http.status == 200 && http.statusText == "OK")
			OnComplete( http.responseText, http.responseXML );
		else
			OnError( http.status, http.statusText, http.responseText );   
	}
}

//**********************************************************************************//
// Function which handles status LOADING
//**********************************************************************************//
function OnLoading() {
	loading_img("busy"); 
}

//**********************************************************************************//
// Function which handles status LOADED
//**********************************************************************************//
function OnLoaded() { 
}

//**********************************************************************************//
// Function which handles status INTERACTIVE
//**********************************************************************************//
function OnInteractive() {
}

//**********************************************************************************//
// Function which handles status ABORT
//**********************************************************************************//
function OnAbort() {
}

//**********************************************************************************//
// Function which handles status COMPLETE
//**********************************************************************************//
function OnComplete(responseText, responseXML) {
	loading_img("idle"); 
	retStr = responseText.split("|");
	handleResponse(retStr);
}

//**********************************************************************************//
// Function which handles status ERROR
//**********************************************************************************//
function OnError(status, statusText, responseText) {
	errText  =	"Unfortunately an error occured during the saving of data to the server. \r\n";
	errText  = errText + "Please try your previous operation again, or try refreshing the page. \r\n";
	errText  = errText + "Status Code : " + status + " \r\n";
	errText  = errText + "Status Text : " + statusText + " \r\n";
	alert(errText);
}

//**********************************************************************************//
// Function which adds a key/value pair to the querystring
//**********************************************************************************//
function addParameter(key, value) {
	toPost = toPost + key + "=" + value	+ '&';
}

//**********************************************************************************//
// Function which clears the querystring parameters
//**********************************************************************************//
function clearParameters() {
	toPost = '';	
}

//**********************************************************************************//
// Function which performs the actual post to the server
//**********************************************************************************//
function doPost() {
	http = getHTTPObject(); 
	http.onreadystatechange = handleHttp;
	http.open('POST', LOGIN_PREFIX);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); 
	http.setRequestHeader("Content-length", toPost.length); 
	http.setRequestHeader("Connection", "close"); 
	http.send(toPost);
}

//**********************************************************************************//
// Function which handles the AJAX busy/idle animation
//**********************************************************************************//
function loading_img(disp) {
	if(DOMGetElement("AJAX_Status") != null) {
		if(disp == "busy")
			var src = "/AJAX/loading.gif";
		else if(disp == "idle")
			var src = "/AJAX/loader.gif"; 
			
		imageHolder = DOMGetElement("AJAX_Status");
		imageHolder.src = src;
	}
}	

//**********************************************************************************//
// Method that sets up a cross-browser XMLHttpRequest object
//**********************************************************************************//
function getHTTPObject() {
	var http_object;

	// MSIE Proprietary method
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			http_object = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				http_object = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (E) {
				http_object = false;
			}
		}
	@else
		xmlhttp = http_object;
	@end @*/

	// Mozilla and others method
	if (!http_object && typeof XMLHttpRequest != 'undefined') {
		try {
			http_object = new XMLHttpRequest();
		}
		catch (e) {
			http_object = false;
		}
	}
	return http_object;
}
