﻿
/*
 * Provides suggestions for locations.
 */
function LocationProvider(url) {

    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.");
    }

    this.url = url;
}

/*
 * Request suggestions for the given autosuggest control. 
 */
LocationProvider.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                                                          bTypeAhead /*:boolean*/) {

    var oHttp = this.http;
                                                             
    //if there is already a live request, cancel it
    if (oHttp.readyState != 0) {
        try
        {
            oHttp.abort();
        }
        catch(ex) {
            //alert("ex");
        }
    }                 
    
    //build the URL
    var sURL = this.url + "/GetLocation?searchText=" + encodeURIComponent(oAutoSuggestControl.textbox.value) + "&maxNumber=10";
    
    oHttp.open("get", sURL , true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            //evaluate the returned text JavaScript (an array)
            if(oHttp.responseXML)
            {
                var json = oHttp.responseXML.documentElement.firstChild.nodeValue;    
                var aSuggestions = eval(json);
        
                //provide suggestions to the control
                oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);        
            }
        }    
    };
    oHttp.send(null);
};