var keyBuffer = "";
var keyboardNav;

var KeyboardNav = Class.create({
	initialize: function() {
		this.container = $("nav");
		this.tabs    = this.container.select("li a");
                this.count   = this.tabs.length;
                this.active  = 0;
                
		this.tabs.each(function(el) {
	          if (el.className == "active"){
                    el.className = "active selected";
                  };
		});
	},
        open: function(){
          window.location = this.tabs[this.active];
        },
        next: function(){
                var selected = 0;
                this.tabs.each(function(el, index) {
	          switch(el.className){
                    case "active selected":
                      el.className = "active";
                      selected = index + 1;
                      break;
                    case "selected":
                      el.className = "";
                      selected = index + 1;
                      break;
                    default:
                      break;
                  }
		});
                if (selected >= this.count) selected = 0;
                if (this.tabs[selected].className == "active"){
                  this.tabs[selected].className = "active selected";
                }else{
                  this.tabs[selected].className = "selected";
                }
                this.active = selected;
	},
        previous: function(){
                var selected = 0;
                this.tabs.each(function(el, index) {
	          switch(el.className){
                    case "active selected":
                      el.className = "active";
                      selected = index - 1;
                      break;
                    case "selected":
                      el.className = "";
                      selected = index - 1;
                      break;
                    default:
                      break;
                  }
		});
                if (selected < 0) selected = this.count - 1;
                if (this.tabs[selected].className == "active"){
                  this.tabs[selected].className = "active selected";
                }else{
                  this.tabs[selected].className = "selected";
                }
                this.active = selected;
        }
});

function keystrokeActions(key) {
  // check whether the focus is on a text input field in which case shortcuts are disabled
  // not sure about the quality of the browser compatibility is on this
  if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == "TEXTAREA"){
    return;
  }else{
    doubleKeystrokes(key);
  }
};

function doubleKeystrokes(key) {
  if (keyBuffer == ""){
    singleKeystrokes(key);
  } else {
    switch(keyBuffer + key){
      case 'gh': // go home
        window.location = "/";
        break;
      case 'gd':
        window.location = "/destinations";
        break;
      case 'gi':
        window.location = "/ideas";
        break;
      case 'gt':
        window.location = "/trips";
        break;
      case 'gb':
        window.location = "/blogs";
        break;
      case 'ge':
        window.location = "/deals";
        break;
      case 'gp':
        window.location = "/tips";
        break;
      case 'ga':
        window.location = "/awards";
        break;
      case 'gm':
        window.location = "/magazines";
        break;
      default:
        singleKeystrokes(key);
        break;
    };
  };
};

function singleKeystrokes(key) {
  switch(key){
    case '?':
      openHelpDoc();
      break;
    case ':':
      openFauxvim();
      break;
    case 'n': // next page
      window.location = $$("a.next")[0];
      break;
    case 'p': // previous page
      window.location = $$("a.prev")[0];
      break;
    case 'j': // scroll down
      window.scrollBy(0,250);
      break;
    case 'k': // scroll up
      window.scrollBy(0,-250);
      break;
    case 'L': // next nav item
      keyboardNav.next();
      break;
    case 'H': // previous nav item
      keyboardNav.previous();
      break;
    case 'O': // open selected nav item
      keyboardNav.open();
      break;
    default:
      keyBuffer = key;
      break;
  };
};

function openHelpDoc(){
  Effect.toggle("keyboard-shortcuts-container", "appear", { duration: 0.1 });
};

function openFauxvim(){
  if ($("fauxvim-container").style.display != 'none'){
    Effect.toggle("fauxvim-container", "appear", { duration: 0, afterFinish: function(){ $("fauxvim-input").blur(); }});
  }else{
    Effect.toggle("fauxvim-container", "appear", { duration: 0, afterFinish: function(){ $("fauxvim-input").focus(); }});
    $("fauxvim-input").value = ":";
  }
};

function fauxvimCommand(command){
  Effect.toggle("fauxvim-container", "appear", { duration: 0, afterFinish: function(){ $("fauxvim-input").blur(); }});
  commandPieces = command.split(" ");
  command = commandPieces[0];
  options = commandPieces.without(command).join(" ")
  switch(command){
    case ':o': // open the vim terminal
      vimOpen(options);
      break;
    case ':open':
      vimOpen(options);
      break;
    case ':h': // open the help docs
      openHelpDoc();
      break;
    case ':help':
      openHelpDoc();
      break;
    case ':s':
      vimSearch(options);
      break;
    case ':search':
      vimSearch(options);
      break;
    case ':robocop':
      window.open("http://www.youtube.com/watch?v=D7rjLQuW2nQ");
      break;
    default:
      alert("ERROR - That command doesn't exist. Try again n00b.")
      break;
  }
}

function vimSearch(searchString){
  window.location = ("/search?query=" + escape(searchString));
}

function vimOpen(url){
  locationArray = ["home","destinations","ideas","trips","blog","deals","tips","awards","magazines"]
  if (locationArray.indexOf(url) == -1){
    var match = /^http/.test(url)
    // if it starts with http go to the url
    if (match == true) window.location = url;
    // if it doesn't start with http google search it
    else window.location = ("http://www.google.com/search?q=" + escape(url));
  }else{ // if it matches one of the nav items in locationArray
    if (url == "blog") url = "blogs";
    window.location = ("/" + url);
  }
}

function escapeKey(){
  if ($("fauxvim-container").style.display != 'none') openFauxvim();
  if ($("keyboard-shortcuts-container").style.display != 'none') openHelpDoc();
}

Event.observe(window, 'load', function() {
  Event.observe(document, 'keypress', function(e){
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    if (code == 27 ) escapeKey();
    else keystrokeActions(character);
  });
  keyboardNav = new KeyboardNav();
});