var _req;
var _div;
var _keyCode;
var _highlightedSuggestionIndex = -1;
var _suggestionCount = 0;
var _highlightedDiv = null;
var _txtFld = null;
var _originalVal;
//document.onkeydown= keydownHandler;

document.onmousedown = function(){
	HideDiv("autocomplete");
	//event.cancelBubble=true;
}

String.prototype.trim=function(){
	var
		r=/^\s+|\s+$/,
		a=this.split(/\n/g),
		i=a.length;
	while(i-->0)
		a[i]=a[i].replace(r,'');
	return a.join('\n');
}


function Init()	{
	if (window.XMLHttpRequest) { // Non-IE browsers
		_req = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject){ // IE
		_req = new ActiveXObject("Microsoft.XMLHTTP");
	}
} 
		
SendQuery=function(e,key)
{
	Init(); 
	if(!e) e = window.event;
	_keyCode = e.keyCode;
	_txtFld = (e.srcElement) ? e.srcElement : e.target;  //Firefox I love you!
	//alert(_keyCode);
	createDiv(_txtFld);
	var url="/xml/callto.aspx?query=" + key;
	//url = escapeURI(url);
	//alert (url);
	if (_keyCode==38 || _keyCode==40) //// 38 is up cursor key, 40 is down cursor key...
	{
		upDownCursorHandler();
	}
	else if (_keyCode == 13)
	{
		_originalVal = key;
		HideDiv("autocomplete");
		//move cursor to last.
		setRange(_txtFld,_txtFld.value.length,_txtFld.value.length);
	}
	else if(_req!=null)
	{
		_originalVal = key;
		_highlightedSuggestionIndex = -1;
		_req.onreadystatechange = processStateChange;
		_req.open("GET", url, true);
		_req.send(null);
	}
}

function escapeURI(uri)
{
	if (encodeURIComponent)
		return encodeURIComponent(uri);
	if (escape)
		return escape(uri);
}

processStateChange = function(){
	if (_req.readyState == 4){// only if "OK"
		if (_req.status == 200)	{
if(_req.responseText=="")
	HideDiv("autocomplete");
else{
	eval(_req.responseText);
}
		}
		else{
			document.getElementById("autocomplete").innerHTML= "errors occured:<br>"+_req.statusText;
		}
	}
}

ShowDiv = function(divid){
	if (document.layers) document.layers[divid].visibility="show";
	else document.getElementById(divid).style.visibility="visible";
}
HideDiv = function(divid){
	try{
		if (document.layers) document.layers[divid].visibility="hide";
		else document.getElementById(divid).style.visibility="hidden";
	}
	catch(e){}
}

window.onload = function(){
	if (document.getElementById("autocomplete"))
		HideDiv("autocomplete");
		//document.forms[0].TextBox1.focus();
}

function createDiv(txtFld)
{
	var obj = document.getElementById("autocomplete");
	if (obj) return false;
	_div = document.createElement("DIV");
	_div.id = "autocomplete";
	_div.style.borderRight = "black 1px solid";
	_div.style.borderLeft = "black 1px solid";
	_div.style.borderTop = "black 1px solid";
	_div.style.borderBottom = "black 1px solid";
	_div.style.zIndex = "1";
	_div.style.backgroundColor = "white";
	_div.style.position="absolute";
	_div.style.visibility="hidden";
	_div.style.paddingLeft = "3";
	setDivSizePosition(txtFld);
	document.body.appendChild(_div);
	return false;
}

function setDivSizePosition(txtFld)
{
	if(_div)
	{
		_div.style.left=calculateOffsetLeft(txtFld)+"px";
		_div.style.top=calculateOffsetTop(txtFld)+txtFld.offsetHeight-1+"px";
		_div.style.width=calculateWidth(txtFld)+"px"
	}
}

function calculateWidth(txtFld)
{
	if(navigator&&navigator.userAgent.toLowerCase().indexOf("msie")==-1)
	{
		return txtFld.offsetWidth-2
	}
	else
	{
		return txtFld.offsetWidth
	}
}

calculateOffsetLeft=function(r){
	return calc(r,"offsetLeft")
}

calculateOffsetTop = function(r){
	return calc(r,"offsetTop")
}

calc = function(r,attr)
{
	var kb=0;
	while(r)
	{
		kb+=r[attr]; 
		r=r.offsetParent;
	}
	return kb;
}

callback = function(a){
	_div = document.getElementById("autocomplete");
	while (_div.childNodes.length >0){
		_div.removeChild(_div.childNodes[0]);
	}
	var count = a.length;
	if (count == 0) HideDiv("autocomplete");
	else{
		for (var i=0; i<a.length; ++i){
			var sp = document.createElement("DIV");
			sp.id = "_div" + i.toString();
			sp.onmouseover=omover;
			sp.onmouseout=omout;
			sp.style.fontSize = "11px";
			sp.style.fontFamily = "arial,sans-serif";
			sp.innerHTML = a[i];
			_div.appendChild(sp);
		}
		ShowDiv("autocomplete");
	}
}

omover = function(){
	this.style.color="red";
	this.style.backgroundColor="lightyellow";
	this.style.cursor="pointer";
}
omout = function(){
	this.style.color="black";
	this.style.backgroundColor="white";
}


callback1 = function(a,b,c){
	_div = document.getElementById("autocomplete");
	while (_div.childNodes.length >0){
		_div.removeChild(_div.childNodes[0]);
	}
	_suggestionCount = a.length;
	if (_suggestionCount == 0) HideDiv("autocomplete");
	else{
		for (var i=0; i<a.length; ++i){
			var div = document.createElement("DIV");
			div.style.width="250px";
			//var sp =  document.createElement("SPAN");
			//sp.style.display="block";
			//sp.style.paddingLeft="2";
			//sp.style.paddingRight="2";
			//sp.style.width="250";
			//div.style.border="1 green dashed"

			var sp1 = document.createElement("SPAN");
			sp1.style.fontSize = "11px";
			sp1.style.cssFloat = "left";
			sp1.style.textAlign="left"
			sp1.style.fontFamily = "arial,sans-serif";
			sp1.style.width = "150";
			//sp1.style.wordWrap="break-word";
			//sp1.style.border="1 solid red";
			sp1.style.paddingTop="2px";
			sp1.className = "Suggest";
			sp1.innerText = a[i];
			sp1.textContent = a[i];  //Firefox

			var sp2 = document.createElement("SPAN");
			sp2.style.fontSize = "10px";
			sp2.style.fontFamily = "arial,sans-serif";
			sp2.style.textAlign="right";
			sp2.style.color="green";
			sp2.style.cssFloat = "right";
			sp2.style.paddingTop="2px";
			sp2.style.width = "100";
			//sp2.style.border="1 solid blue";
			//sp2.style.wordWrap="break-word";
			sp2.className = "SuggestCount";
			sp2.innerText = " " + c[i] + ", " + b[i];
			sp2.textContent = " " + c[i] + ", " + b[i];


			div.id = "_div" + i.toString();
			div.onmouseover=omover;
			div.onmouseout=omout;
			div.onmousedown=omdown;
			div.appendChild(sp1);
			div.appendChild(sp2);
			//div.appendChild(sp);
			_div.appendChild(div);
		}
		ShowDiv("autocomplete");
		//alert(_div.innerHTML);
	}
}

newcallback1 = function(a){
	_div = document.getElementById("autocomplete");
	while (_div.childNodes.length >0){
		_div.removeChild(_div.childNodes[0]);
	}
	_suggestionCount = a.length;
	if (_suggestionCount == 0) HideDiv("autocomplete");
	else{
		for (var i=0; i<a.length; ++i){
			var div = document.createElement("DIV");
			var sp =  document.createElement("SPAN");
			sp.style.display="block";
			sp.style.paddingLeft="2";
			sp.style.paddingRight="2";
			var sp1 = document.createElement("SPAN");
			sp1.style.fontSize = "11px";
			sp1.style.cssFloat = "left";
			sp1.style.fontFamily = "arial,sans-serif";
			sp1.innerHTML = a[i];
			sp1.style.wordWrap="break-word";
			sp1.className = "Suggest";

	
			div.id = "_div" + i.toString();
			div.onmouseover=omover;
			div.onmouseout=omout;
			div.onmousedown=omdown;
			div.appendChild(sp1);
			div.appendChild(sp2);
  		        _div.appendChild(div);
		}
		ShowDiv("autocomplete");
	}
}
		
getSpanValue = function(i,className){
	var sp=i.getElementsByTagName("span");
	if(sp){
		for(var f=0; f<sp.length; ++f){
			if(sp[f].className==className){
				var value=sp[f].innerHTML;
				if(value=="&nbsp;") {
				return"";
			} else{
			var s=stripCR(value);
			return s
		}
	}
		}
	}else{
		return ""
	}
}

function stripCR(va){
	for(var i=0,s="",zb="\n\r"; i<va.length; i++) {
		if (zb.indexOf(va.charAt(i))==-1) {
		s+=va.charAt(i);
		} else {
		s+=" ";
		}
	}
	return s
}

var omdown=function(){
	v=getSpanValue(this,"Suggest");
	//document.forms[0].TextBox1.value = v.trim();
	v=decode(v);
	_txtFld.value = v.trim();
	HideDiv("autocomplete");
}

function upDownCursorHandler(){
	// 38 is up cursor key, 40 is down cursor key...
	if(_keyCode==40){
		highlit(_highlightedSuggestionIndex+1);
	}else if(_keyCode==38){
		highlit(_highlightedSuggestionIndex-1);
	}
}
function highlit(indx){
	if (indx < 0) return;
	if (_suggestionCount <= indx) return;
	_highlightedSuggestionIndex = indx;
	completeList = document.getElementById("autocomplete");
	if (completeList)
	{
		if (_highlightedDiv)  //Set previously highlighted item to un-highlighted
		{
			_highlightedDiv.style.color="black";
			_highlightedDiv.style.backgroundColor="white";
		}
		_highlightedDiv = completeList.childNodes[_highlightedSuggestionIndex];
		var v = getSpanValue(_highlightedDiv,"Suggest");
		//alert(decodeURI(v));
		//document.forms[0].TextBox1.value = v.trim();
		v=decode(v);
		//_oldVal = _txtFld.value;
		//alert (_txtFld.createTextRange().htmlText);
		_txtFld.value = v.trim();
		setRange(_txtFld,_originalVal.length,_txtFld.value.length);
		_highlightedDiv.style.color="red";
		_highlightedDiv.style.backgroundColor="lightyellow";
//		_highlightedDiv.style.cursor="pointer";
//		HideDiv("autocomplete");
	}
}

function decode(s)
{
	return s.replace("&amp;","&");
}

var setRange = function(inputField,start,end){
	if (inputField.setSelectionRange){
		inputField.focus();
		inputField.setSelectionRange(start, end);
	}
	else if(inputField.createTextRange){
		var tr= inputField.createTextRange();
		tr.collapse(true);
		tr.moveEnd('character',end);
		tr.moveStart('character',start);
		tr.select();
	}
}

