//Create and manage ajax requests.
//To create new request:
/*
function request_name(any_parameters)
{
    var xhrObject=asyncAjaxRequestGet(url);
    xhrObject.onreadystatechange=function ()
    {

        if(validateAjaxResponse(xhrObject)=="Ready")
        {
            //Code to be processed if request successfully completed.
        }
        if(validateAjaxResponse(xhrObject)=="Not Ready")
        {
            //Code to be processed if request IS NOT successfully completed.

        }

    };
}

OR ------

function request_name(any_parameters,function_success,function_failure)
{
    var xhrObject=asyncAjaxRequestGet(url);
    xhrObject.onreadystatechange=function ()
    {

        if(validateAjaxResponse(xhrObject)=="Ready")
        {
            function_success();
        }
        if(validateAjaxResponse(xhrObject)=="Not Ready")
        {
            function_failure();

        }

    };
}
 */
//Setup the XmlHttpRequest object and return it.

var Ajax = {
xmltext:"",

    setup:function()
    {
        var ajaxreq;
   
        if(window.XMLHttpRequest)
        {
            ajaxreq=new XMLHttpRequest();
        }
        else if(window.ActiveXObject)
        {
            ajaxreq=new ActiveXObject("Microsoft.XMLHTTP");
        }

        if(ajaxreq!=null)
        {
            return ajaxreq;
        }
        else
        {
            return null;
        }
    },

    //Create an asynchronous AJAX 'Get' request given url with parameters
    asyncAjaxRequestGet:function (url)
    {
        var xhr=Ajax.setup();

        xhr.open("Get",url+"?"+Math.random(),true);

        xhr.send(null);

        return xhr;
    },

    //Create an synchronous AJAX 'Get' request given url with parameters
    syncAjaxRequestGet:function (url)
    {
        var xhr=Ajax.setup();

        xhr.open("Get",url,false);

        xhr.send(null);
        return xhr.responseText;
    
    },


    //Create an asynchronous AJAX 'Post' request given url with parameters
    asyncAjaxRequestPost:function (params,url)
    {
        var xhr=Ajax.setup();

        xhr.open("POST", url, true);

        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Content-length", params.length);
        xhr.setRequestHeader("Connection", "close");

        xhr.send(params);
        return xhr;
    },



    //Validate response to see if the proper response was returned
    validateAjaxResponse: function (xhr)
    {
        if(xhr.readyState==4)
        {
            if(xhr.status==200)
            {
                return "Ready";
            }
            if(xhr.status!=200)
            {
                return "Not Ready";
            }
        }
    },

    //Get status of response for debug
    responseStatus:function (xhr)
    {
        return  "State: "+xhr.readyState+"   HTTP Status: "+xhr.status+"<br>"+xhr.responseText;
    }
   
};



