
var reqUrl;

/**
 * Provides suggestions for state names (USA).
 * @class
 * @scope public
 */
function RemoteStateSuggestions(reqPath) 
{
	reqUrl = reqPath;

    if (typeof XMLHttpRequest != "undefined") 
    {
        this.http = new XMLHttpRequest();
    } 
    else if (typeof ActiveXObject != "undefined") 
    {
        this.http = new ActiveXObject("MSXML2.XmlHttp");
    } 
    else 
    {
        alert("No XMLHttpRequest object available. This functionality will not work.");
    }
}

/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
RemoteStateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                          bTypeAhead /*:boolean*/) {
    var oHttp = this.http;
                                                             
    //if there is already a live request, cancel it
    if (oHttp.readyState != 0) 
    {
        oHttp.abort();
    }                 
    
    //build the URL
	var sURL = reqUrl + "?userInput=" + encodeURIComponent(oAutoSuggestControl.textbox.value);    
   	var time = new Date(); 
	sURL += '&dt=' + time;

    //open connection
    oHttp.open("get", sURL , true);
    oHttp.onreadystatechange = function () 
    {
        if (oHttp.readyState == 4) 
        {
            //evaluate the returned text JavaScript (an array)
            var aRtnText = eval(oHttp.responseText);

		    var aSuggestions = [];
		    var sTextboxValue = oAutoSuggestControl.textbox.value;
		    
		    if (sTextboxValue != null && aRtnText != null)
		    {
			    if (sTextboxValue.length > 0)
			    {
			        //convert value in textbox to lowercase
			        var sTextboxValueLC = sTextboxValue.toLowerCase();
			
			        //search for matching states
			        for (var i=0; i < aRtnText.length; i++) 
			        { 
			            //convert state name to lowercase
			            var sStateLC = aRtnText[i].toLowerCase();
			           
			            //compare the lowercase versions for case-insensitive comparison
			            if (sStateLC.indexOf(sTextboxValueLC) == 0) 
			            {
			                //add a suggestion using what's already in the textbox to begin it                
			                aSuggestions.push(sTextboxValue + aRtnText[i].substring(sTextboxValue.length));
			            } 
			        }
			    }
	
	            //provide suggestions to the control
	            oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);        
	        }    
        }    
    };
    oHttp.send(null);
    

};
