jQuery(function() {

    var changed = false;
    jQuery( 'input, textarea, select, checkbox' ).on( 'change', function (e) {
        if (jQuery(this).attr('id') == 'pwlpara-members-search-input' ) {
            return;
        }

        if ( ! changed ) {
            window.onbeforeunload = function () {
                return pwlpara.i18n.navWarning;
            };
            changed = true;
        }
    });

    jQuery('.pwlpara-pro-feature').find('*').each(function() {
        jQuery(this).attr('tabindex', '-1');
    });

    jQuery( 'input[type="submit"]' ).not('#pwlpara-offer-category-filter').on('click', function () {
        window.onbeforeunload = '';
    });

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

    jQuery('#pwlpara-inactive-settings-link').on('click', function(e) {
        e.preventDefault();
        jQuery('.pwlpara-section-header-item[data-section="settings"]').trigger('click');
        jQuery(this).blur();
    });

    jQuery('.pwlpara-section-header-item').on('click', function(e) {
        e.preventDefault();

        var section = jQuery(this).attr('data-section');
        var currentSection = jQuery('.pwlpara-section-header-item-selected').attr('data-section');

        if (section == currentSection && jQuery('#pwlpara-section-' + section).attr('data-id').length) {
            pwlparaSetUrlParams(section, null);
            window.location = window.location.href;
            return;
        }

        pwlparaHandleSectionChange(section);
        pwlparaSetUrlParams(section, jQuery('#pwlpara-section-' + section).attr('data-id'));
    });

    jQuery('.pwlpara-section-header-item').on('mouseenter', function() {
        // Mouse enters: change to the active image
        var img = jQuery(this).find('.pwlpara-section-header-item-icon');
        img.attr('src', img.attr('data-active-image-src'));
    });

    jQuery('.pwlpara-section-header-item').on('mouseleave', function() {
        // Mouse leaves: change back to the regular image
        if (!jQuery(this).hasClass('pwlpara-section-header-item-selected')) {
            var img = jQuery(this).find('.pwlpara-section-header-item-icon');
            img.attr('src', img.attr('data-image-src'));
        }
    });

    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('.pwlpara-section-header-item:first').attr('data-section');
            } else {
                // Clear focus
                jQuery(':focus').blur();
            }

            pwlparaHandleSectionChange(section);
        }
    });
});

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

        var currentSection = url.searchParams.get('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);
    }
}

function pwlparaHandleSectionChange(section) {
    jQuery('.pwlpara-section-header-item').removeClass('pwlpara-section-header-item-selected');
    jQuery('.pwlpara-section-header-item .pwlpara-section-header-item-icon').attr('src', function() { return jQuery(this).attr('data-image-src'); });
    jQuery('.pwlpara-section-header-item[data-section="' + section + '"]').addClass('pwlpara-section-header-item-selected');
    jQuery('.pwlpara-section-header-item[data-section="' + section + '"] .pwlpara-section-header-item-icon').attr('src', function() { return jQuery(this).attr('data-active-image-src'); });

    jQuery('.pwlpara-section').hide();
    jQuery('#pwlpara-section-' + section).show();

    switch (section) {
        case 'members':
            if (jQuery('#pwlpara-members-table-container').html() == '') {
                pwlparaLoadMembers();
            }
            break;

        case 'offers':
            if (jQuery('#pwlpara-section-offers-table-container').html() == '') {
                pwlparaLoadOffers();
            }
            break;
    }
}

function pwlparaHandleFormSubmission(formId) {
    jQuery(formId).on('submit', function(e) {
        var messageContainer = jQuery(formId + '-message');
        var buttons = jQuery(formId + '-buttons-container');
        var form = jQuery(this).serialize();
        var action = jQuery(this).attr('data-action');

        buttons.hide();
        messageContainer.html('<span>' + pwlpara.i18n.saving + '</span>');

        jQuery.post(ajaxurl, {'action': 'pwlpar-' + action, 'form': form, 'security': pwlpara.nonces.submitForm }, function(result) {
            if (result.success) {
                window.location = result.data.url;
            } else {
                buttons.show();
                messageContainer.html(result.data.html);
            }
        }).fail(function(xhr, textStatus, errorThrown) {
            buttons.show();
            if (errorThrown) {
                messageContainer.html(errorThrown);
            } else {
                messageContainer.text(pwlpara.i18n.error);
            }
        });

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

function pwlparaBindMediaPicker( selector, button_selector, destinationImage )  {
    var clicked_button = false;

    jQuery(selector).each(function (i, input) {
        var button = jQuery(input).next(button_selector);
        button.on('click', function (event) {
            event.preventDefault();
            var selected_img;
            clicked_button = jQuery(this);

            var pwlpar_media_set_image = function() {
                var selection = wp.media.frames.pwlpar_frame.state().get('selection');

                if (!selection) {
                    return;
                }

                selection.each(function(attachment) {
                    var url = attachment.attributes.url;
                    clicked_button.prev(selector).val(url);
                });

                pwlparaUpdateImage(selector, destinationImage);
            };

            if (wp.media.frames.pwlpar_frame) {
                wp.media.frames.pwlpar_frame.off('close').on('close', pwlpar_media_set_image);
                wp.media.frames.pwlpar_frame.off('select').on('select', pwlpar_media_set_image);
                wp.media.frames.pwlpar_frame.open();
                return;
            }

            wp.media.frames.pwlpar_frame = wp.media({
                title: pwlpara.i18n.select_image,
                multiple: false,
                library: {
                    type: 'image'
                },
                button: {
                    text: pwlpara.i18n.use_selected_image
                }
            });

            wp.media.frames.pwlpar_frame.on('close', pwlpar_media_set_image);
            wp.media.frames.pwlpar_frame.on('select', pwlpar_media_set_image);
            wp.media.frames.pwlpar_frame.open();
        });
   });
}

function pwlparaUpdateImage(source, destination) {
    var logoImage = jQuery(source).val();
    if (logoImage) {
        jQuery(destination).show();
        jQuery(destination).attr('src', logoImage);
    } else {
        jQuery(destination).hide();
        jQuery(destination).attr('src', logoImage);
    }
}
