commandLine = Class.create({
  initialize: function(element, cmndLine) {
    this.console   = element;
    this.cmndLine  = cmndLine;
    this.command   = this.cmndLine.down('input[name=cmnd]');
    this.observers = [];
    this.cmndHistory = [];
    this.searchIndex = 0;
    this.helpMessage = this.console.down('.stdout').cloneNode(true);
    this.focus();
    this.initObservers();
  },

  initObservers: function() {
    this.observers += this.command.observe('keypress', this.onKeyPressNotifier.bind(this));
    this.observers += this.console.observe('click', this.onClickNotifier.bind(this));
  },

  puts: function(message) {
    msg = new Element('span', {
      class: 'stdout'
    });
    msg.update(message);
    this.cmndLine.insert({before: msg});
  },

  sendCommand: function(command) {
    this.cmndHistory.push(this.command.value);
    this.searchIndex = 0;
    this.command.value = "";
    if (command == "clear") { this.clear(); return };
    if (command == "help") { this.cmndLine.insert({before: this.helpMessage.cloneNode(true)}); return };
    msg  = "I'm still writing the functional code of the console."
    msg += "Please be patient :)"
    this.puts(msg);
    this.console.scrollTop = this.console.scrollHeight;
  },

  clear: function() {
    $$('.stdout').each(function(element) {
      if (element.id != "cmnd-line") {
        element.remove();
      }
    });
  },

  historySearchBackwards: function() {
    historyItemCount = this.cmndHistory.length;
    if (this.searchIndex < historyItemCount) { this.searchIndex++ };
    index = this.searchIndex;
    this.searchByIndex(index);
  },

  historySearchForward: function() {
    if (this.searchIndex > 0) { this.searchIndex-- };
    index = this.searchIndex;
    this.searchByIndex(index);
  },

  searchByIndex: function(index) {
    if (index == 0) { this.command.value = "" ; return };
    cmnd = this.cmndHistory[this.cmndHistory.length - index]
    //if ( cmnd === undefined) { return }
    this.command.value = cmnd;
  },

  // Event notifiers
  onKeyPressNotifier: function(e) {
    this.keyPress(e);
  },

  onClickNotifier: function(e) {
    this.focus(e);
  },

  // Event handlers

  keyPress: function(e) {
    if (e.keyCode == 13) { // Enter
      this.sendCommand(this.command.value);
    } else if (e.keyCode == 38) { // Up
      this.historySearchBackwards();
    } else if (e.keyCode == 40) { // Down
      this.historySearchForward();
    }
    //console.log(e.keyCode);
  },

  focus: function(e) {
    this.command.focus();
  },
});
