/**
 * liveSearch
 * uses ajax to peform as you type search queries
 * @usage: $("#input_box").liveSearch(url);
 */
jQuery.fn.liveSearch = function(url) {

  return this.each(function () {

  	var timeout = undefined; // used to ensure queries are sent only when typing has stopped
  
  	var delay = 500; // delay (in ms) after the last keystroke to wait before we do the ajax call 
  
  	var last_search = undefined; // stores last search query to cut down on roundtrips
  
  	var $input = $(this); // input element
  
  	// append the hidden search results container to the dom after the input element
  	var $result = $("<ul class='liveSearch_result'></ul>").hide().css("position", "absolute").insertAfter($input);
  
  	// switch off the browser auto complete for the input box
  	$input.attr("autocomplete", "off").addClass("liveSearch_input");
  
  	$input.blur(function () {
  	
  		setTimeout(function() {
  			$result.hide()}, 200
  		);
  		
  	});
  	
  	// bind the ajax call to the input box key up event
  	$input.keyup(function() {
  
  		if(timeout != undefined) {
  			clearTimeout(timeout);
  		}
  	
  		if (last_search != $input.val()) {
  
  			// new search is different to the last search
  
  			timeout = setTimeout(function() {
  
  				timeout = undefined;
  				ajax_search($input, $result);
  				last_search = $input.val(); // remember this search so we don't do it again next time
  
  			}, delay); 
  
  		}
      
  	});

    
  });

  
	function ajax_search($input, $result) {

		$result.hide().empty();

		if ($input.val() != "") {		

			// only search if we have something to search for

			$input.addClass("liveSearch_loading"); // adds the ajax anim to the input box

			// perform the ajax call
			$.ajax({

				// url: url + "?q="+$input.val(),

				url: url + "?q="+$input.val()+"&r="+$("#root").val(),


				success: function(data) {
				
					if ($.trim(data) == "") {
					
						$result.hide();
					
					}
					else {

						// append the results to the results container
						$result.append(data);
	
						// re-position the results container in case the dom has changed
	
						var pos = $input.offset();
	
						$result.css({
							top: (pos.top + $input[0].offsetHeight) + 1 + "px",
							left: pos.left - 232 + "px"
						}).show();
						
					}

				},
				complete: function () {
					// hide the ajax anim
					$input.removeClass("liveSearch_loading");
				}				

			});
			
		}

	}

}
