const stdCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function std_generateString(length) {
    let result = '';
    const stdCharactersLength = stdCharacters.length;
    for (let i = 0; i < length; i++) {
        result += stdCharacters.charAt(Math.floor(Math.random() * stdCharactersLength));
    }

    return result;
}
jQuery(document).ready(function ($) {
    "use strict";

    $('.std-sortable').sortable({
        placeholder: "std-sortable-placeholder",
        forcePlaceholderSize: true
    });
    /**
     *
     * @type object
     */
    var notice_timeout;

    /**
     * @type object
     */
    var translation_strings = std_backend_obj.translation_strings;

    /**
     * Generates required notice
     *
     * @param {string} info_text
     * @param {string} info_type
     *
     */
    function std_generate_info(info_text, info_type) {
        clearTimeout(notice_timeout);
        switch (info_type) {
            case 'error':
                var info_html = '<p class="std-error">' + info_text + '</p>';
                break;
            case 'info':
                var info_html = '<p class="std-info">' + info_text + '</p>';
                break;
            case 'ajax':
                var info_html = '<p class="std-ajax"><img src="' + std_backend_obj.plugin_url + 'images/ajax-loader.gif" class="std-ajax-loader"/>' + info_text + '</p>';
            default:
                break;

        }
        $('.std-form-message').html(info_html).show();
        if (info_type != 'ajax') {
            notice_timeout = setTimeout(function () {
                $('.std-form-message').slideUp(1000);
            }, 5000);
        }

    }

    /**
     * Performs clipboard copy action
     * 
     * @param {object} element
     * @returns null
     */
    function std_copyToClipboard(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(element).text()).select();
        document.execCommand("copy");
        $temp.remove();
    }

    function std_title_to_alias(str) {
        str = str.replace(/^\s+|\s+$/g, ''); // trim
        str = str.toLowerCase();

        // remove accents, swap ñ for n, etc
        var from = "àáäâèéëêìíïîòóöôùúüûñç·/,:;";
        var to = "aaaaeeeeiiiioooouuuunc------";
        for (var i = 0, l = from.length; i < l; i++) {
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }

        str = str.replace(/[^a-z0-9 _]/g, '') // remove invalid chars
            .replace(/\s+/g, '_') // collapse whitespace and replace by _
            .replace(/_+/g, '_'); // collapse dashes

        return str;
    }

    function std_initialize_checkbox_toggle() {
        $('.std-field input[type="checkbox"]').each(function () {
            if (!$(this).parent().hasClass('std-checkbox-toggle') && !$(this).hasClass('std-disable-checkbox-toggle')) {
                var input_name = $(this).attr('name');
                $(this).parent().addClass('std-checkbox-toggle');
                $('<label></label>').insertAfter($(this));
            }
        });
    }
    std_initialize_checkbox_toggle();

    /**
     * Settings section show hide
     */
    $('body').on('click', '.std-nav-item', function () {
        var tab = $(this).data('tab');
        $('.std-nav-item').removeClass('std-active-nav');
        $(this).addClass('std-active-nav');
        $('.std-settings-each-section').hide();
        $('.std-settings-each-section[data-tab="' + tab + '"]').show();

    });

    /**
     * Form components slide toggle
     */

    $('body').on('click', '.std-component-head h4', function () {
        $(this).closest('.std-form-each-component').find('.std-component-body').slideToggle();
        if ($(this).next('.dashicons').hasClass('dashicons-arrow-down')) {
            $(this).next('.dashicons').removeClass('dashicons-arrow-down').addClass('dashicons-arrow-up');
        } else {
            $(this).next('.dashicons').removeClass('dashicons-arrow-up').addClass('dashicons-arrow-down');
        }
    });

    /**
     * Open Media Uploader
     */
    $('body').on('click', '.std-file-uploader', function () {
        var selector = $(this);

        var image = wp.media({
            title: translation_strings.upload_button_text,
            // mutiple: true if you want to upload multiple files at once
            multiple: false
        }).open()
            .on('select', function (e) {
                // This will return the selected image from the Media Uploader, the result is an object
                var uploaded_image = image.state().get('selection').first();
                console.log(uploaded_image.toJSON());
                // We convert uploaded_image to a JSON object to make accessing it easier
                // Output to the console uploaded_image
                var image_url = uploaded_image.toJSON().url;
                var image_id = uploaded_image.toJSON().id;
                // Let's assign the url value to the input field
                selector.parent().find('input[type="text"]').val(image_url);
                selector.parent().find('input[type="hidden"]').val(image_id);
                if (selector.parent().find('.std-image-preview').length > 0) {
                    selector.parent().find('.std-image-preview').html('<img src="' + uploaded_image.toJSON().sizes.thumbnail.url + '"/>');
                }
            });
    });

    /**
     * Shortcode generation through alias
     */
    $('body').on('keyup', '.std-alias-field', function () {
        var alias = $(this).val();
        var shortcode = '[std alias="' + alias + '"]';
        $('.std-shortcode-preview').html(shortcode);
    });



    /**
     * Subscription Form Settings submission
     * 
     */
    $('body').on('submit', '.std-subscription-form', function (e) {
        e.preventDefault();
        var form_action = ($(this).data('form-action')) ? $(this).data('form-action') : 'std_form_save_action';
        if (form_action != 'std_settings_save_action') {
            tinymce.triggerSave();
        }
        var selector = $(this);
        var form_data = $(this).serialize();
        $.ajax({
            type: 'post',
            url: std_backend_obj.ajax_url,
            data: {
                action: form_action,
                _wpnonce: std_backend_obj.ajax_nonce,
                form_data: form_data
            },
            beforeSend: function (xhr) {
                std_generate_info(translation_strings.ajax_message, 'ajax');
            },
            success: function (res) {
                res = $.parseJSON(res);
                if (res.status == 200) {
                    std_generate_info(res.message, 'info');
                    if (res.redirect_url) {
                        window.location = res.redirect_url;
                        exit;
                    }
                } else {
                    std_generate_info(res.message, 'error');
                }
            }
        });
    });

    /**
     * Subscription Form Delete
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-form-delete', function () {
        if (confirm(translation_strings.delete_form_confirm)) {
            var selector = $(this);
            var form_id = $(this).data('form-id');
            $.ajax({
                type: 'post',
                url: std_backend_obj.ajax_url,
                data: {
                    action: 'std_form_delete_action',
                    form_id: form_id,
                    _wpnonce: std_backend_obj.ajax_nonce,
                },
                beforeSend: function (xhr) {
                    std_generate_info(translation_strings.ajax_message, 'ajax');
                },
                success: function (res) {
                    res = $.parseJSON(res);
                    if (res.status == 200) {
                        std_generate_info(res.message, 'info');
                        selector.closest('tr').fadeOut(500, function () {
                            $(this).remove();
                        });
                    } else {
                        std_generate_info(res.message, 'error');
                    }
                }
            });
        }
    });
    /**
     * Subscription Form Copy
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-form-copy', function () {
        if (confirm(translation_strings.copy_form_confirm)) {
            var selector = $(this);
            var form_id = $(this).data('form-id');
            $.ajax({
                type: 'post',
                url: std_backend_obj.ajax_url,
                data: {
                    action: 'std_form_copy_action',
                    form_id: form_id,
                    _wpnonce: std_backend_obj.ajax_nonce,
                },
                beforeSend: function (xhr) {
                    std_generate_info(translation_strings.ajax_message, 'ajax');
                },
                success: function (res) {
                    res = $.parseJSON(res);
                    if (res.status == 200) {
                        std_generate_info(res.message, 'info');
                        std_generate_info(res.message, 'info');
                        if (res.redirect_url) {
                            window.location = res.redirect_url;
                            exit;
                        }
                    } else {
                        std_generate_info(res.message, 'error');
                    }
                }
            });
        }
    });

    /**
     * Subscriber alias filter
     * 
     * @since 1.0.0
     */
    $('body').on('change', '.std-export-alias-trigger', function () {
        $(this).closest('form').submit();
    });

    /**
     * Shortcode clipboard copy
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-clipboard-copy', function () {
        var copy_element = $(this).parent().find('.std-shortcode-preview').select();
        std_copyToClipboard(copy_element);
        std_generate_info(translation_strings.clipboad_copy_message, 'info');
    });

    /**
     * Show hide toggle
     * 
     * @since 1.0.0
     */
    $('body').on('change', '.std-toggle-trigger', function () {

        var toggle_ref = $(this).val();
        var toggle_class = $(this).data('toggle-class');
        $('.' + toggle_class).hide();
        $('.' + toggle_class + '[data-toggle-ref="' + toggle_ref + '"]').show();

    });

    /**
     * Color Picker Initialization
     * 
     * @since 1.0.0
     */
    $('.std-color-picker').wpColorPicker();

    $('.std-field input[type="checkbox"]').each(function () {
        if (!$(this).parent().hasClass('std-checkbox-toggle') && !$(this).hasClass('std-disable-checkbox-toggle')) {
            var input_name = $(this).attr('name');
            $(this).parent().addClass('std-checkbox-toggle');
            $('<label></label>').insertAfter($(this));
        }
    });


    /**
     * Form save trigger 
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-form-save-trigger', function () {
        $('.std-subscription-form').submit();
    });

    /**
     * Mailchimp connect trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-mailchimp-connect', function () {
        $('.std-mailchimp-api-response').slideUp(500);
        var mailchimp_api_key = $('.std-mailchimp-api-key').val();
        var api_pattern = /^[0-9a-zA-Z*]{32}-[a-z]{2}[0-9]{1,2}$/;
        if (api_pattern.test(mailchimp_api_key)) {
            $.ajax({
                type: 'post',
                url: std_backend_obj.ajax_url,
                data: {
                    action: 'std_mailchimp_connect_action',
                    api_key: mailchimp_api_key,
                    _wpnonce: std_backend_obj.ajax_nonce,
                },
                beforeSend: function (xhr) {
                    std_generate_info(translation_strings.ajax_message, 'ajax');
                },
                success: function (res) {
                    res = $.parseJSON(res);
                    if (res.status == 200) {
                        std_generate_info(res.message, 'info');
                        std_generate_info(res.message, 'info');
                        var list_template = wp.template('mc-lists');
                        $('.std-mailchimp-lists-wrap').html(list_template(res.api_response));
                        $('.std-mailchimp-lists-input').val(res.api_raw_response);
                        $('.std-mailchimp-status-flag').val(1);
                        $('.std-mailchimp-status').html(translation_strings.mc_connect);
                        $('.std-mailchimp-status').removeClass('std-mc-disconnected').addClass('std-mc-connected');
                    } else {
                        std_generate_info(res.message, 'error');
                        $('.std-mailchimp-lists-wrap').html('');
                        $('.std-mailchimp-lists-input').val('');
                        $('.std-mailchimp-status-flag').val(0);
                        $('.std-mailchimp-status').html(translation_strings.mc_disconnect);
                        $('.std-mailchimp-status').removeClass('std-mc-connected').addClass('std-mc-disconnected');
                        if (res.api_response) {
                            $('.std-mailchimp-api-response').html(JSON.stringify(res.api_response)).show();
                        }
                    }
                }
            });
        } else {
            std_generate_info(translation_strings.invalid_api_key, 'error');
        }
    });
    /**
     * Mailerlite connect trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-mailerlite-connect', function () {
        $('.std-mailerlite-api-response').slideUp(500);
        var mailerlite_api_key = $('.std-mailerlite-api-key').val();


        $.ajax({
            type: 'post',
            url: std_backend_obj.ajax_url,
            data: {
                action: 'std_mailerlite_connect_action',
                api_key: mailerlite_api_key,
                _wpnonce: std_backend_obj.ajax_nonce,
            },
            beforeSend: function (xhr) {
                std_generate_info(translation_strings.ajax_message, 'ajax');
            },
            success: function (res) {
                res = $.parseJSON(res);
                if (res.status == 200) {
                    std_generate_info(res.message, 'info');
                    std_generate_info(res.message, 'info');
                    var group_template = wp.template('ml-groups');
                    $('.std-mailerlite-lists-wrap').html(group_template(res.api_response));
                    $('.std-mailerlite-lists-input').val(res.api_raw_response);
                    $('.std-mailerlite-status-flag').val(1);
                    $('.std-mailerlite-status').html(translation_strings.ml_connect);
                    $('.std-mailerlite-status').removeClass('std-ml-disconnected').addClass('std-ml-connected');
                } else {
                    std_generate_info(res.message, 'error');
                    $('.std-mailerlite-lists-wrap').html('');
                    $('.std-mailerlite-lists-input').val('');
                    $('.std-mailerlite-status-flag').val(0);
                    $('.std-mailerlite-status').html(translation_strings.ml_disconnect);
                    $('.std-mailerlite-status').removeClass('std-ml-connected').addClass('std-ml-disconnected');
                    if (res.api_response) {
                        $('.std-mailerlite-api-response').html(JSON.stringify(res.api_response)).show();
                    }
                }
            }
        });

    });
    /**
     * Sendinblue connect trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-sendinblue-connect', function () {
        $('.std-sendinblue-api-response').slideUp(500);
        var sendinblue_api_key = $('.std-sendinblue-api-key').val();


        $.ajax({
            type: 'post',
            url: std_backend_obj.ajax_url,
            data: {
                action: 'std_sendinblue_connect_action',
                api_key: sendinblue_api_key,
                _wpnonce: std_backend_obj.ajax_nonce,
            },
            beforeSend: function (xhr) {
                std_generate_info(translation_strings.ajax_message, 'ajax');
            },
            success: function (res) {
                res = $.parseJSON(res);
                if (res.status == 200) {
                    std_generate_info(res.message, 'info');
                    std_generate_info(res.message, 'info');
                    var list_template = wp.template('mc-lists');
                    $('.std-sendinblue-lists-wrap').html(list_template(res.api_response));
                    $('.std-sendinblue-lists-input').val(res.api_raw_response);
                    $('.std-sendinblue-status-flag').val(1);
                    $('.std-sendinblue-status').html(translation_strings.mc_connect);
                    $('.std-sendinblue-status').removeClass('std-sib-disconnected').addClass('std-sib-connected');
                } else {
                    std_generate_info(res.message, 'error');
                    $('.std-sendinblue-lists-wrap').html('');
                    $('.std-sendinblue-lists-input').val('');
                    $('.std-sendinblue-status-flag').val(0);
                    $('.std-sendinblue-status').html(translation_strings.mc_disconnect);
                    $('.std-sendinblue-status').removeClass('std-sib-connected').addClass('std-sib-disconnected');
                    if (res.api_response) {
                        $('.std-sendinblue-api-response').html(JSON.stringify(res.api_response)).show();
                    }
                }
            }
        });

    });

    /**
     * Convertkit connect trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-convertkit-connect', function () {
        $('.std-convertkit-api-response').slideUp(500);
        var convertkit_api_key = $('.std-convertkit-api-key').val();


        $.ajax({
            type: 'post',
            url: std_backend_obj.ajax_url,
            data: {
                action: 'std_convertkit_connect_action',
                api_key: convertkit_api_key,
                _wpnonce: std_backend_obj.ajax_nonce,
            },
            beforeSend: function (xhr) {
                std_generate_info(translation_strings.ajax_message, 'ajax');
            },
            success: function (res) {
                res = $.parseJSON(res);
                if (res.status == 200) {
                    std_generate_info(res.message, 'info');
                    std_generate_info(res.message, 'info');
                    var group_template = wp.template('ck-forms');
                    $('.std-convertkit-lists-wrap').html(group_template(res.api_response));
                    $('.std-convertkit-lists-input').val(res.api_raw_response);
                    $('.std-convertkit-status-flag').val(1);
                    $('.std-convertkit-status').html(translation_strings.ml_connect);
                    $('.std-convertkit-status').removeClass('std-disconnected').addClass('std-connected');
                } else {
                    std_generate_info(res.message, 'error');
                    $('.std-convertkit-lists-wrap').html('');
                    $('.std-convertkit-lists-input').val('');
                    $('.std-convertkit-status-flag').val(0);
                    $('.std-convertkit-status').html(translation_strings.ml_disconnect);
                    $('.std-convertkit-status').removeClass('std-connected').addClass('std-disconnected');
                    if (res.api_response) {
                        $('.std-convertkit-api-response').html(JSON.stringify(res.api_response)).show();
                    }
                }
            }
        });

    });

    /**
     * Resets mailchimp connection trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-mailchimp-reset', function () {
        if (confirm(translation_strings.mc_reset)) {
            $('.std-mailchimp-lists-wrap').html('');
            $('.std-mailchimp-lists-input').val('');
            $('.std-mailchimp-status-flag').val(0);
            $('.std-mailchimp-status').html(translation_strings.mc_disconnect);
            $('.std-mailchimp-status').removeClass('std-mc-connected').addClass('std-mc-disconnected');
        }
    });
    /**
     * Resets convertkit connection trigger
     * 
     * @since 2.0.4
     */
    $('body').on('click', '.std-convertkit-reset', function () {
        if (confirm(translation_strings.ck_reset)) {
            $('.std-convertkit-lists-wrap').html('');
            $('.std-convertkit-lists-input').val('');
            $('.std-convertkit-status-flag').val(0);
            $('.std-convertkit-status').html(translation_strings.mc_disconnect);
            $('.std-convertkit-status').removeClass('std-connected').addClass('std-disconnected');
        }
    });
    /**
     * Resets mailerlite connection trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-mailerlite-reset', function () {
        if (confirm(translation_strings.ml_reset)) {
            $('.std-mailerlite-lists-wrap').html('');
            $('.std-mailerlite-lists-input').val('');
            $('.std-mailerlite-status-flag').val(0);
            $('.std-mailerlite-status').html(translation_strings.mc_disconnect);
            $('.std-mailerlite-status').removeClass('std-ml-connected').addClass('std-ml-disconnected');
        }
    });
    /**
     * Resets sendinblue connection trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-sendinblue-reset', function () {
        if (confirm(translation_strings.sib_reset)) {
            $('.std-sendinblue-lists-wrap').html('');
            $('.std-sendinblue-lists-input').val('');
            $('.std-sendinblue-status-flag').val(0);
            $('.std-sendinblue-status').html(translation_strings.mc_disconnect);
            $('.std-sendinblue-status').removeClass('std-sib-connected').addClass('std-sib-disconnected');
        }
    });

    $('body').on('click', '.std-checkbox-toggle-trigger', function () {
        var toggle_class = $(this).data('toggle-class');
        var toggle_type = ($(this).data('toggle-type')) ? $(this).data('toggle-type') : 'on';
        switch (toggle_type) {
            case 'on':
                if ($(this).is(':checked')) {
                    $('.' + toggle_class).show();
                } else {
                    $('.' + toggle_class).hide();
                }
                break;
            case 'off':
                if ($(this).is(':checked')) {
                    $('.' + toggle_class).hide();
                } else {
                    $('.' + toggle_class).show();

                }
                break;
        }

    });

    /**
     * Log clear trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-clear-log-trigger', function () {
        $(this).parent().find('textarea').val('');
    });

    /**
     * Constant Contact connect trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-constant_contact-connect', function () {
        $('.std-constant_contact-api-response').slideUp(500);
        var cc_api_key = $('.std-constant_contact-api-key').val();
        var cc_access_token = $('.std-constant_contact-access-token').val();
        $.ajax({
            type: 'post',
            url: std_backend_obj.ajax_url,
            data: {
                action: 'std_constant_contact_connect_action',
                api_key: cc_api_key,
                access_token: cc_access_token,
                _wpnonce: std_backend_obj.ajax_nonce,
            },
            beforeSend: function (xhr) {
                std_generate_info(translation_strings.ajax_message, 'ajax');
            },
            success: function (res) {
                res = $.parseJSON(res);
                if (res.status == 200) {
                    std_generate_info(res.message, 'info');
                    std_generate_info(res.message, 'info');
                    var list_template = wp.template('mc-lists');
                    $('.std-constant_contact-lists-wrap').html(list_template(res.api_response));
                    $('.std-constant_contact-lists-input').val(res.api_raw_response);
                    $('.std-constant_contact-status-flag').val(1);
                    $('.std-constant_contact-status').html(translation_strings.mc_connect);
                    $('.std-constant_contact-status').removeClass('std-cc-disconnected').addClass('std-cc-connected');
                } else {
                    std_generate_info(res.message, 'error');
                    $('.std-constant_contact-lists-wrap').html('');
                    $('.std-constant_contact-lists-input').val('');
                    $('.std-constant_contact-status-flag').val(0);
                    $('.std-constant_contact-status').html(translation_strings.mc_disconnect);
                    $('.std-constant_contact-status').removeClass('std-cc-connected').addClass('std-cc-disconnected');
                    if (res.api_response) {
                        $('.std-constant_contact-api-response').html(JSON.stringify(res.api_response)).show();
                    }
                }
            }
        });

    });

    /**
     * Resets constant contact connection trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-constant_contact-reset', function () {
        if (confirm(translation_strings.cc_reset)) {
            $('.std-constant_contact-lists-wrap').html('');
            $('.std-constant_contact-lists-input').val('');
            $('.std-constant_contact-status-flag').val(0);
            $('.std-constant_contact-status').html(translation_strings.mc_disconnect);
            $('.std-constant_contact-status').removeClass('std-cc-connected').addClass('std-cc-disconnected');
        }
    });
    /**
     * Resets constant contact connection trigger
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-constant_contact_v3-reset', function () {
        if (confirm(translation_strings.cc_reset)) {
            $('.std-constant_contact-lists-wrap').html('');
            $('.std-constant_contact-lists-input').val('');
            $('.std-constant_contact-status-flag').val(0);
            $('.std-constant_contact-status').html(translation_strings.mc_disconnect);
            $('.std-constant_contact-status').removeClass('std-cc-connected').addClass('std-cc-disconnected');
        }
    });

    /**
     * Deletes subscriber
     * 
     * @since 1.0.0
     */
    /**
     * Subscription Form Delete
     * 
     * @since 1.0.0
     */
    $('body').on('click', '.std-subscriber-delete', function () {
        if (confirm(translation_strings.delete_subscriber_confirm)) {
            var selector = $(this);
            var subscriber_id = $(this).data('subscriber-id');
            $.ajax({
                type: 'post',
                url: std_backend_obj.ajax_url,
                data: {
                    action: 'std_subscriber_delete_action',
                    subscriber_id: subscriber_id,
                    _wpnonce: std_backend_obj.ajax_nonce,
                },
                beforeSend: function (xhr) {
                    std_generate_info(translation_strings.ajax_message, 'ajax');
                },
                success: function (res) {
                    res = $.parseJSON(res);
                    if (res.status == 200) {
                        std_generate_info(res.message, 'info');
                        selector.closest('tr').fadeOut(500, function () {
                            $(this).remove();
                        });
                    } else {
                        std_generate_info(res.message, 'error');
                    }
                }
            });
        }
    });

    $('body').on('keyup', 'input[name="form_title"]', function () {
        var form_title = $(this).val();
        var form_alias = std_title_to_alias(form_title);
        if ($('input[name="form_alias"]').attr('readonly') != 'readonly') {
            $('input[name="form_alias"]').val(form_alias);

        }
    });

    $('body').on('keyup', 'input[name="form_alias"]', function () {
        var form_alias = $(this).val();
        form_alias = std_title_to_alias(form_alias);

        if ($(this).attr('readonly') != 'readonly') {
            $(this).val(form_alias);

        }
    });

    $('body').on('click', '.std-alias-force-edit', function () {
        $(this).parent().find('input[type="text"]').removeAttr('readonly');
    });

    $('body').on('click', '.std-domain-add-trigger', function () {
        var domain_template = wp.template('email-domain');
        $('.std-unallowed-email-domains-list').append(domain_template());
    });

    $('body').on('click', '.std-remove-domain-trigger', function () {
        $(this).parent().remove();
    });

    $('body').on('click', '.std-unsubscribe-link', function () {
        var copy_element = $(this).closest('td').find('.std-unsubscribe-link-ref').select();
        std_copyToClipboard(copy_element);
        std_generate_info(translation_strings.unsubscribe_clipboad_copy_message, 'info');
    });

    $('body').on('click', '.std-instant-download-trigger', function () {
        if ($(this).is(':checked')) {
            $('.std-instant-download-button-label').show();
        } else {
            $('.std-instant-download-button-label').hide();
        }
    });
    $('body').on('click', '.std-subscriber-search-wrap .dashicons-search', function () {
        $(this).closest('form').submit();
    });

    $('body').on('click', '.std-custom-field-type-trigger-btn', function () {
        $('.std-custom-field-type-trigger-btn').removeClass('btn-selected');
        $(this).addClass('btn-selected');
        var field_type = $(this).data('field-type');
        $('#std-custom-field-type option').removeAttr('selected');
        $('#std-custom-field-type option[value="' + field_type + '"]').prop('selected', true);
    });

    $('body').on('click', '.std-custom-field-add-trigger', function () {
        var custom_field_label = $('#std-custom-field-label').val();
        var custom_field_key = std_generateString(5);
        if (custom_field_label == '') {
            std_generate_info(translation_strings.custom_field_error, 'error');
        } else {
            var field_type = $('#std-custom-field-type').val();
            var data = { label: custom_field_label, field_key: custom_field_key, field_type: field_type };
            var field_template = wp.template('std-custom-' + field_type);
            $('.std-fields-holder').append(field_template(data));
            std_initialize_checkbox_toggle();
            $('#std-custom-field-label').val('');

            $('.std-form-wrap').animate({
                scrollTop: $('.std-fields-holder .std-form-each-component').last().offset().top + 100
            }, 'slow');
            $('.std-sortable').sortable({
                placeholder: "std-sortable-placeholder",
                forcePlaceholderSize: true
            });
            $('.std-radio-list-wrap').sortable({
                placeholder: "std-sortable-placeholder",
                forcePlaceholderSize: true
            });

        }


    });

    $('body').on('click', '.std-custom-field-trash', function () {
        if (confirm(translation_strings.delete_custom_field)) {
            $(this).closest('.std-form-each-component').remove();
        }
    });

    $('body').on('click', '.std-add-option-trigger', function () {
        var field_key = $(this).data('field-key');
        var field_type = $(this).data('field-type');
        var option_html = wp.template('std-radio-button-list');
        $(this).parent().find('.std-radio-list-wrap').append(option_html({ field_type: field_type, field_key: field_key }));

    });

    $('body').on('click', '.std-delete-dropdown-trigger', function () {
        if (confirm(translation_strings.delete_option)) {
            $(this).parent().remove();
        }
    });

    /**
    * Show hide toggle for Select and Radio
    * 
    * @since 1.0.0
    */
    $('body').on('change', '.std-toggle-trigger', function () {

        var toggle_ref = $(this).val();
        var toggle_class = $(this).data('toggle-class');
        $('.' + toggle_class).hide();
        $('.' + toggle_class + '[data-toggle-ref="' + toggle_ref + '"]').show();

    });

    $('body').on('click', '.std-checked-radio-ref', function () {
        $(this).closest('.std-radio-list-wrap').find('.std-checked-radio-val').val(0);
        if ($(this).is(':checked')) {
            $(this).next('input[type="hidden"]').val(1);
        } else {
            $(this).next('input[type="hidden"]').val(0);
        }
    });


});


