/** todo: convert to jquery **/
var TypeAhead = {
  the_input:null,
  Init: function() {
    TypeAhead.the_input = $("#search_input");
    TypeAhead.the_autocomplete = $("#search_dropdown");
    TypeAhead.the_input.value = TypeAhead.the_input.attr("placeholder");
    TypeAhead.the_input.bind("focus", TypeAhead.Focus);
    TypeAhead.the_input.bind("blur", TypeAhead.Blur);
    TypeAhead.the_input.bind("keyup", TypeAhead.Search);
    TypeAhead.the_input.bind("keydown", TypeAhead.KeyDown);
    $(document).bind("click", TypeAhead.Click);
    TypeAhead.the_input.blur();
  },
  Focus: function(e) {
    TypeAhead.Preload();
    if ($(this).val() == $(this).attr("placeholder")) {
      $(this).val("");
    }
  },
  Blur: function (e) {
    if ($(this).val() == "") {
      $(this).val($(this).attr("placeholder"));
    }
  },
  Preload: function () {
    if(!TypeAhead.search_candidates_fetched) {
      $.ajax({
        url:'/ajax/?req=RpcApiWww_GetTypeAhead',
        success: function(res) {
          TypeAhead.search_candidates_fetched = true;
          if(res.result_code == Rpc.RESULT_SUCCESS) {
            TypeAhead.search_candidates = res.data;
          }
        }
      });
    }
  },

  Search: function(e) {
    TypeAhead.CloseAutocomplete();
    var search_term = $.trim(TypeAhead.the_input.val());
    if(search_term.length == 0) {
      return;
    }
    var lowercase_search_term = search_term.toLowerCase();
    var searchbox = TypeAhead.the_input;
    if(TypeAhead.search_candidates) {
      var found_types = [];
      var search_results_prefix = {};
      var search_results_substr = {};
      var item_index = 0;
      for(var i=0; i < TypeAhead.search_candidates.length; i++) {
        var entry = TypeAhead.search_candidates[i];
        if(entry.name.toLowerCase().indexOf(lowercase_search_term) == 0) {
          if(!search_results_prefix[entry.type]) {
            search_results_prefix[entry.type] = [];
          }
          search_results_prefix[entry.type].push(entry);
          if ($.inArray(entry.type,found_types) == -1) {
            found_types[found_types.length] = entry.type;
          }
        } else if(entry.name.toLowerCase().indexOf(lowercase_search_term) != -1) {
          if(!search_results_substr[entry.type]) {
            search_results_substr[entry.type] = [];
          }
          search_results_substr[entry.type].push(entry);
          if ($.inArray(entry.type,found_types) == -1) {
            found_types[found_types.length] = entry.type;
          }
        }
      }

      if(found_types.length == 0) {
        return;
      }

      li_tpl = $.template('li_tpl',
                          '<a href="${link}" class="clearfix" id="search_autocomplete_item_${item_index}" onfocus="this.hideFocus=true;">' +
                          '<img src="${mug}" class="mug" />' +
                          '<span class="details">' +
                          '<span class="name">{{html name}}</span>' +
                          '<span class="type">${type}</span>' +
                          '</span>' +
                          '</a>');

      for(var t=0; t < found_types.length; t++) {
        var entry_type = found_types[t];
        var num_results = 0;
        if(search_results_prefix[entry_type]) {
          for(var i=0; i < search_results_prefix[entry_type].length; i++) {
            num_results++;
            if(num_results > 5) {
              return;
            }
            var entry = search_results_prefix[entry_type][i];
            var name = $('<div/>').text(entry.name).html().replace(new RegExp('('+search_term+')','ig'),"<strong>$1</strong>");
            TypeAhead.the_autocomplete.append($.tmpl('li_tpl',{name: name,
                                                               item_index: item_index,
                                                               mug: entry.img,
                                                               type: entry.type,
                                                               link: entry.link}));
            $('#search_autocomplete_item_' + item_index).bind('keydown', TypeAhead.KeyDown);
            item_index++;
          }
        }
        if(search_results_substr[entry_type]) {
          for(var i=0; i < search_results_substr[entry_type].length; i++) {
            num_results++;
            if(num_results > 5) {
              return;
            }
            var entry = search_results_substr[entry_type][i];
            var name = $('<div/>').text(entry.name).html().replace(new RegExp('('+search_term+')','ig'),"<strong>$1</strong>");
            TypeAhead.the_autocomplete.append($.tmpl('li_tpl',{name: name,
                                                               item_index: item_index,
                                                               mug: entry.img,
                                                               type: entry.type,
                                                               link: entry.link}));
            $('#search_autocomplete_item_' + item_index).bind('keydown', TypeAhead.KeyDown);
            item_index++;
          }
        }
      }

      TypeAhead.the_autocomplete.show();
    }
  },

  CloseAutocomplete: function() {
    TypeAhead.the_autocomplete.hide();
    TypeAhead.the_autocomplete.empty();
  },

  KeyDown: function(ev) {
    if(TypeAhead.the_autocomplete.is(':visible')) {
      var items = TypeAhead.the_autocomplete.children();
      var current_index = -1;
      event_id = ev.target.id;
      if(event_id.indexOf('search_autocomplete_item_') != -1) {
        current_index = parseInt(event_id.replace('search_autocomplete_item_', ''));
        $(this).removeClass('search-autocomplete-item-focused');
      }

      var nextElement = null;
      if(ev.keyCode == $.ui.keyCode.UP) {
        ev.preventDefault();
        current_index = Math.max(0, current_index-1);
        nextElement = $('#search_autocomplete_item_' + current_index);
      } else if(ev.keyCode == $.ui.keyCode.DOWN) {
        ev.preventDefault();
        current_index = Math.min(items.length-1, current_index+1);
        nextElement = $('#search_autocomplete_item_' + current_index);
      } else if(ev.keyCode == $.ui.keyCode.ESCAPE) {
        TypeAhead.CloseAutocomplete();
        return;
      }

      if(nextElement) {
        $('#search_autocomplete_item_' + current_index).focus();
        $('#search_autocomplete_item_' + current_index).addClass('search-autocomplete-item-focused');
      }


    }
  },

  Click: function(ev) {
    if($(ev.target).closest('#'+TypeAhead.the_autocomplete.id).length == 0 &&
       $(ev.target).attr('id') != TypeAhead.the_input.id) {
      TypeAhead.CloseAutocomplete();
    }
  }
  
}

