jQuery(function() {
    jQuery('.pwlpar-section-button, .pwlpar-rewards-empty-button').on('click', function(e) {
        e.preventDefault();

        var section = jQuery(this).attr('data-section');
        pwlparSetUrlParams(section, null);
        pwlparShowSection(section);
    });

    jQuery('.pwlpar-disabled').off('click.pwlpar').on('click.pwlpar', function(e) {
        e.preventDefault();
        return false;
    });

    jQuery('#pwlpar-checkout-rewards-join').off('change.pwlpar').on('change.pwlpar', function() {
        var createAccount = jQuery('#createaccount');
        if (this.checked && createAccount && !createAccount.prop('checked')) {
            createAccount.prop('checked', true).trigger('change');
        }

        jQuery('#pwlpar-checkout-rewards-join-form').toggle(this.checked);
    });

    jQuery('#createaccount').off('change.pwlpar').on('change.pwlpar', function() {
        if (!this.checked) {
            jQuery('#pwlpar-checkout-rewards-join').prop('checked', false).trigger('change');
        }
    });

    jQuery('#pwlpar-join-button').off('click.pwlpar').on('click.pwlpar', function(e) {
        var url = jQuery(this).attr('href');
        url += (url.indexOf('?') === -1 ? '?' : '&') + 'pwlpar_action=join';

        location.href = url;

        e.preventDefault();
        return false;
    });

    window.addEventListener("popstate", function(e) {
        if ('URLSearchParams' in window) {
            var url = new URL(window.location);
            var section = url.searchParams.get('section');
            if (!section) {
                section = jQuery('.pwlpar-section-button:first').attr('data-section');
            }

            pwlparShowSection(section);
        }
    });
});

function pwlparShowSection(section) {
    jQuery('.pwlpar-section-button').removeClass('pwlpar-section-button-active');
    jQuery('.pwlpar-section-button[data-section="' + section + '"]').addClass('pwlpar-section-button-active');

    jQuery('.pwlpar-section').hide();
    jQuery('.pwlpar-section[data-section="' + section + '"]').show();
}

function pwlparSetUrlParams(section, id) {
    if ('URLSearchParams' in window) {
        var url = new URL(window.location);

        var currentSection = jQuery('.pwlpar-section-button-active').attr('data-section');
        var currentId = url.searchParams.get('id');
        if (currentSection == section && currentId == id) {
            return;
        }

        url.searchParams.set('section', section);
        if (id) {
            url.searchParams.set('id', id);
        } else {
            url.searchParams.delete('id');
        }

        history.pushState(null, '', url);
    }
}
