var WsrObject = new WsrSuggestionObject();

function WsrSuggestionObject()
{
	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("wsrDiv"))
		{
			// theSelect exists too, so get it
			theSelect = document.getElementById("wsrListBox")
	
			// and clear the options
			theSelect.options.length = 0;
		}
		else
		{
			// create a div
			theDiv = document.createElement("div");
			theDiv.setAttribute("id","wsrDiv");
			theDiv.style.position='absolute';
			theDiv.style.top=(WsrObject.getAbsolutePosition(txtBox).y+22)+"px";
			theDiv.style.left=(WsrObject.getAbsolutePosition(txtBox).x)+"px";
			theDiv.style.display='block';
			theDiv.style.zIndex='100';
			
			// create listbox
			theSelect = document.createElement("select");
			theSelect.setAttribute("id","wsrListBox");
			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))){WsrObject.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('wsrListBox');document.getElementById(txtBox.id).value=lbx.options[lbx.selectedIndex].text;WsrObject.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++)
		{
			// separate name-value pair
			var parts = suggestions[i].split('|');
	
			// create an item
			var itm = new Option(parts[1].replace('.htm',''),parts[0]);
	
			// 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("wsrDiv"))
		{
			document.body.removeChild(theDiv);
		}
		
		if (txtBox)
		{
			txtBox.focus();
		}
	}
	
	this.FocusSuggestions = function()
	{
		try
		{
			var lbx = document.getElementById("wsrListBox");
			
			// 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 = WsrObject.getHTTPObject();
		var url = '';
       
        if (request)
        {
            // false makes the call synchronous, which is needed here
            request.open("POST","/pages/AjaxHandler.ashx",false);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            request.send("action=wsrlookup&w="+txtBox.value+"&go=1");
            
            url = 'http://apps.leg.wa.gov/documents/laws/wsr/' + request.responseText.replace('|','').replace('\\','/');
        }
        
        return url;
    }

	/*** DEPRECATED ***/
    this.GoToUrl = function(txtBox)
    {
        // look up result
        var request = WsrObject.getHTTPObject();
       
        if (request)
        {
            request.onreadystatechange =
                function()
                {
                    if (request.readyState == 4)
                    {  
                        var result = request.responseText;
                        
                        if (result == '')
                        {
                            alert('No document found.');
                        }
                        else if (result.indexOf('`')==-1)
                        {
                            // we found only one, so build the url
                            var url = 'http://apps.leg.wa.gov/documents/laws/wsr/' + result.replace('|','').replace('\\','/');
							
							var ok = window.open(url);
							
							if(!ok)
							{
								alert('Could not open the document. You may need to disable your pop-up blocker for this site.');
							}
                        }
                    }
                }
            request.open("POST","/pages/AjaxHandler.ashx",true);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            request.send("action=wsrlookup&w="+txtBox.value+"&go=1");
        }
    }

	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;
	}
}

function WsrList()
{
    this.SearchTerm = '';
    this.CtrlId = '';
    this.Timer = null;
}

function GetWsrList(txtBox,count)
{
    // in case there's one already running
    clearTimeout(WsrList.Timer);

    WsrList.SearchTerm = txtBox.value;
    WsrList.TextBox = txtBox;
    WsrList.Timer = setTimeout('LoadWsrList('+count+');',100);
}

function LoadWsrList(count)
{
    try
    {
        var request = WsrObject.getHTTPObject();
        
        if (request)
        {
            request.onreadystatechange = 
                function()
                {
                    if (request.readyState == 4)
                    {
						if (WsrList.TextBox.value!='')
						{
							var len=WsrList.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=='' || WsrList.TextBox.value.toUpperCase() == request.responseText.split('|')[1].substring(0,len).toUpperCase())
							{
								WsrObject.ShowSuggestions(WsrList.TextBox,request.responseText);
							}
	                    }
                    }
                }
            request.open("POST","/pages/AjaxHandler.ashx",true);
            request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            var params = "action=wsrlookup&w="+WsrList.SearchTerm;
            if (count)
            {
				params += "&count="+count;            
            }
            request.send(params);
        }
    }
    catch(e){}
}
