﻿// this sets the character on which to start suggesting listingRefs
var LR_AutoSuggestOnLetter = 6;

// Key constants
var LR_KEY_COMMA = 188;
var LR_KEY_UP = 38;
var LR_KEY_DOWN = 40;
var LR_KEY_ENTER = 13;

// global variables

var txtListingRef;
var divListingRefSuggestions;

var btnRefSearch;

var currentWebListRefs;
var currentListTableCells;

var highlightedWebListIndex = -1;

var selectedListingRef = '';

function LR_Init(lrTextBox, lrSuggestionsDiv, lrSearch) {
    btnRefSearch = lrSearch;
    txtListingRef = lrTextBox;
    
    //disable auto complete because it blocks the suggestions div
    txtListingRef.setAttribute("autocomplete", "off");

    divListingRefSuggestions = lrSuggestionsDiv;

    var pos = $(txtListingRef).offset()
    
    //.attr('style', 'margin-top:30px;margin-left:5px;')
    $(divListingRefSuggestions).css('top', (pos.top + 20) + 'px');
    $(divListingRefSuggestions).css('left', pos.left + 'px');

    //alert('init completed');
    
}

function LR_HandleEnter(e) {
    var keyPressed = e.keyCode ? e.keyCode : e.charCode;
    if (keyPressed == LR_KEY_ENTER) {
        if (highlightedWebListIndex != -1) {
            LR_SelectSuggestion(highlightedWebListIndex);

        }
        else {
            btnRefSearch.click();
        }
        return false;
    }
}

function LR_SuggestListingRef(e) {
    // get the unicode of the key that was pressed
    var keyPressed = e.keyCode ? e.keyCode : e.charCode;
    
    if (keyPressed == LR_KEY_DOWN) {
        if (highlightedWebListIndex < currentWebListRefs.length) {
            LR_HighlightSuggestion(highlightedWebListIndex + 1);
        }
        return -1;
    }
    else if (keyPressed == LR_KEY_UP) {
        if (highlightedWebListIndex > 0) {
            LR_HighlightSuggestion(highlightedWebListIndex - 1);
        }
        return -1;
    }
    else if (keyPressed == LR_KEY_ENTER) {
        //this is handled elsewhere, just hide the list
        $(divListingRefSuggestions).hide(0);
        $(divListingRefSuggestions).empty();
        return -1;
    }

    // check that something has been entered, otherwise clear the suggestions
    if (txtListingRef.value == '') {
        $(divListingRefSuggestions).hide(0);
        $(divListingRefSuggestions).empty();
        return -1;
    }

    // if the number of characters entered is still too few, abort
    if (txtListingRef.value.length < LR_AutoSuggestOnLetter) {
        $(divListingRefSuggestions).hide(0);
        $(divListingRefSuggestions).empty();
        return -1;
    }

    // trim the string of spaces
    currentString = jQuery.trim(txtListingRef.value);

    // repeat checks on current string in case we're dealing with a short string
    // check that something has been entered, otherwise clear the suggestions
    if (currentString == '') {
        $(divListingRefSuggestions).hide(0);
        $(divListingRefSuggestions).empty();
        return -1;
    }

    // if the number of characters entered is still too few, abort
    if (currentString.length < LR_AutoSuggestOnLetter) {
        $(divListingRefSuggestions).hide(0);
        $(divListingRefSuggestions).empty();
        return -1;
    }

    // clear the suggestion div
    $(divListingRefSuggestions).empty();

    // load array of listingRefs - these are stored with the location id as the array index
    //
    // Location|countryid,provinceid,regionid,cityid,urbanid,suburbid
    //
    GetListingRefs(currentString);

}

function LR_HighlightSuggestion(index) {
    if (highlightedWebListIndex > -1) {
        $(currentListTableCells[highlightedWebListIndex]).removeClass('location-row-highlighted');
    }

    $(currentListTableCells[index]).addClass('location-row-highlighted');
    highlightedWebListIndex = index;
}

function LR_selectHighlightedLocation() {
    if (highlightedWebListIndex != -1) {
        LR_SelectSuggestion(highlightedWebListIndex);
    }
}

function LR_SelectSuggestion(index) {
    var fullText = currentWebListRefs[index];
    fullText = fullText.replace(", ", ",");
    
    var listingref = fullText.split(',')[0];

    txtListingRef.value = listingref;
    
    $(divListingRefSuggestions).empty();
    $(divListingRefSuggestions).hide(0);
    highlightedWebListIndex = -1;
    selectedListingRef = txtListingRef.value;
}

function GetListingRefs(startsWith) {
    $.ajax(
    {
        type: "POST",
        url: "/Ajax/GetListingRefs.aspx",
        data: "StartsWith=" + startsWith,
        success: function(message) {

            currentWebListRefs = message.split('|');
            //alert(message);
            if (currentWebListRefs.length > 0 && currentWebListRefs[0].length > 0) {

                // start building up html to write to the suggestion div
                var suggestionString = '';
                var html = '<table>';

                for (i = 0; i < currentWebListRefs.length; i++) {
                    suggestionString = '';
                    suggestionString += '<tr><td id="td-' + i + '"';

                    // set classes for alternating rows
                    if (i % 2 == 0) {
                        suggestionString += ' class="location-altrow"';
                    }
                    else {
                        suggestionString += ' class="location-row"';
                    }

                    // set the mouseover highlighting for the
                    suggestionString += 'onMouseOver="javascript:LR_HighlightSuggestion(\'' + i + '\');" onMouseOut="javascript:unHighlightLocation(\'' + i + '\');" onClick="javascript:LR_SelectSuggestion(\'' + i + '\');">';

                    suggestionString += currentWebListRefs[i];

                    // add the location string to the table, closing the table cell and row
                    html += suggestionString + '</td></tr>';
                }

                html += '</table>';

                //$(divListingRefSuggestions).html(stringIndex + currentString + '<br/>' + html);
                $(divListingRefSuggestions).html(html);

                //build up an array of references to cells
                currentListTableCells = new Array(currentWebListRefs.length);

                for (i = 0; i < currentWebListRefs.length; i++) {
                    currentListTableCells[i] = document.getElementById('td-' + i);
                }

                $(divListingRefSuggestions).show(0);

                var text = txtListingRef.value;
                var somethingSelected = false;

                if (text != null && text != '') {
                    for (i = 0; i < currentWebListRefs.length; i++) {
                        if (currentWebListRefs[i] == text) {
                            LR_HighlightSuggestion(i);
                            somethingSelected = true;
                            break;
                        }
                    }
                }

                if (!somethingSelected) {
                    LR_HighlightSuggestion(0);
                }
               // alert('showing...?');
            }
            else {
                //alert('nothing to show');
                $(divListingRefSuggestions).hide(0);
            }
        }
    });
}

function validateSelectedListingRef() {


    var valid = true;

    if (selectedListingRef == null ||selectedListingRef.length == 0) {
        valid = false;
        if ($(txtListingRef).hasClass('valError') == false) {
            $(txtListingRef).addClass('valError');


            var pos = $(txtListingRef).offset()

            $("#search_wrapper").append('<div id="' + txtListingRef.id + '_errorDiv' + '">?</div>');
            var errdiv = document.getElementById(txtListingRef.id + '_errorDiv');

            $(errdiv).css('top', (pos.top + 1) + 'px');
            $(errdiv).css('left', (pos.left + $(txtListingRef).width() + 2) + 'px');

            $(errdiv).addClass('errorDiv');

            $("#search_wrapper").append('<div id="' + txtListingRef.id + '_errorMessageDiv' + '">Invalid listing reference.</div>');
            var errmsgdiv = document.getElementById(txtListingRef.id + '_errorMessageDiv');
            $(errmsgdiv).hide(0);

            $(errmsgdiv).css('top', (pos.top + 21) + 'px');
            $(errmsgdiv).css('left', pos.left + 'px');
            $(errmsgdiv).css('width', ($(txtListingRef).width() - 12) + 'px');

            $(errmsgdiv).addClass('errorMessageDiv');

            $(errdiv).mouseover(function() {
                $(errmsgdiv).show(0);
            });

            $(errdiv).mouseout(function() {
                $(errmsgdiv).hide(0);
            });
        }

    }
    return valid;
}
