var WacObject = new WacSuggestionObject();

function WacSuggestionObject()
{
	this.ShowSuggestions = function(txtBox,suggestionList)
	{
		if (suggestionList == '')
		{
			this.HideSuggestions(txtBox);
			return;
		}

		var suggestions = suggestionList.split('`');
		var theDiv;
		var theSelect;
		
		// if the div already exists (assigning in the if, not a == mistake)
		if (theDiv = document.getElementById("wacDiv"))
		{
			// theSelect exists too, so get it
			theSelect = document.getElementById("wacListBox")
	
			// and clear the options
			theSelect.options.length = 0;
		}
		else
		{
			// create a div
			theDiv = document.createElement("div");
			theDiv.setAttribute("id","wacDiv");
			theDiv.style.position='absolute';
			theDiv.style.top=(WacObject.getAbsolutePosition(txtBox).y+22)+"px";
			theDiv.style.left=(WacObject.getAbsolutePosition(txtBox).x)+"px";
			theDiv.style.display='block';
			theDiv.style.zIndex='100';
			
			// create listbox
			theSelect = document.createElement("select");
			theSelect.setAttribute("id","wacListBox");
			theSelect.setAttribute("multiple","multiple");
		
			// wire up events
			theSelect.onchange = function(){document.getElementById(txtBox.id).value=this.options[this.selectedIndex].text;};
			theSelect.onkeyup = function(e){e=e||event;if((e.which&&(e.which==13||e.which==27))||(e.keyCode&&(e.keyCode==13||e.keyCode==27))){WacObject.HideSuggestions(txtBox);}};
			// had to add setTimeout for IE. At the onclick it doesn't know the selected index
			theSelect.onclick = function(){setTimeout(function(){var lbx=document.getElementById('wacListBox');document.getElementById(txtBox.id).value=lbx.options[lbx.selectedIndex].text;WacObject.HideSuggestions(txtBox);},1);};
	
			// add listBox to div
			theDiv.appendChild(theSelect);
		
			// add div to body
			document.body.appendChild(theDiv);	
		}
		
        	// set the size of the lisBox
		theSelect.setAttribute("size",suggestions.length<10?suggestions.length:10);

		// create items
		for(var i = 0; i < suggestions.length; i++)
		{
			// create an item
			var itm = new Option(suggestions[i],suggestions[i]);
	
			// append itm to theSelect
			theSelect.options[i]= itm;
		}
	}
	
	this.HideSuggestions = function(txtBox)
	{
		var theDiv;
	
		// if the div exists (assigning in the if, not a == mistake)
		if (theDiv = document.getElementById("wacDiv"))
		{
			document.body.removeChild(theDiv);
		}
		
		if(txtBox)
		{
			txtBox.focus();
		}
	}
	
	this.FocusSuggestions = function()
	{
		try
		{
			var lbx = document.getElementById("wacListBox");
			
			// kicks this off after the keypress is done
			setTimeout(function(){try{lbx.focus();lbx.selectedIndex=0;lbx.onchange();}catch(e){}},1);
		}
		catch(e){}
	}

    this.GetUrl = function(txtBox)
    {
		if (txtBox.value=='')
		{
			return '';
		}
    
        // look up result
        var request = WacObject.getHTTPObject();
        var url='';
        
        if (request)
        {
            // false makes the call synchronous, which is needed here
            request.open("POST","/lookup/waclookup.aspx",false);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            request.send("w="+txtBox.value+"&go=1");

            url = 'http://apps.leg.wa.gov/WAC/default.aspx?cite=' + request.responseText;
        }
        
        return url;
    }

	this.getAbsolutePosition = function(element)
	{
        var r = { x: element.offsetLeft, y: element.offsetTop };
	    if (element.offsetParent)
	    {
	        var tmp = this.getAbsolutePosition(element.offsetParent);
            r.x += tmp.x;
            r.y += tmp.y;
	    }
	    return r;
	}
	
	this.getHTTPObject = function()
	{
		var xhr = false;
		if (window.XMLHttpRequest)
		{
			xhr = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			try
			{
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e)
			{
				try
				{
					xhr = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e)
				{
					xhr = false;
				}
			}
		}
		return xhr;
	}
}

// WAC **************************
function WacList()
{
    this.SearchTerm = '';
    this.CtrlId = '';
    this.Timer = null;
}

function GetWacList(txtBox,count)
{
    // in case there's one already running
    clearTimeout(WacList.Timer);

    WacList.SearchTerm = txtBox.value;
    WacList.TextBox = txtBox;
    WacList.Timer = setTimeout('LoadWacList('+count+');',100);
}

function LoadWacList(count)
{
    try
    {
        var request = WacObject.getHTTPObject();
        
        if (request)
        {
            request.onreadystatechange = 
                function()
                {
                    if (request.readyState == 4)
                    {
						if (WacList.TextBox.value!='')
						{
							var len=WacList.TextBox.value.length;
						
							// if the response was empty, call showSuggestions to clear out the list
							// OR if the first suggestion starts with what's in the textbox,
							// go ahead and show suggestions. Checking for this handles responses that
							// don't come back in the same order the calls were sent out.
							if (request.responseText=='' || WacList.TextBox.value.toUpperCase() == request.responseText.substring(0,len).toUpperCase())
							{
								WacObject.ShowSuggestions(WacList.TextBox,request.responseText);
							}
	                    }
                    }
                }
            request.open("POST","/lookup/waclookup.aspx",true);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            var params = "w="+WacList.SearchTerm;
            if (count)
            {
				params += "&count="+count;            
            }
            request.send(params);
        }
    }
    catch(e){}
}
