var keepAliveImage = null;

function KeepAlive()
{
    if(!keepAliveImage)
    {
        bodyTag = document.getElementsByTagName("body")[0];

        keepAliveImage = document.createElement("img");
        var d = new Date();
        var t = d.getTime();
        keepAliveImage.setAttribute("src", "keepalive.jsp?t="+t);
        keepAliveImage.style.position = "absolute";
        keepAliveImage.style.height = "1px";
        keepAliveImage.style.width = "1px";
        bodyTag.appendChild(keepAliveImage);

    }
    else
    {
        var d = new Date();
        var time = d.getTime();
        keepAliveImage.src = "keepalive.jsp?d=" + time;
    }
    
    setTimeout("KeepAlive()", 300000);
}
//1440000 = 24minutes
setTimeout("KeepAlive()", 300000);

var getXMLHttpObj;
if(typeof(XMLHttpRequest)!='undefined')
{
    getXMLHttpObj = function(){ return new XMLHttpRequest(); }
} else {
    getXMLHttpObj = function(){
        var activeXObjects = ['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)
            {}
        }
    }
}


var reqNames = new Array();
var reqs = new Array();
var ajaxListeners = new Array();
/*
 * This method will keep track of request objects that were created against
 * a particular name/id. If we already have an object created for a specific name/id
 * then that object will be returned by this method. If not, we will create a new
 * one and return it. This functions basically as a hashmap of id to ajax object so
 * we can keep track of the progress of the request and process the result when its done.
 */
function getReqByName(name)
{
    for(i=0; i<reqNames.length; i++)
        if (reqNames[i]==name)
        {
            if (reqs[i]==null)
            {
               reqs[i] = getXMLHttpObj();
            }
            return reqs[i];
        }

    // Couldn't find the req name. Create a new entry...
    reqNames[reqNames.length] = name;
    newReq = getXMLHttpObj();
    reqs[reqs.length] = newReq;
    return newReq;
}

/*
 * Sends a request to check for an update based on a particular ID (the url IS the ID).
 * Just so we're clear, we are using the url that points to the inner jsp as the ID.
 * Once the request comes back, checkForAjaxUpdateDone will be fired. See that method
 * for details.
 *
 * This check is hard-coded right now at a 1 second interval.
 */
function checkForAjaxUpdate(url, soundEffect, params)
{
   currentUpdateId = document.getElementById(url+"UpdateId").value;
   req = getReqByName(url);
   if (window.XMLHttpRequest)
   {
       req.open("GET", "UpdateCheck?identifier="+url.replace("::Q::", "?")+"&w="+new Date().getTime(), true);
       req.onreadystatechange = function() {checkForAjaxUpdateDone(url, soundEffect, params);};
       req.send(null);
   }
   // IE/Windows ActiveX version
   else if (window.ActiveXObject)
   {
       req.open("GET", "UpdateCheck?identifier="+url.replace("::Q::", "?")+"&w="+new Date().getTime(), true);
       req.onreadystatechange = function() {checkForAjaxUpdateDone(url, soundEffect, params);};
       req.send();
   }
   setTimeout("checkForAjaxUpdate('"+url+"', '"+soundEffect+"', "+stringArrayToString(params)+")", 1000);
}

function stringArrayToString(array)
{
    var parametersArrayString = "[";
    if (array!=null)
        for(var i = 0; i<array.length; i++)
            parametersArrayString += "'"+array[i]+"',";
    parametersArrayString = parametersArrayString.replace(",$", "");
    parametersArrayString += "]";
    return parametersArrayString;
}

/*
 *This method is fired when the "check" for an update returns from the server.
 *This will not contain any data but rather just a unique code that we can compare
 *with our local code to see if we have the latest updates. If not, we call
 *the updateAjax() method to request the new html data.
 */
function checkForAjaxUpdateDone(url, soundEffect, params)
{
    req = getReqByName(url);
    // only if req is "loaded"
    if (req.readyState == 4)
    {
        // only if "OK"
        if (req.status == 200 || req.status == 304)
        {
            results = req.responseText.replace(/^\s+|\s+$/g, '').replace(/[(\r|\n)]+/g, '');
            if (results!=document.getElementById(url+"UpdateId").value)
            {
                document.getElementById(url+"UpdateId").value = results;
                updateAjax(url, soundEffect, params);
            }
        }
    }
}


/*
 * This is a simple function that submits an url to the server without loading
 * the response to the page. The response is actually not tracked.
 *
 * This method should be used to submit chat messages or other simple one-way
 * requests that are not necessary to be tracked to ensure they reach their
 * destination.
 */
function basicAjaxRequest(url)
{
   req = getXMLHttpObj();
   if (window.XMLHttpRequest)
   {
       req.open("GET", url, true);
       req.send(null);
   }
   // IE/Windows ActiveX version
   else if (window.ActiveXObject)
   {
       req.open("GET", url, true);
       req.send();
   }
}

/*
 * Requests to the server to give us the latest ajax area data so we can update
 * the page with it.
 * updateAjaxDone() is fired when this request comes back.
 */
function updateAjax(url, soundEffect, params)
{
   req2 = getReqByName(url);
    
   var paramUrl = url.replace("::Q::", "?");
   if (paramUrl.indexOf("?")==-1)
       paramUrl+="?";
   for(var i = 0; i<params.length; i=i+2)
       paramUrl+="&"+params[i]+"="+params[i+1];
   paramUrl = paramUrl.replace("?&", "?");
   if (window.XMLHttpRequest)
   {
       req2.open("GET", paramUrl, true);
       req2.onreadystatechange = function() {updateAjaxDone(url, soundEffect);};
       req2.send(null);
   }
   // IE/Windows ActiveX version
   else if (window.ActiveXObject)
   {
       req2.open("GET", paramUrl, true);
       req2.onreadystatechange = function() {updateAjaxDone(url, soundEffect);};
       req2.send();
   }
}

/*
 * Updates the page's ajax area with the new html that just came in from the server.
 *
 *  This method is automatically called when updateAjax() method is invoked and the
 *  request has finally returned.
 */
function updateAjaxDone(url, soundEffect)
{
    req2 = getReqByName(url);
    if (req2.readyState == 4)
    {
        // only if "OK"
        if (req2.status == 200 || req2.status == 304)
        {
            jQuery(document.getElementById(url)).html(req2.responseText);
            //document.getElementById(url).innerHTML = req2.responseText;
            if (soundEffect!=null)
            {
                newAudio(soundEffect, 'soundEffect', 3, 0);
            }
            for(var i = 0; i<ajaxListeners.length; i++)
                ajaxListeners[i]('updated', url);
        } else {
            document.getElementById(url).innerHTML="ajax error:\n" + req2.statusText;
        }
    }
}

function addAjaxListener(func)
{
    ajaxListeners.push(func);
}