// Kyle Peterson
// http://codebit.wordpress.com
// http://codebit.wordpress.com/2012/08/26/session-timeout-warning-popup-for-multiple-tabs/
//
// This script depends on Warning.htm.
//
// Customizations (c) 2013, eSecuritel, LLC.

function SessionTimeoutWarning(iSessionTimeoutValue) {
    var self = this;

    self.iSecondsTillWarning = ((iSessionTimeoutValue - 1) * 60);
    self.iSecondsTillRedirect = 60;
    self.iMSecWarningDelayMax = 4000;
    self.sShowCountdownCookieName = "TimeoutWarningDisplay";
    self.sSemaphoreCookieName = 'TimeoutWarningSemaphore';
    self.sLastAccessTimeCookieName = "TimeoutWarningLastAccessTime";
    self.sWarningURL = "/eSecuritel/HITS/WebSite/warning.htm?SessionTimeoutValue=" + iSessionTimeoutValue;
    self.sLogoutURL = "/esecuritel/HITS/WebSite/LogOff.aspx";
    self.sPopupBlockedMessage = "Your browser blocked a popup trying to warn you that your session is about to time out.  Disable your popup blocker for this site so you can receive the warning popup next time.";

    self.StartTimeoutWarningTimer = function (bFirstLoad) {
        self.SetTimeoutWarningTimer("now");
        if (bFirstLoad === true) {
            setInterval(self.CheckTimeoutWarningTime, 1000);
        }
    };

    self.SetTimeoutWarningTimer = function (sSwitch) {
        switch (sSwitch.toLowerCase()) {
            case "now":
                self.CreateCookie(self.sLastAccessTimeCookieName, (new Date()).getTime());
                break;
            case "zero":
                self.CreateCookie(self.sLastAccessTimeCookieName, 0);
                break;
        }
    }
    
    self.CheckTimeoutWarningTime = function() {
        var iLastAccessTime = parseInt(self.ReadCookie(self.sLastAccessTimeCookieName), 10);
        if (iLastAccessTime === 0) {
            window.location.href = self.sLogoutURL;
        }
        var iNow = (new Date()).getTime();
        var iTimeoutWarningTime = iLastAccessTime + (self.iSecondsTillWarning * 1000);
        //console.log("CheckTimeoutWarningTime: " + (iTimeoutWarningTime - iNow).toString());
        if (iNow >= iTimeoutWarningTime) {
            //if it's been 1 second since the warning time stop trying to open the warning popup
            //-this controls opening the popup so that after the iTimeoutWarningTime has passed the pages won't try
            //to keep opening the popup
            if (iNow <= iTimeoutWarningTime + 1000) {
                //console.log(" TimeoutWarning Triggered + 1 sec")
                var delayMs = Math.floor(Math.random() * self.iMSecWarningDelayMax);
                //console.log('DelayedTimeOutWarning, ' + delayMs.toString());
                //Delay checking the existance of the semphore cookie and possibly opening the timeout dialog for a 
                //variable number of microseconds to prevent all open windows from checking/creating the cookie
                //at the same time.  This prevents multiple dialogs from opening at the same time.
                setTimeout(self.DelayedTimeoutWarning, delayMs);
            } else {
                return false;
            }
        } else {
            var oTitleParts = document.title.split("|");
            var sOriginalTitle = (oTitleParts.length == 1) ? oTitleParts[0] : oTitleParts[1];
            if (self.ReadCookie(self.sShowCountdownCookieName) == "1") {
                var iSecondsLeft = (iTimeoutWarningTime - iNow) / 1000;
                var iMinutes = Math.floor(iSecondsLeft / 60);
                var iSeconds = Math.floor(iSecondsLeft % 60);
                var sTime = ((iMinutes < 10) ? "0" + iMinutes : iMinutes) + ":" + ((iSeconds < 10) ? "0" + iSeconds : iSeconds);
                document.title = sTime + " | " + sOriginalTitle;
            } else {
                document.title = sOriginalTitle;
            }
        }
    };

    self.DelayedTimeoutWarning = function () {
        var cookie = self.ReadCookie(self.sSemaphoreCookieName);
        if (cookie == '') {
            self.CreateCookie(self.sSemaphoreCookieName, 'does not matter');
            self.TimeoutWarning();
        }
    }

    self.ToggleTimeoutWarningDisplay = function () {
        if (self.ReadCookie(self.sShowCountdownCookieName) != "1") {
            self.CreateCookie(self.sShowCountdownCookieName, "1");
        } else {
            self.CreateCookie(self.sShowCountdownCookieName, "0");
        }
    };

    self.StartTimeoutRedirectTimer = function () {
        setTimeout(self.TimeoutRedirect, self.iSecondsTillRedirect * 1000);
    };

    self.TimeoutWarning = function () {
        var win = window.open(self.sWarningURL, "TimeoutWarning", "width=420, height=260, scrollbars=0, status=0");
        if (win === null || typeof (win) === "undefined") {
            //popup didn't exist
            alert(self.sPopupBlockedMessage);
        } else {
            //browsers like chrome do physically create the window object but they hide
            //the window so we have to check if it is a shrunken window
            win.onload = function () {
                //wait a little bit before checking the dimensions of the popup content to be certain
                //chrome has had time to update it's properties
                setTimeout(function () {
                    if (win.innerHeight === 0) {
                        alert(self.sPopupBlockedMessage);
                    }
                }, 500);
            };
        }
    };

    self.TimeoutRedirect = function () {
        if (window.opener && window.opener.open && !window.opener.closed) {
            window.opener.location.href = self.sLogoutURL;
        }
        //set to zero so all tabs can identify a redirect happening and redirect themselves too
        self.SetTimeoutWarningTimer("zero");
        window.close();
    };

    //-----------------------------------------------------------------------------
    // COOKIES (http://www.quirksmode.org/js/cookies.html)
    //-----------------------------------------------------------------------------

    self.CreateCookie = function (name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    };

    self.ReadCookie = function (name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return "";
    };
}


function getURLParam(name) {
    // get query string part of url into its own variable
    var url = window.location.href;
    var query_string = url.split("?");

    if (query_string.length > 1) {

        // make array of all name/value pairs in query string
        var params = query_string[1].split("&");

        // loop through the parameters
        var i = 0;
        while (i < params.length) {
            // compare param name against arg passed in
            var param_item = params[i].split("=");
            if (param_item[0] == name) {
                // if they match, return the value
                return param_item[1];
            }
            i++;
        }
    }
    return "";
}

// logout solution thru meta tag 
//http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2