var site = "http://jb";

$(function() { // do the following on DOMload
  $('.searchbox').each(function(){
    var current   = this;
    var id        = current.id;
    var box_id    = id+'_search'
    var title     = 'Find '+id;
    // add a searchbox to each searchbox classed div
    $('<label for = "'+box_id+'">'+title+'</label><input type="text" name="'+id+'" value="" id="'+box_id+'"/>').appendTo(this);
  });
  // add a general results box, and then hide it
  $("body").append('<div id = "results"></div>');
  $("#results").hide();
  // attach a function to each search box that will perform the search
  $('.searchbox input').keyup(function() {
    var current     = this;
    var my_id       = '#'+current.id;
    var inputString = current.value;
    var name        = current.name;
    // chec to see if after keyup there is any value to send to the querypage
    if(inputString.length == 0) {
      $("#results").slideUp('fast');
    } else if(inputString.length > 1) { // only search when we have two or mode characters
      $.post(site+"/xhrsearch.php", {t: name, q:""+inputString+""}, function(data){
        var searchfor  = name;
        var searchterm = inputString;
        var offset     = $(my_id).offset();
        var width      = $(my_id).outerWidth({ margin: true });
        var y          = offset.top + $(my_id).outerHeight({ margin: true });
        var x          = offset.left;
        // add a close link to each results set
        var close      = '<p><a href="#" onclick="$(\'#results\').slideUp(\'fast\')">Close</a></p>'
        if(data.length > 0) {
          $("#results").html(data+close);
          $("#results").css("position","absolute").css("top",(y) + "px").css("left",(x) + "px").slideDown('fast');
        } else {
          $("#results")
            .html("<p>No "+searchfor+" matches found for '"+searchterm+"'</p>"+close)
            .css("position","absolute")
            .css("top",(y) + "px")
            .css("left",(x) + "px")
            .slideDown('fast');
        }
      });
    }
  });
});