jQuery(document).ready(function($) {
  $('#hb-searchinput').attr('autocomplete', 'off');
  createSearchBox();
  $('#hb-searchinput').keyup(onSearchBoxKeyPressed).focus(onSearchBoxActive).blur(onSearchBoxBlur);
});


function createSearchBox() {
  jQuery.create('ul' ,
           {'id': 'mcs-search-box', 'class': 'mcs-search-box'}
          )
          .appendTo('body')
}

function onSearchBoxKeyPressed(e) {
  var value = jQuery('#hb-searchinput')[0].value
  if (value.length > 5) {
    var pos = jQuery('#hb-searchinput').position()
    jQuery('#mcs-search-box').css({"top": (pos.top+27)+'px', "left": (pos.left-20)+'px'})
    searchBoxToggle(true);
    startSearch(value);
  } else {
    searchBoxToggle(false);
  }
}

function searchBoxToggle(open, callback) {
  if (open) {
    if (jQuery('#mcs-search-box')[0].getAttribute('vis') != 'true') {
      jQuery('#mcs-search-box')[0].setAttribute('vis', 'true');
      jQuery('#mcs-search-box').fadeIn('fast');
    }
  } else {
    if (jQuery('#mcs-search-box')[0].getAttribute('vis') != 'false') {
      jQuery('#mcs-search-box')[0].setAttribute('vis', 'false');
      jQuery('#mcs-search-box').fadeOut('fast');
    }
  }
}

function onSearchBoxActive(e) {
  onInputFocus(e);
  var value = jQuery('#hb-searchinput')[0].value
  if (value.length > 5) {
    searchBoxToggle(true);
  }
}

function onSearchBoxBlur(e) {
  jQuery('#mcs-search-box').fadeOut('fast');
  jQuery('#mcs-search-box')[0].setAttribute('vis', 'false');
  onInputBlur(e);  
}

var Inter = null;
var searchc = null;

function startSearch(term) {
  jQuery('#mcs-search-box').empty();
  jQuery('#hb-searchinput').addClass('working');
  if(Inter)
    Inter = clearTimeout(Inter)
  Inter = setTimeout("search('"+term+"')", 400)
}

function search(term) {
  jQuery.getJSON(searchJSONpath+"?s="+term+"&jsoncallback=?", 
    function(data){
        jQuery.each(data,
                    function(i,item){
                      if (i < 5) {
                        addEntry(item.title, item.url)
                      } else if (i == 5) {
                        addEntry('find more »', blogUrl+'?s='+term, 'more')
                      } else return false;
                    });
    jQuery('#hb-searchinput').removeClass('working');
  });
}

function addEntry (val, url, cl) {
  if (cl)
    jQuery.create('li',{'class': cl}, jQuery.create('a', {'href': url}, val)).appendTo(jQuery('#mcs-search-box')).fadeIn('fast')
  else
    jQuery.create('li',{}, jQuery.create('a', {'href': url}, val)).appendTo(jQuery('#mcs-search-box')).fadeIn('fast')
}
