$(function(){
	initSearch();
	
	$.widget( "custom.catcomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var self = this, currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}
				self._renderItem( ul, item );
			});
		}
	});
	
	$( "#SearchQ" ).catcomplete({
		delay: 0,
		source: sessvars.listAutocomplete,
		select: function( event, ui ) {
			$("#SearchQ").val(ui.item.value);
			$('#SearchForm').submit();
		}
	}).data('catcomplete')._renderItem = function(ul, item){
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( '<a>' + item.label + '</a>')
			.appendTo( ul );
	};
});
function initSearch() {
	if (sessvars.listAutocomplete == undefined) {
		$('#loadingAutocomplete').show();
		$.getJSON("/restaurantes/getAutocomplete", function(data) {  
			sessvars.listAutocomplete = data;
			$('#loadingAutocomplete').hide();
			$( "#SearchQ" ).catcomplete('option', "source", sessvars.listAutocomplete);
	    });
	}
	sessvars.$.flush();
}
