var lastSearchTerm;

$(document).ready( function() {
	// SearchSuggestions
	$('#searchfield').keyup( function(event) {
		event.stopImmediatePropagation();
		
		var searchQuery = $(this).attr('value');
		if( lastSearchTerm == searchQuery )
			return false;
		
		lastSearchTerm = searchQuery;
		if( searchQuery.length < 3 ) {
			$('.SearchSuggestions').css('display', 'none');
			return false;
		}
		
		setTimeout("getSearchSuggestions('" + searchQuery + "')", 350);
		return true;
	});
	
	// SearchSuggestionsBrowse
	$('#searchfield').keydown( function(event) {
		event.stopImmediatePropagation();
		
		if( event.keyCode == 38 ) // arrow up
		{
			SearchSuggestionsBrowse('up'); 
			return false;
		}
		else if( event.keyCode == 40 ) // arrow down
		{
			SearchSuggestionsBrowse('down'); 
			return false;
		}
		else if( event.keyCode == 9 ) // tab
		{
			ApplySuggestionViaTabKey();
			return false;
		}
		else if( event.keyCode == 13 ) // enter
		{
			SearchSuggestionsSubmit();
			return false;
		}
		
		// aktive suggestion nach keypress "deaktivieren"
		$('.SearchSuggestions .suggestionactive').attr('class', 'suggestion');
	});
	
	// hover per js, da sonst doppelte hovers wenn pfeiltasten benutzt werden
	$('.SearchSuggestions').mouseover( function(event) {
		var suggestion = $(event.target).parent('.suggestion');
		if( suggestion.length != 1)
			return false;
		
		$('.SearchSuggestions .suggestionactive').attr('class', 'suggestion');
		suggestion.attr('class', 'suggestionactive');
		return false;
	});
	
	$('.SearchSuggestions').mouseout( function() {
		$('.SearchSuggestions .suggestionactive').attr('class', 'suggestion');
		return false;
	});
});

function getSearchSuggestions(searchquery)
{
	if( $('#searchfield').attr('value') != searchquery ) {
		return false;
	}
	
	var suggestionBox = $('.SearchSuggestions');
	
	$.ajax({
		   type: "POST",
		   url: DSTORE_BASE_URL + '/index.php',
		   data: {screen:$('#searchfield').attr('rel'),Search:searchquery},
		   dataType: 'json',
		   success: function(response)
		   {
			   // response in javascript objekt eval'en
			   var suggestions = $.evalJSON(unescape(response.Content));
			   
			   // alte suggestions entfernen falls vorhanden
			   suggestionBox.children('.suggestion').remove();
			   suggestionBox.children('.suggestionactive').remove();

			   // referenz-zeile einer suggestion in der "dropdown"-box kopieren
			   // diese wird verwendet um die gefundenen suggestions in die box einzufügen
			   var suggestionRow = $('.SearchSuggestionReferenceRow').clone();
			   suggestionRow.attr('class', 'suggestion');
			   
			   if( suggestions.length == 0 ) {
				   suggestionBox.css('display', 'none');
				   return true;
			   }
			   
			   // gefundene suggestions durchlaufen und zur dropdown-box hinzufügen
			   for( var i=0; i < suggestions.length; i++ )
			   {
				   var newSuggestion = suggestionRow.clone();
				   var regex = new RegExp($('#searchfield').attr('value'), 'i');
				   var foundAtPos = suggestions[i].Value.search(regex);
				   if( foundAtPos > -1 ) {
					   var searchTermInResult = suggestions[i].Value.slice(foundAtPos, foundAtPos + $('#searchfield').attr('value').length);
					   newSuggestion.children('.suggestvalue').html(suggestions[i].Value.replace( regex, '<strong>' + searchTermInResult + '</strong>'));
				   }
				   else {
					   newSuggestion.children('.suggestvalue').html(suggestions[i].Value);
				   }
				   
				   newSuggestion.children('.searchvalue').html(suggestions[i].Value);
				   newSuggestion.children('.type').html(suggestions[i].TypeLabel);
				   if( suggestions[i].NoOfHits > 1 )
					   newSuggestion.children('.hits').html('(' + suggestions[i].NoOfHits + ')');

				   switch(suggestions[i].Type)
				   {
				   		case 'Kategoriebezeichnung':
				   			newSuggestion.children('.url').html('index.php?screen=dstore.webshop.category&tnid=' + suggestions[i].TreeNodeID);
				   			break;
				   		case 'Produktbezeichnung':
				   		case 'Artikelnummer':
				   			if( suggestions[i].TreeNodeID > 0 )
				   				newSuggestion.children('.url').html('index.php?screen=dstore.webshop.view&tnid=' + suggestions[i].TreeNodeID);
				   			break;
				   		case 'Marke':
				   			//newSuggestion.children('.url').html('index.php?screen=dstore.webshop.productsOfBrand&Marke=' + suggestions[i].Value);
				   			break;
				   }

				   // onclick-event fuer suggestion: übernehmen und artikel-screen bzw. suche aufrufen
			   		newSuggestion.children('.suggestvalue').click( function(event) {
			   			event.stopImmediatePropagation();

			   			$('#searchfield').attr('value', $(this).siblings('.searchvalue').html());
			   			if( $(this).siblings('.url').length == 1 && $(this).siblings('.url').html().length > 0 ) {
			   				window.location.href = $(this).siblings('.url').html().replace(/\&amp\;/, '&');
			   			}
			   			else {
			   				$('#searchfield').closest('form').submit();
			   			}
			   			
			   			return false; 
			   		});
				   
				   suggestionBox.append(newSuggestion);
			   }
			   
			   suggestionBox.css('display', 'block');
			   
		   },
		   error: function(response)
		   {
			   suggestionBox.children('.suggestion').remove();
			   suggestionBox.children('.suggestionactive').remove();
		   }
	});
}

function SearchSuggestionsBrowse(direction)
{
	if( direction != 'down' && direction != 'up' )
		return false;
	
	var suggestionBox = $('.SearchSuggestions');
	if( suggestionBox.css('display') != 'block' )
		return false;

	var suggestions = suggestionBox.children();
	var currentActiveSuggestion = $('.SearchSuggestions .suggestionactive');
	if( currentActiveSuggestion.length < 1 ) {
		if( direction == 'down' )
			browseToPos = 0;
		else if( direction == 'up' )
			browseToPos = suggestions.length - 1;
	}
	else
	{
		if( suggestions.length == 1 )
			return false;
		
		if( direction == 'down' )
			var browseToPos = currentActiveSuggestion.prevAll().length + 1;
		else if( direction == 'up' )
			var browseToPos = currentActiveSuggestion.prevAll().length - 1;
		
		if( browseToPos < 0 )
			browseToPos = suggestions.length - 1;
		else if( browseToPos >= suggestions.length )
			browseToPos = 0;
		
		currentActiveSuggestion.attr('class', 'suggestion');
	}
	
	$(suggestions[browseToPos]).attr('class', 'suggestionactive');
	return true;
}

function ApplySuggestionViaTabKey()
{
	var currentActiveSuggestion = $('.SearchSuggestions .suggestionactive');
	if( currentActiveSuggestion.length == 0 ) {
		return true;
	}
	
	$('#searchfield').attr('value', currentActiveSuggestion.children('.searchvalue').html());
	$('.SearchSuggestions').css('display', 'none');
}

function SearchSuggestionsSubmit()
{
	var currentActiveSuggestion = $('.SearchSuggestions .suggestionactive');

	if( currentActiveSuggestion.length > 0 ) {
		if( currentActiveSuggestion.children('.url').html() != '' ) {
			window.location.href = currentActiveSuggestion.children('.url').html().replace(/\&amp\;/, '&');
		}
		else {
			$('#searchfield').attr('value', currentActiveSuggestion.children('.searchvalue').html());
			$('#searchfield').closest('form').submit();
		}
		
		return true;
	}
	
	$('#searchfield').closest('form').submit();
	return true;
}
