$(document).ready(function() {
	
	// submit the form only if text has been entered
	// go back to home page of nothing entered
	
	
	$("form[name='searchForm'], form[name='searchFormBg']").submit(function() {	
		var search = $("input[name='q']", $(this)).val();
		search = search.replace(/^\s+|\s+$/g,""); // remove non-alpha characters
		if (search.length == 0) {
			window.location.href = "http://" + window.location.host;
		}
		return search.length > 0;
	});
	
	// register stuff for auto-suggestion
	var options = {
		cacheLength: 0, 
		scroll: false, 
		selectFirst: false, 
		formatItem : autoSuggestionFormatItem, 
		highlight: function(value){return value;}
	};	
	$("form#searchForm input[name='q']").autocomplete("/getautocomplete.php", options);	
	
	$("form#searchForm input[name='q']").result(function(event, data, formatted) {
 		$("form[name='searchForm']").submit();
	});
});

// TODO this function is also in mystart.js.  We should reuse the same function
function autoSuggestionFormatItem(data, index, max, value, term) {
	// if the first item, add the "Suggestions" text 
	if (index == 1) {
		value += '<span class="sug_title">Suggestions</span>';
	}
	
	// if the last element, add the "close" link
	if (index == max) {
		// add close button to panel, if not already there
		if ($("div.ac_results span.close_panel").length == 0) {
			$("div.ac_results").append('<span class="close_panel">close</span>');
		}
	}
	
	return value;
}
