$(document).ready(function() {
	var sh_cache = {};
	// call this function to run search helper on search_term and put them in sh_results
	var run_search_helper = function(search_term) {
		
		// if the search query is 3 letters long then pop the search assist down and send a request to search helper
		// the code that handles this request is found in ajax/search_helper_ajax.php
		if (search_term.length > 2) {
			if(sh_cache[search_term]) {
				$("#sh_results").html(sh_cache[search_term].output);
			} else {
				ajax_url = "/ajax_index.php?main_page=search_helper" + "&query=" + search_term;
		        $.ajax({
		            type: "GET",
		            url: ajax_url,
		            dataType: "json",
		            success: function(data){
		        		if(data.success) {
		        			$("#sh_results").html(data.output);
		        			sh_cache[search_term] = data;
		        		} else {
		        			$("#sh_results").text("No results.");
		        		}
		            },
		            error: function(request, error_string, e){
		            	$("#sh_results").text("No results.");
		            }
		        });
	
	            $("#searchhelper").slideDown();
	            
			}
        // if the search query is shorter than 3 letters then don't search    
		} else {
			$("#sh_results").text("No results.");
		}
	};
	
	// listen for keyup events and then run a timer to wait for inaction before sending search helper requests
	// this makes sure the user has stopped typing and prevents the server from doing unnecessary searches
	var timer;
	$("input[name=keyword]").keyup(function() {
		// if there's a search waiting to run, cancel it since we've got a new search
		if (timer != null) {
			clearTimeout(timer);
		}
		
		var search_term = $("input[name=keyword]").val();
		timer = setTimeout(function(){run_search_helper(search_term);}, 500); // wait this long before sending request
	});
	
	// button to hide search assist
	$("#sh_close").click(function() {
		$("#searchhelper").slideUp();
	});
});