<div id="search_container">
  <div id='search_head'>
    <button type="button" id="search_close" class="close pull-left">&times;</button>
    <div id='search_time'></div>
  </div>
  <div id='search_results'></div>
  <div id='search_footer'></div>
</div>
<script>

var Search = function(){
  var s = this;
  var interval = 0;
  var keyword;
  var processLock=false;
  this.init = function(){
    $("#q").keyup(function(){s.queueSearch();});
    $("#search_form").submit(function(){s.queueSearch(); return false; });
    $("#search_close").click(function(){$("#search_container").fadeOut(300);});
  }

  this.queueSearch = function(){
    if($("#q").val() != keyword && $("#q").val()!=""){
      keyword = $("#q").val();
      interval=500;
      if(!processLock) s.processSearch();
    }else if($("#q").val()==""){
      keyword = ""
      $("#search_container").fadeOut(300);
    }
  }
  this.processSearch = function(){
    keyword_tmp = keyword;
    processLock = true;
    if(interval==0 && keyword!=""){
      $.getJSON("/site_search", {"keywords" : keyword}, function(data){
        if(keyword_tmp != keyword) {
            processLock = false;
            s.processSearch();
            return;
          }
        $("#search_results").scrollTop(0);
        $("#search_results").html("");
        $("#search_time").html("Found "+data.results.length+" Results, Search Time: "+data.time+"ms");
        $.each(data.results,function(key,res){
          search_result = 
            "<div class='search_result'>"+
            "<a href='"+res.url+"' target='_blank'>"+
              "<div class='seach_title'>"+res.title+"</div>"+
            "</a>"+
            "<span>"+res.content+"</span>"+
            "</div>";
          $("#search_results").append(search_result);
        });
        $("#search_container").fadeIn(300);
        processLock = false;
      });
    }else if(interval>0){
      interval -= 100;
      setTimeout(s.processSearch,100);
    }
  }
  s.init();
}();

</script>