/**
AJAX implementation of a data service with barrier-free integration
between browsers and server technologies.

Sends an XML DOM as a request to the data service that handles the request and sends back 
an XML DOM with two nodes: a command (JS function), and a set of JS escaped parameters to 
the JS function such as:
	3, 21, 'this isn\'t hard', 'string content'
so that the response handler can treat it as a string with an eval command. As such references
to objects may not work reliably.

USAGE:
AjaxRequest(null, EXAMPLE_AjaxResponse, "getDBUser", "var1", "val1")
function EXAMPLE_AjaxResponse(resObj) {
	alert(AjaxResParam(resObj, "args"));
}

*/
function AjaxRequest() {
	var AjaxUrl = AjaxRequest.arguments[0] ? AjaxRequest.arguments[0] : "/includes/ajax_common.php";
	var JsResHandler = AjaxRequest.arguments[1];
	var JsResExtra = null;
	var AjaxAction = AjaxRequest.arguments[2];
	var AjaxSend = "AJAX_Action="+escape(AjaxAction);
	for (var i=3; i<AjaxRequest.arguments.length; i=i+2) {
		AjaxSend += "&"+AjaxRequest.arguments[i]+"="+escape(AjaxRequest.arguments[i+1]);
	}
	var newAjaxRequest = null;
	if (window.XMLHttpRequest)
		newAjaxRequest = new XMLHttpRequest();
	else if (window.ActiveXObject)
		newAjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	else return false;
	newAjaxRequest.onreadystatechange = function () {
		if (newAjaxRequest.readyState == 4) {
			var responseDOM = newAjaxRequest.responseXML.documentElement;
			if (!responseDOM) {
				alert("Bad response received: \n\n"+newAjaxRequest.responseText);
				return;
			} else if(AjaxResParam(responseDOM, "error")) {
				alert("AJAX Handler reported an error:\n\n"+AjaxResParam(responseDOM, "error"))
				return;
			}
			JsResHandler(responseDOM);
			return;
		}
	}
	newAjaxRequest.open('POST', AjaxUrl, true);
	newAjaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	newAjaxRequest.send(AjaxSend);
}

function AjaxResParam(resObj, param) {
	if (!resObj) {
		alert("AjaxResParam: Object does not exist");
		return null;
	} else if (!resObj.getElementsByTagName(param)) {
		alert("AjaxResParam: Object is not a valid DOM");
		return null;
	} else if (!resObj.getElementsByTagName(param).item(0)) {
//		alert("AjaxResParam: Parameter '"+param+"' is not a valid (existing) DOM element");
		return null;
	}
	return resObj.getElementsByTagName(param).item(0).firstChild.data;
}
