//MembersAJAX.js - set up to generalize AJAX used in ForumAjax.inc so AJAX can be used anywhere on the memberside if it was needed

//set up 7/21/2008 (Aaron)
//11/05/2008 - forgeParamStr was using the wrong uri encode function (Aaron)
//11/25/2008 - changed to permit strings in the extra params in ajaxGet/Post (Aaron)

//========================================AJAX===========================================
//Allow direct ajax invocation if not already able
if( !window.XMLHttpRequest ) XMLHttpRequest = function()
{
    //try a bunch of versions
    var activeXObjects = ['MSXML3.XMLHTTP', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
    for(var i=0; i<activeXObjects.length; i++)
    {
        try
        {
            return new ActiveXObject(activeXObjects[i]);
        }
        catch(err) //err is a js error object w/stuff like err.description, but we use the throw to create our own error object
        {
            if(i == activeXObjects.length - 1)
            {
                alert("This page uses AJAX. An XMLHttpRequest alternative could not be found for your browser.")
            }
        }
    }
}

/*
-------------Example Receive-------------
//called when you receive a response from calling ChangeTable()
//somewhere on your page you must have the div or whatever you want that is to be changed
//you can pass extra parameters to ajaxGET/POST and they'll be sent here after txtdata in the order you send
function ChangeTableReceive(txtdata)
{
    var flddiv = document.getElementById("field_code_div");
    //this rewrites the select box & options gotten from the server (IE has bug with select.innerHTML)
    flddiv.innerHTML = txtdata;
}
*/


    
//receivingFunctions must be defined beforehand, function that calls this afterward
//ajax simplifier using GET method (URL should as usual be under 2000 chars)
function ajaxGET(url, receivingFunction)
{
    var AjaxObj = new XMLHttpRequest;
    
    //supplying a random # as a qstring param seems to be the simplest cross-platform method of eliminating page caching
    url = URL_Push(url,"RANDOM",Math.random())
    
    //allows unlimited additional parameters to be passed to the receivingFunction after the first 2 required by GET
    var functionCallText = ""
    for(var i=2; i<arguments.length; i++)
    {
        if(typeof arguments[i] === 'string')
        {
            functionCallText+= ", '" + arguments[i] + "'"
        }
        else
        {
            functionCallText+= ", " + arguments[i]
        }
    }
    functionCallText = "receivingFunction(AjaxObj.responseText" + functionCallText + ")"
    
    //create a f(x) around the receiving f(x) that will handle the readyState stuff so receiving f(x) is only called when data is there
    AjaxObj.onreadystatechange = function()
    {
        if (AjaxObj.readyState == 4 && AjaxObj.status == 200)
        {
          if (AjaxObj.responseText)
          {
              eval(functionCallText);
          }
        }
    }
    AjaxObj.open("GET", url, true);
    AjaxObj.send(null);
}


/*
-----------Example Calling Function-------------
    //somewhere on your page you have it call this, like in an onchange
    function ChangeTable()
    {
        var tableName = document.theForm.file_name[document.theForm.file_name.selectedIndex].value   
        if(tableName == "") return;
        
        var url = "<%=THIS_PAGE%>?action=<%= ACTION_AJAX_COLUMNS %>&TABLE=" + tableName
        
        ajaxGET(url, ChangeTableReceive)
    }
    
    
-------------------------------------------    
    Finally on your asp page you need a function that gets called when the ajax request is sent to the server.
    All this does response.Expires = -1 (indicates cached page should immediately expire on server) 
    and then writes out data with response.write. You can request the data sent on the form/url as normal.
   
   
   
   
-----------------------------------------------------------------------------------------------------------------------------------   
   You can also use POST instead of GET. To do so, use ajaxPOST instead of ajaxGET in your calling function. You'll also need
   to use forgeParamStr() to take what you want to send and package it up as below:
   
   var paramStr = forgeParamStr("batch",batch,"check",check,"status_id",status_id,"user_id", user_id, "returnOrNot", returnOrNot)
   ajaxPOST(url, ChangeTableReceive, paramStr)
   
   
*/



//takes a variable # of parameters (first the name, then the value) and returns them as a parameter string for the POST to use
function forgeParamStr()
{
    var paramStr = ""
    for(var i=0; i<arguments.length; i+=2)
    {
        if(i > 0)
        {
            paramStr += "&"
        }
        paramStr += arguments[i] + "=" + encodeURIComponent(arguments[i+1])
    }
    return paramStr
}

    

//ajax simplifier using POST method
function ajaxPOST(url, receivingFunction, paramStr)
{
    var AjaxObj = new XMLHttpRequest;
    
    //supplying a random # as a qstring param seems to be the simplest cross-platform method of eliminating page caching
    url = URL_Push(url,"RANDOM",Math.random())
    
    
    //allows unlimited additional parameters to be passed to the receivingFunction after the first 3 required by POST
    var functionCallText = ""
    for(var i=3; i<arguments.length; i++)
    {
        if(typeof arguments[i] === 'string')
        {
            functionCallText+= ", '" + arguments[i] + "'"
        }
        else
        {
            functionCallText+= ", " + arguments[i]
        }
    }
    functionCallText = "receivingFunction(AjaxObj.responseText" + functionCallText + ")"
    
    //create a f(x) around the receiving f(x) that will handle the readyState stuff so receiving f(x) is only called when data is there
    AjaxObj.onreadystatechange = function()
    {
        if (AjaxObj.readyState == 4 && AjaxObj.status == 200)
        {
          if (AjaxObj.responseText)
          {
              eval(functionCallText);
          }
        }
    }
    
    AjaxObj.open("POST", url, true);
    
    //set header info for POST
    AjaxObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    AjaxObj.setRequestHeader("Content-length", paramStr.length);
    AjaxObj.setRequestHeader("Connection", "close");
    
    AjaxObj.send(paramStr);
}



function URL_Push(url,name,value)
{
    if(url.search(/\?/) == -1)
    {
        //if no ? then we need to put one in
        return url + "?" + name + "=" + value;
    }
    else
    {
        //already has ? so use & to add another param to qstring
        return url + "&" + name + "=" + value;
    }
}

