jQuery(function() {
	function format(item) {
		if(lastCat != item.cat) {
		   lastCat = item.cat;
		   result = "<div class=\"autocompleteCat\">";
		   switch(item.cat) {
			   	case "title":
			   		result += "Produkte";
					break;
				case "cat":
					result += "Kategorien";
					break;
				case "vendor":
					result += "Hersteller";
					break;
		   }
		   result += "</div>" + item.name;
		   return result;
		}
		else return item.name;
	}
	autocompleteField.autocomplete('structured_autocomplete.php', {
		max: 15, // how many results to display at most
		minChars: 2,
		dataType: "json",
		cacheLength: 1,
		matchSubset: false,
		autoFill: false,
		selectFirst: false,
		scrollHeight: 280,
		// remove the comment marks in the next line to explicitly set the width of the suggestions box
		// width: 200,
		parse: function(data) {
			return jQuery.map(data.suggestions, function(row) {
				row = row.split("|");
				lastCat = "";
				/* sometimes the suggestion text contains the | symbol, so re-join it manually, leaving out the last two parts */
				text = row.slice(0, row.length - 2).join("|");
				return {
					data: {name: text, cat: row[row.length - 2], count: row[row.length - 1]},
					value: text,
					result: text,
				}
			});
		},
		formatItem: function(item) {
			return format(item);
		},
		extraParams: {
			query: function() { return autocompleteField.val(); }
		}
	});
});


