salmon.namespace.addNamespace("boots.header.typeAhead");
boots.header.typeAhead = {
	template:"<div id=\"searchTypeAhead\"></div>",
	searchText:"",
	TypeAheadMinChars:4, // These values are defaults, they can be overriden in 
	TypeAheadResults:10, // PC_IA_0201_011-Search.jsp as part of the search form.
	TypeAheadIsEnabled:true,
	delayMs:700,
	lastTimerStartMs:(new Date().getTime()),
	lastTimerId:"",
	
	sendTypeAheadAjaxRequest:function(ajaxURL) {
		var TA = boots.header.typeAhead;
		TA.lastTimerId = "";
		$.get(ajaxURL, "", function(data) {TA.typeAheadSearchResult(data);}, "html");
	},
	init:function(){
		$("body").append(this.template);
		this.getTypeAheadValues();
		if (this.TypeAheadIsEnabled) {
			this.setEvents();
		}
	},
	typeAheadSearch:function(e) {
		var TA = boots.header.typeAhead;
		if(e.keyCode == "40" && $("#searchTypeAhead").text().length>0){
			TA.focusOnTheList();
		} else if ((e.keyCode<32 && e.keyCode!=8) || (e.keyCode>=33 && e.keyCode<46) || (e.keyCode>=112 && e.keyCode<=123)) {
			//these are special keys, do not trigger another request
		} else {
			//check if need to cancel current timer
			if (TA.lastTimerId!="") {
				var currentTimeMs = new Date().getTime();
				if ((currentTimeMs - TA.lastTimerStartMs) < TA.delayMs) {
					clearTimeout(TA.lastTimerId);
				}
			}

			TA.searchText = document.getElementById("search").value;
			TA.searchText = TA.searchText.replace(/^\s*/, "").replace(/\s*$/, "");
			if (TA.searchText.length >= TA.TypeAheadMinChars && TA.searchText!="#sid#") {
				var newDepSearch = document.getElementById("searchDepartments").value;
				var url = "/webapp/wcs/stores/servlet/EndecaTypeAheadSearch?storeId="+WCParam.storeId+"&catalogId="+WCParam.catalogId+"&langId="+WCParam.langId;
				url = url + "&recordsCount=" + TA.TypeAheadResults;
				//url = url + "&ajaxRequestId=" + (new Date().getTime());
				url = url + "&searchText=" + TA.searchText;
				url = url + "&newDepSearch=" + newDepSearch;
				//$.get(url, "", function(data) {TA.typeAheadSearchResult(data);}, "html");

				//create new timer
				TA.lastTimerStartMs = new Date().getTime();
				TA.lastTimerId = setTimeout(function(){boots.header.typeAhead.sendTypeAheadAjaxRequest(url)}, TA.delayMs);
			} else {
				TA.clearTypeAhead();
			}
		}
	},
	focusOnTheList:function() {
		$("#searchTypeAhead").find("a:first").addClass("current").focus();
		$("#searchTypeAhead").unbind("keydown").bind("keydown",function(event) {
			var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
			if(key == "40"){
				//down
				if($(this).find("a.current").parent().next().length > 0){
					$(this).find("a.current").removeClass("current").parent().next().find("a").addClass("current").focus();
				} else {
					$(this).find("a.current").removeClass("current").parents("ul").find("a:first").addClass("current").focus();
				}
				event.preventDefault();
				return false;
			} else if (key == "38"){
				//up
				if($(this).find("a.current").parent().prev().length > 0){
					$(this).find("a.current").removeClass("current").parent().prev().find("a").addClass("current").focus();
				} else {
					$(this).find("a.current").removeClass("current").parents("ul").find("a:last").addClass("current").focus();
				}
				event.preventDefault();
				return false;
			} else if (key == "13"){
				//enter
				//don't need to do anything, enter works from the focus
			}
		});
	},
	typeAheadSearchResult:function(data) {
		var newData = data;
		if (data.indexOf("taAjaxRequestId")!=-1) {
			$("#searchTypeAhead").empty().append(newData);
			this.showTypeAhead();
		} else {
			this.clearTypeAhead();
		}
	},
	highlightTerms:function(){
		searchTerms = this.searchText.split(" ");
		max = searchTerms.length;
		for(var i=0; i<max; i++){
			var pattern = new RegExp( searchTerms[i] , "i");
			$("#searchTypeAhead").find("a").each(function(){
				var linkText = $(this).html();
				/* Maybe not need these 4, but I definitely did on local dev */
				linkText = linkText.replace(/&lt;p&gt;/i,"");
				linkText = linkText.replace(/&lt;\/p&gt;/i,"");
				linkText = linkText.replace(/&amp;amp;/i,"&amp;");
				linkText = linkText.replace(/&amp;nbsp;/i," ");
				linkText = linkText.replace(/&amp;trade;/i,"&#153;");
				linkText = linkText.replace(/&lt;br \/&gt;/i,"");
				linkText = linkText.replace(/strong>/g,"XXXXXX>");
				linkText = linkText.replace(/STRONG>/g,"XXXXXX>");
				var match = linkText.match(pattern);
				if(match !== null){
					linkText = linkText.replace(pattern,"<strong>"+match[0]+"</strong>");
				}
				linkText = linkText.replace(/XXXXXX>/g,"strong>");
				$(this).html(linkText)
			});
		}
	},
	clearTypeAhead:function(){
		$("#searchTypeAhead").empty();
		boots.header.typeAhead.hideTypeAhead();
	},
	showTypeAhead:function(){
		var pos = $("#CatalogSearchForm input#search").position();
		$("#searchTypeAhead").show().css({
			"zIndex":10000,
			"left":pos.left,
			"top":pos.top + 21
		});
		this.highlightTerms();
		this.watchMouseClick();
	},
	hideTypeAhead:function(){
		$("#searchTypeAhead").hide();
		$("body").unbind("mousedown");
	},
	watchMouseClick:function(){
		$("body").unbind("mousedown").bind("mousedown",function(e){
			var link = "" + e.target;
			if(link.indexOf("http") >= 0) {
				location.replace(link);
			} else {
				boots.header.typeAhead.hideTypeAhead();
			}
		});
	},
	getTypeAheadValues:function(){
		this.TypeAheadMinChars = parseInt($("#ia_sitesearch").find("#TypeAheadMinChars").attr("value")) || this.TypeAheadMinChars;
		this.TypeAheadResults = parseInt($("#ia_sitesearch").find("#TypeAheadResults").attr("value")) || this.TypeAheadResults;
		this.TypeAheadIsEnabled = ($("#ia_sitesearch").find("#TypeAheadIsEnabled").attr("value") == "N") ? false : true;
	},
	setEvents:function(){
		$("#CatalogSearchForm input#search").bind("keyup focus",function(event) {
			boots.header.typeAhead.typeAheadSearch(event);
		});
		//$("#CatalogSearchForm input#search").bind("blur",this.clearTypeAhead);
	}
}
$(document).ready(function(){
	boots.header.typeAhead.init();
});

