
var search_animationSpeed = 0;
var search_staySpeed = 600;
var search_keyCombinationSpeed = 200;

var search_hideTimeout = 0;
var search_searchBoxFirstHit = true;
var search_searchKeyInputInterval = 0;

var search_productsFound = false;
var search_articlesFound = false;
var search_stocksFound = false;
var search_hitEnter = false;
var search_results = new Array();
var search_selectedResult = -1;

var search_queryString = "";

function search_showLoadBar(){
	if ($('#search-result-box').is(':hidden')) {
		$("#search-loading-box").show();
	}
}

function search_hideLoadBar(){
	$("#search-loading-box").hide();
}

function search_hideResultBox(){
	search_hideLoadBar();
	search_hideTimeout = window.setTimeout(function(){
		window.clearTimeout(search_hideTimeout);
		$("#search-result-box").hide(search_animationSpeed);
	}, search_staySpeed);
}

function search_stopHideResultBox(){
	window.clearTimeout(search_hideTimeout);
}

function search_highlightText(text, query){
	var fi = text.indexOf(query);
	if(fi == -1) fi = 0;
	
	var highlight = document.createElement("b");
	highlight.appendChild(document.createTextNode(query.toUpperCase()));
	var beforeNode = document.createTextNode(text.substr(0, fi).toUpperCase());
	var afterNode = document.createTextNode(text.substr(fi + query.length).toUpperCase() + ": ");
	
	var completeNode = document.createElement("span");
	completeNode.appendChild(beforeNode);
	completeNode.appendChild(highlight);
	completeNode.appendChild(afterNode);
	
	return completeNode;
	
	//var re = new RegExp(query);
	//return text.replace(re, tagBefore + query + tagAfter);
}

function search_addSearchResult(obj, number){
	var productBox = document.getElementById("product-results");
	var stockBox = document.getElementById("stock-results");
	var articleBox = document.getElementById("article-results");
	
	// construct li node
	var liNode = document.createElement("li");
	liNode.setAttribute("id", "r"+number);
	
	var href = "";
	
	switch (obj.type) {
	case "PRODUCT":
		search_productsFound = true;
		href = search_siteRootLink + "product/" + obj.linkTarget;
		productBox.appendChild(liNode);
		break;
		
	case "ARTICLE":
		search_articlesFound = true;
		href = obj.linkTarget;
		liNode.appendChild(search_highlightText(obj.matchedKeyword, search_queryString));
		articleBox.appendChild(liNode);
		break;
		
	case "PULS":
        search_articlesFound = true;
        href = obj.linkTarget;
        liNode.appendChild(search_highlightText(obj.matchedKeyword, search_queryString));
        liNode.appendChild(document.createTextNode(" (PULS) "));
        articleBox.appendChild(liNode);
        break;
		
	case "UNDERLYING":
		search_stocksFound = true;
		href = search_siteRootLink + "product/" + obj.linkTarget;
		stockBox.appendChild(liNode);
		break;

	case "UNDERLYING_MORE":
		search_stocksFound = true;
		href = obj.linkTarget;
		stockBox.appendChild(liNode);
		break;
		
	default:
		break;
	}
	
	// construct link
	var aNode = null;
	if(href != ""){
    	aNode = document.createElement("a");
    	aNode.setAttribute("href", href);
    	var text = document.createTextNode(obj.identifier);
    	aNode.appendChild(text);
	}else{
	    aNode = document.createTextNode(obj.identifier);
	}
	
	// append link node last
	liNode.appendChild(aNode);
	
	// append protected icon
	/*if(obj.noAccess){
	    var icon = document.createElement("span");
	    icon.setAttribute("class", "protected-icon");
	    liNode.appendChild(icon);
	}*/
	
}

function search_clearSearchBox(){
	search_productsFound = false;
	search_articlesFound = false;
	search_stocksFound = false;
	search_selectedResult = -1;
	
	var productBox = document.getElementById("product-results");
	var stockBox = document.getElementById("stock-results");
	var articleBox = document.getElementById("article-results");
	
	var nodes = productBox.childNodes;
	for(var i = nodes.length-1; i >= 0; i--){
		productBox.removeChild(nodes[i]);
	}

	nodes = stockBox.childNodes;
	for(var i = nodes.length-1; i >= 0; i--){
		stockBox.removeChild(nodes[i]);
	}

	nodes = articleBox.childNodes;
	for(var i = nodes.length-1; i >= 0; i--){
		articleBox.removeChild(nodes[i]);
	}
}

function search_searchResult(objs){
	if (search_hitEnter) {
		return;
	}
	
	search_clearSearchBox();
	search_hideLoadBar();
	
	search_results = objs;
	if(objs != null && objs.length > 0){
		for(var i = 0; i < objs.length; i++){
			search_addSearchResult(objs[i], i);
		}
	}

	if(search_productsFound || search_queryString.length < 4){
		$("#product-result-box .nonefound").hide();
	}else{
		$("#product-result-box .nonefound").show();
	}
	if(search_articlesFound){
		$("#article-result-box .nonefound").hide();
	}else{
		$("#article-result-box .nonefound").show();
	}
	if(search_stocksFound){
		$("#stock-result-box .nonefound").hide();
	}else{
		$("#stock-result-box .nonefound").show();
	}
	
	$("#search-result-box").show(search_animationSpeed);
}

function search_searchError(msg){
	//alert("Error: " + msg);
}

function search_startSearch(s){
	// TODO: stop already ongoing search process
	search_showLoadBar();
	search_queryString = s;
	search_hitEnter = false;
	
	SearchService.doSearch(s, {
			callback:search_searchResult,
			timeout:5000,
			errorHandler:search_searchError
		}
	);
}

function search_searchInput(e){
	if (search_hitEnter) {
		return;
	}
	
	var text = e.target.value;
	
	if(text.length < 3){
		$(".morethan3").show();
		$(".morethan4").show();
		return;
	}else if(text.length < 4){
		$(".morethan3").hide();
		$(".morethan4").show();
	}else{
		$(".morethan3").hide();
		$(".morethan4").hide();
	}

	search_startSearch(text);
}

function search_getCurrentTime(){
	var d = new Date();
	return d.format("dd. mmmm yyyy HH:MM");
}

function search_selectionDown(){
	if(search_selectedResult + 1 == search_results.length){
		$($("#result-box-content li")[search_selectedResult]).removeClass("marked");
		search_selectedResult = -1;
	}else if(search_selectedResult < 0){
		search_selectedResult++;
		$($("#result-box-content li")[search_selectedResult]).addClass("marked");
	}else{
		$($("#result-box-content li")[search_selectedResult]).removeClass("marked");
		search_selectedResult++;
		$($("#result-box-content li")[search_selectedResult]).addClass("marked");
	}
}

function search_selectionUp(){
	if(search_selectedResult < 0){
		search_selectedResult = search_results.length - 1;
		$($("#result-box-content li")[search_selectedResult]).addClass("marked");
	}else if(search_selectedResult == 0){
		$($("#result-box-content li")[search_selectedResult]).removeClass("marked");
		search_selectedResult--;
	}else{
		$($("#result-box-content li")[search_selectedResult]).removeClass("marked");
		search_selectedResult--;
		$($("#result-box-content li")[search_selectedResult]).addClass("marked");
	}
}

function search_hitResult(){
	search_hitEnter = true;
	$("#search-loading-box").hide();
	$("#search-result-box").hide();
	
	if(search_selectedResult > -1){
		var href = $("#result-box-content li").find("a")[search_selectedResult].href;
		window.location.href = href;
	}
}

common_registerEop(function(){
	// input color is initially grey
    // switch not done by common-input because field gets initial focus already
	$("#searchbar").addClass("search-input-grey");
	$("#searchbar").click(function(e){
		if(search_searchBoxFirstHit) {
			e.target.value='';
			$("#searchbar").removeClass("search-input-grey");
			search_searchBoxFirstHit = false;
		}
	});
	//$("#searchbar").focus();
	$("#searchbar").keydown(function(e){
	    if(search_searchBoxFirstHit) {
            e.target.value='';
            search_searchBoxFirstHit = false;
            $("#searchbar").removeClass("search-input-grey");
        }
	});
	$("#searchbar").blur(function(e){
	    // close results
	    search_hideResultBox();
	});
	
	$("#searchbar").keyup(function(e){
		// limit keys that trigger a search
		if (e.which == 32 // space
				|| e.which == 8 // back-space
				|| (65 <= e.which && e.which <= 65 + 25) // a-z
				|| (e.which >= 96)) // pretty much everything else
		{
			
			// delay input processing for fast typers
			window.clearTimeout(search_searchKeyInputInterval);
			search_searchKeyInputInterval = window.setTimeout(function(){
				window.clearTimeout(search_searchKeyInputInterval);
				search_searchInput(e);
			}, search_keyCombinationSpeed);
			
		}else if(e.which == 27){ // esc
			search_hideResultBox();
		}else if(e.which == 40){ // down
			search_selectionDown();
		}else if(e.which == 38){ // up
			search_selectionUp();
		}else if(e.which == 13){ // enter
			search_hitResult();
		}
	});

	// hide result box events
	$("#result-box-content").mouseleave(search_hideResultBox);
	$("#result-box-content").mouseenter(search_stopHideResultBox);
	$("#result-box").mouseleave(search_hideResultBox);
	$("#search-box").mouseenter(search_stopHideResultBox);
	
	// show current time
	window.setInterval(function(){
		$("#timedisplayspan").text(search_getCurrentTime());
	}, 30000);
	$("#timedisplayspan").text(search_getCurrentTime());
	
});


