var redirected = false;

$(document).ready(
    function() {
        //first, we need to create the necessary state/city selects
        var locationsDoc = loadXMLDoc('/tnxml/united-states-cities.xml');
        var stateOptions = '';
        var states = locationsDoc.getElementsByTagName('state');
        var citySelects = '';
        for(var i = 0; i < states.length; i++)
        {
            var stateName = states[i].getAttribute('name');
            var stateSpid = states[i].getAttribute('spid');
            stateOptions += '<option value="' + stateSpid + '">' + stateName + '</option>';
            citySelects += '<select id="adv_search_city_select_' + stateSpid + '">';
            citySelects += '<option value="">-- Select a City --</option>';//-- Select a City --
            for(var j = 0; j < states[i].childNodes.length; j++)
            {
                if (states[i].childNodes[j].nodeName == "city")
                {
                    var cityNameValue = states[i].childNodes[j].getAttribute('name').replace(/\s/g, "+");
                    //specific changes for some city names
                    switch(cityNameValue)
                    {
                        case 'New+York+City':
                            cityNameValue = 'New+York';
                            break;
                        case 'Washington+D.C.':
                            cityNameValue = 'Washington';
                            break;
                    }
                    var cityName = states[i].childNodes[j].getAttribute('name');
                    citySelects += '<option value="' + cityNameValue + '">' + cityName + '</a><br />';
                }
            }
            citySelects += '</select>';
        }
        
        $('#adv_search_state_select').append(stateOptions);
        $('#all_adv_search_city_select').html(citySelects);
        
        $('#adv_search_state_select').change(function(){
            var spid = $(this).val();
            if(spid == '0')
            {
                //enable the zipcode input - not doing this anymore
                //$('#adv_search_zip').attr('disabled', false);
                $('#adv_search_city_select').attr('disabled', true);
                $('#adv_search_city_select').html('<option value="">-- Select a City --</option>');//-- Select a city --
            }
            else
            {
                //disable the zipcode input - not doing this anymore
                //$('#adv_search_zip').attr('disabled', true);
                $('#adv_search_city_select').html($('#adv_search_city_select_' + spid).html());
                $('#adv_search_city_select').attr('disabled', false);
            }
        });

        $('#adv_search_submit').click(
            function() {
                RedirFromAdvSearch('all'); //for now we will just use a non-specific search.  We MAY change this as some point in the future
            }
        );
        
        //once it's all built and bound, put the values from the querystring in, and if there are none, make the inputs blank
        //(for some reason the 'Search by Artist... etc.' text is appearing in the boxes.)
        var queryString = GetQueryStringObj();
        if(queryString)
        {
            //inputs
            if(queryString['startDate'])
            {
                $('#adv_search_start_date').val(queryString['startDate']);
            }
            if(queryString['endDate'])
            {
                $('#adv_search_end_date').val(queryString['endDate']);
            }
            if(queryString['zip'])
            {
                $('#adv_search_zip').val(urlDecode(queryString['zip']));
            }
            else
            {
                $('#adv_search_zip').val($('#adv_search_zip').attr('initialtxt'));
            }
            //selects
            if(queryString['spid'] && queryString['ctyname'])
            {
                $('#adv_search_state_select').val(queryString['spid']);
                $('#adv_search_state_select').change(); //perform change function to determine the correct 'on top' city select
                $('#adv_search_city_select').val(queryString['ctyname']);
            }
            //checkboxes
            if(queryString['pcid'])
            {
                //if we have a query string, we need to uncheck 'All', then check each category that's specified
                $('#adv_search_cat_check_all').attr('checked', false);
                var checkedCats = queryString['pcid'].split('|');
                for(var i = 0; i < checkedCats.length; i++)
                {
                    switch(checkedCats[i])
                    {
                        case '1':
                            $('#adv_search_cat_check_sports').attr('checked', true);
                            break;
                        case '2':
                            $('#adv_search_cat_check_concerts').attr('checked', true);
                            break;
                        case '3':
                            $('#adv_search_cat_check_theater').attr('checked', true);
                            break;
                    }
                }
            }
        }
        
        $('#adv_search_start_date').datepicker({ minDate: 0 });
        
        var advMinDate = ($("#adv_search_start_date").val() != '') ? new Date($("#adv_search_start_date").val()) : 0;
        $('#adv_search_end_date').datepicker({ minDate: advMinDate });
        
        $('#adv_search_start_date').datepicker('option', 'onSelect', function(theDate){
            //$(this).datepicker('hide', 'fast');
            $('#adv_search_end_date').datepicker('option', 'minDate', new Date(theDate));
        });
        
        $('#adv_search_zip').focus(
            function() {
                if ($(this).val() == $(this).attr('initialTxt')) {
                    $(this).val('');
                }
            }
        );
        $('#adv_search_zip').blur(
            function() {
                if ($(this).val() == '') {
                    $(this).val($(this).attr('initialTxt'));
                }
            }
        );
        $('#adv_search_zip').keypress(
            function(e) {
                if (e.which == 13) {
                    $('#adv_search_submit').click();
                }
            }
        );
        //disable functionality has been disabled
        /*$('#adv_search_zip').keyup(function(){
            //if the field doesn't have anything in it (or if it's just the initial text), we should enable the state select
            if ($(this).val() == '' || $(this).val() == $(this).attr('initialTxt'))
            {
                $('#adv_search_state_select').attr('disabled', false);
            }
            else
            {
                $('#adv_search_state_select').attr('disabled', true);
            }
        });*/
        
        //add checkbox behavior
        $('.adv_search_cat_check').click(function(){
            
            /*//this is behavior of all checkboxes being checked at once when 'All' is checked (w/toggle)
            //if this is the 'All' button, mirror the change in check in all other checkboxes
            if($(this).attr('id') == 'adv_search_cat_check_all')
            {
                $('.adv_search_cat_check:not(#adv_search_cat_check_all)').attr('checked', $(this).is(':checked'));
            }
            //otherwise, make sure that the 'All' checkbox correctly reflects the status of the checkboxes
            else
            {
                var allElseChecked = true;
                $('.adv_search_cat_check:not(#adv_search_cat_check_all)').each(function(){
                    if(!$(this).is(':checked'))
                    {
                        allElseChecked = false;
                    }
                });
                $('#adv_search_cat_check_all)').attr('checked', allElseChecked);
            }*/
            
            //however, we are going to use a version where 'All' is checked independently - like on search page
            if($(this).attr('id') == 'adv_search_cat_check_all')
            {
                $(this).attr('checked', true);
                $('.adv_search_cat_check:not(#adv_search_cat_check_all)').attr('checked', false);
            }
            //otherwise, make sure that the 'All' checkbox correctly reflects the status of the checkboxes
            else
            {
                //to keep consistency with search page, we will only re-check 'All' if everything has been unchecked
                var allElseUnChecked = true;
                $('.adv_search_cat_check:not(#adv_search_cat_check_all)').each(function(){
                    if($(this).is(':checked'))
                    {
                        allElseUnChecked = false;
                    }
                });
                $('#adv_search_cat_check_all').attr('checked', allElseUnChecked);
            }
        });
    }
);


function RedirFromAdvSearch(srchTerm) {
    if (!redirected) {
        var spid = $('#adv_search_state_select').val();
        var cityName = $('#adv_search_city_select').val();
        var zipCode = $('#adv_search_zip').val();
        //make sure that there is either a) a zipcode that matches the regex, or b) a location chosen - location overwrites zipcode
        if((spid != 0 && cityName != '') || !zipCode.search("^(\\d{5})(-\\d{4})?$"))
        {
            redirected = true;
            
            try
		    {
                pageTracker._trackEvent('Event Search', srchTerm.toLowerCase(), 'advanced 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 = urlEncode(srchTerm); //custom encode that will allow C# to correctly read url
            //if . is in front of an escaped term (%something) the page will have an error - prevent this situation
            srchTerm = srchTerm.replace(/\.%/g, "%");
            
            var redirLoc = "/ticket/" + srchTerm + "-events.aspx";
            
            //if zipcode is filled in correctly use that - otherwise use the location
            if(!zipCode.search("^(\\d{5})(-\\d{4})?$"))
            {
                redirLoc += '?zip=' + urlEncode(zipCode);
            }
            else
            {
                if (cityName == 'New+York')
                    redirLoc += '?inLoc=New+York+-+Five+Boroughs';
                else
                    redirLoc += '?cid=217&spid=' + urlEncode(spid) + '&ctyname=' + cityName;
            }
            
            //then add on all of the extra info (like dates/category)
            var startDate = $('#adv_search_start_date').val();
            if(startDate != '')
            {
                redirLoc += '&startDate=' + startDate;
            }
            var endDate = $('#adv_search_end_date').val();
            if(endDate != '')
            {
                redirLoc += '&endDate=' + endDate;
            }
            
            var category = 0;
            var possibleCats = '';
            var allElseChecked = true;
            $('.adv_search_cat_check:not(#adv_search_cat_check_all)').each(function(){
                if(!$(this).is(':checked'))
                {
                    allElseChecked = false;
                }
                else
                {
                    possibleCats += ((possibleCats.length > 0) ? '|' : '') + $(this).val();
                }
            });
            //if not 'All' categories are chosen, then we want to change this to the actual categories
            if(!allElseChecked && !$('#adv_search_cat_check_all').is(':checked'))
            {
                category = possibleCats;
            }
            if(category != 0)
            {
                redirLoc += '&pcid=' + category;
            }
        }
        else
        {
            alert("Please enter a valid US zipcode, or pick a city from the dropdown menu.");
            return;
        }
        
        location.href = redirLoc;
     }
}

function OpenStartDate_Adv()
{
    $('#adv_search_start_date').datepicker('show');
}

function OpenEndDate_Adv()
{
    $('#adv_search_end_date').datepicker('show');
}

