﻿var xmlhttpKeepAlive = null;
var keepAliveState = 'False';
function keepAlive() {

    xmlhttpKeepAlive = null;

    if (window.XMLHttpRequest) {// code for all new browsers
        xmlhttpKeepAlive = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {// code for IE5 and IE6
        xmlhttpKeepAlive = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttpKeepAlive != null) {

        xmlhttpKeepAlive.onreadystatechange = keepAlive_state_Change;


        var params = "keep=" + keepAliveState;

        xmlhttpKeepAlive.open("POST", "/KeepAlive.ashx", true);
        //Send the proper header information along with the request
        xmlhttpKeepAlive.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttpKeepAlive.setRequestHeader("Content-length", params.length);
        xmlhttpKeepAlive.setRequestHeader("Connection", "close");

        xmlhttpKeepAlive.send(params);  

    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }
}

function keepAlive_state_Change() {
    if (xmlhttpKeepAlive.readyState == 4) {// 4 = "loaded"
        if (xmlhttpKeepAlive.status == 200) {
            if (xmlhttpKeepAlive.responseText == 'logout') {

                document.location.href = '/logout.aspx?redirect=' + document.location.href;

            } else if (xmlhttpKeepAlive.responseText == 'False') {
                //Do nothing as we do not want to keep refreshing as we have turned it off
        } else {
                // 3121 - Increase keep alive to something more sensible
                // 2011-03-24
                // Peter Mills
                // Now at a minute, instead of 5 seconds
                setTimeout('keepAlive()', 60000);
            }
        }
        else if (xmlhttpKeepAlive.status == 0) {
            // Ajax was interupted, this is normal, so don't error about it
        }

        else {
            //An error has occured. What to do with these error. For now we will display the error in the form of a message box
            alert("error: " + xmlhttpKeepAlive.responseText + " - " + xmlhttpKeepAlive.status);
        }
    }
}


function switchState(sender) {

    //I know that the logic is reversed here but this is becase the keepAliveState has not been switched yet
    if( keepAliveState.toString().toLowerCase() == 'true') {
        keepAliveState = 'false';
    }
    else {
        keepAliveState = 'true';
    }

    keepAlive();

}


    




