jQuery(document).ready(function() {
	var lastSelectedResultHref;
	var positionSearch = function(){
		var mainCont = $('#container');
		var right = $(window).width() - (mainCont.offset().left + mainCont.outerWidth());
		$('ul.searchpreview').css({'left': 'inherit', 'right': right});
		
		//reselect last selected result
		var $lastSelected = $('ul.searchpreview li:not(.headline):has(a[href="'+lastSelectedResultHref+'"])');
		if(lastSelectedResultHref && $lastSelected.size() > 0){
		    $lastSelected.addClass('highlight').siblings().removeClass('highlight');
		}
	}
	$(window).bind('resize', positionSearch);
	$('ul.searchpreview li').live('click', function(){
		try{ET_Event.click('Instant-Suche result-click', $(this).find('a').attr('href'));}catch(err){}
		location.href = $(this).find('a').attr('href');
	});
	$('#searchfield').keyup(function(event){		    
		//key navigation
		var $currentSelection = $('ul.searchpreview li.highlight:not(.headline)');
		if(event.keyCode == 40) { //down
		    if($currentSelection.size() < 1){
			$currentSelection = $('ul.searchpreview li:not(.headline):last');
		    }
		    var $next = $currentSelection.nextAll(':not(.headline)').first().size() > 0 ? $currentSelection.nextAll(':not(.headline)').first() : $currentSelection.siblings(':not(.headline)').andSelf().first();
		    lastSelectedResultHref = $next.addClass('highlight')
		    .siblings().removeClass('highlight')
		    .end().find('a').attr('href');
		    try{ET_Event.click('Instant-Suche arrow-keys');}catch(err){}
	        }else if(event.keyCode == 38){ // up
		    if($currentSelection.size() < 1){
			$currentSelection = $('ul.searchpreview li:not(.headline):first');
		    }
		    var $next = $currentSelection.prevAll(':not(.headline)').first().size() > 0 ? $currentSelection.prevAll(':not(.headline)').first() : $currentSelection.siblings(':not(.headline)').andSelf().last();
		    lastSelectedResultHref = $next.addClass('highlight')
		    .siblings().removeClass('highlight')
		    .end().find('a').attr('href');
		    try{ET_Event.click('Instant-Suche arrow-keys');}catch(err){}
		}else if(event.keyCode == 13 && $currentSelection.size() > 0){ //return
		    try{ET_Event.click('Instant-Suche return-key mit Auswahl', $currentSelection.find('a').attr('href'));}catch(err){}
		    var delayRedirect = function(){
			location.href = $currentSelection.find('a').attr('href');
		    }
		    setTimeout(delayRedirect, 50);
		return false;
		}else{
		    var query = $(this).val();
		    if(query.length > 1){
			$('#searchcontainer').load('/suchergebnis/', {q: query}, positionSearch);
		    }else{
			$('#searchcontainer').empty();
		    }
		}
	});
});
