var CONTEXT_PATH = "/";
var DEBUG = true;
var ERROR = { NOT_LOGGED_IN:17 };
var KBD = { LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SPACE: 32, DELETE: 46, ESC: 27, BACKSPACE: 8 };
var LOGD = false;
var SPACEY = false;

var led;
var globalFeedback;
var FEEDBACK_MESSAGE_DISPLAY = false;

/**
 * Support functions
 */

var logg = function(msg) {}

String.prototype.trim = function () {
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

$.preloadImages = function(arguments) {
  for(var i = 0; i < arguments.length; i++) {
    $("<img>").attr("src", arguments[i]);
  }
}

$.fn.fadeToggle = function(speed, callback) {
   return this.animate({opacity: 'toggle'}, speed, callback);
};

var Led = function(id) {
  this.element = $("#" + id);
  this.element.fadeTo(0, 0);
  this.element.css("display", "inline");
}

Led.prototype.on = function(message) {
  //var el = this.element;
  //el.stop(true, true);
  //el.fadeTo(300, 1);
  logg("led.on()");
  var msg = message ? message : $("#message_loading").val();
  messageOkay(msg, true); // don't autohide
}

Led.prototype.off = function(message) {
  //var el = this.element;
  //el.stop(true, true);
  //el.fadeTo(1000, 0);
  messageHide();
}


var initGlobalFeedback = function() {
  globalFeedback = $("#global_feedback");
  globalFeedback.text("");
  globalFeedback.fadeTo(0, 0, function() {
    $(this).css("display", "block");
  });
}

var messageOkay = function(msgText, dontautohide) {

  //alert("messageOkay(" + msgText + ", " + dontautohide + ")");

  globalFeedback.stop(false, false);
  globalFeedback.fadeTo(1,0, function() {
    globalFeedback.html(msgText);
    globalFeedback.addClass("okay");

    globalFeedback.fadeTo(300, 1, function() {
      if (dontautohide) {
        blinkHide($(this));
        return;
      } else {
        $(this).fadeTo(8000, 0);
      }
    });
  });
}

var blinkHide = function(element) {
  element.fadeTo(370, 0, function() {
    blinkShow(element);
  });
}

var blinkShow = function(element) {
  element.fadeTo(370, 1, function() {
    blinkHide(element);
  });
}

var messageError = function(msgText, dontautohide) {
  globalFeedback.addClass("error");
  globalFeedback.html(msgText);
  globalFeedback.stop(false, true).fadeTo(300, 1, function() {
    if (dontautohide) {
      return;
    }
    $(this).fadeTo(5000, 0);
  });
}

var messageHide = function() {

  //alert("messageHide()");

  globalFeedback.removeClass("error").removeClass("okay");
  globalFeedback.text("");
  globalFeedback.stop(true, true).fadeTo(300, 1);
}


/**
 *
 * Init support routines.
 */

$(document).ready(function() {

  led = new Led("loading_led");
  initGlobalFeedback();
  initLanguageBtn();

  LOGD = parseInt($("#logd").val()) == 1 ? true : false;
  SPACEY = parseInt($("#spacey").val()) == 1 ? true : false;
});


var initLanguageBtn = function() {
  $("#btn_language").click(function() {
    $("#form_language").submit();
  });
}

