/* Search item categories, initialised when the page first loads. */
var searchCategories = new Array();

/* Prepare the Ajax Communication Object */
function getXmlHttpRequestObject() {
	
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Ihr Browser unterstützt die dynamische Suche leider nicht. Bitte machen Sie ein Update Ihres Browsers auf die neueste Version!");
	}
}

var searchReq = getXmlHttpRequestObject();

var callIdCurrent = '';

/* Request a suggestion from the server. Implements a delay, so that the server is only called if a 
 * period of time passes without another key being pressed. */ 
function searchSuggest() {
	
	callIdCurrent =  new Date().getTime();
	setTimeout('searchSuggestDelayed(' + callIdCurrent + ')', 150);
}

/* Use the Ajax Communication Object to retrieve suggestions from the web server, but only
 * after the delay has been checked. */
function searchSuggestDelayed(callId) {
	
	// The webserver is only called for a request if the timout passed before another key was pressed.
	var callIdValid = 
		callId == callIdCurrent; 
	
	if (callIdValid && (searchReq.readyState == 4 || searchReq.readyState == 0)) {
		
		var searchTerm = escape(document.getElementById('search_box').value);
		searchReq.open("GET", 'suggest.php?search_term=' + searchTerm, true);
		searchReq.onreadystatechange = handleSearchSuggest; 
		searchReq.send(null);
	}		
}

/* Handle data returned from the web server in response to an AJAX suggest request
 * via the Ajax Communication Object. */
function handleSearchSuggest() {
	document.getElementById('search_suggest').style.display = 'block';
	if (searchReq.readyState == 4) {
		
		// The new HTML that will be displayed.
		suggestionsHTML = '';
		
		var search_suggest = document.getElementById('search_suggest');
		//var searchResultPreview = document.getElementById('searchResultPreview');
		var numberOfMaxSearchResults = 5;
		
		var responseText = searchReq.responseText;
		//alert(responseText);
		
		//  Convert the serialized data from the server to a Javascript array.
		var tmp = eval("(" + responseText + ")");
		var cats = tmp.categories;
		var suggestions = tmp.suggestions;
		var suggestion_count = suggestions.length;
		
		if (suggestion_count == 0) { 
			
			// No search terms were suggested, so hide the suggest aread.
			//searchResultPreview.style.display = 'block';
			suggestionsHTML += getHTMLSuggestionHeader();
			suggestionsHTML += getHTMLSuggestionHeaderCategory();
			suggestionsHTML += getHTMLNoResult(document.getElementById('search_box').value);
			suggestionsHTML += getHTMLSuggestionFooter(tmp.moreResultsLinks);
			
			
		} else { 
			
			// At least one search term was suggested, so display the suggest area
			//searchResultPreview.style.display = 'block';
			
			// While looping through suggestions, track whether a new search category has been encountered.
			categoryPrevious = -1;
			suggestionsHTML += getHTMLSuggestionHeader();
			
			// loop through all returned suggestions.
			for(i = 0; i < suggestion_count; i++) {
				
				var category = suggestions[i].category;
				
				// Write a category header if a new category is encountered.
				if (category != categoryPrevious) {
					
					categoryPrevious = category;
					
					suggestionsHTML += getHTMLSuggestionHeaderCategory(cats[category]);
					
				}
					
				// Write the current suggestion as a link.
				suggestionsHTML += getHTMLSuggestionLink(suggestions[i].term, suggestions[i].image, suggestions[i].url, i, numberOfMaxSearchResults, suggestion_count);
			}
			
			// Finally write a new search submit button.
			//suggestionsHTML += getHTMLSuggestionsSubmit();
			
			// Write the footer
			suggestionsHTML += getHTMLSuggestionFooter(tmp.moreResultsLinks);
		}
		
		// Update the search area with the new HTML containing search suggestions.
		search_suggest.innerHTML = suggestionsHTML;
	}
}

function removeSearchPreview() {
	document.getElementById('search_suggest').style.display = 'none';
}

function displaySearchPreview() {
	document.getElementById('search_suggest').style.display = 'block';
}

	
/* Called when any of the suggested search terms are clicked. */
function setSearch(value) {
	
	document.getElementById('search_suggest').innerHTML = '';
	document.getElementById('search_suggest').style.display = 'none';
	document.getElementById('search_box').value = value;
	document.getElementById('quick_find').submit();
}

/* Focus the search form when the page loads */
function formFocus() {
	
	mainForm = document.forms[0]; 
	
	if (mainForm) {
		mainForm.elements[1].focus();
	}
}

function getHTMLSuggestionHeaderCategory(category) {
	
		if(category) {
			
			return '' + 
			'	</ul><div class="suggest_header_category"><span class="suggest_header_category_raquo">&raquo;&nbsp;</span>' + category + '</div>' + 
			'	<ul class="resultList">';
		} else {
			return '' + 
			'	</ul><ul class="resultList">';
		}
		
}

/* Construct HTML for a suggestion category header. */
function getHTMLSuggestionHeader() {
	
		return '' + 
		'<div class="searchResultPreview" id="searchResultPreview" onmouseout="removeSearchPreview();" onmouseover="displaySearchPreview();" >' +
		'	<!--<div class="searchResultPreviewHeadline"><img src="templates/BluePassion/images/searchProducts.png" alt="" /></div>//-->';
	
}

/* Construct HTML for no result. */
function getHTMLNoResult(searchTerm) {

	return '' +
		'<li class="noResult">Leider wurden für den Suchbegriff "' + searchTerm + '" keine Produkte gefunden.</li>';
}

/* Construct HTML for a suggestion link. */
function getHTMLSuggestionLink(term, image, url, counter,  numberOfMaxSearchResults, suggestion_count) {
	
	var cssStyle = 'result-item';
	
	if(((suggestion_count-1) == counter) || ((numberOfMaxSearchResults-1) == counter)) {
		cssStyle = 'last';
	}
	
	return '' + 
		'<li class="' + cssStyle + '" id="result-item' + counter + '">' +
		//'	<a href="' + url + '" class="searchResultItemLink"><img class="productImage" src="' + image + '" alt="" /></a>' +
		'		<a href="' + url + '" class="searchResultItemLink">' + term + '</a>' +
		'	<div class="dummy"></div>' +
		'</li>';
		
}

/* Construct HTML for the suggestions footer. */
function getHTMLSuggestionFooter(moreResultsLinks) {
	var ret = '</ul>';
	var link_count = moreResultsLinks.length;	
	
	
	for(i = 0; i < link_count; i++) {
		ret += '	<a href="'
		
		if(moreResultsLinks[i].url)
		{
			ret += 'javascript:moreResults(\'' + moreResultsLinks[i].url + '\')';
		}
		else
		{
			ret += 'javascript:moreResultsDefault()';
		}
			
		ret += '" class="searchResultAllResults';
		if(link_count == (i - 1))
		{
			ret += 'Last';
		}
		ret += '"><span class="searchResultAllResultsPrefix">&raquo;</span> ';
		ret += moreResultsLinks[i].name;
		ret += '</a>';
		var name = moreResultsLinks[i].name;
		
	}
	
	ret += '</div>';
	return ret;
}

/* Construct HTML for the suggestions footer with no result. */
function getHTMLSuggestionFooterNoResult() {

	return '' + 
		'	</ul>' +
		'</div>';
}

/* Construct HTML for the suggestions submit button. */
function getHTMLSuggestionsSubmit() {
	
	return '' +
		'<div id="submit_inner">' +
		'	<input type="submit" value="Search" class="submit"/>' +
		'</div>'; 
}

function homepageChangeTo(divName) {
	if(divName == 'featured_products') {
		document.getElementById('featured_products').style.display = 'block';
		document.getElementById('new_products').style.display = 'none';
	} else if(divName == 'new_products') {
		document.getElementById('featured_products').style.display = 'none';
		document.getElementById('new_products').style.display = 'block';
	}
}

function moreResults(url)
{
	url += '&keywords=' + escape(document.getElementById('search_box').value);
	window.location = url;
}

function moreResultsDefault()
{
	document.getElementById('quick_find').submit();
}