// ------------------------------------------------------------
// Globals
// ------------------------------------------------------------
var gCurrentSuggestItem   = -1;
var gIgnoreLocationBlur   = false;
var gLocationFocused = false;
//var gLocationSearchInputId = 'ctl00_ContentPlaceHolderMain_SearchBox_TextBoxLocation';

// ------------------------------------------------------------
// Handler for focus in the location search field
// ------------------------------------------------------------
function locationFocus(evt)
{
     var searchBox = document.getElementById(gLocationSearchInputId);
     if (searchBox)
     {
        searchBox.value = '';
      //  searchBox.className = 'LocationSearchInput';
        gLocationFocused = true;
     }
}

// ------------------------------------------------------------
// 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();
        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)
    {
        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) {
                if (new RegExp('^[0-9]+$').test(locationSearch.value))
                    updateLocationSuggest(['Mobil ID']);
                else 
                    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];
        
        if (searchTerm == document.getElementById(gLocationSearchInputId).value)
        {
            if (hitList.length > 0)
            {
                updateLocationSuggest(hitList);
            }
            else
            {
                hideLocationSuggest();
                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
        suggestDiv.removeChild(suggestDiv.firstChild);        
	    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 = document.getElementById(gLocationSearchInputId);
    	    if (searchBox)
    	    {
	          //  suggestDiv.style.left    = findPosX(searchBox) + 'px';
	          //  suggestDiv.style.top     = (findPosY(searchBox) + searchBox.clientHeight + 3) +  '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 = 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(useForm)
{
    var suggestItem = document.getElementById('LocationSuggestItem' + gCurrentSuggestItem);
    var searchBox   = document.getElementById(gLocationSearchInputId);
    if (searchBox && new RegExp('^[0-9]+$').test(searchBox.value)) {
        window.location.href = gAppRoot + "Templates/ObjectView.aspx?mobileref=" + searchBox.value;
    }
    else 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.replace('+', ';plus;')) + '&karta=0';
            if (useForm && document.forms['ObjectSearchForm']) {
                doObjectSearch(url);
            }
            else {
                window.location.href = url;
            }
        }
    }
    else {
        if (searchBox) {
            var searchTerm = searchBox.value;

            // Fire the search
            if (!gLocationFocused && (searchTerm != '') && (searchBox.className != 'LocationSearchInputTip')) {
                // Submit either using a form or a get request
                var url = gAppRoot + 'Templates/ObjectSearchResult.aspx?loc=' + encodeURIComponent(searchTerm.replace('+', ';plus;'));
                if (useForm && document.forms['ObjectSearchForm']) {
                    doObjectSearch(url);
                }
                else {
                    window.location.href = url;
                }
            }
        }
    }
}
