var resultsShowing	= new Boolean(false);

$(document).ready(function() {

	// after a key has been pressed in the search text input field
	$("#searchPC").keyup(function() {
		// grab the value of the field
		var data = $(this).val();
		// if there is a value
		if (data.length > 2) {
			// send the query
			sendAJAX(data);
		// if there is not a value
		} else {
			// empty the results list
//			$("#results-wrapper .results").empty();
			// hide the window
			$("#results-wrapper").css("visibility", "hidden");
			resultsShowing = false;
		}
	// hide the window if the text field is no longer selected
	}).blur(function() {
		setTimeout(function(){
			$("#results-wrapper").css("visibility", "hidden");
			resultsShowing = false;
		}, 350);
	// open the window if the text field is selected
	}).focus(function() {
		// grab the value of the field
		var data = $(this).val();
		// if there is a value
		if (data.length > 2) {
			// send the query
			sendAJAX(data);
		}
	});

});

// send a dynamically loaded query to the autocomplete script
function sendAJAX(query) {

	// create the query url
	var url = '/cgi/perfcomplete.cgi?q=' + query;
	var encurl = encodeURL(url);
	// use jquery's load function to fill the results list
	$("#results-wrapper .results").load(encurl, null, function() {
		// make sure the results list is visible
		$("#results-wrapper").css("visibility", "visible");
		resultsShowing = true;
		// add a click function to the results, this has to be done here because the function won't
		// pass to the content that was loaded after the initial document ready function.
		$("#results-wrapper .results .result").click(function() {
			// grab the value of the "rel" attribute from this item
			var text = $(this).attr("rel");
			// set the text input field value to the selected search item and retain it's focus
			$("#searchPC").val(text);
			$("#searchPC").focus();
			document.forms["searchform"].submit();
			// reapply the query with the new value
			sendAJAX(text);
		});
	});

}

// encode a url so it works with our script, then return it
function encodeURL(url) {
	var plus = "+";
	// replace the spaces with pluses
	var newurl = url.replace(/ /g, plus);
	return newurl;
}

