﻿// allows to extend user session for pages that user normally need more time to process
//using this page requires the page to register for ajax calls
//----------------------------------
//indicates whether user performed any activity since last ajax call
var _isUserActivityDetected = false;
var _intervalId = 0;
//----------------------------------
//register the page to extend user session based on user activity
//sessionTimeout session timeout in minutes
//isIgnoreActivity indicates whether to take user activity into consideration, or to execute ajax call regardless - this should only be used if some controls can't be hooked to in terms of activity
//----------------------------------
function RegisterExtendUserSession(sessionTimeout, isIgnoreActivity)
{
    //just in case this was already registered, we disables the previous one
    UnRegisterExtendUserSession();
    
    //take out 2 min from session timeout just to ne on safe side
    var msActivityInterval = (sessionTimeout - 2) * 60 * 1000;
    
    //if we not ignoring activity we hook body events to detect user activity
    if(!isIgnoreActivity)
    {
        document.body.onkeypress = IndicateUserSessionActivity;
        document.body.onmousemove = IndicateUserSessionActivity;
    }
    //checks for activity for every period
    var functionToExecute = 'CheckRefreshUserSession(' + isIgnoreActivity + ');';
    _intervalId = setInterval(functionToExecute, msActivityInterval);
}
//disables the user session interval
function UnRegisterExtendUserSession()
{
    try
    {
        if(_intervalId==0)
            return;
            
        //clears the interval
        clearInterval(_intervalId);
        _intervalId = 0;
    }
    catch(e){}
}
//----------------------------------
//indicates that user has made some activity
//----------------------------------
function IndicateUserSessionActivity()
{
    _isUserActivityDetected = true;
}
//----------------------------------
//if user made any activity since last time calls the page using ajax, so session is refreshed
//isIgnoreActivity - when true we exute the ajax call regardless of user activity
//----------------------------------
function CheckRefreshUserSession(isIgnoreActivity)
{
    if(_isUserActivityDetected || isIgnoreActivity)
    {
        Get('','');
        _isUserActivityDetected = false;
    }
}

