$(function () {	
	

	
// http://ivan.rolik.name/2013/06/17/jquery-ui-autocomplete-with-category/
	$.widget("custom.catcomplete", $.ui.autocomplete, {
	  _renderMenu: function(ul, items) {
		var currentCategory,
		  _this = this;
		ul.addClass('search-autocomplete');
		currentCategory = "";
		return $.each(items, function(index, item) {
		  if (item.category !== currentCategory) {
			ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
			currentCategory = item.category;
		  }
		  return _this._renderItem(ul, item);
		});
	  },
	  
	  
	  
	  _renderItem: function(ul, item) {
		var $anchor, html_anchor, re;
		re = new RegExp("(" + this.term + ")", "gi");

		html_anchor = '<a href="' + item.label.url + '">' + item.label.name + '</a>';
        $anchor = $(html_anchor);
		
        if (item.label.type == 2) {	
			$anchor.click(function() {
			  document.location.href = $(this).attr('href');
			});
		} else {
			
			if (item.label.type == 1) {	
			
				$anchor.click(function() {
				  $('#spec').val($(this).attr('href'));
				});
				
			} else if (item.label.type == 3) {

				$anchor.click(function() {
				  $('#metro').val($(this).attr('href'));
				});

			}				
		}
		
		return $("<li></li>").data("item.autocomplete", {
		  label: item.label.url,
		  value: item.label.name
		}).append($anchor).appendTo(ul);
	  }
	});
	
	
	
	
    $("#search_doc_sp").catcomplete({
        delay: 0,
        source: "/search_doc_new/?type=1&city_id="+$("#search_doc_sp").attr("data-city")+"&host="+window.location.hostname+"&t=1",
		minLength: 0
    }).focus(function() {
       $(this).catcomplete("search", $(this).val());
    });
	
    $("#search_doc_metro").catcomplete({
        delay: 0,
        source: "/search_doc_new/?type=2&city_id="+$("#search_doc_sp").attr("data-city")+"&host="+window.location.hostname+"&t=1",
		minLength: 0
    }).focus(function() {
       $(this).catcomplete("search", $(this).val());
    });
	
});