// Global variables
var SearchUrl = "getitemlist.avfp"; // The server-side script
var lastZip = ""; // The last search term that we displayed
var IncrementalSearchTimer;
var ZipSearchHttp;
var ZipSearchResults = null;
var lastSender = "";

// Event handler that gets called whenever the search term is changed
function SearchTermChanged(sndr) { 
    if (lastSender != sndr.getAttribute('id')) {
        lastZip = '';
        lastSender = sndr.getAttribute('id');
    }
    if (!ZipSearchHttp) {
        // Browser does not support XMLHttpRequest object
        return;
    }

    window.clearTimeout(IncrementalSearchTimer);
    // Use a timer to reduce the number of AJAX requests for fast typists
    IncrementalSearchTimer = window.setTimeout("DoSearch()", 300);
}

// Makes an AJAX request to the ActiveVFP server that performs the search
function DoSearch() {
    var Zip = document.getElementById(lastSender).value;
    // Make sure the the search string is different from the last search and that it's a valid Zip code
    //var RegExpZip = /^\d+$/;

    if (lastZip != Zip) {
        if ((ZipSearchHttp.readyState == 2 || ZipSearchHttp.readyState == 3) && lastZip != '' && (Zip.indexOf(lastZip) >= 0)) {
            // A search with a more generic search term than the current term is currently in progress via AJAX
            // We should be able to filter the result set of the search in progress
            // Keep trying until the server responds
            IncrementalSearchTimer = window.setTimeout("DoSearch()", 100);
            //ResultHtml = getZipList(ZipSearchResults.searchresults, Zip);
            //document.getElementById('warningdiv').innerHTML = ResultHtml;
            //lastZip = Zip;
        } else if (ZipSearchHttp.readyState != 2 && ZipSearchHttp.readyState != 3 && ZipSearchResults != null && (Zip.indexOf(ZipSearchResults.Zip) >= 0) && ZipSearchResults.hasresults) {
            // The current search term is a more specific term of the last search
            // Filter the previously received result set
            ResultHtml = getZipList(ZipSearchResults.searchresults, Zip)
                //document.getElementById('warningdiv').innerHTML = ResultHtml;
            lastZip = Zip;
        } else {
            // The result set for the current search term is not a sub-set of what we already have
            // Send a new AJAX request to the server
            if (ZipSearchHttp.readyState == 2 || ZipSearchHttp.readyState == 3) {
                // Abort previous AJAX request currently in progress
                ZipSearchHttp.abort();
            }
            if (Zip.length > 1) {
                // Include the search string in the query string portion of the URL
                var frmdata = new FormData();

                frmdata.append('findWhat', Zip);
                frmdata.append('sender', lastSender);
                ZipSearchHttp.open("POST", SearchUrl, true);
                ZipSearchHttp.onreadystatechange = handleHttpResponse();
                ZipSearchHttp.send(frmdata);
            }
            lastZip = Zip;
        }
    }
}

// Handles the AJAX results returned by the ActiveVFP server
function handleHttpResponse() {
    if (ZipSearchHttp.readyState == 4) {
        var ResultHtml = '';
        ZipSearchResults = null;
        if (ZipSearchHttp.status == 200 && ZipSearchHttp.responseText != '') {
            // Use eval to parse the JSON string.  Note that this is not the safest technique
            // A much better approach is to use one of the many JSON libraries available
            // For details, refer to http://www.json.org/js.html
            try {
                ZipSearchResults = JSON.parse(ZipSearchHttp.responseText);
            } catch (e) {
                alert(ZipSearchHttp.responseText);
            }
            console.log('searchresults', ZipSearchHttp.responseText);
            if (ZipSearchResults != null) {
                var jsonData = JSON.parse(ZipSearchHttp.responseText);
                if (ZipSearchResults.searchresults != undefined) {
                    // for (var i = 0; i < ZipSearchResults.searchresults.rows.length; i++) {
                    //  var counter = ZipSearchResults.searchresults.rows[i];
                    // console.log('thecode', counter.thecode);
                    // console.log('thename', counter.thename);
                    // }
                    ResultHtml = getZipList(ZipSearchResults.searchresults, '');
                    console.log('options list', ResultHtml);
                }
            }
        }
        document.getElementById('warningdiv').innerHTML = ResultHtml;
    }
}

// Creates html table with Zip codes returned from the server
function getZipList(searchresults, filter) {
    var ResultHtml = '';
    if (!ZipSearchResults.hasresults) {
        if (ZipSearchResults.resultscount > 0) {
            ResultHtml = ZipSearchResults.resultscount.toString() + " results.  Please narrow your search.";
            return ResultHtml
        } else {
            ResultHtml = 'No Zip codes match the search string';
            return ResultHtml;
        }

    }
    var founds = 0;
    if (ZipSearchResults.searchresults != undefined) {
        // The server returned a result set
        var listname = lastSender + '_list';
        var dtvar = document.getElementById(listname);
        dtvar.innerHTML = '';
        var options = '';
        for (i = 0; i < searchresults.rows.length; i++) {
            if ((searchresults.rows[i].thename + searchresults.rows[i].thecode).indexOf(filter) >= 0) {
                options += '<option value="' + searchresults.rows[i].thecode + ' : ' + searchresults.rows[i].thename + '" />';
                founds = founds + 1
            }
        }
        dtvar.innerHTML = options;
    }
    if (options == '') {
        ResultHtml = "No mathes found with the search string";
    } else { ResultHtml = "A total of " + founds + " matches found"; }
    return ResultHtml;
}