

var timeoutWarning = $.extend(timeoutWarning || {}, timeoutWarning, {
  getLabel: function(label) {
    var labels = {
      errorHeader: "Uw ingevoerde gegevens zijn gewist",
      errorBodyPart1: "Uw privacy is belangrijk. De ingevulde gegevens worden daarom automatisch gewist als u langer dan %TOTALTIME% minuten pauzeert.",
      errorBodyPart2: "Deze tijd is inmiddels verstreken.",
      errorButton: "Opnieuw invoeren",
      warningHeader: this.isUserLoggedIn ? "U wordt (bijna) uitgelogd!" : "Uw ingevoerde gegevens worden (bijna) gewist!",
      warningBodyPart1: this.isUserLoggedIn ? "Uw privacy is belangrijk. U wordt daarom automatisch uitgelogd of ingevulde gegevens worden automatisch gewist als u langer dan %TOTALTIME% minuten pauzeert." : "Uw privacy is belangrijk. U wordt daarom automatisch uitgelogd of ingevulde gegevens worden automatisch gewist als u langer dan %TOTALTIME% minuten pauzeert.",
      warningBodyPart2: this.isUserLoggedIn ? "U hebt nog %REMAININGTIME% %MINUTE(S)% voordat u automatisch wordt uitgelogd. Als u gegevens aan het invullen was, zullen deze verloren gaan." : "U hebt nog %REMAININGTIME% %MINUTE(S)% om verder te gaan. Als u langer wacht, zult u opnieuw moeten beginnen.",
      warningBodyShort: this.isUserLoggedIn ? "Uit veiligheidsoverwegingen worden uw gegevens gewist na %TOTALTIME% minuten van inactiviteit. U heeft nog %REMAININGTIME% %MINUTE(S)% voordat de gegevens worden gewist." : "Uit veiligheidsoverwegingen worden uw gegevens gewist na %TOTALTIME% minuten van inactiviteit. U heeft nog %REMAININGTIME% %MINUTE(S)% voordat de gegevens worden gewist.",
      warningButton: "Verder gaan",
      minutes: "minuten",
      minute: "minuut"
    };
    return labels[label];
  },
  settings: {
    totalTime : 15,
    warnAfterTime : 10,
    updateTextTime : 1,
    refreshSessionTime : 15,

    
    sessionExpirationReloadUrl: (typeof sessionExpirationReloadUrl != "undefined" ? sessionExpirationReloadUrl: null)
  },
  variables : {
    minuteInMillis : 60000,
    timer : null,
    totalMinutes : 0,
    warningTimer: null,
    triggerWarning : true
  },

  resetWarningTimerDelayed: function () {
    if (timeoutWarning.warningTimer) {
      window.clearTimeout(timeoutWarning.warningTimer);
    }

    timeoutWarning.warningTimer = window.setTimeout(function () {
      timeoutWarning.warningTimer = null;
      timeoutWarning.resetWarningTimer();
    }, 5000);
  },

  'addEventHandlers': function () {
    $(document).on('submit', 'form', function () {
      timeoutWarning.stopTimer();
    });

    $(document).on('click', '.session-invalidate-cancel', function (e) {
      $('.session-invalidate-wrapper').addClass('hidden');
      timeoutWarning.resetWarningTimer();
      timeoutWarning.enableSubmit();
    });

    if (!this.isUserLoggedIn) {
      $(document).on('focus', '.formulier :input', function () {
        timeoutWarning.initWarningTimer();
      });
    }

    $(document).on('focus keydown', '.formulier :input', function(e) {
      if (timeoutWarning.isTimerInitialized()) {
        timeoutWarning.resetWarningTimerDelayed();
      }
    });

  },
  isTimerInitialized: function () {
    return $('#timer-container').length > 0;
  },

  isConfirmStep: function () {
    return $('.form-confirm-step').length > 0;
  },

  initTimer : function() {
    $('body').append('<div class="reveal-modal medium" id="timer-container" role="alert-dialog" aria-live="polite" aria-describedby="timer-description" aria-labelledby="timer-heading" data-reveal/>');

     $('#timer-container').append('<div id="timer-head"><h1 class="content-gutter" id="timer-heading">' + timeoutWarning.getLabel('warningHeader') + '</h1>'+
        '<p class="content-gutter" id="timer-description">' + this.getTimerHtml(timeoutWarning.getLabel('warningBodyPart1')) + '</p></div>' +
        '<div class="row"><div class="small-8 columns"><span class="content-gutter" id="timer" role="timer" aria-live="polite" aria-relevant="all">' + this.getTimerHtml(timeoutWarning.getLabel('warningBodyPart2')) + '</span>' +
        '</div><div class="small-4 columns"><button class="expand" id="timer-close" type="button" onclick="timeoutWarning.doContinue();" data-stay-enabled>' + timeoutWarning.getLabel('warningButton') + '</button></div>');

    this.setKeepAliveTimer();
    this.addEventHandlers();

    // If the user is logged in or the form is in its final step, trigger the init immediately instead of waiting for input field focus
    if (this.isUserLoggedIn || timeoutWarning.isConfirmStep()) {
      timeoutWarning.initWarningTimer();
    }
  },
  setKeepAliveTimer : function(){
    this.variables.timer = setTimeout(function(){timeoutWarning.keepAlive()}, this.settings.refreshSessionTime * this.variables.minuteInMillis);
  },
  keepAlive : function() {
    if (this.variables.triggerWarning){
      this.stopTimer();
      this.keepSessionAlive();
      this.setKeepAliveTimer();
    }
  },
  initWarningTimer : function() {
    if (this.variables.triggerWarning){
      this.variables.triggerWarning = false;
      this.resetWarningTimer();
    }
  },
  setWarningTimer : function() {
    this.variables.timer = setTimeout(function(){timeoutWarning.showWarning()}, this.settings.warnAfterTime * this.variables.minuteInMillis);
  },
  showWarning : function() {
    this.disableSubmit();
    this.variables.totalMinutes = (this.settings.totalTime - this.settings.warnAfterTime);
    this.updateTime();
    this.variables.timer = setTimeout(function(){timeoutWarning.countDown()}, this.settings.updateTextTime * this.variables.minuteInMillis);
  },
  showError : function() {
    $.getJSON('/ru/scripts/timer/invalidate?' + Math.floor(Math.random() * Math.pow(10,16)));
    var errorHtml =
      '<div id="timer-head"><h1 class="content-gutter" id="timer-heading">' + timeoutWarning.getLabel('errorHeader') + '</h1>'+
      '<p class="content-gutter" id="timer-description">' + this.getTimerHtml(timeoutWarning.getLabel('errorBodyPart1')) + '</p></div>' +
      '<div class="row"><div class="small-8 columns"><span class="content-gutter" id="timer">' + this.getTimerHtml(timeoutWarning.getLabel('errorBodyPart2')) + '</span>' +
      '</div><div class="small-4 columns"><button class="expand session-invalidate-cancel" id="timer-close" type="button" onClick="timeoutWarning.closeError();">' + timeoutWarning.getLabel('errorButton') + '</button></div>';
    $('#timer-container').html(errorHtml).foundation('reveal', 'open');
    keepFocus($('.reveal-modal'));
    $('form').trigger('resetForm');
  },
  closeError : function() {

    // Add the "force reset" data attribute on each form in order to prevent accidental form unload confirm popups
    $('form').each(function() {
      $(this).data('confirm-exit', false);
    });

    $('#timer-container').foundation('reveal', 'close');
    if(this.settings.sessionExpirationReloadUrl === null) {
      location.reload();
    } else {
      document.location = this.settings.sessionExpirationReloadUrl;
    }
  },
  updateTime : function() {
    if (!this.isOtherPopupVisible()) {
      $('#timer-container').foundation('reveal', 'open');
    }
    $('#timer').html(this.getTimerHtml(timeoutWarning.getLabel('warningBodyPart2')));
    keepFocus($('.reveal-modal'));
    $(".session-invalidate-message").html(this.getTimerHtml(timeoutWarning.getLabel('warningBodyShort')));
    $(".session-invalidate-wrapper").removeClass('hidden');
  },
  isOtherPopupVisible: function() {
    return $('.reveal-modal-bg').is(':visible');
  },
  doContinue : function() {
    this.hideWarning();
    this.enableSubmit();
    this.resetWarningTimer();
  },
  hideWarning : function() {
    $('#timer-container').foundation('reveal', 'close');
  },
  countDown : function() {
    this.variables.totalMinutes -= 1;
    if (this.variables.totalMinutes <= 0) {
      if (this.settings.sessionExpirationReloadUrl !== null) {
        setTimeout(function(){timeoutWarning.closeError();}, 3000);
        $.getJSON('/ru/scripts/timer/invalidate?' +  Math.floor( Math.random()*Math.pow(10,16) ), function (json) {
          this.closeError();
        });
      } else {
        this.showError();
      }
      return;
    }
    this.variables.timer = setTimeout(function(){timeoutWarning.countDown()}, this.settings.updateTextTime * this.variables.minuteInMillis);

    this.updateTime();
  },
  resetWarningTimer : function() {
    this.stopTimer();
    this.keepSessionAlive();
    this.setWarningTimer();
  },
  stopTimer : function() {
    clearTimeout(this.variables.timer);
  },
  keepSessionAlive : function() {
    $.getJSON('/ru/scripts/timer/calljs?' + Math.floor(Math.random() * Math.pow(10,16)));
  },
  disableSubmit : function() {
      //should store enabled/disabled state in data attribute to be able to determine whether it should be re-enabled
      $(":input:not([data-stay-enabled])").each(function(){
          var $disabledState = $(this).attr("disabled");
          $(this).attr("disabled", "disabled").data('disabledState',$disabledState).addClass("disabled");
      });
  },
  enableSubmit : function() {
      //check for data attribute whether this button was originally disable, if so, don't enable.
      $(":input:not([data-stay-enabled])").each(function(){
          if($(this).data("disabledState")!=="disabled"){
              $(this).removeAttr("disabled").removeClass("disabled");
          }
      });
  },
  getTimerHtml: function (label) {
    var timerHtml;
    timerHtml = label.replace(/%REMAININGTIME%/g, '<span id="time-count">' + this.variables.totalMinutes + '</span>')
    timerHtml = timerHtml.replace(/%TOTALTIME%/g, this.settings.totalTime);
    timerHtml = timerHtml.replace(/%MINUTE\(S\)%/g, (this.variables.totalMinutes > 1) ? this.getLabel('minutes'): this.getLabel('minute'));
    return timerHtml;
  }
});

$(document).ready(function(){
  if ($('.formulier').length > 0 || timeoutWarning.isUserLoggedIn) {
    timeoutWarning.initTimer();
  }
});