/* Hotkeys code */

$(function() { initialize_hotkeys(); });

// beware: anonymous functions/closures do not fly well in here, at all. be sure to create explicit named functions
var theHotkeys = [
//0 - real, 1 - display, 2 - bindTo, 3 - fxn, 4 - description
  [{disableInInput: true,  combi: 'l'},           'l',            document,         navigation_newer, "Go to the next pile, file, or topic"],
  [{disableInInput: true,  combi: 'h'},           'h',            document,         navigation_older, "Go to the previous pile, file, or topic"],
  [{disableInInput: true,  combi: 'j'},           'j',            document,         prev_item, "Go down the list of items on the page"],
  [{disableInInput: true,  combi: 'k'},           'k',            document,         next_item, "Go up the list of items on the page"],
  [{disableInInput: true,  combi: 'm'},           'm',            document,         mark_as_favorite, "Mark or unmark this comment or topic as a favorite"],

  [{disableInInput: true,  combi: 'return'},      'Return',       document,         open_cur_item, "Open the topic or View-File you're on, or Show All Images"],

  [{disableInInput: true,  combi: 'backspace'},   'Backspace',    document,         go_back, "Go back"],
  [{disableInInput: true,  combi: 'p'},           'p',            document,         go_to_pile, "Go to or refresh the Pile now"],
  [{disableInInput: true,  combi: 'd'},           'd',            document,         go_to_discuss, "Go to or refresh Discuss now"],

  [{disableInInput: true,  combi: 'g'},           'g',            document,         click_on_good, "Flip on [this is good]"],
  [{disableInInput: true,  combi: 'b'},           'b',            document,         click_on_bad, "Flip on [this is bad]"],
  [{disableInInput: true,  combi: 'o'},           'o',            document,         click_on_offensive, "Flip on [this might be offensive]"],
  [{disableInInput: true,  combi: 'c'},           'c',            document,         click_on_comment_box, "Drop into the comment box"],
  //[{disableInInput: false, combi: 'ctrl+return'}, 'Ctrl+Return',  "#comment_body,#topic_comment_body",  click_on_submit, "Submit your comment (only works inside the comment box)"],

  [{disableInInput: true,  combi: '1'},           '1',            document,         go_to_menu0, "Go to the first menu item (discuss/main)"],
  [{disableInInput: true,  combi: '2'},           '2',            document,         go_to_menu1, "Go to the second menu item"],
  [{disableInInput: true,  combi: '3'},           '3',            document,         go_to_menu2, "Go to the third menu item"],
  [{disableInInput: true,  combi: '4'},           '4',            document,         go_to_menu3, "Go to the fourth menu item"],
  [{disableInInput: true,  combi: '5'},           '5',            document,         go_to_menu4, "Go to the fifth menu item"],
  [{disableInInput: true,  combi: '6'},           '6',            document,         go_to_menu5, "Go to the sixth menu item"],
  [{disableInInput: true,  combi: '7'},           '7',            document,         go_to_menu6, "Go to the seventh menu item"],
  [{disableInInput: true,  combi: '8'},           '8',            document,         go_to_menu7, "Go to the eighth menu item"],
  [{disableInInput: true,  combi: '9'},           '9',            document,         go_to_menu8, "Go to the ninth menu item"],
  [{disableInInput: true,  combi: '0'},           '0',            document,         go_to_menu9, "Go to the tenth menu item"],
  [{disableInInput: true,  combi: 'u'},           'u',            document,         go_to_user_page, "Go to your user page"],
];

/* Directly webpage-callable code */

var list_index = -1;
function initialize_hotkeys() {
  for (var i=0; i< theHotkeys.length; i++) {
    $(theHotkeys[i][2]).bind('keydown', theHotkeys[i][0], theHotkeys[i][3]);
  } 
  list_index = -1;
}

// initialize the hotkeys that aren't tied to the document (perhaps because the HTML changed)
function reinitialize_hotkeys() {
  for (var i=0; i< theHotkeys.length; i++) {
    if ( theHotkeys[i][2] != document ) {
      $(theHotkeys[i][2]).bind('keydown', theHotkeys[i][0], theHotkeys[i][3]);
    }
  } 
}

function get_navigation_help() {
  var str_arr = new Array();
  str_arr.push("<h1>Keyboard Shortcut Help</h1>\n<table class='help-table'>");
  for (var i=0; i< theHotkeys.length; i++) {
    str_arr.push("<tr><th><strong>"+theHotkeys[i][1]+"</strong></th><td>"+theHotkeys[i][4]+"</td></tr>");
  } 
  str_arr.push("</table>");
  $("#hotkeys-help").html(str_arr.join("\n"));
}


/* Handlers and support */

/* find the "newer" object on the page and navigate to its URL */
var cur_pile = -1;
var last_pile = null;
var cur_pile_item = -1;
var last_pile_item = null;
function navigation_newer() {
  if ($("#newer").attr('href')) {
    document.location = $("#newer").attr('href');
  }

  _move_pile_item( function(piles) {
    // go "left" aka down the list.
    cur_pile = cur_pile + 1;
    if (cur_pile < 0 || cur_pile >= piles.length) {
      cur_pile = 0
    } 
  }, function(pile_length) { 
    cur_pile_item = 0; 
  });
}

/* find the "older" object on the page and navigate to its URL */
function navigation_older() {
  if ($("#older").attr('href')) {
    document.location = $("#older").attr('href');
  }

  _move_pile_item( function(piles) {
    // go "right" aka down the list.
    cur_pile = cur_pile - 1;
    if (cur_pile < 0 || cur_pile >= piles.length) {
      cur_pile = piles.length - 1; 
    } 
  }, function(pile_length) { 
    cur_pile_item = 0; 
  });
}


var last_item = null;
function next_item() {
  _move_item( function(list_length) {
    list_index = list_index - 1;
    if (list_index < 0) {
      list_index = list_length - 1; 
    }
  });

  _move_pile_item( function(piles) { 
      if (cur_pile < 0 || cur_pile >= piles.length) {
        cur_pile = piles.length - 1; 
      } 
    }, 
    function(pile_length) { 
      // move the pile item "up" aka subtract 1
      cur_pile_item = cur_pile_item - 1; 
      if (cur_pile_item < 0) {
        cur_pile_item = pile_length - 1;
      }
    });
}

function prev_item() {
  _move_item( function(list_length) {
    list_index = list_index + 1;
    if (list_index > (list_length - 1)) {
      list_index = 0;
    } 
  });

  _move_pile_item( function(piles) { 
      if (cur_pile < 0 || cur_pile >= piles.length) {
        cur_pile = 0; 
      } 
    }, 
    function(pile_length) { 
      // move the pile item "down" aka add 1
      cur_pile_item = cur_pile_item + 1; 
      if (cur_pile_item >= pile_length) {
        cur_pile_item = 0;
      }
    });
}

function mark_as_favorite() {
  var cur_item = _get_cur_item();
  if (cur_item != null) {
    var fav_link =  cur_item.parent().find("a.favorite-link img");
   
    if (fav_link != null) {
      fav_link.click();
    }
  }
}

function open_cur_item() {
  var cur_item = _get_cur_item();
  if (cur_item != null) {
    var topic_link =  cur_item.parent().find("a.comments-link");
   
    if (topic_link != null && topic_link.length > 0) {
      document.location = topic_link.attr('href');
      return;
    }

    var show_images = cur_item.parent().find(".show-image");
    if (show_images != null && show_images.length > 0) {
      $.each(show_images, function(i,val) {
        $(val).click();
      });
      return;
    } 
  }

  var view_file_link = $("#view-file-link a");
  if (view_file_link != null && view_file_link.length > 0 ) {
    insertFile();
    return;
  }

  if (last_pile_item != null && last_pile_item.length > 0) {
    document.location = last_pile_item.find(".fname a").attr('href');
    return;
  }
}

/* Utilities */

function _move_pile_item(compute_pile, compute_pile_item) {
  var piles = $('.pile'); 
  if (piles != null && piles.length > 0) {
    compute_pile(piles);

    var the_pile = piles.eq(cur_pile);

    last_pile = the_pile;

    var pile_items = the_pile.find(".filelist .fileline");

    compute_pile_item(pile_items.length);

    if ( pile_items != null && pile_items.length > 0) {
      var the_pile_item = pile_items.eq(cur_pile_item);

      if (last_pile_item != null) {
        last_pile_item.find(".fname a").removeClass("pile-target");
      }
      the_pile_item.find(".fname a").addClass("pile-target");
      last_pile_item = the_pile_item;
    }
  }
}

function _get_cur_item() {
  var list = _get_list();
  if ( (list.length > 0) && (list_index >= 0) && (list_index < list.length) ) {
    return list.eq(list_index);
  }
  return null;
}

function _move_item(compute_next_index) {
  var list = _get_list();
  if ( list.length > 0 ) {
    compute_next_index(list.length);
    var cur_item = list.eq(list_index);
    if (last_item != null) {
      last_item.removeClass("target");
    }
    $.scrollTo(cur_item, 0, {axis:'y',offset:-75});
    cur_item.addClass("target");
    last_item = cur_item;
  }
}

/* retrieves the list of iteratable objects on the page */
function _get_list() {
  if ($(".discussPage").length > 0) {
    return $(".topic .topic-body");
  }
  if ($(".fileViewPage").length > 0) {
    return $("#fileinfo h1, .comment .commentbody");
  }
  if ($(".discussViewPage").length > 0) {
    return $(".topic .topic-body, .topic-comment .topic-comment-body");
  }

  return $(".made-up-non-existent-object-just-for-this-func"); // empty array
}

function click_on_good(evt)        { click_on_comment_item(evt, "#comment_vote_good", false);}
function click_on_bad(evt)         { click_on_comment_item(evt, "#comment_vote_bad", false);}
function click_on_offensive(evt)   { click_on_comment_item(evt, "#comment_offensive", false);}
function click_on_comment_box(evt) { click_on_comment_item(evt, "#comment_body, #topic_comment_body", true); }
function click_on_submit(evt)      { click_on_comment_item(evt, "#submit", false); }

function click_on_comment_item(evt, selector, also_focus) {
  var item = $(selector);
  if (!item || item.length == 0) {
    return true;
  }

  $.scrollTo(item, 500, {axis:'y',offset:-75});
  item.click();
  if (also_focus) {
    item.focus();
  }
  evt.stopPropagation();  
  evt.preventDefault();
  return false;
}

function go_back() { history.go(-1); }
function go_to_pile() { document.location = "/"; }
function go_to_discuss() { document.location = "/discuss/"; }

function click_on_menu_item(index) {
  var items = $("#sitemenu li a");

  if (!items || ((items.length - 1) < index)) {
    return;
  }

  var item = items.eq(index);

  if (item.html().indexOf("signout") > -1 ) {
    if (!confirm("Are you sure you want to sign out?")) {
      return;
    }
  }

  document.location = item.attr('href'); 
}


function go_to_menu0(){click_on_menu_item(0);}
function go_to_menu1(){click_on_menu_item(1);}
function go_to_menu2(){click_on_menu_item(2);}
function go_to_menu3(){click_on_menu_item(3);}
function go_to_menu4(){click_on_menu_item(4);}
function go_to_menu5(){click_on_menu_item(5);}
function go_to_menu6(){click_on_menu_item(6);}
function go_to_menu7(){click_on_menu_item(7);}
function go_to_menu8(){click_on_menu_item(8);}
function go_to_menu9(){click_on_menu_item(9);}
function go_to_user_page(){
  var item = $("#loggedin a.user-link");

  if (!item || item.length == 0) {
    return;
  }
  
  document.location = item.attr('href'); 
}


