var hide_results_timeout = false;

class Finder {

static find(query){
  $.ajax({
      url: "/find",
      type: 'GET',
      data: { query: query }
  }).done(function(result) {
    $("#header .results").html(result);

    $('#header .results *').click(function() {
      clearTimeout(hide_results_timeout);
      $("#header input").focus();
    });
  });
}

static do_find(url,query,html){
  $.ajax({
      url: url,
      type: 'GET',
      data: { query: query }
  }).done(function(result) {
    $(html).html(result);
  });
}

}

var last_query = null; var header_input_timeout = null; $.xhrPool = [];

$.xhrPool.abortAll = function() {

$(this).each(function(idx, jqXHR) {
    jqXHR.abort();
});
$(this).each(function(idx, jqXHR) {
    var index = $.inArray(jqXHR, $.xhrPool);
    if (index > -1) {
        $.xhrPool.splice(index, 1);
    }
});

};

$.ajaxSetup({

beforeSend: function(jqXHR) {
    $.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
    var index = $.inArray(jqXHR, $.xhrPool);
    if (index > -1) {
        $.xhrPool.splice(index, 1);
    }
}

});

$(document).ready(function(){

$("#header input").focusin(function() {
  $("#header .results").addClass("toggled");
})

$("#header input").focusout(function() {
  hide_results_timeout = setTimeout(function() {
    $("#header .results").removeClass("toggled"); 
  },200);
});

$('#header .results *').click(function() {
  clearTimeout(hide_results_timeout);
  $("#header input").focus();
});

$('#header input').keyup(function() {
    clearTimeout(header_input_timeout);

    if($('#header input').val().length > 2 && $.trim($('#header input').val())) {
      header_input_timeout = setTimeout(function() {
        $.xhrPool.abortAll();
        if (last_query != $.trim($('#header input').val())) {
          last_query = $.trim($('#header input').val());
          if (last_query.length > 2) {
            Finder.find(last_query);
          }
        }
      }, 1000);
    }
});

});