// ------------------------------------------------------------
// Globals
// ------------------------------------------------------------
var gCurrentSuggestItem = -1;
var gIgnoreLocationBlur = false;
var gLocationFocused = false;
//var gLocationSearchInputId = 'ctl00_ContentPlaceHolderMain_SearchBox_TextBoxLocation';

var gCurrentSearchBox = null;

// ------------------------------------------------------------
// Handler for focus in the location search field
// ------------------------------------------------------------
function locationFocus(evt, searchBox) {
    if (!searchBox) {
        searchBox = document.getElementById(gLocationSearchInputId);
    }

    if (searchBox) {
        searchBox.value = '';
        searchBox.className = 'LocationSearchInput';
        gLocationFocused = true;

        gCurrentSearchBox = searchBox;
    }
}

// ------------------------------------------------------------
// Handler for keydown in the location search field
// ------------------------------------------------------------
function locationOnKeyDown(evt) {
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    if (keyCode == 38) // up
    {
        highlightSuggestItem(gCurrentSuggestItem - 1);

        // This is to avoid a bug in Safari that fires duplicate events
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        return true;
    }
    else if (keyCode == 40) // down
    {
        highlightSuggestItem(gCurrentSuggestItem + 1);

        // This is to avoid a bug in Safari that fires duplicate events
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        return true;
    }
    else if ((keyCode == 13) || (keyCode == 9)) // enter or tab
    {
        fireLocationSearch();
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        return false;
    }

    return true;
}

// ------------------------------------------------------------
// Handler for keypress in the location search field
// ------------------------------------------------------------
function locationOnKeyPress(evt) {
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;
    // This is to prevent postbacks when enter is pressed
    if (keyCode == 13) {
        evt.preventDefault();
        return false;
    }
}

// ------------------------------------------------------------
// Handler for keyup in the location search field
// ------------------------------------------------------------
function locationOnKeyUp(evt, controlId) {
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;
    var locationSearch = document.getElementById(controlId);

    if (locationSearch && (keyCode != 38) && (keyCode != 40)) // up and down
    {
        if (locationSearch.value != '') {
            if (locationSearch.value.length > 1) {
                fireLocationSuggestRequest(locationSearch.value);
            }
        }
        else {
            hideLocationSuggest();
        }
    }

    return true;
}

// ------------------------------------------------------------
// Fires suggestion request to the server.
// ------------------------------------------------------------
function fireLocationSuggestRequest(search) {
    var url = gAppRoot + 'Pages/SearchLocations.aspx?search=' + encodeURIComponent(search);

    var wRequest = new Sys.Net.WebRequest();
    wRequest.set_url(url);
    wRequest.add_completed(locationSuggestCompleted);
    wRequest.invoke();
}

// ------------------------------------------------------------
// Callback method that is called when a suggestion request is complete
// ------------------------------------------------------------
function locationSuggestCompleted(executor, eventArgs) {
    if (executor.get_responseAvailable()) {
        var arr = eval('(' + executor.get_responseData() + ')');
        var searchTerm = arr[0];
        var hitList = arr[1];

        var searchBox = gCurrentSearchBox;
        if (!searchBox) searchBox = document.getElementById(gLocationSearchInputId);

        if (searchBox && (searchTerm == searchBox.value)) {
            if (hitList.length > 0) {
                updateLocationSuggest(hitList);
            }
            else {
                hideLocationSuggest();
                if (isNaN(searchTerm)) {
                    setLocationSuggestNoHitsVisibility(true);
                }
            }
        }
    }
}

// ------------------------------------------------------------
// Updates the suggest "drop-down" with new items.
// ------------------------------------------------------------
function updateLocationSuggest(locationArr) {
    var suggestDiv = document.getElementById('LocationSuggestDiv');
    if (suggestDiv) {
        // Clear the current items and create a new parent node
        while (suggestDiv.hasChildNodes()) {
            suggestDiv.removeChild(suggestDiv.lastChild);
        }
        var parentDiv = document.createElement("div");

        // Loop over all the new items and add a div for each item
        for (var i = 0; i < Math.min(locationArr.length, 25); i++) {
            var itemDivHtml =
	            '<div id="LocationSuggestItem' + i +
	            '" class="' + ((i == 0) ? 'SuggestItemSelected' : 'SuggestItem') +
	            '" onmouseover="highlightSuggestItem(' + i + ')" ' +
	            ' onclick="fireLocationSearch()">' +
	            locationArr[i] +
	            '</div>';

            // Add to parent div
            parentDiv.innerHTML += itemDivHtml;
        }

        // Add parent-node to container
        suggestDiv.appendChild(parentDiv);

        // Set first item as selected
        gCurrentSuggestItem = 0;

        // Display the div below the text-field if it's not already visible
        if (suggestDiv.style.display != 'block') {

            var searchBox = gCurrentSearchBox;
            if (!searchBox) searchBox = document.getElementById(gLocationSearchInputId);

            if (searchBox) {
                //	            suggestDiv.style.left    = findPosX(searchBox) + 'px';
                suggestDiv.style.top = (findPosY(searchBox) + searchBox.clientHeight + 3) + 'px';
                suggestDiv.style.left = findPosX(searchBox) + 'px';
                suggestDiv.style.display = 'block';
                hideWindowedControls();
            }
        }

        // Hide "No hits"-message
        setLocationSuggestNoHitsVisibility(false);
    }
}

// ------------------------------------------------------------
// Hides the suggest "drop-down"
// ------------------------------------------------------------
function hideLocationSuggest() {
    var suggestDiv = document.getElementById('LocationSuggestDiv');
    if (suggestDiv) {
        suggestDiv.style.display = 'none';
        gCurrentSuggestItem = -1;
        showWindowedControls();
    }
}

// ------------------------------------------------------------
// Hides or shows the "No hits"-message below the search field.
// ------------------------------------------------------------
function setLocationSuggestNoHitsVisibility(isVisible) {
    var suggestNoHitsDiv = null;

    if (gCurrentSearchBox) suggestNoHitsDiv = gCurrentSearchBox.noHitsDiv;

    if (!suggestNoHitsDiv) suggestNoHitsDiv = document.getElementById('LocationSuggestNoHits');

    if (suggestNoHitsDiv) {
        suggestNoHitsDiv.style.display = isVisible ? 'block' : 'none';
    }
}

// ------------------------------------------------------------
// Highlights the suggest item with the specified index
// ------------------------------------------------------------
function highlightSuggestItem(index) {
    // The currently selected item
    var oldItem = document.getElementById('LocationSuggestItem' + gCurrentSuggestItem);
    // The new item to select
    var newItem = document.getElementById('LocationSuggestItem' + index);

    if (oldItem && newItem) {
        oldItem.className = 'SuggestItem';
        newItem.className = 'SuggestItemSelected';
        gCurrentSuggestItem = index;
    }
}

// ------------------------------------------------------------
// Fires the location search request
// ------------------------------------------------------------

function fireLocationSearch() {
    var suggestItem = document.getElementById('LocationSuggestItem' + gCurrentSuggestItem);
    var searchBox = document.getElementById(gLocationSearchInputId);

    if (suggestItem) {
        var searchTerm = suggestItem.innerHTML;

        // We copy the text of the currently selected item to the text box.
        // This is just for show, the actual search is performed below.
        if (searchBox) {
            searchBox.value = searchTerm;
        }

        // Fire the search
        if ((searchTerm != '') && searchBox && (searchBox.className != 'LocationSearchInputTip')) {
            // Submit either using a form or a get request
            var url = gAppRoot + 'Templates/ObjectSearchResult.aspx?loc=' + encodeURIComponent(searchTerm) + '&karta=0';
            window.location.href = url;
            return;
        }
    }
    else {
        if (searchBox) {
            if (isNaN(searchBox.value)) {
                var searchTerm = searchBox.value;
                // Fire the search
                if (!gLocationFocused && (searchTerm != '') && (searchBox.className != 'LocationSearchInputTip')) {

                    var url = gAppRoot + 'Templates/ObjectSearchResult.aspx?loc=' + encodeURIComponent(searchTerm);
                    window.location.href = url;
                    return;
                }
            }
            else if (searchBox.value.length == 4) {
                var url = gAppRoot + 'Templates/ObjectSearchResult.aspx?zip=' + encodeURIComponent(searchBox.value);
                window.location.href = url;
                return;
            }
            else {
                var url = gAppRoot + 'Templates/ObjectSearchResult.aspx?mobid=' + encodeURIComponent(searchBox.value);
                window.location.href = url;
                return;
            }
        }
    }
}
