
var search_timeout = undefined;

function ajax_search() {
   if(search_timeout != undefined) {
       clearTimeout(search_timeout);
   }
   var $this = this; // save reference to 'this'
   search_timeout = setTimeout(function() {
       search_timeout = undefined;
       query = $('#search-query').attr('value');
       if (query.trim() != '') {
           $('#search-query').css('background','url("/media/img/ajax/indicator.gif") no-repeat scroll right center #EEEEEE');
           $.get('/search/live/', {q:query}, function (response) {
                $('#search-query').css('background','#EEEEEE');
                if (response.trim() != '') {
                    $('#search-autocomplete').html(response);
                    $('#search-autocomplete').show();
                    bind_highlight();
                } else {
                    $('#search-autocomplete').hide();
                }
           })
       } else {
           $('#search-autocomplete').html('');
           $('#search-autocomplete').hide();
       }
       
   }, 500);
}

$(function () {
   $('#search-magnifier').click(function () {
      $('#search-form').submit(); 
   });
   
   $('#search-query').keypress(function (e) {
       var code = (e.keyCode ? e.keyCode : e.which);
       var current = $('.selected:first', $('#search-autocomplete'));
       if ($('#search-autocomplete').css('display') != 'none') {
           if (code == 38) {
               if (current.size()) {
                   //selected_id = current.attr('id').match(/\d+/g));
                   if (current.prev('tr')) {
                       current.removeClass('selected');
                       current.prev('tr').addClass('selected');
                   } 
               } else {
                   $('tr:last', $('#search-autocomplete')).addClass('selected');
               }
               return;
           } else if (code == 40) {
               if (current.size()) {
                   //selected_id = current.attr('id').match(/\d+/g));
                   if (current.next('tr')) {
                       current.removeClass('selected');
                       current.next('tr').addClass('selected');
                   } 
               } else {
                   $('tr:first', $('#search-autocomplete')).addClass('selected');
               }
               return;
           } else if (code == 13) {
               if (current.size()) {
                   e.preventDefault();
                   document.location.href = $('a.detail-link', current).attr('href');
               }
           }
       }
       
       ajax_search();
   })

   $('#search-query').focusin(function () {
       console.log($('#search-autocomplete').html());
       if ($('#search-autocomplete').html() != '') {
           $('#search-autocomplete').show();
       }
   })
   
   $('#search-query').focusout(function () {
       setTimeout(function() {
          $('#search-autocomplete').fadeOut(200);
       }, 100);

   });
});
