
/*======================= Suche Autocomplete ===========================*/

function Autocomplete() {
	var self = this;
	
	if ($('#headerSearchInput').length != 0) {
		self.initFormatResults();
		self.init();
	}
}

Autocomplete.appendLang = function (link) {
	if (link && link.indexOf("?") != -1) {
		return link + "&L=" + getLang();
	}
	
	return link ? link + "?L=" + getLang() : '';
};

Autocomplete.doTheHighlight = function (value, term) {
	if (term == null || value == null) {
		return "";
	}
	
    // Escape any regexy type characters so they don't bugger up the other reg ex
    term = term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");

    // Join the terms with a pipe as an 'OR'
    term = term.split(' ').join('|');
//    var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi");
    var regex = new RegExp("(?!<[^<>]*)(" + term + ")(?![^<>]*>)", "gi");
    
    return value.replace(regex, "<span class=\"matched\">$1</span>");
};

Autocomplete.prototype.init = function () {
	var $autocomplete = $("#headerSearchInput").catcomplete({
		minLength: 3,
		delay: 600,
		source: function(request, response) {
			var term_ = $.trim(request.term);
			
			if (term_.match(/^[üöäÜÖÄßa-zA-Z0-9, \/-]+$/g)) {
				$.ajax({
					url: HOST + "/index.php",
					dataType: "json",
					data: {
						type: 20, //typo3 ajaxType = 20
						L: getLang(),
						part: term_
					},
					beforeSend: function(jqXHR, settings) {
					},
					success: function(data) {
						response($.map(data, function(item) {
							if (item.label == null) return; 
							return {
								link: item.link,
								label: item.label,
								value: item.value,
								category: item.category
							};
						}));
					},
					error: function(xhr, status, error) {
						$('#headerSearchInput').removeClass('ui-autocomplete-loading');
						//alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
						//alert("responseText: "+xhr.responseText);
						//alert("status: "+status);
						//alert("error: "+error);
					}
				});
			} else {
				$('#headerSearchInput').removeClass('ui-autocomplete-loading');
			}
		},
		position: { 
			of: $("#headerSearchInput"),
			my : "right top", 
			at: "right bottom",
			offset: "23 2"
		},		
		search: function(event, ui) { 
//			alert('search');
		},
		change: function(event, ui) {  
//			alert('change');
		},		
		focus: function(event, ui) {
			$(".ui-autocomplete li.ui-menu-item").removeClass("ui-state-focus");
		    $("#ui-active-menuitem").closest("li").addClass("ui-state-focus");
			
		    $(".ui-autocomplete li.ui-menu-item").find('.oe_link_text').removeClass('ui-state-focus-blue-arrow');
		    $("#ui-active-menuitem").closest("li").find('.oe_link_text').addClass('ui-state-focus-blue-arrow');
		    
			return false;
		},		
//		select: function(event, ui) {
//			return false;
////			alert(ui.item ?
////				"Selected: " + ui.item.link :
////				"Nothing selected, input was " + this.value);
//		},
	    open: function(event, ui){
	    	$("ul.ui-autocomplete li a").each(function() {
	    		var htmlString = unescape($(this).html());
//				var htmlString = $(this).html().replace(/&lt;/g, '<');
//				htmlString = htmlString.replace(/&gt;/g, '>');
//				htmlString = htmlString.replace(/iconArrowBlueSec_grau/g, 'iconArrowBlueSec');
	    		
	    		$(this).html(htmlString);
	    	});
					           
           	$('.list-item').hover(
				function() {
//					$(this).css('color','#000');
					
					$(this).addClass("ui-state-hover");
//					$(this).parent().removeClass("ui-state-focus");
//					$(this).find('.oe_link_text').removeClass('ui-state-focus-blue-arrow');
				}, 
				function() {
					$(this).removeClass("ui-state-hover");
				}
			);
           	
			$('.list-item').bind('click', function() {
				var link = $(this).attr('href');
				if ($(this).parent().parent().attr('class') != 'pic-ul') {
					link = Autocomplete.appendLang(link);
				}
				window.document.location.href = link;
				return false;
			});
		}
	});
	
	$autocomplete.data("catcomplete")._renderItem = function( ul, item ) {
        var t = Autocomplete.doTheHighlight(item.label, $("#headerSearchInput").val());
		
		var cssClassLI = "", cssClassA = "";
		if (item.category == "last") {
			cssClassLI = " last";
			cssClassA = " oe_gray fontColor_black last-item";
		}
		
		return $('<li class="ui-menu-item' + cssClassLI + '" role="menuitem"></li>')
			.data("item.catcomplete", item)
			.append('<a href="' + item.link + '" class="list-item' + cssClassA + '">' + escape(t) + '</a>')
			.appendTo(ul);
	};
	
	$autocomplete.data("catcomplete").menu.options.selected = function(event, ui) { 
		if(event.originalEvent.keyCode === 13) {
			var item = ui.item.data("item.catcomplete");
			if (item.category == "Bilder") {
				window.document.location.href = item.link;
			} else {
				window.document.location.href = Autocomplete.appendLang(item.link);
			}
		}
	    return false;
	};
};

Autocomplete.prototype.initFormatResults = function () {
	$.widget("custom.catcomplete", $.ui.autocomplete, {
		_renderMenu: function(ul, items) {
			var self = this, currentCategory = "";
			var elementLI, elementUL;
			
			$.each(items, function(index, item) {
				if (item.category != currentCategory) {
					elementLI = $("<li class='ui-autocomplete-category'></li>");
					elementLI.append("<span class='fontColor_black'>" + item.category + "</span>");
					ul.append(elementLI);
					currentCategory = item.category;
					
					if (item.category == 'Bilder') {
						elementUL = $("<ul class='pic-ul'></ul>");
						elementLI.append(elementUL);
					}
				}
				
				if (item.category == 'Bilder') {
					self._renderItem(elementUL, item);
				} else {
					self._renderItem(ul, item);
				}
				
				// last item
				if (index+1 == items.length) {
					item.label = "<span class=\"oe_link_text iconArrowGrey\">Alle Suchergebnisse</span>";
					item.link = '/index.php?id=147&L=' + getLang() + '&q=' + $("#headerSearchInput").val();;
					item.value = "*";
					item.category = "last";
					
					self._renderItem(ul, item);
				}
			});
		}
	});		
};

/*===========================================================*/

$(function(){
	new Autocomplete();
});






