
// depends on the cookies and timers plugins

jQuery.detlog = function(options) {

  var settings = jQuery.extend({
    'cookiename': 'BSQ_Login_INSECURE',
    'refresh_interval': 500,
    'timer_label': 'logincheck',
    'fn': function(target, status) {},
    'target': 'body',
    'debug': true
  }, options);

  if (!jQuery.fn.everyTime) {
    throw new Error("Login detection depends on the timers plugin");
  }

  if (!jQuery.cookie) {
    throw new Error("Login detection depends on the cookie plugin");
  }

  if (!settings.cookiename || settings.cookiename == '') {
    throw new Error("Invalid cookiename");
  }

  var log = {log: function() {}};

  if (settings.debug && window.console) {
    log = window.console;
  }

  var loginCheck = function() {
    var cookie = jQuery.cookie(settings.cookiename);
    if (cookie && cookie.length > 24) {
      return true;
    } else {
      return false;
    }
  };

  var loginStatus = loginCheck();

  log.log("Logged in: " + loginStatus);

  $(settings.target).everyTime(
                      settings.refresh_interval,
                      settings.timer_label,
                      function() {
                        var newLoginStatus = loginCheck();
                        if (loginStatus && !newLoginStatus) {
                          log.log("Logged out!");
                          loginStatus = newLoginStatus;
                          settings.fn(this, loginStatus);
                        } else if (newLoginStatus && !loginStatus) {
                          log.log("Logged in!");
                          loginStatus = newLoginStatus;
                          settings.fn(this, loginStatus);
                        }
                      },
                      0);


};
