// JavaScript Document
// BY: Cameron McGregor
// CREATED: July 09, 2007
// ABSTRACT: Contains javascript functions used for generic AJAX handler requests

//Post an XML HTTP Request for AJAX
// This code was taken from common.js originally written by Will Price
// doAsynchonous - whether or not to perform the operation asynchronously (done synchronously if not specified)
function xmlHandlerPost(params, doAsynchronous, responseEl, responseFunc) 
{
    var xmlHttpReq = false;
    var req = "";
    var len = params.length;

	//Make sure doAsynchronous is false if undefined
	doAsynchronous = (typeof doAsynchronous == 'undefined') ? false : doAsynchronous;

    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlHttpReq.open("POST", "/AJAXHandler", doAsynchronous);
    xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	//Build request string
	if (len > 0)
	{
		var equalPos = params[0].indexOf("=");
		if (equalPos > 0)
			req = params[0].substr(0, equalPos) + "=" + escape(params[0].substr(equalPos + 1));
		for (i = 1; i < params.length; i++)
		{
			equalPos = params[i].indexOf("=");
			if (equalPos > 0)
				req = req + "&" + params[i].substr(0, equalPos) + "=" + escape(params[i].substr(equalPos + 1));
		}
	}
	
    //Do asynchronous request
    if (doAsynchronous && responseEl)
    {
        xmlHttpReq.onreadystatechange = function() {
            if (xmlHttpReq.readyState == 4) {
                responseEl.innerHTML = xmlHttpReq.responseText;
            }
        }

        //Compose and send the request string
        xmlHttpReq.send(req);

    }
	//Call a method when completed
	else if (responseFunc)
	{
		//Handle asynchronous responses
		if (doAsynchronous)
		{
			xmlHttpReq.onreadystatechange = function() 
			{
				if (xmlHttpReq.readyState == 4) 
					responseFunc(xmlHttpReq.responseText);
            }
		}

		//Compose and send the request string
        xmlHttpReq.send(req);

		//Handle synchronous responses
		if (!doAsynchronous)
			responseFunc(xmlHttpReq.responseText);
	}
    //Return results on synchronous requests
    else
    {
        //Compose and send the request string
        xmlHttpReq.send(req);

		//Write to a response element if the user provided one
		if (responseEl)
			responseEl.innerHTML = xmlHttpReq.responseText;
		else
			return xmlHttpReq.responseText;
    }	
    
}


//=============END AJAXHandler JS==============