/* ------------------------------------------------------------------------------------------------------------------------------ */
// functions for submitting asynchronous requests
/* ------------------------------------------------------------------------------------------------------------------------------ */
// create the appropriate request object
function createRequestObject() {
	// required to use the functions in this file
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		ro = new XMLHttpRequest();
	}
	return ro;
}

var ajaxtarget;
var ajaxtargettype;
var ajaxrequestpending	= false;
var ajaxwaitcount		= 0;
var ajaxwaitmsg;

/* ------------------------------------------------------------------------------------------------------------------------------ */
function createAjaxRequest(url,parmstr,target,targettype,waittarget) {
	submitAjaxRequest(url,parmstr,target,targettype);

	if (waittarget)	{
		ajaxrequestpending	= true;
		ajaxwaitcount		= 0;
		displayAjaxProcessing(waittarget);
	}

}

/* ------------------------------------------------------------------------------------------------------------------------------ */
function submitAjaxRequest(url,parmstr,target,targettype) {
	// url			- the script location that will process this request
	// parmstr		- the string of parameters to pass to the script i.e. ?email=email@domain.com&password=password
	// target		- the name/id of the response target i.e. where we want to direct the results of the request
	// targettype	- the response target type is either an html element (div, td, etc) or a javascript function

	ajaxtarget		= target;
	ajaxtargettype	= targettype;

	// create the request object
	http = createRequestObject();

	request	= url+parmstr;
	http.open('get', request);

	// MS needs special help as usual
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		http.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	}

	// submit and handle the result
	http.onreadystatechange = processAjaxResponse;
	http.send(null);
}

/* ------------------------------------------------------------------------------------------------------------------------------ */
function processAjaxResponse() {
	//alert(http.readyState);

	if(http.readyState == 4){
		//alert('Got response\n\n'+response);
		if (ajaxtargettype == 'html') {
			document.getElementById(ajaxtarget).innerHTML = http.responseText;
		}
		if (ajaxtargettype == 'script') {
			eval(ajaxtarget + '(http.responseText);');
		}
		if (ajaxtargettype == 'xml') {
			eval(ajaxtarget + '(http.responseXML);');
		}
	}
}

/* ------------------------------------------------------------------------------------------------------------------------------ */
function displayAjaxProcessing(target) {

	var node	= document.getElementById(target);

	var msg;
	if (ajaxwaitmsg) {	msg	= ajaxwaitmsg;
	} else {			msg	= 'Processing - Please Wait ';}

	//if (!ajaxrequestpending) {	hideElement(target);
	//} else {					showElement(target); }

	node.style.fontWeight	= 900;

	// recursive calls with a 1 second delay
	// while the elapsed time is less than 120 seconds
	// and the request hasn't yet completed
	if (ajaxwaitcount<120 && ajaxrequestpending) {
		ajaxwaitcount++;
		timerID = setTimeout('displayAjaxProcessing(\''+target+'\')',1000);

		if (ajaxwaitcount > 0) {	node.innerHTML	= msg + '(elapsed: &nbsp;&nbsp;&nbsp;'+ ajaxwaitcount + ' seconds)';
		} else {					node.innerHTML	= msg; }
	} else {
		clearTimeout(timerID);
	}

	if (ajaxwaitcount>=120 && ajaxrequestpending) {	
			node.innerHTML	= 'This request may have \'timed out\''; 
			ajaxrequestpending	= false;
	}
}


/* ------------------------------------------------------------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------------------------------------------------------------ */
// response data processing
/* ------------------------------------------------------------------------------------------------------------------------------ */
// hold the returned ajax data in a response array (of AjaxData objects)
var AjaxResponse	= new Array();

/* ------------------------------------------------------------------------------------------------------------------------------- */
function AjaxData(field,value) {
	this.field	= field;
	this.value	= value;
}

/* ------------------------------------------------------------------------------------------------------------------------------- */
function parseAjaxResponse(result) {
	msg	= "parseAjaxResponse() \n";
	var fields	= new Array();

	result	= result.replace(/\n|\r/g,"");

	// get the fields
	re				= /<AR(\w*|\d*|_)>/gi;
	var done	= false;
	var count	= 0;
	while (!done) {
		fieldarray	= re.exec(result);
		if (fieldarray) {	fields.push(fieldarray[1])
		} else {			done = true; }
	}

	//msg	+= "parsed " + fields.length + " fields\n";
	//msg	+= "fields: \n" + fields.toString() + " \n";
	//msg	+= "result \n" + result + " \n";
	
	if (fields.length>0) {
		// get the field values
		for (var idx in fields) {
			field	= fields[idx];
			eval('re = /<AR'+field+'>(.*)<\\/'+field+'>/gi');
			valuearray	= re.exec(result);

			// add the ajax field/value pair to AjaxResponse array
			if (valuearray) {
				value			= valuearray[1];
				var response	= new AjaxData(field,value);
				AjaxResponse.push(response);
				msg	+= "loaded field: " + field + " \n";
				//msg	+= "<b>" +field + "</b> " + value +" \n";
			} else { msg	+= "unable to parse value for " + field+ " \n"; }
		}
		//msg	+= "parsed " + AjaxResponse.length + " fields\n";
	}
	//msg	= result.replace(/</g,"&lt;");
	//msg	+= "result \n" + result + " \n";
	//msg	= msg.replace(/\n/g,"<br>");
	//writeToDebug(msg);
	//writeToElement('debugmsg', msg);
};


/* ------------------------------------------------------------------------------------------------------------------------------- */
function loadAjaxResponse(responsejson) {
	// data arriving in JSON format (Javascript Object Notation)

	//alert(responsejson);
	var msg	= '';
	eval("var response = ("+responsejson+")");

	for (i in response) {
		//msg	+= i + ' ' + response[i] + '<br>';
		//loadDataField(i,response[i]);
		msg	+= i + '<br>';
		field	= i;
		value	= response[i];
		var responseobj	= new AjaxData(field,value);
		AjaxResponse.push(responseobj);
	}
	//showElement('reportresults');
	//writeDebug(msg,'');

}

/* ------------------------------------------------------------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------------------------------------------------------------ */

/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/*
 * Copyright 2005 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Original code by Matthew Eernisse (mde@fleegix.org)
 * Additional bugfixes by Mark Pruett (mark.pruett@comcast.net)
 *
*/
// The var docForm should be a reference to a <form>
/*--------------------------------------------------------------------------*/
function formData2QueryString(docForm) {
	var submitContent = '';
	var formElem;
	var lastElemName = '';

	for (i = 0; i < docForm.elements.length; i++) {
		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'select-one':
			submitContent += formElem.name + '=' + escape(formElem.value) + '&'
			break;

			// Radio buttons
			case 'radio':
			if (formElem.checked) {
			submitContent += formElem.name + '=' + escape(formElem.value) + '&'
			}
			break;

			// Checkboxes
			case 'checkbox':
			if (formElem.checked) {
				// Continuing multiple, same-name checkboxes
				if (formElem.name == lastElemName) {
					// Strip of end ampersand if there is one
					if (submitContent.lastIndexOf('&') == submitContent.length-1) {
						submitContent = submitContent.substr(0, submitContent.length - 1);
					}
					// Append value as comma-delimited string
					submitContent += ',' + escape(formElem.value);
				} else {
					submitContent += formElem.name + '=' + escape(formElem.value);
				}
				submitContent += '&';
				lastElemName = formElem.name;
			}
			break;

		}
	}

	// Remove trailing separator
	submitContent = submitContent.substr(0, submitContent.length - 1);
	return submitContent;
}


