var timeoutId;
$(document).ready(function() {

    set_states();
    check_wait_list();
    check_branding();
    activity_type_set();
    apply_dropdown_hack();

    if ($("#camps_tab").hasClass("active")) {
        get_camp_providers();
    };

    if ($("#communtiy_events_tab").hasClass("active")) {
        get_community_event_providers();
    };

    function get_states(callback){
        hash = '';
        $('.states_list li').addClass('print_hide');
        $('.state_input:checked').each(function(){
            $('.'+this.id+'_state_li').removeClass('print_hide');
            if (hash !== undefined && hash.length != 0){
                hash += ":"+this.id;
            } else {
                hash = this.id;
            };
        });
        $('#id_state_selection').attr('value',hash);
        if ($('#id_state_selection').val() == ''){
            $('#all_states').attr('checked','checked');
            $('.all_state_li').removeClass('print_hide');
        }else{
            $('#all_states').removeAttr("checked");
            $('.all_state_li').addClass('print_hide');
        };
        set_timmer(callback);
    };

    $('.state_input').click(function() {
        get_states();
    });

    $('#all_states').change(function() {
        if ($('#all_states').attr('checked') != 'checked'){
            $('.state_input:checked').removeAttr("checked");
            $('#id_state_selection').attr('value','');
            $('#all_states').attr('checked','checked');
            get_states();
        } else {
            get_states();
        };
    });

    function set_states() {
        hash = $('#id_state_selection').val();
        $('.states_list li').addClass('print_hide');
        $('.state_input').removeAttr("checked");
        if(hash !== undefined && hash.length != 0){
            state_ids = hash.split(':');
            $('.state_input').removeAttr("checked");
            for(i=0; i < state_ids.length; i++){
                $('#' + state_ids[i]).attr("checked","checked");
                $('.' + state_ids[i] + '_state_li').removeClass('print_hide');
            };
        };
        if ($('#id_state_selection').val() == ''){
            $('#all_states').attr('checked','checked');
            $('.all_state_li').removeClass('print_hide');
        }else{
            $('#all_states').removeAttr("checked");
            $('.all_state_li').addClass('print_hide');
        };
    }

    //Show Hide States Check Boxes
    $(".state_image").click(function () {
        if($(".state_box").hasClass('hidden')){
            $(".state_box").removeClass('hidden');
        }else{
            $(".state_box").addClass('hidden');
        };
    });

    //Add date text if not there
    set_default_text()

    //share thickbox
    $('#share_button').click(function() {
        thickbox.show('Share Activity Listing', '/search/share/', null,600,350,true);
    });

    //Show Hide Schedule
    $(".minimize_link").click(function () {
        if ($(".schedule").css('display')=='none'){
            $(".schedule").show();
        } else {
            $(".schedule").hide();
        };
    });

    //Set day widgets and hidden inputs
    //Active class is initial set in the template
    $("#activities_tab").click(function () {
        $("#camps_tab").removeClass("active");
        $("#community_events_tab").removeClass("active");
        $(this).addClass("active");
        $('#id_search_camps').attr('checked', false);
        $("#id_search_community_events").attr('checked', false);
        $('#id_search_activity').attr('checked', true);
        $(".state_filter").addClass('hidden');
        $(".state_box").addClass('hidden');
        $(".state_filter").addClass('print_hide');
        $(".state_box").addClass('print_hide');
        get_all_providers();
        set_timmer();
        return false
    });
    $("#camps_tab").click(function () {
        $("#activities_tab").removeClass("active");
        $("#community_events_tab").removeClass("active");
        $(this).addClass("active");
        $('#id_search_activity').attr('checked', false);
        $('#id_search_community_events').attr('checked', false);
        $('#id_search_camps').attr('checked', true);
        $(".state_filter").removeClass('hidden');
        $(".state_filter").removeClass('print_hide');
        $(".state_box").removeClass('print_hide');
        get_camp_providers();
        get_states();
        return false;
    });
    $("#community_events_tab").click(function() {
        $(this).addClass("active");
        $(this).siblings("a").removeClass("active");
        $("#id_search_activity").attr('checked', false);
        $("#id_search_camps").attr('checked', false);
        $("#id_search_community_events").attr('checked', true);
        $(".state_filter").addClass('hidden').removeClass('print_hide');
        $(".state_box").addClass('hidden').removeClass('print_hide');
        get_community_event_providers();
        set_timmer();
        return false;
    });
    $("#sunday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_sunday').attr('checked', false)
        }else{
            $(this).addClass("active")
            $('#id_sunday').attr('checked', true)
        };
        set_timmer()
    });
    $("#monday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_monday').attr('checked', false)
        }else{
            $(this).addClass("active")
            $('#id_monday').attr('checked', true)
        };
        set_timmer()
    });
    $("#tuesday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_tuesday').attr('checked', false)
        }else{
            $(this).addClass("active")
            $('#id_tuesday').attr('checked', true)
        };
        set_timmer()
    });
    $("#wednesday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_wednesday').attr('checked', false)
        }else{
            $(this).addClass("active")
            $('#id_wednesday').attr('checked', true)
        };
        set_timmer()
    });
    $("#thursday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_thursday').attr('checked', false)
        }else{
            $(this).addClass("active")
            $('#id_thursday').attr('checked', true)
        };
        set_timmer()
    });
    $("#friday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_friday').attr('checked', false)
        } else {
            $(this).addClass("active")
            $('#id_friday').attr('checked', true)
        };
        set_timmer()
    });
    $("#saturday").click(function () {
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
            $('#id_saturday').attr('checked', false)
        }else{
            $(this).addClass("active")
            $('#id_saturday').attr('checked', true)
        };
        set_timmer()
    });

    //Auto Populate on change provider and activity dropdowns
    $("#id_activity_type").change(function () {
        var params = {
            'type': $(this).val()
        }
        set_timmer();
        $.get("/search/filters/", params,
            function(data){
                var myObject = eval('(' + data + ')');
                $("#id_provider").empty();
                $("#id_provider").append(myObject.providers);
                $("#id_activity").empty();
                $("#id_activity").append(myObject.activities);
                // $('#id_activity_type, #id_provider, #id_activity, #id_during').each(set_style_select);
                apply_dropdown_hack();
            }
        );
    })

    $("#id_provider").change(function() {
        camp_tab_active = $("#camps_tab").hasClass('active');
        var params = {
                provider: $(this).val(),
                type: $("#id_activity_type").val()
        }
        if (camp_tab_active) {
            params['listing_type'] = "CMP";
        }
        set_timmer();
        $.get(
            "/search/filters/",
            params,
            function(data) {
                var myObject = eval('(' + data + ')');
                $("#id_activity").empty();
                $("#id_activity").append(myObject.activities);
                $("#id_provider").empty().append(myObject.providers);
                // $('#id_activity_type, #id_provider, #id_activity, #id_during').each(set_style_select);
                apply_dropdown_hack();
            }
        );
    });

    $('#id_activity').change(function() {
        camp_tab_active = $("#camps_tab").hasClass('active');
        var params = {
            activity: $(this).val(),
            provider: $("#id_provider").val(),
            type: $("#id_activity_type").val()
        }
        if (camp_tab_active) {
            params['listing_type'] = "CMP";
        }
        set_timmer();
        $.get(
            "/search/filters/",
            params,
            function(data) {
                var response = eval('(' + data + ')');
                $("#id_activity").empty().append(response.activities);
                $("#id_provider").empty().append(response.providers);
                apply_dropdown_hack();
            }
        );
    });

    $('#id_start_date , #id_end_date, #id_during').change(function() {
            set_timmer();
    });

    apply_events_search_jq();

    function set_activity_id() {
        var $this = $(this);
        if($this.val() == '') {
            $this.val('Activity Number');
            $this.addClass('prompt_text');
        }
    }
    $('#id_activity_id')
        .blur(set_activity_id)
        .each(set_activity_id)
        .focus(function() {
            if($(this).val() == 'Activity Number') {
                $(this).removeClass('prompt_text');
                $(this).val('');
            };
        });

    function set_style_select() {
        // if(($(this).val() != 'all')&&($(this).val() != 'all:all')&&($(this).val() != '0')) {
        //     $(this).addClass('filled');
        // } else {
        //     $(this).removeClass('filled');
        // };
    }

    function set_style_input() {
        if(($(this).val() != '')&&($(this).val() != 'Start')&&($(this).val() != 'End')) {
            $(this).addClass('filled');
        } else {
            $(this).removeClass('filled');
        };
    }
    $('#id_start_date, #id_end_date').change(set_style_input).each(set_style_input);

    // Add date picker to the date_picker class objects
    $('.date_picker').datepicker({dateFormat: 'mm/dd/y'});
});



function get_providers(type) {
    var provider_id = $("#id_provider")[0].options[$("#id_provider")[0].selectedIndex].value;

	$.get(
        '/search/filters/',
        {
            listing_type: type,
            provider: provider_id
        },
        function(data) {
            var response = JSON.decode(data);
            $("#id_provider").empty().append(response.providers);
            $("#id_activity").empty().append(response.activities);
            apply_dropdown_hack();
        }
    )
}

function get_community_event_providers() {
    get_providers('TTD');
}

function get_camp_providers() {
    get_providers('CMP');
}

function get_all_providers() {
    get_providers('all');
}


function set_default_text(){
    if ($('#id_end_date').val() == ''){
        $('#id_end_date').attr('value','End');
    };
    if ($('#id_start_date').val() == ''){
        $('#id_start_date').attr('value','Start');
    };
};

function set_timmer(callback){
    //alert('Set Timmer');
    set_default_text()
    $('#activity_listings_content').empty()
    $('#activity_listings_content').append('<div id="loading_holder" style="text-align:center;"><img style="margin-top:100px;margin-bottom:100px;" title="Loading" src="/public/images/ajax-loader.gif" /></div>')
    if(timeoutId != 0) {
        clearTimeout(timeoutId);
        timeoutId = 0;
    }
    cmd = 'update_search(0';
    if (callback) {
        cmd += ', ' + callback;
    }
    cmd += ');';
    timeoutId = setTimeout(cmd, 2000);
};

function apply_events_search_jq(){
    $('#id_conflicts, #id_order').change(function () {
        set_timmer();
    });
    /*$('.cost_button').cluetip({local:true, showTitle: false, arrows:true, positionBy:'fixed', leftOffset:-215, topOffset:-65, width:200, height: 50, cluetipClass:'activity_tree', dropShadowSteps:0});*/
    $('#activity_listings_content ul li.listing_row').click(function() {
        window.location = $(this).find('a.class_link').attr('href');
    });
}

function update_search(page, callback){
    params = {
        partial:'True'
    };

    url = '/search/';
    if (page != 0){
        params.page = page;
    };
    if ($('#id_zip_code').length != 0){
        params.zip_code = $('#id_zip_code').val();
    }else{
        url = $('.my_participants .active a').attr('href');
    };
    params.activity_type = $('#id_activity_type').val();
    params.provider = $('#id_provider').val();
    params.activity = $('#id_activity :selected').val();
    params.start_date = $('#id_start_date').val();
    params.end_date = $('#id_end_date').val();
    params.end_date = $('#id_end_date').val();
    params.during = $('#id_during').val();
    params.activity_id = $('#id_activity_id').val();
    params.state_selection = $('#id_state_selection').val();
    params.order = $('#id_order').val();

    if($('#id_search_activity').attr('checked') == true){
        params.search_activity = 'on';
    };
    if($('#id_search_camps').attr('checked') == true){
        params.search_camps = 'on';
    };
    if($('#id_search_community_events').attr('checked') == true) {
        params.search_community_events = 'on';
    }
    if($('#id_sunday').attr('checked') == true){
        params.sunday = 'on';
    };
    if($('#id_monday').attr('checked') == true){
        params.monday = 'on';
    };
    if($('#id_tuesday').attr('checked') == true){
        params.tuesday = 'on';
    };
    if($('#id_wednesday').attr('checked') == true){
        params.wednesday = 'on';
    };
    if($('#id_thursday').attr('checked') == true){
        params.thursday= 'on';
    };
    if($('#id_friday').attr('checked') == true){
        params.friday = 'on';
    };
    if($('#id_saturday').attr('checked') == true){
        params.saturday = 'on';
    };
    if($('#id_conflicts').attr('checked') == true){
        params.conflicts = 'on';
    };

    $.post(url, params,
        function(data) {
            $('#search_area').empty();
            $('#search_area').append(data);
            apply_events_search_jq();
            $('.popup_small').cluetip({local:true, showTitle: false, arrows:true, positionBy:'fixed', leftOffset:-215, topOffset:-45, width:200, height: 30, cluetipClass:'activity_tree', dropShadowSteps:0});

            $('.popup_medium').cluetip({local:true, showTitle: false, arrows:true, positionBy:'fixed', leftOffset:-215, topOffset:-70, width:200, height: 55, cluetipClass:'activity_tree', dropShadowSteps:0});
            if (callback) {
                callback();
        }
    });
    update_analytics(build_url('/search/', params));
    external_refresh_marquee('forward');
    external_refresh_side_marketing();
};

function check_branding() {
    var set = $("#branded").html();
    if (set == '1') {
       $('#id_provider').attr("disabled", true);
       $('#id_provider').attr("readonly", true);
    }
}
function activity_type_set() {
    var set = $("#activity_type_set").html();
    if (set == '1') {
        $('#id_activity_type').attr('disabled', true);
        $('#id_activity_type').attr('readonly', true);
    }
}
function toggle_filters(){
    if ($("#listing_filters").css("display") == "none") {
        $("#listing_filters").css("display","block");
    } else {
        $("#listing_filters").css("display","none");
    }
}

/* do this to reverse the effects of branding for form submission */
function reverse_branding() {
    set = $("#branded").html();
    if (set == '1') {
       $('#id_provider').attr("disabled", false);
       $('#id_provider').attr("readonly", false);
    }
}

function check_wait_list(){
    set = $('#wait_list').html();
    if (set == '1'){
        $('#id_activity_type').attr("disabled", true);
        $('#id_provider').attr("disabled", true);
        $('#id_activity_type').attr("readonly", true);
        $('#id_provider').attr("readonly", true);
    }
}

function apply_dropdown_hack() {
    // Do some browser detection for IE7 to see if
    // we need to expand select boxes
    if ($.browser.msie) {
        $("#id_activity, #id_provider").each(function() {
            $(this).data('options', $(this).html());
            window.dropdown_menu_hack(this);
        });
         // else {
         //            $("#id_activity, #id_provider").focus(function() {
         //                $(this).data('options', $(this).html());
         //                window.dropdown_menu_hack(this);
         //            });
         //        }
        // reset options
        $("#id_activity, #id_provider").unbind('blur').blur(function() {
            $(this).empty().append($(this).data('options'));
        });
    }
}


/*
 * this is a hack for the dropdown_menu_hack stuff
 * For some reason when the element is getting sent back from
 * the dropdown menu hack the value is forced to be numeric, which conflicts
 * with values like 'all' or '4:all', so we have to set an id on it
 * and use that as a value and then retrieve the information from there
 */
function hackSelect(el) {
    var re = /(\w+|\d+)\_(\d+|\w+)/
    if (re.test(el.id)) {
        var select = '#id_provider';
        var value = el.id.replace(/\_/, ':');
    } else {
        var select = '#id_activity';
        var value = el.id
    }
    // change which option has been selected
    $(select).children().attr('selected', false);
    $(select).children("[value='" + value + "']").attr('selected', true);
    $(select).change();
}


