;(function ($, window) { var prices = {"1":25,"2":45,"3":60}; var calculate_price = function () { var price = get_price(); $('#price').text(price + ' $'); } var get_price = function () { var price = 0; var challenges = 0; var discount = $('#field-size').val() == '' ? 5 : 0; $('input[name^=challenges]').each(function () { var $this = $(this); if ($this.is(':checked')) { challenges += 1; } }); // The keys of 'prices' are strings if ('' + challenges in prices) { price = parseFloat(prices[challenges]) - discount; } else { price = 0; } var donation = $('#field-donation').val(); if (donation) { price += parseFloat(donation.replace(/[\$\s]/, '')); } if (isNaN(price)) { price = 0; } return price; } var disable_submit_button = function () { $('button[type="submit"]').attr('disabled', 'disabled'); } var check_off_options = function () { // if a challenge with options is checked, all non-disabled options are checked too // if a challenge is unchecked, all options are unchecked // if any of the options are checked, the challenge is also checked // if all options are unchecked, the cahllenge is also unchecked var $this = $( this ), checked = $this.is(':checked'), isOption = $this.closest('.field-checkbox').hasClass('option'), callback; if ( isOption ) { if ( checked ) { callback = function ( i, el ) { $( el ).prop( 'checked', true ); } } else { var hasCheckedSiblings = !! $this.closest('.option').siblings('.option').find('input:checked').length; if ( !hasCheckedSiblings ) { callback = function ( i, el ) { $( el ).prop( 'checked', false ); } } } if ( callback ) { $this.parents('.challenge').find('input[type="checkbox"]:first').each( callback ); } } else { if ( checked ) { callback = function ( i, el ) { var $el = $( el ); if ( !$el.attr( 'disabled' ) ) { $el.prop ( 'checked', true ); } }; } else { callback = function ( i, el ) { $( el ).prop( 'checked', false ); } } if ( callback ) { $this.closest('.challenge').find('.option input').each( callback ); } } } $(function () { $('form') .change( calculate_price ) .submit( disable_submit_button ); $('form .challenges .field-checkbox input') .change( check_off_options ) .change(); calculate_price(); }); })(jQuery, window);