/****************************************************************/

/* 
	Customer Community - AJAX libraries							
	based on the Simple AJAX Code-Kit (SACK) v1.6.1	
	See below for SACK licensing

	The customer community libraries are copyright
	2007 - Customer Community Services Pty Ltd

*/

// Dynamic Loading of sack objects 
var dynamicContent_ajaxObjects = new Array(); 
var jsCache = new Array();
var enableCache = false; 
var LoadingMessage = '<table align="center" width="100" style="font-family:verdana; font-size:11px; color: #808080;"><tr valign="middle"><td width="16"><IMG SRC="ccAjax/ajax-loader.gif" ></td><td>Loading ...</tr></table>';
//var LoadingMessage = 'Loading, please wait...';
var gridHiddenValue = "";
var callingDivValue = "";

/**************************************************
Loads the output HTML from the remote script 
***************************************************/
function ajax_loadContent(divId,pathToFile, callingdivId)
{
	//alert('start : ' + ajaxIndex);
	// check if cache enabled NB! dont enable by default
	if(enableCache && jsCache[pathToFile]){
		document.getElementById(divId).innerHTML = jsCache[pathToFile];
		return;
	}
	// Get the next array element
	var ajaxIndex = dynamicContent_ajaxObjects.length;
	// if nothing in the div, display loading message
	if (document.getElementById(divId).innerHTML == ''){ 
			document.getElementById(divId).innerHTML = LoadingMessage ; 
	}
	else {
		// move it to the top of the layers
		document.getElementById(divId).style.zIndex = '1';
		// dim the content we are replacing
		DimTheDiv(divId); 
		// add the loading message
		//document.getElementById(divId).innerHTML = '<div style="position:absolute;" id="test" style="z-index: 3000;">LoadingMessageDisplay</div>' + document.getElementById(divId).innerHTML ;
		WriteIT(LoadingMessage,'Loading');
	}

	dynamicContent_ajaxObjects[ajaxIndex] = new sack();
	dynamicContent_ajaxObjects[ajaxIndex].requestFile = pathToFile;

	dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showContent(divId,ajaxIndex,pathToFile, callingdivId); };  
	dynamicContent_ajaxObjects[ajaxIndex].runAJAX();

} 

/*****************************************************************
	put the content from the ajax into the div
******************************************************************/
function ajax_showContent(divId,ajaxIndex,pathToFile, callingdivId)
{
	//alert('end : ' + ajaxIndex);
	//callingDivValue = "<input type='hidden' id='" + divId + "_CallingDiv' value='" + callingdivId + "'>";
	//gridHiddenValue = "<input type='hidden' id='" + divId + "_CurrentValue' value='" + pathToFile + "'>";
	callingDivValue = "";
	gridHiddenValue = "";

	document.getElementById(divId).innerHTML = callingDivValue + gridHiddenValue + dynamicContent_ajaxObjects[ajaxIndex].response;
	WriteIT('','Loading');
	//alert("calling div : " + callingdivId + "\n" + document.getElementById(callingdivId).innerHTML);
	
	if(enableCache){
	jsCache[pathToFile] = 
	dynamicContent_ajaxObjects[ajaxIndex].response;
	}
	dynamicContent_ajaxObjects[ajaxIndex] = false;
}

/*********************************************************
	passes the form data using the sack object
**********************************************************/
function ajax_postFormData(divId,ThisButtonObject)
{
	var ThisFormObject = ThisButtonObject.form;
	var ThisButtonName = ThisButtonObject.name;
	var ThisOperation = ThisButtonObject.value;
	var AllElements = ThisFormObject.elements;
	var temptext = '';

	// Get the next array element
	var ajaxIndex = dynamicContent_ajaxObjects.length;
	// Create new sack object
	dynamicContent_ajaxObjects[ajaxIndex] = new sack();

	// Loop through all form elements and set variables for the form submission (POST/GET data)
	// This is required by the SACK object otherwise the form values are not recognised by the script when submitted
	for(var i=0;i<AllElements.length;i++){
		if(AllElements[i].type == "text" || AllElements[i].type == "textarea" || AllElements[i].type == "hidden")
		{
			dynamicContent_ajaxObjects[ajaxIndex].setVar(AllElements[i].name, AllElements[i].value); 
			//temptext = temptext + "\n" + AllElements[i].name + " = " + AllElements[i].value ; 
		}   
		else if(AllElements[i].type == "checkbox")
		{
			dynamicContent_ajaxObjects[ajaxIndex].setVar(AllElements[i].name, AllElements[i].checked); 
			//temptext = temptext + "\n" + AllElements[i].name + " = " + AllElements[i].checked ; 

		}
		else if(AllElements[i].type == "select-one")
		{
			dynamicContent_ajaxObjects[ajaxIndex].setVar(AllElements[i].name, AllElements[i].options[AllElements[i].selectedIndex].value); 
			//temptext = temptext + "\n" + AllElements[i].name + " = " + AllElements[i].options[AllElements[i].selectedIndex].value ; 
		}
		else if(AllElements[i].type == "button")
		{
			// Check if the pressed button is same as the found button element, if yes then post it with the form
			if (AllElements[i].name == ThisButtonName)
			{
				dynamicContent_ajaxObjects[ajaxIndex].setVar(AllElements[i].name, ThisOperation); 
			}
		}
		else
		{
			//alert(AllElements[i].type);
		}
	} // for
	
	// alert(temptext);
	

	// if nothing in the div, display loading message
	if (document.getElementById(divId).innerHTML == '') { 
		document.getElementById(divId).innerHTML = LoadingMessage ; 
	}
	// otherwise dim the tables inside the div
	else {
		document.getElementById(divId).style.zIndex = '1';
		// dim the content we are replacing
		DimTheDiv(divId); 
		//document.getElementById(divId).innerHTML = '<div style="position:absolute;" id="test" style="z-index: 3000;">LoadingMessageDisplay</div>' + document.getElementById(divId).innerHTML ;
		WriteIT(LoadingMessage,'Loading');
	}

	//document.getElementById('master_records').innerHTML = document.getElementById('master_records').innerHTML + temptext ;

	// Changed the request file to be form's action (action value is automatically generated by codecharge when record form loads)
	// Change the method to POST/GET from the ThisFormObject
	dynamicContent_ajaxObjects[ajaxIndex].method = ThisFormObject.method;

	dynamicContent_ajaxObjects[ajaxIndex].requestFile = ThisFormObject.action;
  
  var divToRefreshId = "";
  if (document.getElementById(divId + "_CallingDiv"))
  {
	  divToRefreshId = document.getElementById(divId + "_CallingDiv").value;
  }
  //alert(divToRefreshId + " to be refreshed");
  
  // We are using form's action as pathToFile when submitting a form
  // When calling ajax_loadContent, it's a dummy value only
  // This avoids creating a duplicate function to do the same thing
  dynamicContent_ajaxObjects[ajaxIndex].onCompletion = function(){ ajax_showPostbackContent(divId,ajaxIndex,ThisFormObject.action, divToRefreshId); };  
  dynamicContent_ajaxObjects[ajaxIndex].runAJAX();
} 

/*****************************************************************
	put the content from the ajax into the div
******************************************************************/
function ajax_showPostbackContent(divId,ajaxIndex,pathToFile, thisdivToRefresh)
{
	//callingDivValue = "<input type='hidden' id='" + divId + "_CallingDiv' value='" + thisdivToRefresh + "'>";
	//gridHiddenValue = "<input type='hidden' id='" + divId + "_CurrentValue' value='" + pathToFile + "'>";
	
	callingDivValue = "";
	gridHiddenValue = "";

	document.getElementById(divId).innerHTML = callingDivValue + gridHiddenValue + dynamicContent_ajaxObjects[ajaxIndex].response;
	//document.getElementById(divId).innerHTML = dynamicContent_ajaxObjects[ajaxIndex].response;

	refreshDiv(thisdivToRefresh);
	dynamicContent_ajaxObjects[ajaxIndex] = false;
}


/*************************************
	Empty a div area so it is blank
*************************************/
function emptyDiv(divId)
{
	//alert('EMPTYING');
	document.getElementById(divId).innerHTML = "";
}

/****************************************************
	Refresh a div area after database update is done
*****************************************************/

function refreshDiv(divToRefreshId)
{	
	var scriptName = "";
	
	if (divToRefreshId.length > 0)
	{
		if (document.getElementById(divToRefreshId + "_CurrentValue"))
		{
			scriptName = document.getElementById(divToRefreshId + "_CurrentValue").value;
		}
	}
	
	//alert('script is :' + scriptName);
	if (scriptName.length > 0)
	{
		ajax_loadContent(divToRefreshId, scriptName, "");
	}
	else
	{
		//alert("Problem refreshing the listing...");
	}
}
 

function showDiv(divId)
{
	//alert('SHOWING');
	document.getElementById(divId).style.display = "";
}
function hideDiv(divId)
{
	//alert('HIDING');
	document.getElementById(divId).style.display = "none";
}

/***********************************************
	Stuff some content into a div
************************************************/
function WriteIT(text,id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
		x.innerHTML = '';
		x.innerHTML = text;
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML = text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		text2 = '<P CLASS="testclass">' + text + '</P>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}

/*******************************************************
	adds opacity to a div, makes it appear dimmed
********************************************************/
function DimTheDiv(ThisDiv) {
	// use values 1 - 10 and the scripts sets the correct settings 
	// ie uses range from 0 - 100
	// myBodyElements[B].style.filter = 'alpha(opacity=' + 75 + ')';
	// firefox uses 0-1
	// myBodyElements[B].style.opacity = .5;

	// get the elements
	// alert(ThisDiv);
	var myBody = document.getElementById(ThisDiv);
	// alert(myBody);
	// set all the table slightly opaque.
	if (myBody.getElementsByTagName("table"))
	{
		var myBodyElements = myBody.getElementsByTagName("table");
		for(var B=0;B<myBodyElements.length;B++){
			setOpacity(myBodyElements[B], 5 );
		}
	}
	
}

/*****************************************************************
Set the opacity of a div, used to dim the area about to be updated
******************************************************************/
function setOpacity(ThisObject, value) {
	ThisObject.style.opacity = value/10;
	ThisObject.style.filter = 'alpha(opacity=' + value*10 + ')';
}

/********************************************************************************
Get the query string values from a form, used to get form values prior to submit
*********************************************************************************/

function GetQueryStrings(theForm){
		  var AllElements = theForm.elements;
		  var ifdata = "";
		  var elsedata = "";
//		  alert(theForm.elements.length);
//		  alert(AllElements.length);
		  for(var i=0;i<AllElements.length;i++){
			var ThisElement = AllElements[i];
			var nam = ThisElement.name;
			if(ThisElement.length){
				// radio buttons & checkboxes
			  for(var m=0;m<ThisElement.length;m++){
				if(ThisElement[m].selected){
				  ifdata += nam+"="+escape(ThisElement[m].value) + "&";
				}
			  }
			} else {
				// textboxes etc (ignore buttons)
			  if(!((ThisElement.type=="radio"||ThisElement.type=="checkbox" || ThisElement.type=="button")&&ThisElement.checked==false)){
				elsedata += nam+"="+escape(ThisElement.value) + "&";
				// +' type is ' + ThisElement.type;
			  }
			}
		  }
		  // alert('ifData = ' + ifdata);
		  // alert('elsedata = ' + elsedata );
		  return (ifdata + elsedata);
		}


function AJAXgenericpopup(link, WindowWidth, WindowHeight, TheDiv, TheScript)
		{ 
			alert('TheDiv=' + TheDiv);
			alert('TheScript=' + TheScript);
			window.open(link,"","resizable=yes,status=no,toolbar=no,menubar=no,location=no,width="+WindowWidth+",height="+WindowHeight+",left=30,top=30"); 
		} 




/***  END OF CUSTOMER COMMUNITY LIBRARIES ****?

/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}
