﻿var RoS = {};
RoS.createDelegateCallback = function(instance, method, context) {
  return function() {
    var len = arguments.length;
    var args = [];
    var pos;
    for (pos = 0; pos < len; pos++) {
      args[pos] = arguments[pos];
    }
    args[pos] = context;

    return method.apply(instance, args);
  };
};

RoS.browser = {
  version: $.browser.version,
  mozilla: $.browser.mozilla,
  msie: $.browser.msie,
  opera: $.browser.opera,
  safari: $.browser.safari
};

RoS.Utils = {};
RoS.Utils.logger = {
  isEnabled: !!(typeof log == "undefined" || !log),

  debug: function(msg) {
    if (this.isEnabled) {
      log.debug(msg);
    }
  },
  
  info: function(msg) {
    if (this.isEnabled) {
      log.info(msg);
    }
  },
  
  warn: function(msg) {
    if (this.isEnabled) {
      log.warn(msg);
    }
  },
  
  error: function(msg) {
    if (this.isEnabled) {
      log.error(msg);
    }
  }
};

RoS.Utils.messenger = {
  error: function(txt) {
    $('#messages').append('<li><span class="errorMsg">' + txt + '</span></li>');
    $('#messageBar').fadeIn('slow');
  },

  info: function(txt) {
    $('#messages').append('<li><span class="infoMsg">' + txt + '</span></li>');
    $('#messageBar').fadeIn('slow');
  },

  clear: function() {
    $('#messages').html('<li></li>');
    $('#messageBar').hide();
  },

  hide: function() {
    $('#messageBar').fadeOut('slow');
    this.clear();
  },

  block: function(el, msg) {
    if (!msg) {
      msg = '<div><div style="padding: 10px"><h3>Please wait...</h3></div><div><img alt="" src="images/loading.gif" width="40px" height="40px" /></div></div>';
    }

    $(el).block({
      message: msg,
      css: {
        top: '150px'
      }
    });
  },

  ensureCancel: function(cancelEl, msg) {
    $(cancelEl).click(function(e) {
      if (!confirm(msg)) {
        e.preventDefault();
      }
    });
  },

  unblock: function(el) {
    $(el).unblock();
  }
};

RoS.Utils.session = {
  _warnTimeout: 0,
  _expireTimeout: 0,
  _warnId: null,
  _expireId: null,
  _extendUrl: null,
  _expirationUrl: null,

  _disposeWarn: function() {
    if (this._warnId) {
      window.clearTimeout(this._warnId);
    }
  },

  _disposeExpire: function() {
    if (this._expireId) {
      window.clearTimeout(this._expireId);
    }
  },

  _warn: function() {
    this._disposeWarn();

    var extendFn = RoS.createDelegateCallback(this, this.extend);

    $('#sessionExtend').click(function(e) {
      extendFn();
      e.preventDefault();
    });

    $('#main').block({
      message: $('#sessionWarning'),
      css: {
        border: 'none',
        cursor: 'default',
        'text-align': 'left',
        top: '150px',
        width: '510px'
      }
    });
  },

  _expire: function() {
    this._disposeExpire();
    window.location = this._expirationUrl;
  },

  initialize: function(warningTimout, expirationTimout, extendUrl, expirationUrl, showWarningTimoutCountdown) {
    var now = new Date().getTime();
    var timeout = parseInt(expirationTimout);
    var expiredTime = new Date();
    expiredTime.setTime(now + timeout);
    $('#expirationTime').html("You session will expired on <b>" + expiredTime.toLocaleString() + "</b>");
    this._warnTimeout = warningTimout;
    this._expireTimeout = expirationTimout;
    this._extendUrl = extendUrl;
    this._expirationUrl = expirationUrl;
    this._warnId = window.setTimeout(RoS.createDelegateCallback(this, this._warn), warningTimout);
    this._expireId = window.setTimeout(RoS.createDelegateCallback(this, this._expire), expirationTimout);
    $('#sessionExtend').unbind('click');

    if (showWarningTimoutCountdown) {
      var warningT = parseInt(warningTimout);
      var targetTime = new Date();
      targetTime.setTime(now + warningT);
      CountStepper = Math.ceil(CountStepper);
      if (CountStepper == 0)
        CountActive = false;
      SetTimeOutPeriod = (Math.abs(CountStepper) - 1) * 1000 + 990;
      putspan("white", "black");
      var ddiff;
      if (CountStepper > 0)
        ddiff = new Date(now - targetTime);
      else
        ddiff = new Date(targetTime - now);
      gsecs = Math.floor(ddiff.valueOf() / 1000);
      CountBack(gsecs);
    } else {
      $("#countdown").hide();
    }
  },

  dispose: function() {
    this._disposeWarn();
    this._disposeExpire();
  },

  extend: function() {
    var warningTimout = this._warnTimeout;
    var expirationTimout = this._expireTimeout;
    var extendUrl = this._extendUrl;
    var expirationUrl = this._expirationUrl;
    $.get(this._extendUrl, { t: (new Date()).getTime().toString() }, function(result) {
      RoS.Utils.session.initialize(warningTimout, expirationTimout, extendUrl, expirationUrl);
    });
    this.dispose();
    $('#main').unblock();
  }
};

$.blockUI.defaults.centerY = false;
$.blockUI.defaults.css.top = '15px';

var SetTimeOutPeriod;
var TargetDate;
var DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
var CountActive = true;
var LeadingZero = true;
var CountStepper = -1;
var FinishMessage = "Session warning has triggered!";

function calcage(secs, num1, num2) {
  s = ((Math.floor(secs / num1)) % num2).toString();
  if (LeadingZero && s.length < 2)
    s = "0" + s;
  return "<b>" + s + "</b>";
}

function CountBack(secs) {
  if (secs < 0) {
    $("#cntdwn").html(FinishMessage);
    return;
  }
  DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs, 86400, 100000));
  DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs, 3600, 24));
  DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs, 60, 60));
  DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs, 1, 60));

  $("#cntdwn").html(DisplayStr);
  if (CountActive)
    setTimeout("CountBack(" + (secs + CountStepper) + ")", SetTimeOutPeriod);
}

function putspan(backcolor, forecolor) {
  $("#countdown").html("<span id='cntdwn' style='background-color:" + backcolor +
                "; color:" + forecolor + "'></span>");
}
