// A timer that will expire the session after a set period.
var sessionTimer;

// The time after which the "your session will expire soon" message will be displayed.
var WARNING_DELAY = 0;
if (g_autologoutinterval > 0)
{
   // Subtract 1 minute because there will be a 1 minute countdown dialog after
   // this timer expires.
   WARNING_DELAY = (g_autologoutinterval -1) * 60 * 1000; // logout interval for role
}

// Display a countdown to session expiry on the warning dialog.
var COUNTDOWN_DELAY = 1000; // 1 second
var COUNTDOWN_START_SECONDS = 60;
var logoutCountdown = COUNTDOWN_START_SECONDS;
var timeoutCountdownMessage = gettext_noop("Your session will expire in %(seconds)s seconds.");

// Stop the timers if there are any ajax calls underway. We don't want to terminate
// the session due to a slow ajax call.
var globalAjaxCount = 0;

// Have a threshold for mouse movements before the autologout timer is reset.
// Small random movements from the mouse can continually reset it otherwise.
// The batch size needs to be fairly large, as one QA PC was observed to
// generate batches of up to 8 events in under 500ms.
var MOUSE_EVENT_COUNT_THRESHOLD = 10;
var mouse_move_counter = 0;
var mouse_move_group_start = Date.now();
var MOUSE_EVENT_TIME_THRESHOLD = 500;

// When the warning timer expires, display a message and start the session
// close timer.
function handle_warning_timeout() {
   showTimeoutWarning();
   clearTimeout(sessionTimer);
   sessionTimer = setTimeout(handle_sessionclose_countdown, COUNTDOWN_DELAY); 
}


// Handle session close countdown events and redirect the user to the logout page
// when the countdown completes.
function handle_sessionclose_countdown() {
   if (logoutCountdown > 1) {
      logoutCountdown--;
      updateTimeoutWarning();
      clearTimeout(sessionTimer);
      sessionTimer = setTimeout(handle_sessionclose_countdown, COUNTDOWN_DELAY);
   }
   else {
      clearTimeout(sessionTimer);
      window.location = '/session/auto_logout/'; 
   }
}


function showTimeoutWarning() {
   var formatStr = gettext(timeoutCountdownMessage);
   dict = {'seconds': logoutCountdown};
   var message = interpolate(formatStr, dict, true);
   showSessionTimeoutDialog(message);
}


function updateTimeoutWarning() {
   var formatStr = gettext(timeoutCountdownMessage);
   dict = {'seconds': logoutCountdown};
   var message = interpolate(formatStr, dict, true);
   $('#sessionTimeoutPopupContent').html(message);
}


$(document).ready(function () {
   // Set focus to the Username field. HTML5 has a focus attribute but
   // this is not supported by IE9.
   $('#id_username').focus();

    $('#logout_menu').on("click", "#logoutButton", function(e) {
        return confirm(gettext("Are you sure you want to logout?"));
    });

   // Autologout is not applicable on the login page or if the client is victor.
   if ($('#suppress_autologout').length > 0 ||
       $('#client_is_victor').length > 0 ||
       WARNING_DELAY == 0)
      return;

   // Set a timer that will expire the session after a set period.
   sessionTimer = setTimeout(handle_warning_timeout, WARNING_DELAY);

   // Now set up handlers to reset the timer on any page activity
   // provided there are no active ajax calls.
   $(document).on('mousemove keyup', function(event) {
      if (globalAjaxCount === 0) {
         var now = Date.now();

         // Have a threshold for mouse movements before the autologout timer is reset.
         // Small random movements from the mouse can continually reset it otherwise.
         // Group events into batches of MOUSE_EVENT_COUNT_THRESHOLD events.
         // If a batch takes < MOUSE_EVENT_TIME_THRESHOLD milliseconds it is treated as
         // a user-initiated mouse movement. Otherwise it is assumed that they are
         // unrelated random events.
         if (event.type === "mousemove") {
            var groupDuration = now - mouse_move_group_start;
            mouse_move_counter++;

            // We haven't filled a batch yet.
            if (mouse_move_counter < MOUSE_EVENT_COUNT_THRESHOLD) {
               return;
            }

            // The batch duration was over the threshold. Assume these are random events.
            if (groupDuration >= MOUSE_EVENT_TIME_THRESHOLD) {
               mouse_move_counter = 0;
               mouse_move_group_start = now;
               return;
            }
         }

         // The batch duration was under the threshold. Reset the timer.
         mouse_move_counter = 0;
         mouse_move_group_start = now;
         clearTimeout(sessionTimer);

         if (logoutCountdown < COUNTDOWN_START_SECONDS) {
            hideSessionTimeoutDialog();
            logoutCountdown = COUNTDOWN_START_SECONDS;
         }

         sessionTimer = setTimeout(handle_warning_timeout, WARNING_DELAY);
      }
   });


   // Stop the session timers if any ajax operation is underway.
   // Restart when all ajax operations complete.
   $(document).ajaxSend(function(event, jqXHR, settings) {
      globalAjaxCount++;
      clearTimeout(sessionTimer);
   });


   $(document).ajaxComplete(function(event, jqXHR, settings) {
      if (globalAjaxCount > 0) globalAjaxCount--;

      if (globalAjaxCount === 0) {
         sessionTimer = setTimeout(handle_warning_timeout, WARNING_DELAY);
      }
   });
});

