// global variables
var SearchURL = "/HessSearchPage.aspx?q="
var SuggestionURL = "/SearchService.asmx/GetSuggestionsArray";
var msgNoSuggestion = "No Suggestion Found";
var msgSearch = "Search Typed Text >>";
var searchHighlited = 0;
var acListTotal = 0;
var acListCurrent = -1;
var acDelay = 200;
var blurDelay = 100;
var settingTimeout;
var acURL = null;
var acSearchId = null;
var acResultsId = null;
var acSearchField = null;
var acResultsDiv = null;

function setAutoComplete(field_id, results_id, get_url) {

    // initialize vars
    acSearchId = "#" + field_id;
    acResultsId = "#" + results_id;
    acURL = get_url;

    // create the results div
    //$("body").append('<div id="' + results_id + '" class="searchResults"></div>');

    // register mostly used vars
    acSearchField = $(acSearchId);
    acResultsDiv = $(acResultsId);

    // on key up listener
    acSearchField.keyup(function(e) {

        // get keyCode (window.event is for IE)
        var keyCode = e.keyCode || window.event.keyCode;
        // check an treat up and down arrows
        var lastVal = acSearchField.val();
        var previousText = acSearchField.val(); //acSearchField.val().substring(0, spaceIndex + 1);
        if (updownArrow(keyCode, previousText)) {
            return;
        }

        // check for an ESC
        if (keyCode == 27) { //|| keyCode == 32) { //  space 32
            clearAutoComplete();
            return;
        }

        if (keyCode == 13) { // ENTER key

            txt = $('#searchField').val();

            if (txt != '') {
                clearAutoComplete();
                // disable searchField while forwarding to results pg...
                document.body.style.cursor = 'wait';
                $('#searchField').attr("disabled", true);
                document.location.href = SearchURL + escape(txt);
            }

            return;
        }
        // if is text, call with delay
        clearTimeout(settingTimeout);
        settingTimeout = setTimeout(function() { autoComplete(lastVal, previousText) }, acDelay);
    });
}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue, previousText) {
    // get the current field value
    var fieldValue = acSearchField.val();
    // if it's empty, or if the last value is 'Space', clear the resuts box and return
    if ((fieldValue == '')) { //|| (lastValue == '')) {
        clearAutoComplete();
        return;
    }

    $.ajax({ type: "POST",
        url: SuggestionURL,
        dataType: "xml",
        data: 'Letters=' + lastValue, //$('#searchField').val(),
        processData: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
        success: function(xml) { ajaxFinish(xml, previousText); }
    });
}

function ajaxFinish(xml, previousText) {

    var listSuggest = "";
    if ($("status", xml).text() != "2") { // validate

        if (1 == 2) { //($("s", xml).text() == '') { // no suggestion 
            listSuggest += '<div align=left>' + msgNoSuggestion + '</div>';
        }
        else {
            $("s", xml).each(function() {
                listSuggest += '<div class="suggestion unselected" align=right>' + $(this).attr("w") + '</div>';
            });
        }
        //Add 'search link' at the end
        listSuggest += '<div align=right class="suggestion unselected"><A href=' + SearchURL + escape(acSearchField.val()) + '>' + msgSearch + '</A></div>';

        // update the results div
        acResultsDiv.html(listSuggest);
        acResultsDiv.css("display", "block");
        // for all divs in results
        // on mouse over clean previous selected and set a new one
        var divs = $(acResultsId + " > div");
        divs.mouseover(function() {
            divs.each(function() { this.className = "unselected"; });
            this.className = "selected";
        });

        // on click copy the result text to the search field and hide
        divs.click(function() {
            if (this.childNodes[0].nodeValue == msgNoSuggestion) {
                //no concatenation 
            }
            else if (this.childNodes[0].nodeValue != null) {
                acSearchField.val(this.childNodes[0].nodeValue); //(previousText + this.childNodes[0].nodeValue);
            }
            acSearchField.focus();
            acSearchField.val(acSearchField.val());
            clearAutoComplete();
        });

    }
    else {
        clearAutoComplete();
        return;
    }

}

function ajaxError(xmlObj, textStatus, errorThrown) {  // typically only one of textStatus or errorThrown will have info

    // if error, clear the result and call ajaxFinish() to render 'No Suggestion'
    // This is like Custom Error Message.
    $('#result').empty();
    ajaxFinish(xmlObj);

}

// clear auto complete box
function clearAutoComplete() {
    acResultsDiv.html('');
    acResultsDiv.css("display", "none");
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode, previousText) {
    if (keyCode == 40 || keyCode == 38) {

        if (keyCode == 38) { // keyUp
            if (acListCurrent == 0 || acListCurrent == -1) {
                acListCurrent = acListTotal - 1;
            } else {
                acListCurrent--;
            }
        }
        else { // keyDown
            if (acListCurrent == acListTotal - 1) {
                acListCurrent = 0;
            } else {
                acListCurrent++;
            }
        }
        // loop through each result div applying the correct style
        acResultsDiv.children().each(function(i) {
            if (i == acListCurrent) { //current node
                if (this.childNodes[0].nodeValue == msgNoSuggestion) {
                    //no concatenation 
                }
                else if (this.childNodes[0].nodeValue == null) {
                    //no concatenation
                    //set the highlight of search link (last node)
                    searchHighlited = 1;
                }
                else if (this.childNodes[0].nodeValue != null) {
                    acSearchField.val(this.childNodes[0].nodeValue); //(previousText + this.childNodes[0].nodeValue);
                    acResultsDiv.children()[acResultsDiv.children().length - 1].childNodes[0].href = SearchURL + escape(acSearchField.val());
                }
                this.className = "selected";
            }
            else // non-current node 
            {
                this.className = "unselected";
                searchHighlited = 0;
            }
        });       // end loop    
        return true;
    }
    else {
        // reset
        acListCurrent = -1;
        return false;
    }
}

function SubmitSearch() {
    window.location = SearchURL + acSearchField.val();
}
function UpdateLink() {
    this.innerHTML = SearchURL + acSearchField.val();
}
