/*

Written by Nick Baker for Williams College Libraries.
You may copy this code as long as credit is given.

Ajax('some url')
Uses XML formed like this:
<response>
	<method>
		<function>1ST JAVASCRIPT FUNCTION TO CALL</function>
		<parameter>FIRST PARAMETER</parameter>
		<parameter>ETC...</parameter>
	</method>
	<method>
		<function>NTH FUNCTION TO CALL</function>
		<parameter>FIRST PARAMETER</parameter>
		<parameter>SECOND PARAMETER</parameter>
		<parameter>ETC...</parameter>
	</method>
</response>

Based on documentation from this excellent tutorial:
http://www.xml.com/pub/a/2005/02/09/xml-http-request.html
*/
var req;
function Ajax(url) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = AjaxProcessor;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = AjaxProcessor;
            req.open("GET", url, true);
            req.send();
        }
    }
}
/*
Processes the XML when the request is returned.  Works with Ajax();
*/
function AjaxProcessor() {
    
	if (req.readyState == 4) { // only if req shows "complete"
		
		if (req.status == 200) { // only if "OK"
		
			if(req.responseXML == null) { response = null; }
			else { response = req.responseXML.documentElement; }
			
			if(response == null) {
				AjaxError("The XML response was not well formed.");
			} else {
			
				if(response.getElementsByTagName('method')[0] == null) {
					AjaxError("No method call defined.");
				} else {
				
					// Get the method to call from the XML returned
					method = response.getElementsByTagName('method'); //[0].firstChild.data;
					
					for(var j=0; j<method.length; j++) {
						
						// Get the function name
						functionName = method[j].getElementsByTagName('function')[0].firstChild.data
						
						// Get the parameters to call from the XML.
						params = method[j].getElementsByTagName('parameter');
						
						// Build a parameters list from the params.
						pList = '';			
						for(i=0; i < params.length; i++) {
							pList += (pList == '' ? '' : ', ') +
								(params[i].firstChild != null ? 
									'params['+i+'].firstChild.data' : 
									'\'\'');
						}
						
						// Execute the method with the given parameters.
						eval(functionName + '('+pList+')');
					
					} // end each method
				} // end if method defined
			} // end if well formed
		} // end if ok
	} // end if complete
}

function AjaxError(errorMsg) {
	if(errorMsg != null) { alert(errorMsg); }
}
function AjaxSilent() { }