(function($){
    function update_registration_price() {
        var p_tier, p_package, p_dates,
            pc_all_day, pc_morning, pc_afternoon, pc_evening,
            tt_package, tt_single_event = 0, tt_fees = 0, tt_discounts = 0, tt_membership = 0, tt_donation = 0, total;


        p_package = false;
        p_tier = false;

        // :checked seems to have race condition so use prop
        $('#pricing input[type="radio"]').each(function(){
            if ($(this).prop("checked")) {
                p_package = $(this);
            }
        });
        $('#attendees input[type="radio"]').each(function(){
            if ($(this).prop("checked")) {
                p_tier = $(this).val();
            }
        });

        if (!p_package || !p_tier) {
            $('#price_summary .summary').remove();
            return;
        }

        if (p_package.val() == 0) {
            p_dates = [];
            p_package = 0;
            tt_package = 0;
        }
        else {
            p_dates = p_package.closest('.package').data("dates");
            p_dates = p_dates.split(",");
            p_package = p_package.val();
            tt_package = parseFloat($('#pricing .package .rate[data-id="'+p_package+'_'+p_tier+'"]').data("price"));
        }

        pc_all_day = parseFloat($('#pricing .single_events .rate_group[data-time-slot="All Day"] .rate[data-id="'+p_tier+'"]').data("price"));
        pc_morning = parseFloat($('#pricing .single_events .rate_group[data-time-slot="Morning"] .rate[data-id="'+p_tier+'"]').data("price"));
        pc_afternoon = parseFloat($('#pricing .single_events .rate_group[data-time-slot="Afternoon"] .rate[data-id="'+p_tier+'"]').data("price"));
        pc_evening = parseFloat($('#pricing .single_events .rate_group[data-time-slot="Evening"] .rate[data-id="'+p_tier+'"]').data("price"));


        $('#program .event_group input[type="checkbox"]').each(function(){
            if ($(this).prop("checked")) {
                var edate = $(this).closest(".event_group").data("date");
                var event = $(this).closest(".event");

                if ($.inArray(edate, p_dates) < 0) {

                    if (!event.data("in-between")) {
                        switch ($(this).closest(".time_slot").data("time-slot")) {
                            case "All Day":
                                tt_single_event += pc_all_day;
                                break;
                            case "Morning":
                                tt_single_event += pc_morning;
                                break;
                            case "Afternoon":
                                tt_single_event += pc_afternoon;
                                break;
                            case "Evening":
                                tt_single_event += pc_evening;
                                break;
                        }
                    }

                    // Check for combo discount
                    var combo = event.find('.combo');
                    if (combo.length) {
                        var combo_id = combo.data('event-id');
                        var combo_event = $('#program .event[data-id="'+combo_id+'"]');
                        if (combo_event.find('input[type="checkbox"]').prop("checked")) {
                            var combo_date = combo_event.closest(".event_group").data("date");
                            // Combo only works if both events are not part of a package
                            if ($.inArray(combo_date, p_dates) < 0) {
                                tt_discounts += parseFloat(combo.data("discount"));
                            }
                        }
                    }
                }

                tt_fees += parseFloat($(event).data("fees"));
            }
        });


        if ($('#membership .agree input[type="checkbox"]').prop("checked")) {
            if ($('#membership input[name="membership_type"]:checked').val() == "individual") {
                tt_membership = 15;
            }
            else {
                tt_membership = 20;
            }

            if ($('#membership input[name="membership_donation"]:checked').length > 0) {
                tt_donation = parseInt($('#membership input[name="membership_donation"]:checked').val());
                if (tt_donation < 0) {
                    tt_donation = parseFloat($('#membership input[name="membership_donation_amount"]').val());
                    if (isNaN(tt_donation) || tt_donation < 0) {
                        tt_donation = 0;
                    }
                }
            }
        }

        total = tt_package + tt_single_event + tt_fees - tt_discounts + tt_membership + tt_donation;

        var html = '<div class="summary"> <h4>Price Summary</h4> <table>';
        if (tt_package > 0) {
            html += '<tr><th>Package</th><td>$'+tt_package.toFixed(2)+'</td></tr>';
        }
        if (tt_single_event > 0) {
            html += '<tr><th>Single Events</th><td>$'+tt_single_event.toFixed(2)+'</td></tr>';
        }
        if (tt_fees > 0) {
            html += '<tr><th>Extra Event Fees</th><td>$'+tt_fees.toFixed(2)+'</td></tr>';
        }
        if (tt_discounts > 0) {
            html += '<tr><th>Special Discounts</th><td>$-'+tt_discounts.toFixed(2)+'</td></tr>';
        }

        if (tt_membership > 0) {
            html += '<tr><th>Membership</th><td>$'+tt_membership.toFixed(2)+'</td></tr>';
        }
        if (tt_donation > 0) {
            html += '<tr><th>Donation</th><td>$'+tt_donation.toFixed(2)+'</td></tr>';
        }


        html += '<tr class="total"><th>Total</th><td>$'+total.toFixed(2)+'</td></tr>';

        html += '</table></div>';

        $('#price_summary .summary').remove();
        if (total > 0) {
            $("#price_summary").prepend(html);
        }
    }

    function show_overwrite_warning(check, $conflicting) {
        $('#event_warning_popup a').unbind("click");

        $('#event_warning_popup .selected').text(
            $(check).closest("label").text()
        );

        $('#event_warning_popup .confllicted').text(
            $conflicting.closest("label").text()
        );

        $('#event_warning_popup a.cancel').click(function(e){
            e.preventDefault();
            $('#event_warning_popup').hide();
            $(check).prop("checked", false);
        });
        $('#event_warning_popup a.continue').click(function(e){
            e.preventDefault();
            update_event_selections(check, false);
            $('#event_warning_popup').hide();
        });

        $('#event_warning_popup').show();
    }
    function update_event_selections(check, allow_popup) {
        var event, time_slot, full_day, in_between, time_slot, conflicting = false;

        event = $(check).closest(".event");
        full_day = $(event).data("full-day");
        in_between = $(event).data("in-between");

        time_slot = $(event).closest(".time_slot").data("time-slot");

        switch (time_slot) {
            case "All Day":
                if (!in_between) {
                    $(check).closest(".event_group").find('[data-time-slot="All Day"] input[type="checkbox"]').each(function(){
                        if ($(this).is(check)) {
                            return true;
                        }

                        if ($(this).closest(".event").data("in-between") && !full_day) {
                            return true;
                        }

                        $(this).prop("checked", false);
                    });
                }

                if (allow_popup) {
                    conflicting = $(check).closest(".event_group").find('[data-time-slot="Morning"] input[type="checkbox"]:checked');
                    if (conflicting.length == 0) {
                        conflicting = $(check).closest(".event_group").find('[data-time-slot="Afternoon"] input[type="checkbox"]:checked');
                        if (conflicting.length == 0 && full_day) {
                            conflicting = $(check).closest(".event_group").find('[data-time-slot="Evening"] input[type="checkbox"]:checked')
                        }
                    }

                    if (conflicting.length > 0) {
                        show_overwrite_warning(check, conflicting);
                        return false;
                    }
                }

                $(check).closest(".event_group").find('[data-time-slot="Morning"] input[type="checkbox"]').prop("checked", false);
                $(check).closest(".event_group").find('[data-time-slot="Afternoon"] input[type="checkbox"]').prop("checked", false);
                if (full_day) {
                    $(check).closest(".event_group").find('[data-time-slot="Evening"] input[type="checkbox"]').prop("checked", false);
                }
                break;
            case "Morning":
                if (!in_between) {
                    $(check).closest(".event_group").find('[data-time-slot="Morning"] input[type="checkbox"]').each(function(){
                        if ($(this).is(check)) {
                            return true;
                        }

                        if ($(this).closest(".event").data("in-between")) {
                            return true;
                        }

                        $(this).prop("checked", false);
                    });
                }

                if (allow_popup) {
                    conflicting = $(check).closest(".event_group").find('[data-time-slot="All Day"] input[type="checkbox"]:checked');
                    if (conflicting.length > 0) {
                        show_overwrite_warning(check, conflicting);
                        return false;
                    }
                }

                $(check).closest(".event_group").find('[data-time-slot="All Day"] input[type="checkbox"]').prop("checked", false);
                break;
            case "Afternoon":
                if (!in_between) {
                    $(check).closest(".event_group").find('[data-time-slot="Afternoon"] input[type="checkbox"]').each(function(){
                        if ($(this).is(check)) {
                            return true;
                        }

                        if ($(this).closest(".event").data("in-between")) {
                            return true;
                        }

                        $(this).prop("checked", false);
                    });
                }

                if (allow_popup) {
                    conflicting = $(check).closest(".event_group").find('[data-time-slot="All Day"] input[type="checkbox"]:checked');
                    if (conflicting.length > 0) {
                        show_overwrite_warning(check, conflicting);
                        return false;
                    }
                }

                $(check).closest(".event_group").find('[data-time-slot="All Day"] input[type="checkbox"]').prop("checked", false);
                break;
            case "Evening":
                if (!in_between) {
                    $(check).closest(".event_group").find('[data-time-slot="Evening"] input[type="checkbox"]').each(function(){
                        if ($(this).is(check)) {
                            return true;
                        }

                        if ($(this).closest(".event").data("in-between")) {
                            return true;
                        }

                        $(this).prop("checked", false);
                    });
                }

                if (allow_popup) {
                    conflicting = $(check).closest(".event_group").find('[data-time-slot="All Day"] [data-full-day="1"] input[type="checkbox"]:checked');
                    if (conflicting.length > 0) {
                        show_overwrite_warning(check, conflicting);
                        return false;
                    }
                }

                $(check).closest(".event_group").find('[data-time-slot="All Day"] [data-full-day="1"] input[type="checkbox"]').prop("checked", false);
                break;
        }

        update_registration_price();

        return true;
    }

    $(function(){
        // Adjust menus to be width of text and ensure submenus dont popup off screen
        function adjust_submenu(e, level) {
            var widths, w, max, next, oc, on;

            oc = $("#subnav").offset();
            $(e).each(function(k, v){
                $(v).closest(".nav").width(1000).css("display", "block");

                widths = $(v).children().map(function(){
                    $(this).css("position", "absolute");
                    $(this).css("width", "auto");
                    w = $(this).width();
                    $(this).css("position", "");
                    return w;
                }).get();

                max = Math.max.apply(this, widths);
                max += 1;

                if (level == 1 && max < $(v).closest("li").outerWidth()) {
                    max = $(v).closest("li").outerWidth() - 10;
                }

                $(v).closest(".nav").width(max);

                next = $(v).find(".nav.level-" + (level + 1));
                if (next.length > 0) {
                    adjust_submenu($(v).find(".nav.level-" + (level + 1) + " > ul"), level + 1);

                    next.css("display", "block");
                    on = next.offset();
                    next.css("display", '');

                    if (on.left + next.outerWidth() - oc.left > $("#subnav").outerWidth()) {
                        next.css("left", -next.outerWidth());
                    }
                    else {
                        next.css("left", max);
                    }
                }

                $(v).closest(".nav").css("display", '');
            });
        }
        adjust_submenu("#subnav .nav.level-1 > ul", 1);

        if ($("#gallery_layout .gallery a").length > 0) {
            $("#gallery_layout .gallery a").lightBox();
        }


        if ($("#program.step1").length > 0) {
            $('#attendees input[type="radio"]').click(function(){
                update_registration_price();
            });

            $('#pricing input[type="radio"]').click(function(){
                update_registration_price();
            });
        }

        $('#program .event_group input[type="checkbox"]').click(function(e){
            // If check removed, only update the price
            if (!$(this).prop("checked")) {
                update_registration_price()
                return;
            }

            if (!update_event_selections(this, true)) {
                //e.preventDefault();
            }
        });

        $('#membership .agree input[type="checkbox"]').click(function(e){
            update_registration_price();
        });

        $('#membership input[type="radio"]').click(function(e){
            if ($('#membership .agree input[type="checkbox"]').prop("checked")) {
                update_registration_price();
            }
        });

        $('#membership input[name="membership_donation_amount"]').bind("keyup blur", function(e){
            if ($('#membership .agree input[type="checkbox"]').prop("checked")) {
                update_registration_price();
            }
        });

        if ($('#event_warning_popup').length > 0) {
            $('body').append($('#event_warning_popup').remove());
        }

        // Events toggles
        $('#program .event_group .time_slots').hide().closest(".event_group").find("h5").addClass("collapsed").addClass("toggle");

        $('#program .event_group > h5').click(function(){
            if ($(this).closest(".event_group").find(".time_slots").not(":visible")) {
                $(this).removeClass("collapsed");
            }
            $(this).closest(".event_group").find(".time_slots").slideToggle(0, function(){
                if ($(this).is(":hidden")) {
                    $(this).closest(".event_group").find("h5").addClass("collapsed");
                }
            });
        });

        // Membership toggle
        $('#membership .content').hide();
        $('#membership h4').addClass("collapsed").addClass("toggle").click(function(){
            if ($('#membership .content').not(":visible")) {
                $(this).removeClass("collapsed");
            }
            $('#membership .content').slideToggle(0, function(){
                if ($(this).is(":hidden")) {
                    $('#membership h4').addClass("collapsed");
                }
            });
        });

        // Registrations
        $('#registrations input[name="submit_checkout"]').click(function(e){
            $('#registrations form .information').remove();

            if ($('#registrations input[type="checkbox"]:checked').length == 0) {
                e.preventDefault();

                $('#registrations form').append(
                    '<p class="message information">Before you can proceed to the checkout process, you must check off which items you would like to pay for.</p>'
                );
            }
        });

        $('#registrations input[name="submit_delete"]').click(function(e){
            $('#registrations form .information').remove();

            if ($('#registrations input[type="checkbox"]:checked').length == 0) {
                e.preventDefault();

                $('#registrations form').append(
                    '<p class="message information">You must check off the items you wish to delete.</p>'
                );
            }
        });

        $('#program #view_guidelines').show().click(function(e){
            e.preventDefault();
            $('#guidelines_popup').show();
        });
        if ($('#guidelines_popup').length > 0) {
            $('body').append($('#guidelines_popup').remove());

            $('#guidelines_popup a.cancel').click(function(e){
                e.preventDefault();
                $('#guidelines_popup').hide();
            });
        }


        $('#checkout_summary .terms p a').click(function(e){
            e.preventDefault();
            $('#terms_popup').show();
        });
        if ($('#terms_popup').length > 0) {
            $('body').append($('#terms_popup').remove());

            $('#terms_popup a.cancel').click(function(e){
                e.preventDefault();
                $('#terms_popup').hide();
            });
        }
        $('#checkout_summary .terms a.continue').click(function(e){
            e.preventDefault();
            $('#checkout_summary .terms').hide();
            $('#payment').show();
        });
    });
})(jQuery);
