﻿
//////////////////////////////////////////////////////////
// Session Timout Implementaion Javascript module
// Sajan Suwal - PSC
// Description & Usage:
//
//
//////////////////////////////////////////////////////////
//Cookie Access Functions
function createCookie(name, value, mins) {
    if (mins) {
        var date = new Date();
        date.setTime(mins);
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(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 null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

//JavaScript to handle session timeout and timeout popup
//uncomment the following session code for popup window mode
//debugger;

var session = {
    // session Info variables
    sessionAlertThres: null, // needs to be defined in minutes
    sessionTimeout: null, // needs to be defined in minutes
    // timers 
    sessionAlertTimeout: null,
    sessionTimeoutTimer: null,
    //other vars
    isPOPUP: false,
    cookieName: "NFM_sessionTimeOut",
    rootIs: null,
    popUp: null,
    refreshed: 1,
    xmlhttp: null,
    myExpireTime: null, //this is the expiretime set by current page.


    /////////////////////////////////////////////////////////////////////
    //function is loaded when web page is loaded.
    //This is the main function to initiate session time out functionality.
    /////////////////////////////////////////////////////////////////////
    startSessionTimer: function() {
        //debugger;
        session.init();
        session.myExpireTime = session.initCookie();
        session.closeSessionAlerts();
        session.sessionTimer();
    },
    //////////////////////////////////////////////////////////////////////


    popup: function() { //returns the popup
        url = arguments[0];
        features = arguments[1];
        returnVal = arguments[2];
        if (features == null)
            features = "";
        if (session.popUp)
            session.popUp.close();
        var wdow = window.open(url, "newWindow", features);
        if (returnVal == true)
            return wdow;
    },

    init: function() {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            session.xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            session.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        if (window.opener)
            session.isPOPUP = true;

    },

    initCookie: function() {
        //create cookie and set value to new expire time in ms
        var d = new Date();
        var currentTime = d.getTime();
        var addTime = parseFloat(session.sessionTimeout) * 60 * 1000;
        var expireInTime = parseFloat(currentTime) + addTime;
        createCookie(session.cookieName, expireInTime, expireInTime + 100);
        return expireInTime;
    },

    //if alert popups exist, close them
    closeSessionAlerts: function() {
        if (window.SessionTimeOutAlert) {
            window.SessionTimeOutAlert.close();
        }
        if ((window.opener)) {
            if (window.opener.SessionTimeOutAlert)
                window.opener.SessionTimeOutAlert.close();
        }
    },

    //read cookie and subtract current time to get time left for session to expire in ms
    getTimeLeftToExpire: function() {
        var expireTimeMS = session.getExpireTimeFrmCookie();
        if (expireTimeMS != null) {
            var d = new Date();
            expireTimeMS = expireTimeMS - d.getTime();
            return expireTimeMS;
        }
        return 0;
    },

    getExpireTimeFrmCookie: function() {
        return parseFloat(readCookie(session.cookieName));
    },

    sessionTimer: function() {
        var expireTimeMS = session.getTimeLeftToExpire();
        var sessionThresMS = session.sessionAlertThres * 60 * 1000;
        session.clearAll();
        if ((expireTimeMS - sessionThresMS) > 0)
            session.sessionAlertTimeout = window.setTimeout(session.loadSessionAlert, (expireTimeMS - sessionThresMS));
        else
            session.loadSessionAlert();

    },

    //clear the session pop up timeout.
    //clear the session expire alert timeout.
    clearAll: function() {
        if (session.sessionAlertTimeout)
            window.clearTimeout(session.sessionAlertTimeout);
        if (session.sessionTimeoutTimer)
            window.clearTimeout(session.sessionTimeoutTimer);
    },

    //execute timeout after 500ms delay
    sessionTimedOut: function() {
        window.setTimeout(session.timedOutAlert, 500);
    },

    //recursively reload page
    reload: function() {
        //if ((window.opener)&&(!window.opener.closed))
    //    window.opener.session.reload();
    if (window.name != "DeliveryPopUp")
        window.location.reload();

    },

    //this function is called on session timeout
    //Check cookie for timeoutand display the session timed out alert box and reload page
    timedOutAlert: function() {
        var timeLeft = session.getTimeLeftToExpire();
        if (timeLeft > 0) {
            session.sessionTimer();
        }
        else {
            //check to see if window has a parent
            if (!session.isPOPUP)//if window has parent don't show alert
            {
                   window.alert("Your Online Account session has timed out.\nAs a security measure, your session ends after " + session.sessionTimeout + " minutes of inactivity." +
                     "\nPlease login again.");
                   session.reload();
            } else {
                var url = location.href.toUpperCase();
                if ((url.indexOf("MYACCOUNT") != -1))
                    window.close();
                else
                    session.reload();
            }


        }
    },

    getSessionAlertThres: function() {
        return session.sessionAlertThres;
    },


    //reset the session by invoking a server page using xmlhttp objects
    activate: function() {
        session.xmlhttp.onreadystatechange = function() {
            // check states here
        }
        session.xmlhttp.open("GET", session.rootIs + "SessionTimeOutAlert.aspx", true);
        session.xmlhttp.send(null);
        session.startSessionTimer(); // start new timer
    },

    //load the session exipre countdown pop up window.
    loadSessionAlert: function() {
        session.closeSessionAlerts(); //close existing alerts before opening new one
        var timeLeft = session.getTimeLeftToExpire();
        session.refreshed = 0;
        if (timeLeft > (session.sessionAlertThres * 60 * 1000)) {
            session.sessionTimer();
        }
        else {
            if ((session.getExpireTimeFrmCookie() == session.myExpireTime)) //check if creator of cookie
                session.generatePopup(timeLeft);
            session.sessionTimeOut = window.setTimeout(session.sessionTimedOut, timeLeft);

        }
    },


    generatePopup: function(tim) {
        tim = parseInt(tim / 1000);
        popUp = window.open('', 'SessionTimeOutAlert', 'location=0,status=0,scrollbars=0,width=290,height=195');
        popUp.document.write('\n<html xmlns="http://www.w3.org/1999/xhtml">');
        popUp.document.write('\n<head>');
        popUp.document.write('\n<title>NFM - Session Timeout Notification</title>');
        //removed for IE8 issues
        //popUp.document.write('\n<link href="' + session.rootIs + 'CSS_Global/eMart_01.css" rel="stylesheet" type="text/css" />');
        //popUp.document.write('\n<script type="text/javascript" language = "javascript"  src="/JScript/Session.js"></script>');
        popUp.document.write('\n<script type="text/javascript">');
        popUp.document.write('\nfunction readCookie(name) {')
        popUp.document.write('\n   var nameEQ = name + "=";')
        popUp.document.write('\n   var ca = document.cookie.split(";");')
        popUp.document.write('\n   for (var i = 0; i < ca.length; i++) {')
        popUp.document.write('\n       var c = ca[i];')
        popUp.document.write('\n       while (c.charAt(0) == " ") c = c.substring(1, c.length);')
        popUp.document.write('\n      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);')
        popUp.document.write('\n  }')
        popUp.document.write('\n  return null;')
        popUp.document.write('\n }')

        popUp.document.write('\nfunction getTimeLeftToExpire(){')
        popUp.document.write('\n var expireTimeMS = getExpireTimeFrmCookie();')
        popUp.document.write('\nif (expireTimeMS != null) {')
        popUp.document.write('\n   var d = new Date();')
        popUp.document.write('\n expireTimeMS = expireTimeMS - d.getTime();')
        popUp.document.write('\n return expireTimeMS;')
        popUp.document.write('\n }')
        popUp.document.write('\n return 0;')
        popUp.document.write('\n }')

        popUp.document.write('\nfunction getExpireTimeFrmCookie(){')
        popUp.document.write('\n   return parseFloat(readCookie("' + session.cookieName + '"));')
        popUp.document.write('\n}  ')
        popUp.document.write('\nvar seconds = 0;');
        popUp.document.write('\nvar interval = -1;');
        popUp.document.write('\nfunction startCountDown(gSeconds) {');
        popUp.document.write('\n interval = 1;');
        popUp.document.write('\n seconds = gSeconds;');
        popUp.document.write('\n   interval = window.setInterval(updateDisplay, 2000);');
        popUp.document.write('\n}');
        popUp.document.write('\nfunction updateDisplay() {');
        popUp.document.write('\n var timeLeft = 0; ')
        popUp.document.write('\n timeLeft = getTimeLeftToExpire();');
        popUp.document.write('\n if (timeLeft>(seconds*1000)) { ');
        popUp.document.write('\n   window.close(); }');
        popUp.document.write('\n   var disp = parseInt(timeLeft/1000);');
        popUp.document.write('\ndocument.getElementById("timer").innerHTML = disp + " ";');
        //popUp.document.write('\n seconds -= 1;');
        popUp.document.write('\n if (window.opener){');
        popUp.document.write('\n if ((window.opener.closed) || (window.opener.session.refreshed == 1)) {');
        popUp.document.write('\n  self.close();');
        popUp.document.write('\n } }');
        popUp.document.write('\n if ((disp <= 0) || (isNaN(disp))) {');
        popUp.document.write('\n  window.clearInterval(interval);');
        popUp.document.write('\n  window.close();');
        popUp.document.write('\n}');
        popUp.document.write('\n}');
        popUp.document.write('\n function doExit() {');
        popUp.document.write('\n if (interval == -1) {');
        popUp.document.write('\n  window.close();');
        popUp.document.write('\n      if (window.opener && !window.opener.closed) {');
        popUp.document.write('\n      window.opener.session.sessionTimer();');
        popUp.document.write('\n      } ');
        popUp.document.write('\n  }');
        popUp.document.write('\n }');
        popUp.document.write('\n function activate() { ');
        popUp.document.write('\n window.opener.session.activate(); window.close();');
        popUp.document.write('\n } ');
        popUp.document.write('\n </script>');
        popUp.document.write('\n</head>');
        popUp.document.write('\n<body id="body"  style="font-size: 8pt;font-family: tahoma, verdana,arial,helvetica,sans-serif;color: #2B2B2B;background-color: #f0f0f0;background-image:url(/GlobalImages/holidaybackground.gif);background-repeat: repeat-x;">');
        popUp.document.write('\n<form id="aspnetForm" name="aspnetForm"  >');
        popUp.document.write('\n<div>');
        popUp.document.write('\n<table border="0" cellpadding="0" cellspacing="0" style="  border: collapse; width: 270px; padding:0; margin:0;">');
        popUp.document.write('\n<tr style="text-align:center;">');
        popUp.document.write('\n <td colspan="3" style="color: #ffffff; font-size: 8pt; height: 25px; width: 119px;background-color:darkgreen;  background-image:url(\'/GlobalImages/greenbarfade.gif\');background-repeat: repeat-x;');
        popUp.document.write('font-family: verdana,arial,helvetica,sans-serif; font-weight: bold; text-transform: uppercase; ');
        popUp.document.write('white-space: nowrap; text-align: center;">');
        popUp.document.write('\n Session Timeout');
        popUp.document.write('\n</td>');
        popUp.document.write('\n</tr>');
        popUp.document.write('\n<tr>');
        popUp.document.write('\n<td colspan="3" align="left" style="font-size: 8pt;font-family: verdana,arial,helvetica,sans-serif;padding-left:10px;padding-top:20px;padding-bottom:25px">');
        popUp.document.write('\nYour session at www.nfm.com website has been inactive for a while. <br> It will time out in <span  id="timer" style="font-weight:bold;"></span> seconds.');
        popUp.document.write('\n<br /><br>');
        popUp.document.write('\nTo keep your session active please');
        popUp.document.write('\n <a href="javascript:activate();">click here</a>.&nbsp; ');
        popUp.document.write('\n </td>');
        popUp.document.write('\n</tr>');
        popUp.document.write('\n<tr>');
        popUp.document.write('\n <td colspan="3" style="color: #ffffff; font-size: 8pt;background-color:darkgreen;  background-image: url(\'/GlobalImages/greenbarfade.gif\');');
        popUp.document.write('font-family: verdana,arial,helvetica,sans-serif; font-weight: bold; text-transform: uppercase; ');
        popUp.document.write('white-space: nowrap; text-align: center; height: 25px; width: 119px;">');
        popUp.document.write('\n</td>');
        popUp.document.write('\n</tr>');
        popUp.document.write('\n </table>  ');
        popUp.document.write('\n</div>');
        popUp.document.write('\n</form>');
        popUp.document.write('\n<script> startCountDown(' + tim + '); </script>');
        popUp.document.write('\n</body>');
        popUp.document.write('\n</html>');
        session.popUp = popUp;

    }



};

