var timer = null;
var dialogHandle = null;
var AlertTime = 300000;  // 5 minutes
var InfoTimeoutInterval = 60000;  // 1 minute
var timeoutTemplate = "<div id='timeout_message'>Your session will expire in [] min...</div>";

function StartTimer(timeout)
{ 
  if (dialogHandle != null)
    CloseDialog();
    
  //alert('timer: ' + timer + '  timeout: ' + timeout);
  timeout = timeout - AlertTime;
  if (timeout > 0)
  {
    //alert('start timer: ' + timeout);
    if (timer != null) window.clearTimeout(timer);
    timer = window.setTimeout("TimeoutDialog()", timeout);
  }
}

function ResetTimer(timeout)
{
  if (opener == null || opener.closed)
  {
    StartTimer(timeout);
  }
  else
  {
    //alert(opener.closed);
    if (!opener.closed)
      opener.ResetTimer(timeout);
  }
}

ResetTimer(GetTimeLeft());


function TimeoutDialog() 
{
  var S = timeoutTemplate.replace("[]", AlertTime / InfoTimeoutInterval);
    
  dialogHandle = Dialog.alert(S, {className:"hansen", width:400, height:null, okLabel:"Continue", onOk:ExtendSession});
  var timeLeft = AlertTime / InfoTimeoutInterval;
  setTimeout("InfoTimeout(" + timeLeft + ")", InfoTimeoutInterval);
}

function InfoTimeout(timeLeft) {
  var S;
  timeLeft--;
  if (timeLeft > 0) 
    S = timeoutTemplate.replace("[]", timeLeft);
  else
    S = "Your session has expired"; 

  var obj = $('timeout_message');
  if (obj)
  {
    obj.update(S);
    if (timeLeft > 0)
      setTimeout("InfoTimeout(" + timeLeft + ")", InfoTimeoutInterval);
  }
}

function ExtendSession() 
{
  CloseDialog();
  var now = new Date();
  var continueURL = "https://" + GetAppPath() + "/OnlineServices/ExtendSession.aspx?t=" + now.getTime();
  //alert(continueURL + '    ' + window.location.protocol);
  var result = new Ajax.Request(continueURL, 
    	              { method: "get",
    	                onSuccess: function(transport) 
    	                {
    	                  var timeLeft = parseInt(transport.responseText);
    	                  //alert('timeLeft: ' + timeLeft);
    	                  if (timeLeft > 0)
    	                    ResetTimer(timeLeft);
    	                  else
    	                    DoLogout();
    	                },
    	                onFailure: function(transport) 
    	                           {
    	                             //alert("failed");
    	                           }
    	              });
}

function DoLogout()
{
  //alert('logout');
  var obj = document.getElementById('lnkLogin');
  if (obj)
  {
    //alert(obj.href);
    window.location = obj.href;
  }
}

function CloseDialog()
{
  dialogHandle.close();
  dialogHandle = null;
}
