$(document).ready(function(){
	// autosuggest
	if ($('input[name=q]').length) {
		
		$.widget( "custom.catcomplete", $.ui.autocomplete, {

				_renderItem: function( ul, item ){
						return $("<li></li>")
								.data( "item.autocomplete", item)
								.append( item.category && item.category.length ? '<a style="padding-left: 45px">' + item.label + "</a>" : "<a>" + item.label + "</a>" )
								.appendTo( ul );

					}
				
			});	
		
		
	var cache = {},lastXhr, prevText, txtDiv = $('#postcode-search').find('div.row2');
	  $('input[name=q]').catcomplete({
			open: function(event, ui) {
				if (txtDiv.length) {
					prevText = txtDiv.text();
					txtDiv.text(txtDiv.text().replace("From the best local restaurants", "Choose your area"))
				}
			},
			close: function(event, ui) {
				if (txtDiv.length)
					txtDiv.text(prevText);
			},
			source: function( request, response ) {
							var term = request.term;
							if ( term in cache ) {
								response( cache[ term ] );
								return;
							}

							lastXhr = $.getJSON( "/postcodes/autocomplete", request, function( data, status, xhr ) {
								cache[ term ] = data;
								if ( xhr === lastXhr ) {
									response( data );
								}
							});
				},
			minLength: 1
	  })
	}
})
