$(function(){
	$("input#product_searchbox").autocomplete({
    	//define callback to format results
		source: function(req, add){
			
			//pass request to server
			$.getJSON("http://sales.starcitygames.com/autocomplete/products_only.php?callback=?", req, function(data) {

				//create array for response objects
				var suggestions = [];
				
				var found_matches = true; 
				
				if (data.F == true) {
				//We found no matches, so clear the prior bits
					$("input#product_searchbox").autocomplete("close"); 
				} else {
				//process response
					$.each(data, function(i, val){
						suggestions.push(val);
					});
					add(suggestions);		
				}
			});
		},
		select: function(event, ui) {
			
			if (ui.item.max_suggestions == true) {
				window.location = 'http://sales.starcitygames.com/cardsearch.php?game_type=1&auto=Y&singlesearch=' + ui.item.name; 
			} else {
				$("input#product_searchbox").val(ui.item.name);
				$("#productsearchform").append('<input name="auto" type="hidden" value="Y">'); 
				$("#productsearchform").submit();
			}
			return false; 
		},
    	minLength: 1, 
    	delay: 150
	}).data( "autocomplete" )._renderItem = function( ul, item ) {
		if (item.max_suggestions == true) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a><b>" + item.matches + " product matches for \"" + item.name + "\"!</b><br><span class='teasertext'>Click here to search!</a></span></a>" )
				.appendTo( ul );
		} else {
			line_information = "<a><b>" + item.name + "</b>"; 
			
			if (item.text != "") {
				line_information += "<br><span class='teasertext'>" + item.text+ "</span>"; 
			}
			
			line_information += "</a>"; 
			
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( line_information )
				.appendTo( ul );
		}
	};
});
