/*
 * Dynatronics TimeOut feature 
 * Version 1.1 (12-29-2010)
 * @requires jQuery v1.4.4 or later
 * @requires jquery.idle-timer.js
 * @requires jquery-ui-1.8.7.custom.min.js
 */

var inactivityTimer = 10 * 60;  //Time in seconds user has before warning dialog
var redirectTimer   = 2 * 60; //Time in seconds user has before session expires
var countdownTimer;

jQuery(document).ready(function() {
  // setup console.log
  if(typeof console === "undefined"){
    console = { log: function() { } };
  }

  //If user is logged in, Call BindTimer
  jQuery.ajax({
    type: 'POST',
    url: IsLoggedInUrl,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: BindTimer
  });
    
  jQuery('#SessionTimeoutWarningDialog').dialog({ 
    title: 'You are about to be logged out!',
    modal: true,
    width: 460, 
    minHeight: 50,
    autoOpen: false,
    resizable: false,
    draggable: false,
    closeOnEscape: false,
    buttons: { 
      'Logout': function() {
        RedirectToLogin();
      },
      'Cancel': function() {
        clearCountdown();
        jQuery(this).dialog('close');
      }
    }, 
    open : function(event, ui) {
      // hide the close button
      jQuery(".ui-dialog-titlebar-close").hide();
    
      clearCountdown();
    
      var counter = redirectTimer;
      updateCountdown(counter);

      countdownTimer = setInterval(function() {
        counter -= 1;
        updateCountdown(counter);
      
        if (counter == 0) {
          jQuery('#SessionTimeoutWarningDialog').dialog('destroy');
          
          jQuery('#SessionTimeoutWarningDialog').dialog({ 
            title: 'You have been logged out!',
            modal: true,
            width: 460, 
            minHeight: 50,
            resizable: false,
            draggable: false,
            closeOnEscape: false,
            buttons: {
              'Login': function() {
                RedirectToLogin();
              }
            },
            open : function(event, ui) {
              // hide the close button
              jQuery(".ui-dialog-titlebar-close").hide();
              jQuery.idleTimer('destroy');
              clearCountdown();
            }
          });
        } 
      }, 1000); 
    }
  });
});
    

//Bind idle Timer to document (default: 10mins)
//If idle for 10mins, check if user is logged in still and has a current session 
//then call DisplaySessionExpireWarning
function BindTimer(result) {
  if (result) {
    jQuery.idleTimer(inactivityTimer * 1000); //
    jQuery(document).bind("idle.idleTimer", function() {
      jQuery.ajax({
        async: false,
        type: 'POST',
        url: IsAuthenticatedUrl,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: DisplaySessionExpireWarning
      });
    });
  };
};   
    
//Calls warning dialog.  displays a timer until session expires.  
//If counter reaches 0, user will be redirected to login
//once windows is closed.
function DisplaySessionExpireWarning(IsAuthSession) {
  if(IsAuthSession && (jQuery.data(document, "idleTimer") == 'idle')) {
    jQuery('#SessionTimeoutWarningDialog').dialog('open');
  }
};
    
function RedirectToLogin() {
  jQuery.ajax({
    async: false,
    type: 'POST',
    url: logoutAction
  });
  window.location = LogoutUrl;
}

function updateCountdown(counter) {
  var secCounter = Math.floor(counter % 60);
  var minCounter = Math.floor(counter / 60);
  var time = ((minCounter <= 0) ? '' : minCounter + ' minutes ') + ((secCounter <= 0) ? '' : secCounter + ' seconds');
  jQuery('#WarningDialogMsg').html(time);
}

function clearCountdown() {
  try {
    clearInterval(countdownTimer);
  }
  catch(err) {
    console.log(e.name + ' : ' + e.message);
  }
}
    
    

