var auto_suggests=[];
Co_Tools.AddEventListenerEx(window, 'load', Global_Window_OnLoad);
function Co_AutoSuggest(ajax_path, o, className_Prefix, obj) {
	this.field=o;this.form=o.form;this.ajax_path=ajax_path||'/scripts/searchsuggest_ajaxLoader.asp';this.className_prefix=className_Prefix||"";
	this.obj=obj;auto_suggests[auto_suggests.length]=this;this.index=auto_suggests.length-1;this.length=0;this.visible=false;this.currentSuggestion=-1;this.selectedItem=null;this.inputLength=0;this.inputValue='';
	this.init=function() {
		if (typeof(this.field)!="object")return;
		this.field.auto_suggest_index=this.index;
		this.field.obj=this;
		this.field.setAttribute("autocomplete","off");
		this.field.onkeyup=function(e) {return this.obj.get_suggestions(e);}
		
		Co_Tools.AddEventListenerEx(window, 'resize', Suggestion_Window_OnResize, [this.index]);
		Co_Tools.AddEventListenerEx(document, 'click', Suggestion_Document_OnClick, [this.index]);
		this.field_position=Co_Tools.GetObjectPosition(this.field);
		with (this.obj.style){position="absolute";display="none";zIndex="999";}
	}
	this.get_suggestions=function(e) {
		 e = e||window.event;
		 
		//keyCode=(e.keyCode)?e.keyCode:e.which;
		//alert(keyCode);
		var keynum = e.keyCode||e.which;
		
		if (keynum == 38 || keynum == 40){
			if(this.selectedItem){this.item_out(this.selectedItem);}
			if (keynum == 40){
				this.currentSuggestion++;
			}else if(keynum == 38){
				this.currentSuggestion--;
			}
			if (this.currentSuggestion < 0) {this.currentSuggestion = this.length-1;}
			if (this.currentSuggestion >= this.length) {this.currentSuggestion = 0;}
			this.selectedItem=document.getElementById('searchSuggestion_' + this.currentSuggestion);
			//Suggestion_ItemOver(document.getElementById('searchSuggestion_' + this.currentSuggestion), this.index, 2)
			if(this.selectedItem){
				this.item_over(this.selectedItem);
				this.set_value(this.selectedItem.title);
			}
		}else if (keynum == 13 || keynum == 3){
			if (this.selectedItem){this.selectedItem.onclick();return false;}
		}else{
			this.currentSuggestion = -1;
			this.inputValue = this.field.value;
			this.inputLength = this.field.value.length;
			if(this.field.value.length>0) {
				var args={uri:this.ajax_path,obj:this,func:this.set_suggestions,searchTerm:this.field.value};
				ajax_call(args);
			}
			else {
				this.toggle_display(false);
			}
		}
	};

	this.set_suggestions=function(data) {
		this.html="";
		var dataDelimiter = "$%!DD!^&";
		var typeDelimiter = "$%!TD!^&";
		data = data.split(typeDelimiter);
		if (data[0] != null) var suggestions = data[0].split(dataDelimiter);
		if (data[1] != null) var bestBets = data[1].split(dataDelimiter);
		if (this.className_prefix == '') {this.className_prefix = 'default_';}
		var suggestionsString = '';
		var suggestionCounter = 0;
		if (suggestions != null && suggestions != ''){
			for (var x = 0;x<suggestions.length;x++){
				var rating  = suggestions[x];
				x++;
				var keywordID = suggestions[x];
				x++
				var keyword = suggestions[x]
				var jsKeyword = keyword.replace(/'/g, "\\'");
				if (rating == "" || rating == "1" || rating == "0"){
					action = 'set_value_and_submit(\''+ jsKeyword + '\')';
				}else if(rating == "3"){
					action = 'gotoKeywordID(\''+ keywordID + '\')';
				}
				suggestionsString += '<div title="' + keyword + '" onMouseOver="Suggestion_ItemOver(this,'+this.index+', 1);" onMouseOut="Suggestion_ItemOut(this,'+this.index+', 1);" id="searchSuggestion_' + suggestionCounter + '" class="' + this.className_prefix + 'searchSuggestions" onclick="auto_suggests['+this.index+'].' + action + ';">' + keyword + '</div>';
				suggestionCounter++;
			}
		}
		
		var bestBetsString = '';
		if (bestBets != null && bestBets != ''){
			for (var x = 0;x<bestBets.length;x++){
				if (bestBets[x]){
					var validbestBet = bestBets[x];
					x++;
					bestBetsString += '<div title="' + bestBets[x] + '" onMouseOver="Suggestion_ItemOver(this,'+this.index+', 2);" onMouseOut="Suggestion_ItemOut(this,'+this.index+', 2);" id="searchSuggestion_' + suggestionCounter + '" class="' + this.className_prefix + 'searchSuggestionsBestBets" onclick="auto_suggests['+this.index+'].gotoAID(\''+ validbestBet + '\');">' + bestBets[x] + '</div>';
					suggestionCounter++;
				}
			}
		}
		if (bestBetsString != ''){
			suggestionsString += '<div class="' + this.className_prefix + 'searchSuggestionsBestBetsHeader">Jump To:</div>' + bestBetsString;
		}
		this.length=suggestionCounter;
		
		if (suggestionsString != ''){
			suggestionsString = '<div class="' + this.className_prefix + 'searchSuggestionsContainer' + (Co_BrowserInfo.IsIE ? ' default_searchSuggestionsContainerSize_ie': ' default_searchSuggestionsContainerSize_ff') + '">' + suggestionsString + '</div>';
			this.html=suggestionsString;
			this.toggle_display(true);
		}
		else {
			this.toggle_display(false);
		}
	};
	this.toggle_display=function(b_display) {
		if (b_display==''||b_display==null)b_display=false;
		if(!this.obj)return;
		if (!b_display&&this.obj.style.display=="none")return;
		if (this.obj.style.display!='none' && !b_display){
			this.obj.style.display='none';
			this.visible=false;
			Co_Tools.ToggleSelect_if_IE(true);
			if (this.window_load_event=true) {Co_Tools.RemoveEventListenerEx(window, 'load', Suggestion_Window_OnLoad);this.window_load_event=false;}
		}else{
			this.obj.style.display="block";
			this.obj.innerHTML=this.html;
			this.height=this.obj.clientHeight;
			this.width=this.obj.clientWidth;
			this.Reposition();
			this.visible=true;
			Co_Tools.ToggleSelect_if_IE(false);
			if (!window.load_complete){Co_Tools.AddEventListenerEx(window, 'load', Suggestion_Window_OnLoad, [this.index]);this.window_load_event=true;}
		}
		if(!this.loaded) {
			if(typeof(fixPNGs)=='function') {fixPNGs();}
		}
		this.loaded=true;
	};
	/*this.selectText=function(obj, start, end){
		var d = document, o = obj.input;
			
        var isStandard = "selectionStart" in obj;
        var isSupported = isStandard || (o = d.selection) && !!o.createRange();
        if(isStandard){
            o.setSelectionRange(start, end);
				}
        else if(isSupported && "1" == "2"){
            var t = o.createTextRange();
            end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
            start -= o.value.slice(0, start).split("\n").length - 1;
            t.move("character", start), t.moveEnd("character", end), t.select();
        }
	}*/
	this.html_entity_decode = function(str) {
		return str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	}
	this.Reposition=function(){
		/*
		this.field_position=Co_Tools.GetObjectPosition(this.field);
		this.field_position[1]+=this.field.clientHeight;
		this.obj.style.left=(this.field_position[0])+"px";
		var screen=Co_Tools.GetWindowDimensions();
		var scroll=Co_Tools.GetWindowScroll();
		var top_pos=this.field_position[1]+1;
		
		var top=0;
		//first check if it would go below the bottom of the screen.
		if ((top=((top_pos+this.height-scroll[1])-screen[1]))>0)top_pos=top_pos-top;
		//then check if it would go above the top - this is done so that if the above code pushes it above the top we will be able to reposition.
		if ((top=(top_pos-scroll[1]))<=0)top_pos=(top_pos+parseInt(0+top.toString().substr(1)));
		
		this.obj.style.top=top_pos+"px";
		*/
		this.obj.style.left="0px";
		this.obj.style.top=(this.field.clientHeight+1)+"px";
	};
	
	
	this.set_value=function(s) {this.field.value=s;};
	this.get_value=function(){return this.field.value;};
	this.Submit=function(){this.form.submit();};
	this.set_value_and_submit=function(s){this.set_value(s);this.Submit();};
	this.gotoAID=function(AID){document.location.href = '/article.asp?aid='+AID; return false;}
	this.gotoKeywordID=function(KID){document.location.href = '/search/keyword.htm/kid/'+KID; return false;}
	this.AddEventListener = function(){};
	
	this.item_over=function(o) {
		var suggestionLength = this.field.value.length;
		if(this.selectedItem){
			this.item_out(this.selectedItem);
		}
		o.className+="_hover";o.className=o.className.replace("_hover_hover","_hover");
		this.currentSuggestion = Number(o.id.replace('searchSuggestion_',''));
		this.selectedItem=o;
		suggestionLength = o.innerHTML.length;
		//this.set_value(document.getElementById('searchSuggestion_' + this.currentSuggestion).innerHTML);
		//this.selectText(this.field, this.inputLength, suggestionLength);
	};
	this.item_out=function(o) {
		o.className=o.className.replace("_hover","");
		//this.set_value(this.inputValue);
	}
	this.init();
}
function Suggestion_ItemOver(o, idx) {auto_suggests[idx].item_over(o);}
function Suggestion_ItemOut(o, idx) {auto_suggests[idx].item_out(o);}
function Suggestion_Window_OnResize(ev, idx) {if(auto_suggests[idx].visible){auto_suggests[idx].Reposition();}}
function Suggestion_Document_OnClick(ev, idx) {
	if (!ev) ev=window.event;var oElm=ev.srcElement||ev.target;var in_modal=false;
	while (oElm=oElm.parentNode) {if (oElm.nodeName.toLowerCase()=="body")break;if (oElm.id==auto_suggests[idx].obj.id){in_modal=true;break;}}
	if (!in_modal) auto_suggests[idx].toggle_display(false);
}
function Suggestion_Window_OnLoad(ev, idx) {auto_suggests[idx].Reposition();}
function Global_Window_OnLoad(ev) {window.load_complete=true;}