/**
 ******************************************************************************
 * Copyright (c) 2006-2007. EMC Corporation.  All Rights Reserved.
 ******************************************************************************
 *
 * Project        WDK
 * File           timeouthandler.js
 * Description    WDK Datagrid Clientside model
 * Created on     27th June 2008
 * Tab width      3
 *
 ******************************************************************************
 */

/* Session Timeout Enhancement:
 */                                                               
function initTimeoutOnFormRefresh(url,contextPath,sessionId,timeout,timeoutWarningInt,excludeList,msg_timeout_warning,msg_timeout_message,msg_timeout_new_window_confirmmessage)
{
   //Resolve the URLS which are to be excluded from displaying a timeoutwarning. The exclude URLs are delimited using commas
   var excludeURLList = excludeList.split(",");
   var excludeURL = false;

   for(var i=0;i<excludeURLList.length;i++)
   {
      if(url == contextPath+excludeURLList[i])
      {
         excludeURL = true;
         break;
      }
   }

   //Convert the timeoutWarningDelay from seconds to milliseconds
   var timeoutWarningDelay = timeoutWarningInt*1000;

   var timeoutVal = new Date();

   // Clear Existing Timeout on Susbequent Calls.
   if (getTopLevelWnd().sessionRefreshTimer != null)
   {
      getTopLevelWnd().clearTimeout(getTopLevelWnd().sessionRefreshTimer);
   }

   // Set/Upate the cookie "timeoutHandler<JSESSIONID>" here for the first time and during subsequent calls
   setCookie("timeoutHandler"+sessionId,timeoutVal.getTime(),null,"/");
   
   //Trace_println("timeouthandler.js: (Re)Set the timeout cookie to the following value:" + timeoutVal.getTime());

   var f=  function handleTimeout()
           {
                //Trace_println("timeouthandler.js: Entered the 'handleTimeout' Method. ");

                // Dont handle session timeout warning/alert check if the cookie value is set to -1
                // (This Special Value is for preventing from displaying alerts twice for multiple windows sharing
                // the same session case)
                if((getCookie("timeoutHandler"+sessionId) != "-1"))
                {
                  // Check whether a timeout warning alert or a session timeout alert message needs to be displayed by reading out the
                  // cookie values , else reset the timer with a difference of <Configured session timeout> minus
                  // the (Current timestamp minus the cookie timestamp which is equivalent to the elapsed time)
                  var currentTimeStamp = new Date();
                  var timeoutHasOccurred = (currentTimeStamp.getTime() - getCookie("timeoutHandler"+sessionId)) >(timeout*1000);
                  var timeoutWillOccur = ((currentTimeStamp.getTime() - getCookie("timeoutHandler"+sessionId)) >= (timeout*1000 - timeoutWarningDelay)) && ((currentTimeStamp.getTime() - getCookie("timeoutHandler"+sessionId)) < (timeout*1000));

                  // Display the warning if the timestamp has not crossed the sessiontimeout value. After displaying the
                  // Warning re-calculate the values with the elapsed time and restart the counter to re-call the handleTimeout method.
                  if(timeoutWillOccur && !timeoutHasOccurred)
                  {
                     // Trace_println("timeouthandler.js: Entered the timeout Warning condition "+timeoutWillOccur+ " "+timeoutHasOccurred +" "+ currentTimeStamp.getTime());
                     // Dont display alert when the page is among the excluded url list
                     // Dont display warning if timeoutWarningDelay is zero: This if condition is not hit...but an extra check
                     if( !excludeURL && !(timeoutWarningDelay == 0) )
                     {
                        alert(msg_timeout_warning+" "+currentTimeStamp+")!!");
                     }
                     // Re-Calculate the timeouthandler call with the difference from when the user responds to the
                     // Warning alert.
                     currentTimeStamp = new Date();
                     var freshTimeStamp = timeout*1000 -(currentTimeStamp.getTime() - getCookie("timeoutHandler"+sessionId));
                     // Trace_println("timeouthandler.js: Fresh TimeStamp after re-calculating the timeouthandler post response to the warning "+freshTimeStamp);
                     if(freshTimeStamp >= 0 )
                     {
                        getTopLevelWnd().sessionRefreshTimer = getTopLevelWnd().setTimeout(f, freshTimeStamp);
                     }
                     else
                     {
                        getTopLevelWnd().sessionRefreshTimer = getTopLevelWnd().setTimeout(f, 0);
                     }
                  }
                  else if(timeoutHasOccurred)
                  {
                     // Trace_println("timeouthandler.js: Timeout has occurred");

                     // Set the cookie value to -1 to indicate that the user
                     // has been notified about a session-timeout for a multi-window case
                     setCookie("timeoutHandler"+sessionId,"-1",null,"/");
                     //Dont display alert when the page is among the excluded url list
                     if(!excludeURL)
                     {
                        alert(msg_timeout_message);
                     }
                     relogin();
                  }
                  else
                  {
                     // Reset the timer with a difference of  <configured session-timeout>  minus <Configured timeout value> and minus
                     // the (Current timestamp minus the cookie timestamp => elapsed time)
                     var newTimeStamp = timeout*1000- timeoutWarningDelay - (currentTimeStamp.getTime() - getCookie("timeoutHandler"+sessionId));
                     // Trace_println("timeouthandler.js: Entered the reset timeout condition " + newTimeStamp);
                     if(newTimeStamp >= 0)
                     {
                        getTopLevelWnd().sessionRefreshTimer = getTopLevelWnd().setTimeout(f, newTimeStamp);
                     }
                     else
                     {
                        getTopLevelWnd().sessionRefreshTimer = getTopLevelWnd().setTimeout(f, 0);
                     }
                  }
               }
               else
               {
                  var answer = confirm(msg_timeout_new_window_confirmmessage);
                  if (answer)
                  {
                    getTopLevelWnd().close();
                  }
               }
            };

   //Sets the timeout check timer.
   getTopLevelWnd().sessionRefreshTimer = getTopLevelWnd().setTimeout(f, timeout*1000- timeoutWarningDelay);
}

function relogin()
{
  setTimeout("loginRedirect()", 3000);
}


/* redirect to the login/main page
*/

function loginRedirect()
{
     fireAppIntgEvent("event=HideDialog");
     fireAppIntgEvent("event=SessionTimeout");

     var targetWindow = getTopLevelWnd();

     if (window.getWindowOpener())
     {
      targetWindow = getTopLevelWndForApplication();
     }

     var strUrl = addBrowserIdToURL(g_virtualRoot+"/component/main");
     navigateToURL(strUrl, "timeout", targetWindow);

     if (window.getWindowOpener())
     {
        window.close();
     }
}


