var searchforms = new Array();
var timeoutId = 0;
var resultCache=new Object();
var keycode=0;
var httpRequest = null;
var currentfid;
var enter = false;

function SearchForm(site,fid,suggdiv) {
	this.site = site;
	this.id = fid;
	this.suggestdiv = suggdiv;
	var thisform = document.getElementById(fid);
	this.inputfield = thisform.q;
	this.inputfield.autoComplete = "off"; // 'block' googlebar...
	this.rows = 0;
	this.rowDivList = null;
    this.highlightedSuggestionIndex = -1;
    this.highlightedSuggestionDiv= null;
	this.keywords = new Array(10); // holds the keywords array
	this.keywordsText = new Array(10); // holds the keywords text array
	this.cursorUpDownPressed = false;
	this.currentInputFieldValue=""; // also inputfield value
	this.partialquery="";
	this.currentKeyword = ""; // holds the current search keyword
	this.currentKeywordText = ""; // holds the current keyword text string
	this.keycode = 0; // holds the last keycode pressed
    if (this.inputfield.addEventListener)
		this.inputfield.addEventListener("keypress", KeyPress, true);
	//thisform.onsubmit= function() { return false;};
}

function InitForm(site,fid,sid) {
	var searchform = new SearchForm(site,fid,sid);
	searchforms[fid] = searchform;
}

function KeyDown(fid,evt) {
	if(!evt && window.event) {
		evt=window.event;
	}
	if (timeoutId) return;
	keycode = evt.keyCode;
	if (isCtrlKey(keycode)) return true;
	if(isSendKey(keycode, fid)) {
		timeoutId = setTimeout("SendQuery('" + fid + "')", 150);
	}
	return UpDown(fid,keycode);
}

function KeyPress(event) {
	if (event.which == 0 && !isShowKey(keycode)) {
		if (event.preventDefault) event.preventDefault();
		return false;
	}
}

UpDown = function(fid,keycode) {
	var inputfield = searchforms[fid].inputfield;
	var inputfieldValue = inputfield.value;
	searchforms[fid].keycode = keycode;
	if(handleCursorUpDownEnter(keycode,fid,inputfieldValue) || isShowKey(keycode))
		return true;
	else
		return false;
}

function handleCursorUpDownEnter(eventCode,fid,inputfieldValue) {
	var highlightedSuggestionIndex = searchforms[fid].highlightedSuggestionIndex;
	var suggestdiv = document.getElementById(searchforms[fid].suggestdiv);
    if (eventCode == 33) // page up
	{
		if (suggestdiv.style.visibility=="visible")
		{
			setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"normal");
			searchforms[fid].highlightedSuggestionIndex = 0;
			highlightNewValue(fid,0);
		}
		return false;
	}
	else if (eventCode == 34) // page down
	{
		if (suggestdiv.style.visibility=="visible")
		{
			setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"normal");
			searchforms[fid].highlightedSuggestionIndex = searchforms[fid].rows-1;
			highlightNewValue(fid,searchforms[fid].rows-1);
		}
		return false;
	}
	else if(eventCode==40)
	{
		if (suggestdiv.style.visibility=="visible")
		{
			highlightNewValue(fid,highlightedSuggestionIndex+1);
			return false;
		}
	}
	else if(eventCode==38)
	{
		if (suggestdiv.style.visibility=="visible")
		{
			highlightNewValue(fid,highlightedSuggestionIndex-1);
			return false;
		}
	}
	else if(eventCode==13||eventCode==3)
	{
		if (eventCode==13) {
			enter = true;
			setLocation(fid);
			return true;
		}
		return false;
	}
	if (keycode != 0)
		ForEachKeyPressed(inputfieldValue,fid);
	return true;
}

// Called when cursor up/down pressed... selects new entry in suggestdiv...
function highlightNewValue(fid,C) {
	searchforms[fid].currentInputFieldValue= searchforms[fid].partialquery;
	if(!searchforms[fid].rowDivList)
	{
		return;
	}
	ShowDiv(fid);
	if(C>=searchforms[fid].rows) {
        C=searchforms[fid].rows-1
        searchforms[fid].highlightedSuggestionDiv=searchforms[fid].rowDivList.item(C);
    }
	if(C<0)	{
        C=-1;
        searchforms[fid].highlightedSuggestionIndex=-1
        searchforms[fid].highlightedSuggestionDiv= null;
        setStyleForElement(searchforms[fid].rowDivList.item(0),"normal");
    }
	if(searchforms[fid].highlightedSuggestionIndex!=-1&&C!=searchforms[fid].highlightedSuggestionIndex) {
		setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"normal");
		searchforms[fid].highlightedSuggestionIndex=-1
	}

	if (C>=0) {
		searchforms[fid].highlightedSuggestionIndex=C;
		searchforms[fid].highlightedSuggestionDiv=searchforms[fid].rowDivList.item(C);
		setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"hilight");
		currentInputFieldValue=searchforms[fid].partialquery;
		var q = valueOfSuggestdiv(searchforms[fid].highlightedSuggestionDiv);
		searchforms[fid].currentKeyword = searchforms[fid].keywords[C];
		searchforms[fid].currentKeywordText = searchforms[fid].keywordsText[C];
	} else {
		searchforms[fid].currentKeyword ="";
		searchforms[fid].currentKeywordText ="";
	}
}

function ForEachKeyPressed(partialquery,fid) {
	var localInputField = searchforms[fid].inputfield;
	var suggestdiv = searchforms[fid].suggestdiv;
	var suggestdiv = document.getElementById(suggestdiv);
	var highlightedSuggestionIndex= searchforms[fid].highlightedSuggestionIndex;
    // This becomes the rows in our suggestion list...
	var J=suggestdiv.getElementsByTagName("LI");

	// # of rows in list...
	var rows = J.length;
	searchforms[fid].rows = rows;
	searchforms[fid].rowDivList=J;
	searchforms[fid].partialquery=partialquery;
	searchforms[fid].currentKeyword = ""; //reset
	searchforms[fid].currentKeywordText = ""; //reset
	var s= localInputField.value;
	if(s=="" || rows==0 || keycode==27 || s.search(/\S/)==-1 || (suggestdiv.style.visibility=="hidden" && ( keycode==35 || keycode==36))) //esc
		HideDiv(fid);
	for(var f=0; f<rows; f++) {
		setStyleForElement(J.item(f),"normal");
	}
	var highlightedSuggestionDiv = searchforms[fid].highlightedSuggestionDiv;
	var noncharkey = false;
	switch(searchforms[fid].keycode) {
		case 8: // back space
		case 33: //page up
		case 34: // page down
		case 35: // end
		case 36: // home
		case 37: // left arrow
		case 39: // right arrow
		case 45: //	????
		case 46: // delete
		noncharkey=true;
		break;
		default:
			// regular keypress ...
		break
	}
	if(!noncharkey && highlightedSuggestionDiv) {
		setStyleForElement(highlightedSuggestionDiv,"hilight");
		var z;
		z=valueOfSuggestdiv(highlightedSuggestionDiv);
		if(z!=localInputField.value) {
			if(localInputField.value!=partialquery) {
				return;
			}
		}
	} else {
		highlightedSuggestionIndex=-1;
    }
}

// Return null if i undefined...
// otherwise return value of span 3...
function valueOfSuggestdiv(i) {
	if(!i) {
		return null;
	}
	return findSpanValueForClass(i,"5")
}

// Find span value with className = dc...
function findSpanValueForClass(i,dc) {
	var ga=i.getElementsByTagName("span");
	if (ga) {
		for (var f=0; f<ga.length; ++f) {
			if (ga[f].className==dc) {
				var value=ga[f].innerHTML;
				if (value=="&nbsp;") {
					return"";
				} else {
					var z=stripCRFromString(value);
					return z
				}
			}
		}
	} else {
		return "";
	}
}

// strip CR from string...
function stripCRFromString(va) {
	for(var f=0,oa="",zb="\n\r"; f<va.length; f++) {
		if (zb.indexOf(va.charAt(f))==-1)
			oa+=va.charAt(f);
		else
			oa+=" ";
	}
	return oa
}

function setLocation(fid) {
	if (searchforms[fid].currentKeywordText) searchforms[fid].inputfield.value=searchforms[fid].currentKeywordText;
	document.getElementById(fid).submit();
}

function SendQuery(fid) {
	timeoutId =0;
	var suggestdiv = searchforms[fid].suggestdiv;
	var s = searchforms[fid].inputfield;
	var query = s.value;
	if (query.length>2 && query.search(/\S/)!=-1) {
		var includes = document.getElementsByName("include");
		var include = "";
		for (var i = 0; i < includes.length; i++) {
			if (includes[i].checked) {
				include = includes[i].value;
				break;
			}
		}
		var result=resultCache[query+include];
		if (result) {
			// Found in our cache...
			ShowDiv(suggestdiv);
			startswithResult(query,include,result[0],result[1],result[2],fid);
		} else {
			var id = (new Date()).getTime() % 1000000000; // bypass caching...
			var url= "cgi/search.cgi?site="+searchforms[fid].site+";suggest=1;q="+encodeURIComponent(query)+";include="+encodeURIComponent(include)+";ord="+id;
			if (httpRequest)
				httpRequest.abort();
			httpRequest = (!window.XMLHttpRequest)? (ActiveXObject ? (new ActiveXObject("Microsoft.XMLHTTP")):""):(new XMLHttpRequest());
			httpRequest.open("GET", url, true);
			httpRequest.onreadystatechange = new Function("Process('" + fid + "')");
			httpRequest.send(null);
		}
	} else {
		HideDiv(fid);
	}
}

function Process(fid) {
	if (httpRequest.readyState == 4) {
		try	{
			if (httpRequest.status == 200) {
				if(httpRequest.responseText=="") {
					HideDiv(fid);
				} else {
					eval('startswithResult(' + httpRequest.responseText + '"' + fid + '");');
				}
			}
		}
		catch(e){}
	}
}

function ShowDiv(fid) {
	if (searchforms[fid]) {
		var x = searchforms[fid].inputfield.offsetLeft;
		var y = searchforms[fid].inputfield.offsetTop+searchforms[fid].inputfield.offsetHeight;
		var suggdiv = document.getElementById(searchforms[fid].suggestdiv);
		suggdiv.style.left = x+"px";		
		suggdiv.style.top = y+"px";
		suggdiv.style.visibility="visible";
	}
}

function HideDiv(fid) {
	if (searchforms[fid]) {
		document.getElementById(searchforms[fid].suggestdiv).style.visibility="hidden";
	}
}

function onBlurHandler(fid, evt) {
	if(!evt && window.event) {
		evt=window.event;
	}
	setTimeout("HideDiv('" + fid + "')", 300);
}

startswithResult=function(partialquery,include,keywordstext,results,keywords,fid) {
	resultCache[partialquery+include]=new Array(keywordstext,results,keywords);
	searchforms[fid].keywords = keywords;
	searchforms[fid].keywordsText = keywordstext;
	if (keywordstext.length==0) {
		HideDiv(fid);
		searchforms[fid].rows=0;
		searchforms[fid].rowDivList=null;
	} else {
        ShowDiv(fid); // ShowDiv has to be before displayFoundList
        searchforms[fid].highlightedSuggestionIndex= -1;
        displayFoundList(keywordstext, results, fid);
        ForEachKeyPressed(partialquery, fid);
	}
}

function displayFoundList(keywordstext, results, fid) {
	var suggestdiv = searchforms[fid].suggestdiv;
	var suggestdiv = document.getElementById(suggestdiv);
	while (suggestdiv.childNodes.length > 0)
		suggestdiv.removeChild(suggestdiv.childNodes[0]);
	if (keywordstext.length!=0)	{
		var pp = document.createElement("DIV");
		var mm = document.createElement("UL");
		currentfid = fid;
		for (var f = 0; f < keywordstext.length; ++f) {
			var u = document.createElement("LI");
			setStyleForElement(u, "normal");
			u.onmouseover=new Function("mover('" + fid + "',"+f +")");
			u.onmouseout=new Function("mout('" +fid +"')");
			if (typeof(document.addEventListener) !="undefined")
				u.addEventListener("mousedown",mdown ,false);
			else
				u.onmousedown=mdown;
			var ua = document.createElement("SPAN");
			u.displaySpan = ua;
			var text = keywordstext[f];
			var text2 = "";
			if (results[f].length>0) {
				text2= " <span class='numresults'>"+results[f]+"</span>";
			}
			ua.innerHTML = "<span class='keywordtext'>"+text+"</span>"+text2;
			u.appendChild(ua);
			mm.appendChild(u);
		}
		pp.appendChild(mm);
		suggestdiv.appendChild(pp);
	}
}

var mdown=function(event) {
	if (isLeftButton(event)) {
		setLocation(currentfid);
	}
};

var mover=function(fid,index) {
	if(searchforms[fid].highlightedSuggestionIndex!=-1 && index!=searchforms[fid].highlightedSuggestionIndex) {
		setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"normal");
		searchforms[fid].highlightedSuggestionIndex=-1
	}
	var suggestdiv = searchforms[fid].suggestdiv;
	var suggestdiv = document.getElementById(suggestdiv);
	J=suggestdiv.getElementsByTagName("LI");
	searchforms[fid].highlightedSuggestionIndex=index;
	searchforms[fid].rowDivList=J;
	searchforms[fid].highlightedSuggestionDiv=searchforms[fid].rowDivList.item(index);
	searchforms[fid].currentKeyword= searchforms[fid].keywords[index];
	searchforms[fid].currentKeywordText= searchforms[fid].keywordsText[index];
	setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"hilight");
};

var mout=function(fid) {
    searchforms[fid].currentKeyword= "";
	searchforms[fid].currentKeywordText= "";
    setStyleForElement(searchforms[fid].highlightedSuggestionDiv,"normal");
};

function setStyleForElement(c,name) {
    if (c!= null && typeof(c) !="undefined") {
		c.className=name;
	}
}

function isSendKey(keycode, fid) {
	var sendkey = true;
	switch(keycode) {
		//case 8: // back space
		case 10: //shift
		case 11: //ctrl
		case 12: //alt
		case 13: //enter
		case 27: //esc
		case 33: //page up
		case 34: // page down
		case 35: // end
		case 36: // home
		case 38: // up arrow
		case 40: // down arrow
		case 37: // left arrow
		case 39: // right arrow
			var suggdiv = document.getElementById(searchforms[fid].suggestdiv);
			if (suggdiv.style.visibility=="hidden") return sendkey;
			// else fall through...
		case 45: //	????
		//case 46: // delete
			sendkey=false;
			break;
		default:
			// regular keypress ...
			break;
	}
	return sendkey;
}

function isShowKey(keycode) {
// 38 is up cursor key, 40 is down cursor key...
	if(keycode==40 || keycode==38 || keycode == 33 || keycode== 34 || keycode==13)
		return false;
	else
		return true;
}

function isCtrlKey(keycode) {
	if(keycode==16 || keycode==17 || keycode == 18)// shift,ctrl,alt
		return true;
	else
		return false;
}

function isLeftButton(e) {
	var leftclick;
	if (!e) var e = window.event;
	if (e.which) leftclick = (e.which == 1);
	else if (e.button) leftclick = (e.button == 0 || e.button==1);
	return leftclick;
}