var autoCompleteSuggestList_city = new Array();

var autoCompleteCurrentlyFetchingList_city = '';

var significantCharacters_city = 2;

var redirected_city = false;

var selectedItem_city = null;

var searchTxt_city = '';

var targetIsAutobox_city = false;

var boxText_city = '';  //used specifically for escape button

$(document).ready(
    function() {
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/g, "");
        }
        String.prototype.ltrim = function() {
            return this.replace(/^\s+/, "");
        }
        String.prototype.rtrim = function() {
            return this.replace(/\s+$/, "");
        }
        

        $('#city_srch_txt').val('Search by City');

        $('#city_srch_txt').focus(
            function() {
                if ($(this).val() == 'Search by City') {
                    $(this).val('');
                    $(this).addClass('focus');
                }
            }
        );
        $('#city_srch_txt').blur(
            function() {
                if ($(this).val() == '') {
                    $(this).val('Search by City');
                    $(this).removeClass('focus');
                }
                if (!targetIsAutobox_city) {
                    closeAutoBox_city();
                }
            }
        );
        
        $('#city_srch_txt').keydown(
            function(e) {
                //up arrow
                if (e.keyCode == 38 && autoCompleteSuggestList_city.length > 0) {
                    if($('#city_srch_auto_suggest').is(':hidden') && selectedItem_city != null)
                    {
                        openAutoBox_city();
                    }
                    else
                    {
                        //don't use selectedItem to choose next item... use .selected class
                        //these might not be the same because of mouse hover
                        openAutoBox_city();  //still need to open it for null case
                        var visualSelection = $('#city_srch_auto_suggest .selected');
                        if(visualSelection.length == 0){ visualSelection = selectedItem_city; }
                        if (visualSelection == null) {
                            selectedItem_city = $("#city_srch_auto_suggest label:last");
                        }
                        else if (visualSelection.attr('text') == $("#city_srch_auto_suggest label:first").attr('text')) {
                            selectedItem_city = null;
                            visualSelect_city(selectedItem_city); //always reset for null, even for advsearch
                        }
                        else {
                            selectedItem_city = visualSelection.prev();
                        }
						
                        alterSearchText_city(selectedItem_city); //we're still using selectedItem for everything; visualSelection is just to
                        //take care of discrepancies between keypress and hover
  
                    }
                    visualSelect_city(selectedItem_city);
                }
                //down arrow
                else if (e.keyCode == 40 && autoCompleteSuggestList_city.length > 0) {
                    if($('#city_srch_auto_suggest').is(':hidden') && selectedItem_city != null)
                    {
                        openAutoBox_city();
                    }
                    else
                    {
                        //don't use selectedItem to choose next item... use .selected class
                        //these might not be the same because of mouse hover
                        openAutoBox_city();  //still need to open it for null case
                        var visualSelection = $('#city_srch_auto_suggest .selected');
                        if(visualSelection.length == 0){ visualSelection = selectedItem_city; }
                        if (visualSelection == null) {
                            selectedItem_city = $("#city_srch_auto_suggest label:first");
                        }
                        else if (visualSelection.attr('text') == $("#city_srch_auto_suggest label:last").attr('text')) {
                            selectedItem_city = null;
                            visualSelect_city(selectedItem_city); //always reset for null, even for advsearch
                        }
                        else {
                            selectedItem_city = visualSelection.next();
                        }

                        alterSearchText_city(selectedItem_city); //we're still using selectedItem for everything; visualSelection is just to
                        //take care of discrepancies between keypress and hover
                    }
                    visualSelect_city(selectedItem_city);
                }
                else if(e.keyCode == 27)
                {

                    resetSearchText_city();
                    boxText_city = searchTxt_city;
                }
            }
        );

        // triggers every time a key is hit on the search textbox
        $('#city_srch_txt').keypress(
            function(e) {
                if (e.which == 13 && $(this).val().length > 0) {
                    closeAutoBox_city();
                    $('#city_srch_btn').click();
                }
            }
        );




        $('#city_srch_txt').keyup(
            function(e) {
                if ($(this).val() != searchTxt_city && e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 27) {
                    searchTxt_city = $(this).val();
                    if ($(this).val().length >= (significantCharacters_city)) {
                        selectedItem_city = null;
                        var curSuggestSet = null;

                        // get the current 3 letter start to the string
                        var curSearchSeed = $(this).val().substring(0, significantCharacters_city);
                        var curSearchText = $(this).val();

                        var curSeedIndex = -1;

                        if (autoCompleteCurrentlyFetchingList_city.indexOf(curSearchSeed) < 0) {

                            // first add it to the list so that if the user types again before the ajax is done, there will not be
                            //      a double entry
                            autoCompleteCurrentlyFetchingList_city += curSearchSeed + "||";
                            
                            var unsafeChars = /<[\/\w]/g; //aka, the beginning of an html tag (closing or opening)
                            //since this is a querystring variable pass we just need to keep html tags out of
                            //the autocomplete search (it will throw an error and stop working)
                            if(!curSearchSeed.match(unsafeChars))
                            {
                                // call ajax autosuggest
                                $.get(
                                    "/ajax/search-autocomplete.aspx?srchSeed=" + escape(curSearchSeed) + "&srchType=city",
                                    function(data) {
                                        curSuggestSet = eval('(' + data + ')');

                                        curSeedIndex = autoCompleteSuggestList_city.push(curSuggestSet) - 1;

                                        var curSuggestList = NarrowDownSuggestList_city(autoCompleteSuggestList_city[curSeedIndex].relatedEntities, curSearchText);

                                        // ok now time to show the div, update it
                                        UpdateAndShowSuggestDiv_city(curSuggestList[0], curSuggestList[1]);
                                    }
                                );
                            }
                        }
                        else {
                            try {
                                for (var i = 0; i < autoCompleteSuggestList_city.length; i++) {
                                    if (autoCompleteSuggestList_city[i].searchedLetters == curSearchSeed) {
                                        curSeedIndex = i;
                                        break;
                                    }
                                }

                                // this could fail if the ajax has not finished loading the seed index yet
                                var curSuggestList = NarrowDownSuggestList_city(autoCompleteSuggestList_city[curSeedIndex].relatedEntities, curSearchText);

                                UpdateAndShowSuggestDiv_city(curSuggestList[0], curSuggestList[1]);
                            }
                            catch (e) {
                            }
                        }
                    }                    
                    //if there are less than the needed letters close the box (will take care of backspace, etc.)
                    else {
                        closeAutoBox_city();
                    }
                }
                else if(e.keyCode == 27) //escape key
                {
                    $('#city_srch_auto_suggest').hide();
                    $('#city_srch_txt').val(boxText_city);
                }
            }
        );






        $('.city_srch_go').click(
            function() {

                RedirFromSearchTerm_city($('#city_srch_txt').val());
            }
        );
    }
);



function NarrowDownSuggestList_city(fullList, refineVal) {

    var retList = new Array();
    var retListClean = new Array();

    var refineReg = new RegExp("(" + refineVal + ")", "gi");

    // get the matches, but only up to 15
    for (var i = 0; i < fullList.length && retList.length <= 15; i++) {
        if (fullList[i].toLowerCase().indexOf(refineVal.toLowerCase()) > -1) {

            retList.push(fullList[i].replace(refineReg, "<b>$1</b>"));
            retListClean.push(fullList[i]);
        }
    }

    return new Array(retList, retListClean);
}






function UpdateAndShowSuggestDiv_city(suggestList, textList) {

    var suggListHtml = '';
    for (var i = 0; i < suggestList.length; i++) {
        suggListHtml += '<label class="suggest_option" text="' + textList[i] + '">';
        suggListHtml += suggestList[i];
        suggListHtml += '</label>';
    }

    $('#city_srch_auto_suggest').html(suggListHtml);
    $('#city_srch_auto_suggest').show();

    // if there are suggestions, add the handlers to them
    if (suggListHtml.length > 0) {
        $('.suggest_option').hover(
            function() {
                //selectedItem = $(this);
                visualSelect_city($(this));
                //alterSearchText(selectedItem);
            }
        );
        $('#city_srch_auto_suggest').click(
            function() {

                selectedItem_city = $(this).children('.selected');
                finalizeChoice_city();
                $('#city_srch_btn').click();
                //RedirFromSearchTerm($(this).text());
            }
        );
        $('#city_srch_auto_suggest').mouseup(
            function()
            {
                $('#city_srch_txt').focus();
            }
        )
        $('#city_srch_auto_suggest').hover(
            function()
            {
                targetIsAutobox_city = true;
            },
            function()
            {
                targetIsAutobox_city = false;
                /*selectedItem = null;
                visualSelect(selectedItem);*/
                //alterSearchText(selectedItem);
            }
        );
    }
}





function RedirFromSearchTerm_city(srchTerm) {
    if (!redirected_city) {

        var redirLoc = "";

        if (srchTerm.trim() == "Search by City" || srchTerm.trim() == '') {
            return;
        }

        redirected_city = true;
        
        try
		{
            pageTracker._trackEvent('Event Search', srchTerm.toLowerCase(), 'city search');
		}
		catch(e)
		{
		}

        srchTerm = srchTerm.trim().replace(" & ", " and "); //synonyms/alternate naming will catch this
        srchTerm = srchTerm.replace(/[-+]+/g, " ").replace(new RegExp("[^\\d\\w\\s!`~@\\$\\(\\)_=;',\\./]", "g"), "").replace(/\s+/g, "-");
        //if / is at the front of a search term it will break... we need to remove it in that case
        srchTerm = srchTerm.replace(/^\/+/, "");
        srchTerm = escape(srchTerm);
        //escape() doesn't encode... * + / @
        //need to manually replace certain characters that javascript escape doesn't encode (that are allowed)
        //important to do this AFTER the encode, or we will be double encoding the %
        srchTerm = srchTerm.replace(new RegExp("/", "g"), "%2f").replace(new RegExp("@", "g"), "%40");
        //if . is in front of an escaped term (%something) the page will have an error - prevent this situation
        srchTerm = srchTerm.replace(/\.%/g, "%");
        
        redirLoc = "/ticket/" + srchTerm + "-events.aspx";
		
        location.href = redirLoc ;  
     }
}




function closeAutoBox_city()
{
    $('#city_srch_auto_suggest').hide();
    if(selectedItem_city != null)
    {
        searchTxt_city = selectedItem_city.attr('text');
        selectedItem_city.removeClass('selected');
    }
}

function openAutoBox_city()
{
    $('#city_srch_auto_suggest').show();
}

function visualSelect_city(element)
{
    $('#city_srch_auto_suggest .selected').removeClass('selected');
    if(element != null)
    {
        element.addClass('selected');
    }
}

function resetSearchText_city()
{
    $('#city_srch_txt').val(searchTxt_city);
}

function alterSearchText_city(element)
{
    if(element != null)
    {
        $('#city_srch_txt').val(element.attr('text'));
    }
    else
    {
        resetSearchText_city();
    }
}

function finalizeChoice_city()
{
    closeAutoBox_city();
    alterSearchText_city(selectedItem_city);

}

