/**
 * Behaviours for the finder 
 */

// Constants
var ADVANCED_SEARCH = '#id_advanced_search_options';
var ADVANCED_SEARCH_TRIGGER = '#id_show_advanced_search';
var ADVANCED_SEARCH_CLOSE = '<img src="' + MEDIA_URL + 'static/images/minus-btn.png" /> Basic Search';
var ADVANCED_SEARCH_OPEN = '<img src="' + MEDIA_URL + 'static/images/plus-btn.png" />  Advanced Search';
var ADVANCED_SEARCH_INPUT = 'input[name=advanced]'

var FINDER_START_DATE = '#id_start_date';
var FINDER_FINISH_DATE = '#id_start_date';

/**
 * Called when the Region changes to update the list of countries
 * for the selected region.
 */
function updateCountries()
{
    $.getJSON("/trips/trip/countries/", 
        {
            region: $("select#id_region").val(), 
            ajax: 'true'
        }, 
        function(data){
            options = '<option value="">All Countries</option>';
            for (var i=0; i<data.length; i++){
                options += '<option value="' + data[i].pk + '">' + data[i]['fields'].name + '</option>';
            }
            $("#finder_form select#id_finder_country, #finder_form select#id_country").html(options);
        }
    );
}

/**
 * For maintaining the state of the advanced search display (opened or closed)
 * between search pages.
 */
function updatePaginationLinks()
{
    $('.pagination a').each(function(){
        var paginationAnchor = $(this);
        var advancedPattern = /advanced\=(True|False)/;
        var oldHref = paginationAnchor.attr('href');
        var newHref = '';

        if ($(ADVANCED_SEARCH_INPUT).val() == 'True'){
            newHref = newHref.replace(advancedPattern, "advanced=True");
        }else{
            newHref = newHref.replace(advancedPattern, "advanced=False");
        }

        paginationAnchor.attr('href', newHref);

    });
}

/**
 * The start and finish dates have jQuery calendars attached
 * for selecting the values.
 */
function init_date_pickers()
{
    /* finder date pickers */
    if($("#id_start_date").length) {
        $("#id_start_date,#id_finish_date").datepicker({ 
            dateFormat : "D, M dd yy",
            beforeShow : limit_date_range,
            buttonImage: MEDIA_URL + "static/images/calendar.gif",
            showOn: "both",
            buttonImageOnly: true,
            changeYear: "true",
            changeMonth: "true",
            showButtonPanel : true
        });
        $("#ui-datepicker-div").hide();
    }
}
 
/**
 * Called to limit the Departs After and Returns Before calendars
 * to today's date and beyond.
 */
function limit_date_range(input) { 
    var default_min_date = new Date();
    default_min_date.setDate(default_min_date.getDate()+4);

    var finish_min_date = default_min_date;
    if ($("#id_start_date").val()){
        finish_min_date = $("#id_start_date").datepicker("getDate");
    }

    return {
        minDate: (input.id == "id_finish_date" ? finish_min_date : default_min_date), 
        maxDate: (input.id == "id_start_date" ? $("#id_finish_date").datepicker("getDate") : null)
    }; 
}                            

/**
 * The state of the advanced search display is stored
 * in a hidden input named 'advanced'. The value is either
 * True or False. This function reads that value and displays
 * or hides the advanced search appropriately.
 */
function init_advanced_search() {

    if ($(ADVANCED_SEARCH_INPUT).val() == 'True'){
        $(ADVANCED_SEARCH).show()
        $(ADVANCED_SEARCH_TRIGGER).html(ADVANCED_SEARCH_CLOSE)
    }else{
        $(ADVANCED_SEARCH).hide()
        $(ADVANCED_SEARCH_TRIGGER).html(ADVANCED_SEARCH_OPEN)
    }    
     
    $(ADVANCED_SEARCH_TRIGGER).click(function(){
        var advanced_search_options = $(ADVANCED_SEARCH);
        if (advanced_search_options.is(':hidden')){
            track_event('Finder', 'AdvancedSearch', 'Opened');
            advanced_search_options.show();
            $(this).html(ADVANCED_SEARCH_CLOSE);
            $(ADVANCED_SEARCH_INPUT).val('True');
        } else {
            track_event('Finder', 'AdvancedSearch', 'Closed');
            advanced_search_options.hide();
            $(this).html(ADVANCED_SEARCH_OPEN);
            $(ADVANCED_SEARCH_INPUT).val('False');
        }
        updatePaginationLinks();
        return false;
    });                      
     
}


/**
 * Do all the work after the dom is ready.
 */
$(document).ready(function(){
    init_date_pickers();
    init_advanced_search();
    init_trip_list_tabs();
     
    $('.brief_trip_description:even').addClass('result_even');
    $('.brief_trip_description:odd').addClass('result_odd');
    $("select#id_region").change(updateCountries);
 
});

