//////AUTO SUGGEST LOCATION //////
var resCache = new Hash();
var MIN_CHAR_INPUT = 3;
var ownLocationSearch = false;
var ESC=27; var TAB=9; var ALT=18; var UP=38; var DOWN=40; var LEFT=37; var RIGHT=39; var ENTER=13; var SHIFT=16; var DEL=46; var BACKSPACE=8;
function setCleanSearch(obj) {
	if (obj.attr("name").length > 0) {
		var termArray = obj.attr("name").split('~', 2);
		var lat = obj.attr("lat");
		var lng = obj.attr("lng");
		if (termArray != null && termArray.length > 0) {
			$("#wherebox").val(extract(cleanWord(termArray[1])));
			removeSuggestionLocation();

			$("#search").append("<input id='location' type='hidden' name='location' value='"+ extract(termArray[0]) + "' />");
			$("#search").append("<input id='lat' type='hidden' name='lat' value='" + lat+ "' />");
			$("#search").append("<input id='lng' type='hidden' name='lng' value='" + lng+ "' />");
		}
	} else {
	 $("#wherebox").val(obj.html());
	}
}

function buildSuggestionBox(words, counts, points, longs, lats, isDYM, value) {
	if (words != null && words.length > 0 && !isDYM) {
		removeSuggestionLocation();

		value = unescape(value);
		if ($("#sb_wherebox").css("display") == "none") {
			showWhere();
		}

		// TODO: Implementation is not correct, now it doesn't work correctly
		// without locations from cookies
		if ($("#whereboxcontent").attr("id") != 'whereboxcontent') {
			$("#sb_wherebox .main").append("<div id='whereboxcontent' class='content_nl'></div>");
		}

		$("#whereboxcontent .suggest").remove();
		$("#whereboxcontent").prepend("<div class='suggest'></div>");

		var topWordsLength = 0;
		if (words.length > 7) {
			topWordsLength = 7;
		} else {
			topWordsLength = words.length;
		}

		for ( var i = 0; i < topWordsLength; i++) {
			$("#whereboxcontent .suggest").append('<a href="#" id="trC' + i + '" class="suggest_link" name="'+ points[i] + '~' + words[i] + 
					'" lat="' + lats[i]+ '" lng="' + longs[i] + '">'+ strongMatch(words[i], value) + '</a>');
		}

		$("#whereboxcontent .suggest_link").click( function() {
			setCleanSearch($(this));
			this.blur();
		});
		$("#whereboxcontent .suggest_link").mouseover( function() {
			$("#whereboxcontent .suggest_link_selected").removeClass("suggest_link_selected");
		});
		$("#sb_wherebox td").height($("#whereboxcontent").height());
	} else {
		$("#whereboxcontent .suggest").remove();
	}
}

function suggestSearch() {
	var inputValue = $("#wherebox").val();

	if (inputValue.length >= MIN_CHAR_INPUT) {
		inputValue = escape(inputValue);
		var res = resCache.getItem(inputValue);
		if (typeof (res) != 'undefined') {
			eval("buildSuggestionBox(" + res + ",'" + inputValue + "')");
		} else {
			$.ajax( {
				url :"/suggestion?value=" + inputValue,
				type :"GET",
				success : function(script) {
					eval("buildSuggestionBox(" + script + ",'" + inputValue	+ "')");
				}
			});
		}
	} else {
		$("#whereboxcontent .suggest").remove();
	}
}

function loadAutoLocationSuggest() {
	var timeoutId = 0;
	var code;
	var originalWhereTerm = "";

	$("#search").submit( function() {
		return submitToSearch();
	});
	
	$("#whatbox").keyup( function(e) {
		if (e.keyCode) {
			code = e.keyCode;
		} else if (e.which) {
			code = e.which;
		}
		
		switch (code) {
			case LEFT:
			case RIGHT:
			case ENTER:
			case SHIFT:
				break;
			case ESC:
				hideWhat();
				break;
			case DOWN:
				var allAnchors=$('#sb_whatbox .items a');
				if(allAnchors.length>0){
					if($("#sb_whatbox .items a.suggest_link_selected").length>0){
						var currentIndex=allAnchors.index($("#sb_whatbox .items a.suggest_link_selected"));
						if(allAnchors.length>currentIndex+1){
							allAnchors.eq(currentIndex+1).addClass("suggest_link_selected");
							allAnchors.eq(currentIndex).removeClass("suggest_link_selected");
							$('#whatbox').val(allAnchors.eq(currentIndex+1).html());
						}
					} else{	
						allAnchors.eq(0).addClass("suggest_link_selected");
						$('#whatbox').val(allAnchors.eq(0).html());
					}

				}
				
				break;
			case UP:
				var allAnchors=$('#sb_whatbox .items a');
				if(allAnchors.length>0){
					if($("#sb_whatbox .items a.suggest_link_selected").length>0){
						var currentIndex=allAnchors.index($("#sb_whatbox .items a.suggest_link_selected"));
						if(currentIndex!=0){
							allAnchors.eq(currentIndex-1).addClass("suggest_link_selected");
							allAnchors.eq(currentIndex).removeClass("suggest_link_selected");
							$('#whatbox').val(allAnchors.eq(currentIndex-1).html());
							return false;	
						}
					} else{
						allAnchors.eq(allAnchors.length-1).addClass("suggest_link_selected");
						$('#whatbox').val(allAnchors.eq(allAnchors.length-1).html());
					}
				}
			break;
			default:
				break;
		}
		
	});

	$("#wherebox").keyup( function(e) {
		clearTimeout(timeoutId);
		if (e.keyCode) {
			code = e.keyCode;
		} else if (e.which) {
			code = e.which;
		}
		
		switch (code) {
			case LEFT:
			case RIGHT:
			case ENTER:
			case SHIFT:
				break;
			case ESC:
				hideWhere();
				$("#wherebox").val(originalWhereTerm);
				break;
			case DOWN:
				var allAnchors=$('#whereboxcontent .suggest a').add('#whereboxcontent .items a');
				if(allAnchors.length>0){
					if($("#whereboxcontent .suggest_link_selected").length>0){
						var currentIndex=allAnchors.index($("#whereboxcontent .suggest_link_selected"));
						if(allAnchors.length>currentIndex+1){
							allAnchors.eq(currentIndex+1).addClass("suggest_link_selected");
							setCleanSearch(allAnchors.eq(currentIndex+1));
							allAnchors.eq(currentIndex).removeClass("suggest_link_selected");
						}
					} else{	
						allAnchors.eq(0).addClass("suggest_link_selected");
						setCleanSearch(allAnchors.eq(0));
					}

				}
				break;
			case UP:
				var allAnchors=$('#whereboxcontent .suggest a').add('#whereboxcontent .items a');
				if(allAnchors.length>0){
					if($("#whereboxcontent .suggest_link_selected").length>0){
						var currentIndex=allAnchors.index($("#whereboxcontent .suggest_link_selected"));
						if(currentIndex!=0){
							allAnchors.eq(currentIndex-1).addClass("suggest_link_selected");
							setCleanSearch(allAnchors.eq(currentIndex-1));
							allAnchors.eq(currentIndex).removeClass("suggest_link_selected");
							return false;	
						}
					} else{
						allAnchors.eq(allAnchors.length-1).addClass("suggest_link_selected");
						setCleanSearch(allAnchors.eq(allAnchors.length-1));
					}
				}
			break;
			default:
				timeoutId = setTimeout(suggestSearch, 10);
				break;
		}
		
	});

	$("#whatbox").focus( function() {
		showWhat();
	});
	$("#wherebox").focus( function() {
		showWhere();
	});
	$("#whatbox").blur( function() {
		hideWhat();
	});
	$("#wherebox").blur( function() {
		hideWhere();
	});

	$(".search-suggest a").click(function() {
		if (!$(this).hasClass("suggest_link")) {
			if ($(this).attr("id") == 'whatdel') {
				$.cookie('il_prev_what', '', {
					expires :-1
				});
				$("#sb_whatbox").remove();
			} else if ($(this).attr("id") == 'wheredel') {
				$.cookie('il_prev_where', '', {
					expires :-1
				});
				$("#sb_wherebox .history").remove();
			} else {
				if ($(this).attr("name") == "wherebox") {
					removeSuggestionLocation();
				}
	
				if (typeof ($(this).attr("latitude")) != "undefined" && typeof ($(this).attr("longitude")) != "undefined") {
					if ($(this).attr("title") == 'BE') {
						$("#" + $(this).attr("name")).val($(this).html());
						ownLocationSearch = true;
					} else {
						$("#" + $(this).attr("name")).val($(this).attr("title"));
					}
					$("#search").append("<input id='lat' type='hidden' name='lat' value='"+ $(this).attr("latitude")+ "' />");
					$("#search").append("<input id='lng' type='hidden' name='lng' value='"+ $(this).attr("longitude")+ "' />");
					$("#search").append("<input id='distance' type='hidden' name='distance' value='3' />");
					$("#search").append("<input id='sort' type='hidden' name='sort' value='distance' />");
				} else {
					$("#" + $(this).attr("name")).val($(this).html());
				}
			}
		}
	});
}

function removeSuggestionLocation(){
	$("#location").remove();
	$("#lat").remove();
	$("#lng").remove();
	$("#distance").remove();
	$("#sort").remove();

	ownLocationSearch = false;
}
//END loadAutoLocationSuggest

function showWhere() {
	if( 'globalhome' == $(".small-box #page").val()){
		$(".small-box #sb_wherebox.search-suggest .content_nl").css("width","276px");
		$("#sb_wherebox").css("top", ($("#wherebox").offset().top + 33) + 'px');
		$("#sb_wherebox").css("left", ($("#wherebox").offset().left - 3) + 'px');
	}
	else {
		$("#sb_wherebox").css("top", ($("#wherebox").offset().top + 26) + 'px');
		$("#sb_wherebox").css("left", ($("#wherebox").offset().left - 5) + 'px');
	}

	var whereHistory = $.cookie("il_prev_where");
	if (whereHistory != null) {
		whereHistory = whereHistory.split("#");
		$("#sb_wherebox .history .items").html("");

		for ( var i = 0; i < whereHistory.length; i++) {
			var historyItem = whereHistory[i].replace(/\+/g, " ").replace(/^\s+|\s+$/g, "");
			$("#sb_wherebox .history .items").append("<a href='#' rel='nofollow'>" + historyItem + "</a>");
		}
		$("#sb_wherebox .history .items a").click( function() {
			$("#wherebox").val($(this).html());
			return false;
		});

		$("#sb_wherebox .history").css("display", "block");
	} else {
		$("#sb_wherebox .history").css("display", "none");
	}

	$("#sb_wherebox").slideDown(200);
}

function showWhat() {
	if( 'globalhome' == $(".small-box #page").val()){
		$(".small-box #sb_whatbox.search-suggest .content_nl").css("width","364px");
		$("#sb_whatbox").css("top", ($("#whatbox").offset().top + 33) + 'px');
		$("#sb_whatbox").css("left", ($("#whatbox").offset().left - 3) + 'px');
	}
	else {
		$("#sb_whatbox").css("top", ($("#whatbox").offset().top + 26) + 'px');
		$("#sb_whatbox").css("left", ($("#whatbox").offset().left - 6) + 'px');
	}
	

	var whatHistory = $.cookie("il_prev_what");
	if (whatHistory != null) {
		whatHistory = whatHistory.split("#");
		$("#sb_whatbox .history .items").html("");

		for ( var i = 0; i < whatHistory.length; i++) {
			var historyItem = whatHistory[i].replace(/\+/g, " ").replace(/^\s+|\s+$/g, "");
			$("#sb_whatbox .history .items").append("<a href='#' rel='nofollow'>" + historyItem + "</a>");
		}

		$("#sb_whatbox .history .items a").click(function() {
			$("#whatbox").val($(this).html().replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
			return false;
		});

		$("#sb_whatbox").slideDown(200);
	}
}

function hideWhere() {
	setTimeout('$("#sb_wherebox").slideUp(200)', 100);
}

function hideWhat() {
	setTimeout('$("#sb_whatbox").slideUp(200)', 100);
}

function strongMatch(str, prefix) {
	prefix = prefix.replace(/\s+/gi," ");
	tempwords = str.replace(/<\/?[^>]+(>|$)/gi,"");

	pos = tempwords.search(",");
	var original= "";
	var re="";
	re = new RegExp("(^"+prefix+")|(\\s+("+prefix+"))|(^"+prefix+",\\s+)|(\\s+("+prefix+"),\\s+) ","gi");
	tempwords = tempwords.replace(re, "<strong>$1$2</strong>");
	return tempwords;
}

function extract(str) {
	return str.replace(/<\/?[^>]+(>|$)/g, "");
}

function cleanWord(word) {
	return word.replace(/\s+\(.+\)/g, "");
}

function Hash() {
	this.length = 0;
	this.items = new Array();
	for ( var i = 0; i < arguments.length; i += 2) {
		if (typeof (arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}

	this.removeItem = function(in_key) {
		var tmp_value;
		if (typeof (this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}

		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value) {
		if (typeof (in_value) != 'undefined') {
			try {
				if (typeof (this.items[in_key]) == 'undefined') {
					this.length++;
				}
			} catch (e) {
			}

			this.items[in_key] = in_value;
		}

		return in_value;
	}

	this.hasItem = function(in_key) {
		return typeof (this.items[in_key]) != 'undefined';
	}
} // END Hash
