"use strict";

var iwbvelWpEditorSettings = {
    mediaButtons: true,
    tinymce: {
        branding: false,
        theme: 'modern',
        skin: 'lightgray',
        language: 'en',
        formats: {
            alignleft: [
                { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: { textAlign: 'left' } },
                { selector: 'img,table,dl.wp-caption', classes: 'alignleft' }
            ],
            aligncenter: [
                { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: { textAlign: 'center' } },
                { selector: 'img,table,dl.wp-caption', classes: 'aligncenter' }
            ],
            alignright: [
                { selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: { textAlign: 'right' } },
                { selector: 'img,table,dl.wp-caption', classes: 'alignright' }
            ],
            strikethrough: { inline: 'del' }
        },
        relative_urls: false,
        remove_script_host: false,
        convert_urls: false,
        browser_spellcheck: true,
        fix_list_elements: true,
        entities: '38,amp,60,lt,62,gt',
        entity_encoding: 'raw',
        keep_styles: false,
        paste_webkit_styles: 'font-weight font-style color',
        preview_styles: 'font-family font-size font-weight font-style text-decoration text-transform',
        end_container_on_empty_block: true,
        wpeditimage_disable_captions: false,
        wpeditimage_html5_captions: true,
        plugins: 'charmap,colorpicker,hr,lists,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpautoresize,wpeditimage,wpemoji,wpgallery,wplink,wpdialogs,wptextpattern,wpview',
        menubar: false,
        wpautop: true,
        indent: false,
        resize: true,
        theme_advanced_resizing: true,
        theme_advanced_resize_horizontal: false,
        statusbar: true,
        toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,wp_adv',
        toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help',
        toolbar3: '',
        toolbar4: '',
        tabfocus_elements: ':prev,:next',
    },
    quicktags: {
        buttons: "strong,em,link,block,del,ins,img,ul,ol,li,code,more,close"
    }
}

jQuery(document).ready(function ($) {
    $(document).on('click', '.iwbvel-timepicker, .iwbvel-datetimepicker, .iwbvel-datepicker', function () {
        $(this).attr('data-val', $(this).val());
    });

    iwbvelReInitDatePicker();
    iwbvelReInitColorPicker();

    // Select2
    if ($.fn.select2) {
        let iwbvelSelect2 = $(".iwbvel-select2");
        if (iwbvelSelect2.length) {
            iwbvelSelect2.select2({
                placeholder: "Select ..."
            });
        }
    }

    $(document).on("click", ".iwbvel-tabs-list li a.iwbvel-tab-item", function (event) {
        if ($(this).attr('data-disabled') !== 'true') {
            event.preventDefault();

            if ($(this).closest('.iwbvel-tabs-list').attr('data-type') == 'url') {
                window.location.hash = $(this).attr('data-content');
            }

            iwbvelOpenTab($(this));
        }
    });

    // Modal
    $(document).on("click", '[data-toggle="modal"]', function () {
        iwbvelOpenModal($(this).attr("data-target"));
    });

    $(document).on("click", '[data-toggle="modal-close"]', function () {
        iwbvelCloseModal();
    });

    // Float side modal
    $(document).on("click", '[data-toggle="float-side-modal"]', function () {
        iwbvelOpenFloatSideModal($(this).attr("data-target"));
    });

    $(document).on("click", '[data-toggle="float-side-modal-close"]', function () {
        if ($('.iwbvel-float-side-modal:visible').length && $('.iwbvel-float-side-modal:visible').hasClass('iwbvel-float-side-modal-close-with-confirm')) {
            swal({
                title: 'Are you sure?',
                type: "warning",
                showCancelButton: true,
                cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
                confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
                confirmButtonText: iwbvelTranslate.iAmSure,
                closeOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    $('.iwbvel-float-side-modal:visible').removeClass('iwbvel-float-side-modal-close-with-confirm');
                    iwbvelCloseFloatSideModal();
                }
            });
        } else {
            iwbvelCloseFloatSideModal();
        }
    });

    $(document).on("keyup", function (e) {
        if (e.keyCode === 27) {
            if (jQuery('.iwbvel-modal:visible').length > 0) {
                iwbvelCloseModal();
            } else {
                if ($('.iwbvel-float-side-modal:visible').length && $('.iwbvel-float-side-modal:visible').hasClass('iwbvel-float-side-modal-close-with-confirm')) {
                    swal({
                        title: ($('.iwbvel-float-side-modal:visible').attr('data-confirm-message') && $('.iwbvel-float-side-modal:visible').attr('data-confirm-message') != '') ? $('.iwbvel-float-side-modal:visible').attr('data-confirm-message') : 'Are you sure?',
                        type: "warning",
                        showCancelButton: true,
                        cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
                        confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
                        confirmButtonText: iwbvelTranslate.iAmSure,
                        closeOnConfirm: true
                    }, function (isConfirm) {
                        if (isConfirm) {
                            $('.iwbvel-float-side-modal:visible').removeClass('iwbvel-float-side-modal-close-with-confirm');
                            iwbvelCloseFloatSideModal();
                        }
                    });
                } else {
                    if (!$('.iwbvel-float-side-modal:visible').hasClass('iwbvel-disable-esc-for-close')) {
                        iwbvelCloseFloatSideModal();
                    }
                }
            }

            $("[data-type=edit-mode]").each(function () {
                $(this).closest("span").html($(this).attr("data-val"));
            });

            if ($("#iwbvel-filter-form-content").css("display") === "block") {
                $("#iwbvel-bulk-edit-filter-form-close-button").trigger("click");
            }
        }
    });

    // Color Picker Style
    $(document).on("change", "input[type=color]", function () {
        this.parentNode.style.backgroundColor = this.value;
    });

    $(document).on('click', '#iwbvel-full-screen', function () {
        if ($('#adminmenuback').css('display') === 'block') {
            openFullscreen();
        } else {
            exitFullscreen();
        }
    });

    if (document.addEventListener) {
        document.addEventListener('fullscreenchange', iwbvelFullscreenHandler, false);
        document.addEventListener('mozfullscreenchange', iwbvelFullscreenHandler, false);
        document.addEventListener('MSFullscreenChange', iwbvelFullscreenHandler, false);
        document.addEventListener('webkitfullscreenchange', iwbvelFullscreenHandler, false);
    }

    $(document).on("click", ".iwbvel-top-nav-duplicate-button", function () {
        let itemIds = $("input.iwbvel-check-item:visible:checkbox:checked").map(function () {
            if ($(this).attr('data-item-type') === 'variation') {
                swal({
                    title: "Duplicate for variations product is disabled !",
                    type: "warning"
                });
            } else {
                return $(this).val();
            }
        }).get();

        if (!itemIds.length) {
            swal({
                title: $('input.iwbvel-check-item[data-item-type="variation"]:visible:checkbox:checked') ? "Duplicate for variations product is disabled !" : "Please select one product",
                type: "warning"
            });
            return false;
        } else {
            iwbvelOpenModal('#iwbvel-modal-item-duplicate');
        }
    });

    // Select Items (Checkbox) in table
    $(document).on("change", ".iwbvel-check-item-main", function () {
        let checkbox_items = $(".iwbvel-check-item");
        if ($(this).prop("checked") === true) {
            checkbox_items.prop("checked", true);
            $("#iwbvel-items-list tr").addClass("iwbvel-tr-selected");
            checkbox_items.each(function () {
                $("#iwbvel-export-items-selected").append("<input type='hidden' name='item_ids[]' value='" + $(this).val() + "'>");
            });
            iwbvelShowSelectionTools();
            $("#iwbvel-export-only-selected-items").prop("disabled", false);
        } else {
            checkbox_items.prop("checked", false);
            $("#iwbvel-items-list tr").removeClass("iwbvel-tr-selected");
            $("#iwbvel-export-items-selected").html("");
            iwbvelHideSelectionTools();
            $("#iwbvel-export-only-selected-items").prop("disabled", true);
            $("#iwbvel-export-all-items-in-table").prop("checked", true);
        }
    });

    $(document).on("change", ".iwbvel-check-item", function () {
        if ($(this).prop("checked") === true) {
            $("#iwbvel-export-items-selected").append("<input type='hidden' name='item_ids[]' value='" + $(this).val() + "'>");
            $(this).closest("tr").addClass("iwbvel-tr-selected");
        } else {
            $("#iwbvel-export-items-selected").find("input[value=" + $(this).val() + "]").remove();
            $(this).closest("tr").removeClass("iwbvel-tr-selected");
        }

        iwbvelCheckSelectAllStatus();

        // Disable and enable "Only Selected items" in "Import/Export"
        if ($(".iwbvel-check-item:checkbox:checked").length > 0) {
            $("#iwbvel-export-only-selected-items").prop("disabled", false);
            iwbvelShowSelectionTools();
        } else {
            iwbvelHideSelectionTools();
            $("#iwbvel-export-only-selected-items").prop("disabled", true);
            $("#iwbvel-export-all-items-in-table").prop("checked", true);
        }
    });

    $(document).on("click", "#iwbvel-bulk-edit-unselect", function () {
        $("input.iwbvel-check-item").prop("checked", false);
        $("input.iwbvel-check-item-main").prop("checked", false);
        iwbvelHideSelectionTools();
    });

    // Start "Column Profile"
    $(document).on("change", "#iwbvel-column-profiles-choose", function () {
        let preset = $(this).val();
        $('.iwbvel-column-profiles-fields input[type="checkbox"]').prop('checked', false);
        $('#iwbvel-column-profile-select-all').prop('checked', false);
        $('.iwbvel-column-profile-select-all span').text('Select All');
        $("#iwbvel-column-profiles-apply").attr("data-preset-key",);
        if (defaultPresets && $.inArray(preset, defaultPresets) === -1) {
            $("#iwbvel-column-profiles-update-changes").show();
        } else {
            $("#iwbvel-column-profiles-update-changes").hide();
        }

        if (columnPresetsFields && columnPresetsFields[preset]) {
            columnPresetsFields[preset].forEach(function (val) {
                $('.iwbvel-column-profiles-fields input[type="checkbox"][value="' + val + '"]').prop('checked', true);
            });
        }
    });

    $(document).on("keyup", "#iwbvel-column-profile-search", function () {
        let iwbvelSearchFieldValue = $(this).val().toLowerCase().trim();
        $(".iwbvel-column-profile-fields ul li").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(iwbvelSearchFieldValue) > -1);
        });
    });

    $(document).on('change', '#iwbvel-column-profile-select-all', function () {
        if ($(this).prop('checked') === true) {
            $(this).closest('label').find('span').text('Unselect');
            $('.iwbvel-column-profile-fields input:checkbox:visible').prop('checked', true);
        } else {
            $(this).closest('label').find('span').text('Select All');
            $('.iwbvel-column-profile-fields input:checkbox').prop('checked', false);
        }
        $(".iwbvel-column-profile-save-dropdown").show();
    });
    // End "Column Profile"

    // Calculator for numeric TD
    $(document).on({
        mouseenter: function () {
            $(this)
                .children(".iwbvel-calculator")
                .show();
        },
        mouseleave: function () {
            $(this)
                .children(".iwbvel-calculator")
                .hide();
        }
    },
        "td[data-content-type=regular_price], td[data-content-type=sale_price], td[data-content-type=numeric]"
    );

    // delete items button
    $(document).on("click", ".iwbvel-bulk-edit-delete-item", function () {
        $(this).find(".iwbvel-bulk-edit-delete-item-buttons").slideToggle(200);
    });

    $(document).on("change", ".iwbvel-column-profile-fields input:checkbox", function () {
        $(".iwbvel-column-profile-save-dropdown").show();
    });

    $(document).on("click", ".iwbvel-column-profile-save-dropdown", function () {
        $(this).find(".iwbvel-column-profile-save-dropdown-buttons").slideToggle(200);
    });

    $('#wp-admin-bar-root-default').append('<li id="wp-admin-bar-iwbvel-col-view"></li>');

    $(document).on({
        mouseenter: function () {
            $('#wp-admin-bar-iwbvel-col-view').html('#' + $(this).attr('data-item-id') + ' | ' + $(this).attr('data-item-title') + ' [<span class="iwbvel-col-title">' + $(this).attr('data-col-title') + '</span>] ');
        },
        mouseleave: function () {
            $('#wp-admin-bar-iwbvel-col-view').html('');
        }
    },
        "#iwbvel-items-list td"
    );

    $(document).on("click", ".iwbvel-open-uploader", function (e) {
        let target = $(this).attr("data-target");
        let element = $(this).closest('div');
        let type = $(this).attr("data-type");
        let mediaUploader;
        let iwbvelNewImageElementID = $(this).attr("data-id");
        let iwbvelProductID = $(this).attr("data-item-id");
        e.preventDefault();
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        if (type === "single") {
            mediaUploader = wp.media.frames.file_frame = wp.media({
                title: "Choose Image",
                button: {
                    text: "Choose Image"
                },
                multiple: false
            });
        } else {
            mediaUploader = wp.media.frames.file_frame = wp.media({
                title: "Choose Images",
                button: {
                    text: "Choose Images"
                },
                multiple: true
            });
        }

        mediaUploader.on("select", function () {
            let attachment = mediaUploader.state().get("selection").toJSON();
            if ($(target).length) {
                $(target).val(attachment[0].id);
                if ($(target + '-url').length) {
                    $(target + '-url').val(attachment[0].url);
                }
                if ($(target + '-preview').length) {
                    $(target + '-preview').html('<div><img src="' + attachment[0].url + '" width="43" height="43" alt=""><button type="button" class="iwbvel-bulk-edit-form-remove-image"><i class="iwbvel-icon-x"></i></button></div>');
                }
            } else {
                switch (target) {
                    case "inline-file":
                        $("#url-" + iwbvelNewImageElementID).val(attachment[0].url);
                        break;
                    case "inline-file-custom-field":
                        $("#iwbvel-file-url").val(attachment[0].url);
                        $('#iwbvel-file-id').val(attachment[0].id)
                        break;
                    case "inline-edit":
                        $("#" + iwbvelNewImageElementID).val(attachment[0].url);
                        $("#iwbvel-modal-image button[data-item-id=" + iwbvelProductID + "][data-button-type=save]").attr("data-image-id", attachment[0].id).attr("data-image-url", attachment[0].url).attr('data-height-fixed', 'false');
                        $("[data-image-preview-id=" + iwbvelNewImageElementID + "]").html("<img src='" + attachment[0].url + "' alt='' />").ready(function () {
                            $('#iwbvel-modal-image button[data-button-type="save"]').prop('disabled', false);
                            setTimeout(function () {
                                iwbvelFixModalHeight($("#iwbvel-modal-image"));
                            }, 150)
                        });
                        break;
                    case "variations-inline-edit":
                        $("#iwbvel-variation-thumbnail-modal .iwbvel-inline-image-preview").html("<img src='" + attachment[0].url + "' alt='' />");
                        $('#iwbvel-variation-thumbnail-modal .iwbvel-variations-table-thumbnail-inline-edit-button[data-button-type="save"]').attr("data-image-id", attachment[0].id).attr("data-image-url", attachment[0].url);
                        break;
                    case "inline-edit-gallery":
                        attachment.forEach(function (item) {
                            $("#iwbvel-modal-gallery-items").append('<div class="iwbvel-inline-edit-gallery-item"><img src="' + item.url + '" alt=""><input type="hidden" class="iwbvel-inline-edit-gallery-image-ids" value="' + item.id + '"></div>');
                        });
                        break;
                    case "bulk-edit-image":
                        element.find(".iwbvel-bulk-edit-form-item-image").val(attachment[0].id);
                        element.find(".iwbvel-bulk-edit-form-item-image-preview").html('<div><img src="' + attachment[0].url + '" width="43" height="43" alt=""><button type="button" class="iwbvel-bulk-edit-form-remove-image"><i class="iwbvel-icon-x"></i></button></div>');
                        break;
                    case "variations-bulk-actions-image":
                        element.find(".iwbvel-variations-bulk-actions-image").val(attachment[0].id);
                        element.find(".iwbvel-variations-bulk-actions-image-preview").html('<div><img src="' + attachment[0].url + '" width="43" height="43" alt=""><button type="button" class="iwbvel-variations-bulk-actions-remove-image"><i class="iwbvel-icon-x"></i></button></div>');
                        break;
                    case "variations-bulk-actions-file":
                        element.find(".iwbvel-variation-bulk-actions-file-item-url-input").val(attachment[0].url);
                        break;
                    case "bulk-edit-file":
                        element.find(".iwbvel-bulk-edit-form-item-file").val(attachment[0].id);
                        break;
                    case "bulk-edit-gallery":
                        attachment.forEach(function (item) {
                            $(".iwbvel-bulk-edit-form-item-gallery").append('<input type="hidden" value="' + item.id + '" data-field="value">');
                            $(".iwbvel-bulk-edit-form-item-gallery-preview").append('<div><img src="' + item.url + '" width="43" height="43" alt=""><button type="button" data-id="' + item.id + '" class="iwbvel-bulk-edit-form-remove-gallery-item"><i class="iwbvel-icon-x"></i></button></div>');
                        });
                        break;
                }
            }
        });
        mediaUploader.open();
    });

    $(document).on("click", ".iwbvel-inline-edit-gallery-image-item-delete", function () {
        $(this).closest("div").remove();
    });

    $(document).on("change", ".iwbvel-column-manager-check-all-fields-btn input:checkbox", function () {
        if ($(this).prop("checked")) {
            $(this).closest("label").find("span").addClass("selected").text("Unselect");
            $(".iwbvel-column-manager-available-fields[data-action=" + $(this).closest("label").attr("data-action") + "] li:visible").each(function () {
                $(this).find("input:checkbox").prop("checked", true);
            });
        } else {
            $(this).closest("label").find("span").removeClass("selected").text("Select All");
            $(".iwbvel-column-manager-available-fields[data-action=" + $(this).closest("label").attr("data-action") + "] li:visible input:checked").prop("checked", false);
        }
    });

    $(document).on("click", ".iwbvel-column-manager-add-field", function () {
        let fieldName = [];
        let fieldLabel = [];
        let action = $(this).attr("data-action");
        let checked = $(".iwbvel-column-manager-available-fields[data-action=" + action + "] input[data-type=field]:checkbox:checked");
        if (checked.length > 0) {
            $('.iwbvel-column-manager-empty-text').hide();
            if (action === 'new') {
                $('.iwbvel-column-manager-added-fields-wrapper .iwbvel-box-loading').show();
            } else {
                $('#iwbvel-modal-column-manager-edit-preset .iwbvel-box-loading').show();
            }
            checked.each(function (i) {
                fieldName[i] = $(this).attr("data-name");
                fieldLabel[i] = $(this).val();
            });
            iwbvelColumnManagerAddField(fieldName, fieldLabel, action);
        }
    });

    $(".iwbvel-column-manager-delete-preset").on("click", function () {
        var $this = $(this);
        $("#iwbvel_column_manager_delete_preset_key").val($this.val());
        swal({
            title: "Are you sure?",
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
            confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
            confirmButtonText: "Yes, I'm sure !",
            closeOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                $("#iwbvel-column-manager-delete-preset-form").submit();
            }
        });
    });

    $(document).on("keyup", ".iwbvel-column-manager-search-field", function () {
        let iwbvelSearchFieldValue = $(this).val().toLowerCase().trim();
        $(".iwbvel-column-manager-available-fields[data-action=" + $(this).attr("data-action") + "] ul li[data-added=false]").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(iwbvelSearchFieldValue) > -1);
        });
    });

    $(document).on("click", ".iwbvel-column-manager-remove-field", function () {
        $(".iwbvel-column-manager-available-fields[data-action=" + $(this).attr("data-action") + "] li[data-name=" + $(this).attr("data-name") + "]").attr("data-added", "false").show();
        $(this).closest(".iwbvel-column-manager-right-item").remove();
        if ($('.iwbvel-column-manager-added-fields-wrapper .iwbvel-column-manager-right-item').length < 1) {
            $('.iwbvel-column-manager-empty-text').show();
        }
    });

    if ($.fn.sortable) {
        let iwbvelColumnManagerFields = $(".iwbvel-column-manager-added-fields .items");
        iwbvelColumnManagerFields.sortable({
            handle: ".iwbvel-column-manager-field-sortable-btn",
            cancel: ""
        });
        iwbvelColumnManagerFields.disableSelection();

        let iwbvelMetaFieldItems = $(".iwbvel-meta-fields-right");
        iwbvelMetaFieldItems.sortable({
            handle: ".iwbvel-meta-field-item-sortable-btn",
            cancel: ""
        });
        iwbvelMetaFieldItems.disableSelection();
    }

    $(document).on("click", "#iwbvel-add-meta-field-manual", function () {
        $(".iwbvel-meta-fields-empty-text").hide();
        let input = $("#iwbvel-meta-fields-manual_key_name");
        iwbvelAddMetaKeysManual(input.val().toLowerCase());
        input.val("");
    });

    $(document).on("click", "#iwbvel-add-acf-meta-field", function () {
        let input = $("#iwbvel-add-meta-fields-acf");
        if (input.val()) {
            $(".iwbvel-meta-fields-empty-text").hide();
            iwbvelAddACFMetaField(input.val(), input.find('option:selected').text(), input.find('option:selected').attr('data-type'));
            input.val("").change();
        }
    });

    $(document).on("click", ".iwbvel-meta-field-remove", function () {
        $(this).closest(".iwbvel-meta-fields-right-item").remove();
        if ($(".iwbvel-meta-fields-right-item").length < 1) {
            $(".iwbvel-meta-fields-empty-text").show();
        }
    });

    $(document).on("click", ".iwbvel-history-delete-item", function () {
        $("#iwbvel-history-clicked-id").attr("name", "delete").val($(this).val());
        swal({
            title: "Are you sure?",
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
            confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
            confirmButtonText: "Yes, I'm sure !",
            closeOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                $("#iwbvel-history-items").submit();
            }
        });
    });

    $(document).on("click", "#iwbvel-history-clear-all-btn", function () {
        swal({
            title: "Are you sure?",
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
            confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
            confirmButtonText: "Yes, I'm sure !",
            closeOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                $("#iwbvel-history-clear-all").submit();
            }
        });
    });

    $(document).on("click", ".iwbvel-history-revert-item", function () {
        $("#iwbvel-history-clicked-id").attr("name", "revert").val($(this).val());
        swal({
            title: "Are you sure?",
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
            confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
            confirmButtonText: "Yes, I'm sure !",
            closeOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                $("#iwbvel-history-items").submit();
            }
        });
    });

    $(document).on('click', '.iwbvel-modal', function (e) {
        if ($(e.target).hasClass('iwbvel-modal') || $(e.target).hasClass('iwbvel-modal-container') || $(e.target).hasClass('iwbvel-modal-box')) {
            iwbvelCloseModal();
        }
    });

    $(document).on("change", 'select[data-field="operator"]', function () {
        if ($(this).val() === "number_formula") {
            $(this).closest("div").find("input[type=number]").attr("type", "text");
        }
    });

    $(document).on('change', '#iwbvel-filter-form-content [data-field=value], #iwbvel-filter-form-content [data-field=from], #iwbvel-filter-form-content [data-field=to]', function () {
        iwbvelCheckFilterFormChanges();
    });

    $(document).on('change', 'input[type=number][data-field=to]', function () {
        let from = $(this).closest('.iwbvel-form-group').find('input[type=number][data-field=from]');
        if (parseFloat($(this).val()) < parseFloat(from.val())) {
            from.val('').addClass('iwbvel-input-danger').focus();
        }
    });

    $(document).on('change', 'input[type=number][data-field=from]', function () {
        let to = $(this).closest('.iwbvel-form-group').find('input[type=number][data-field=to]');
        if (parseFloat($(this).val()) > parseFloat(to.val())) {
            $(this).val('').addClass('iwbvel-input-danger');
        } else {
            $(this).removeClass('iwbvel-input-danger')
        }
    });

    $(document).on('change', '#iwbvel-switcher', function () {
        iwbvelLoadingStart();
        $('#iwbvel-switcher-form').submit();
    });

    $(document).on('click', 'span[data-target="#iwbvel-modal-image"]', function () {
        let tdElement = $(this).closest('td');
        let modal = $('#iwbvel-modal-image');
        let col_title = tdElement.attr('data-col-title');
        let id = $(this).attr('data-id');
        let image_id = $(this).attr('data-image-id');
        let item_id = tdElement.attr('data-item-id');
        let full_size_url = $(this).attr('data-full-image-src');
        let field = tdElement.attr('data-field');
        let field_type = tdElement.attr('data-field-type');

        $('#iwbvel-modal-image-item-title').text(col_title);
        modal.find('.iwbvel-open-uploader').attr('data-id', id).attr('data-item-id', item_id);
        modal.find('.iwbvel-inline-image-preview').attr('data-image-preview-id', id).html('<img src="' + full_size_url + '" />').ready(function () {
            modal.find('.iwbvel-inline-image-preview img').load(function () {
                iwbvelFixModalHeight(modal);
            });
        });
        modal.find('.iwbvel-image-preview-hidden-input').attr('id', id);
        modal.find('button[data-button-type="save"]').attr('data-item-id', item_id).attr('data-field', field).attr('data-image-url', full_size_url).attr('data-image-id', image_id).attr('data-field-type', field_type).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        modal.find('button[data-button-type="remove"]').attr('data-item-id', item_id).attr('data-field', field).attr('data-field-type', field_type).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        modal.find('button[data-button-type="save"]').prop('disabled', true);

        if (image_id == '0') {
            modal.find('button[data-button-type="remove"]').prop('disabled', true);
        } else {
            modal.find('button[data-button-type="remove"]').prop('disabled', false);
        }
    });

    $(document).on('click', '#iwbvel-modal-file-clear', function () {
        let modal = $('#iwbvel-modal-file');
        modal.find('#iwbvel-file-id').val(0).change();
        modal.find('#iwbvel-file-url').val('').change();
    });

    $(document).on('click', '.iwbvel-sub-tab-title', function () {
        $(this).closest('.iwbvel-sub-tab-titles').find('.iwbvel-sub-tab-title').removeClass('active');
        $(this).addClass('active');

        $(this).closest('div').find('.iwbvel-sub-tab-content').hide();
        $(this).closest('div').find('.iwbvel-sub-tab-content[data-content="' + $(this).attr('data-content') + '"]').show();
    });

    if ($('.iwbvel-sub-tab-titles').length > 0) {
        $('.iwbvel-sub-tab-titles').each(function () {
            $(this).find('.iwbvel-sub-tab-title').first().trigger('click');
        });
    }

    $(document).on("mouseenter", ".iwbvel-thumbnail", function () {
        let position = $(this).offset();
        let imageHeight = $(this).find('img').first().height();
        let top = ((position.top - imageHeight) > $('#wpadminbar').offset().top) ? position.top - imageHeight : position.top + 15;

        $('.iwbvel-thumbnail-hover-box').css({
            top: top,
            left: position.left - 100,
            display: 'block',
            height: imageHeight
        }).html($(this).find('.iwbvel-original-thumbnail').clone());
    });

    $(document).on("mouseleave", ".iwbvel-thumbnail", function () {
        $('.iwbvel-thumbnail-hover-box').hide();
    });

    setTimeout(function () {
        $('#iwbvel-column-profiles-choose').trigger('change');
    }, 500);

    $(document).on('click', '.iwbvel-filter-form-action', function () {
        iwbvelFilterFormClose();
    });

    $(document).on('click', '#iwbvel-license-renew-button', function () {
        $(this).closest('#iwbvel-license').find('.iwbvel-license-form').slideDown();
    });

    $(document).on('click', '#iwbvel-license-form-cancel', function () {
        $(this).closest('#iwbvel-license').find('.iwbvel-license-form').slideUp();
    });

    $(document).on('click', '#iwbvel-license-deactivate-button', function () {
        swal({
            title: "Are you sure?",
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
            confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
            confirmButtonText: "Yes, I'm sure !",
            closeOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                $('#iwbvel-license-deactivation-form').submit();
            }
        });
    });

    iwbvelSetTipsyTooltip();

    $(window).on('resize', function () {
        iwbvelDataTableFixSize();
    });

    $(document).on('click', 'body', function (e) {
        if (!$(e.target).hasClass('iwbvel-status-filter-button') && $(e.target).closest('.iwbvel-status-filter-button').length == 0) {
            $('.iwbvel-top-nav-status-filter').hide();
        }

        if (!$(e.target).hasClass('iwbvel-table-item-selector-container') && !$(e.target).closest('.iwbvel-table-item-selector-container').length && $('.iwbvel-table-item-selector-container ul:visible').length) {
            $('.iwbvel-table-item-selector-container ul:visible').fadeOut(50);
        }

        if (!$(e.target).hasClass('iwbvel-quick-filter') && $(e.target).closest('.iwbvel-quick-filter').length == 0) {
            $('.iwbvel-top-nav-filters').hide();
        }

        if (!$(e.target).hasClass('iwbvel-post-type-switcher') && $(e.target).closest('.iwbvel-post-type-switcher').length == 0) {
            $('.iwbvel-top-nav-filters-switcher').hide();
        }

        if (!$(e.target).hasClass('iwbvel-float-side-modal') &&
            !$(e.target).closest('.iwbvel-float-side-modal-box').length &&
            !$('.sweet-overlay:visible').length &&
            !$('.iwbvel-modal:visible').length &&
            $(e.target).attr('data-toggle') != 'float-side-modal' &&
            !$(e.target).closest('.select2-container').length &&
            !$(e.target).is('i') &&
            !$(e.target).hasClass('iwbvel-bulk-edit-form-remove-image') &&
            !$(e.target).hasClass('iwbvel-bulk-edit-custom-field-file-remove-item') &&
            !$(e.target).closest('.media-modal').length &&
            !$(e.target).closest('.sweet-alert').length &&
            !$(e.target).closest('[data-toggle="float-side-modal"]').length &&
            !$(e.target).closest('[data-toggle="float-side-modal-after-confirm"]').length) {
            if ($('.iwbvel-float-side-modal:visible').length && $('.iwbvel-float-side-modal:visible').hasClass('iwbvel-float-side-modal-close-with-confirm')) {
                swal({
                    title: ($('.iwbvel-float-side-modal:visible').attr('data-confirm-message') && $('.iwbvel-float-side-modal:visible').attr('data-confirm-message') != '') ? $('.iwbvel-float-side-modal:visible').attr('data-confirm-message') : 'Are you sure?',
                    type: "warning",
                    showCancelButton: true,
                    cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
                    confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
                    confirmButtonText: iwbvelTranslate.iAmSure,
                    closeOnConfirm: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        $('.iwbvel-float-side-modal:visible').removeClass('iwbvel-float-side-modal-close-with-confirm');
                        iwbvelCloseFloatSideModal();
                    }
                });
            } else {
                iwbvelCloseFloatSideModal();
            }
        }
    });

    $(document).on('click', '.iwbvel-status-filter-button', function () {
        $(this).closest('.iwbvel-status-filter-container').find('.iwbvel-top-nav-status-filter').toggle();
    });

    $(document).on('click', '.iwbvel-quick-filter > a', function (e) {
        if (!$(e.target).closest('.iwbvel-top-nav-filters').length) {
            $('.iwbvel-top-nav-filters').slideToggle(150);
        }
    });
    $(document).on('click', '.iwbvel-post-type-switcher > a', function (e) {
        if (!$(e.target).closest('.iwbvel-top-nav-filters-switcher').length) {
            $('.iwbvel-top-nav-filters-switcher').slideToggle(150);
        }
    });

    $(document).on('click', '.iwbvel-bind-edit-switch', function () {
        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            $('#iwbvel-bind-edit').prop('checked', false);
            $(this).removeClass('active');
        } else {
            $('#iwbvel-bind-edit').prop('checked', true);
            $(this).addClass('active');
        }
    });

    if ($('#iwbvel-bind-edit').prop('checked') === true) {
        $('.iwbvel-bind-edit-switch').addClass('active');
    } else {
        $('.iwbvel-bind-edit-switch').removeClass('active');
    }

    if ($('.iwbvel-flush-message').length) {
        setTimeout(function () {
            $('.iwbvel-flush-message').slideUp();
        }, 3000);
    }

    $(document).on('input', '#iwbvel-top-nav-filters-go-to-page', function () {
        if ($(this).val() == '') {
            return;
        }

        if (parseInt($(this).val()) < parseInt($(this).attr('min'))) {
            $(this).val($(this).attr('min'));
        }

        if (parseInt($(this).val()) > parseInt($(this).attr('max'))) {
            $(this).val($(this).attr('max'));
        }
    });

    $(document).on('click', '.iwbvel-table-item-selector', function () {
        if ($(this).find('ul:visible').length) {
            $(this).find('ul').fadeOut(50);
        } else {
            $(this).find('ul').fadeIn(50);
        }
    });

    $(document).on('click', '.iwbvel-table-item-selector label', function () {
        $(this).find('ul').fadeOut(50);
    });

    $(document).on('change', '.iwbvel-table-item-selector label input:checkbox', function () {
        $('.iwbvel-table-item-selector-checkbox').prop('checked', $(this).prop('checked'));

        if ($(this).val() == 'visible') {
            $('.iwbvel-check-item-main[value="all"]').prop('checked', false);
        } else {
            $('.iwbvel-check-item-main[value="visible"]').prop('checked', false);
        }
    });


    $(document).on("click", '[data-target="#iwbvel-float-side-modal-bulk-new-products"]', function () {
        if ($(this).attr("data-tabs-loaded") != "true") {
            iwbvelBulkNewTabsInit();
        }
    });

    $(document).on("click", ".iwbvel-bulk-edit-delete-duplicate-action", function () {
        let deleteType = $(this).attr("data-delete-type"); // This should be "duplatest_title"
        let alertMessage = "Are you sure you want to delete duplicates?";

        let productIds = $("input.iwbvel-check-item:checkbox:checked")
            .map(function () {
                return $(this).val(); // Get the value of each checked checkbox
            })
            .get(); // Convert jQuery object to a JavaScript array
        swal(
            {
                title: alertMessage,
                type: "warning",
                showCancelButton: true,
                cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
                confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
                confirmButtonText: "Yes, delete duplicates!",
                closeOnConfirm: true,
            },
            function (isConfirm) {
                if (isConfirm) {
                    iwbvelDeleteProduct(productIds, deleteType); // Send the delete type here
                }
            }
        );
        if (productIds.length == 1) {
            swal({
                title: "Please Select More Than One Option!",
                type: "warning",
            });
        }
    });

    $(document).on("click", "#iwbvel-bulk-new-form-do-bulk-new", function () {
        // Get The Quantity Of New Products
        let quantity = $("#iwbvel-bulk-new-form-product-quantity").val();
        if (quantity < 1) {
            swal({
                title: "The 'Quantity' most be one or more!",
                type: "warning",
            });
            return false;
        }

        iwbvelLoadingStart();
        let title = $("#iwbvel-bulk-new-form-product-title").val();
        let slug = $("#iwbvel-bulk-new-form-product-slug").val();
        let sku = $("#iwbvel-bulk-new-form-product-sku").val();
        let description = $("#iwbvel-bulk-new-form-product-description").val();
        let shortDescription = $("#iwbvel-bulk-new-form-product-short-description").val();
        let purchase_note = $("#iwbvel-bulk-new-form-product-purchase-note").val();
        let menu_order = $("#iwbvel-bulk-new-form-product-menu-order").val();
        let sold_individually = $("#iwbvel-bulk-new-form-product-sold-individually").val();
        let reviews_allowed = $("#iwbvel-bulk-new-form-product-enable-reviews").val();
        let status = $("#iwbvel-bulk-new-form-product-product-status").val();
        let catalog_visibility = $("#iwbvel-bulk-new-form-product-catalog-visibility").val();
        let date_created = $("#iwbvel-bulk-new-form-product-date-created").val();
        let author = $("#iwbvel-bulk-new-form-product-author").val();
        let image_id = $(".iwbvel-bulk-edit-form-item-image").val();
        let gallery_image_ids = [];
        $(".iwbvel-bulk-edit-form-item-gallery input[type='hidden']").each(function () {
            let image_ids = $(this).val(); // Get the value of each hidden input
            gallery_image_ids.push(image_ids);
        });
        // Get selected taxonomies from the form
        let taxonomies = {};
        $(".iwbvel-select2-taxonomies").each(function () {
            let taxonomyName = $(this).closest(".iwbvel-form-group").data("name"); // Get taxonomy name
            let selectedValues = $(this).val(); // Get selected values (term IDs or slugs)

            if (selectedValues) {
                taxonomies[taxonomyName] = selectedValues;
            }
        });

        // Get selected attributes from the form
        let attributes = {};
        $(".iwbvel-form-group[data-type='taxonomy']").each(function () {
            let attributeName = $(this).data("name"); // Get attribute name

            // Get selected values (handle multiple selections)
            let selectedValues = $("#iwbvel-bulk-new-form-product-attr-" + attributeName).val() || [];

            let selectedName = $("#iwbvel-bulk-new-form-product-attr-" + attributeName + " option:selected")
                .map(function () {
                    return $(this).text();
                })
                .get();

            // Get visibility and variation usage values
            let isVisible = $("#iwbvel-bulk-new-form-product-attr-is-visible-" + attributeName).val() || "no";
            let usedForVariations = $("#iwbvel-bulk-new-form-product-attr-for-variations-" + attributeName).val() || "no";

            // Store only if there are selected values
            if (selectedValues.length > 0) {
                attributes[attributeName] = {
                    name: selectedName,
                    values: selectedValues,
                    is_visible: isVisible,
                    used_for_variations: usedForVariations,
                };
            }
        });

        // Get the value regular price and round
        let regular_price = $("#iwbvel-bulk-new-form-regular-price").val();
        let round_item_regular_price = $("#iwbvel-bulk-new-form-regular-price-round-item").val();
        //Get the value sales price and round
        let sale_price = $("#iwbvel-bulk-new-form-sale-price").val();
        let round_item_sales_price = $("#iwbvel-bulk-new-form-sale-price-round-item").val();
        //Get the value sale date
        let sale_date_from = $("#iwbvel-bulk-new-form-sale-date-from").val();
        let sale_date_to = $("#iwbvel-bulk-new-form-sale-date-to").val();
        //Get the value of Taxes
        let tax_status = $("#iwbvel-bulk-new-form-tax-status").val();
        let tax_class = $("#iwbvel-bulk-new-form-tax-class").val();
        //Get the value of Shipping
        let shipping_class = $("#iwbvel-bulk-new-form-shipping-class").val();
        let width = $("#iwbvel-bulk-new-form-width").val();
        let height = $("#iwbvel-bulk-new-form-height").val();
        let length = $("#iwbvel-bulk-new-form-length").val();
        let weight = $("#iwbvel-bulk-new-form-weight").val();
        //Get the value of Stock
        let manage_stock = $("#iwbvel-bulk-new-form-manage-stock").val();
        let stock_status = $("#iwbvel-bulk-new-form-stock-status").val();
        let stock_quantity = $("#iwbvel-bulk-new-form-stock-quantity").val();
        let backorders = $("#iwbvel-bulk-new-form-backorders").val();
        //Get the value of Type
        let product_type = $("#iwbvel-bulk-new-form-product-type").val();
        let featured = $("#iwbvel-bulk-new-form-featured").val();
        let virtual = $("#iwbvel-bulk-new-form-virtual").val();
        let downloadable = $("#iwbvel-bulk-new-form-downloadable").val();
        let download_limit = $("#iwbvel-bulk-new-form-download-limit").val();
        let download_expiry = $("#iwbvel-bulk-new-form-download-expiry").val();
        let product_url = $("#iwbvel-bulk-new-form-product-url").val();
        let button_text = $("#iwbvel-bulk-new-form-button-text").val();
        let upsells = $("#iwbvel-bulk-new-form-upsells").val();
        let cross_sells = $("#iwbvel-bulk-new-form-cross-sells").val();
        // Prepare data object to send via AJAX
        let productData = {
            action: "create_bulk_products",
            title: title,
            slug: slug,
            sku: sku,
            description: description,
            short_description: shortDescription,
            purchase_note: purchase_note,
            menu_order: menu_order,
            sold_individually: sold_individually,
            reviews_allowed: reviews_allowed,
            status: status,
            catalog_visibility: catalog_visibility,
            date_created: date_created,
            author: author,
            image_id: image_id,
            gallery_image_ids: gallery_image_ids,
            taxonomies: taxonomies,
            attributes: attributes,
            regular_price: regular_price,
            round_item_regular_price: round_item_regular_price,
            sale_price: sale_price,
            round_item_sales_price: round_item_sales_price,
            sale_date_from: sale_date_from,
            sale_date_to: sale_date_to,
            tax_status: tax_status,
            tax_class: tax_class,
            shipping_class: shipping_class,
            width: width,
            height: height,
            length: length,
            weight: weight,
            manage_stock: manage_stock,
            stock_status: stock_status,
            stock_quantity: stock_quantity,
            backorders: backorders,
            product_type: product_type,
            featured: featured,
            virtual: virtual,
            downloadable: downloadable,
            download_limit: download_limit,
            download_expiry: download_expiry,
            product_url: product_url,
            button_text: button_text,
            upsells: upsells,
            cross_sells: cross_sells,
        };

        iwbvelCreateNewProduct(quantity, productData);
    });

    setTimeout(function () {
        if ($('#iwbvel-quick-search-reset').css('display') == 'none') {
            $('li.iwbvel-quick-filter a').removeClass('active');
        } else {
            $('li.iwbvel-quick-filter a').addClass('active');
        }
    }, 150);

    iwbvelDataTableFixSize();
});