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

    // Inline edit
    $(document).on("click", 'td[data-action="inline-editable"]', function (e) {
        if ($(e.target).attr("data-type") !== "edit-mode" && $(e.target).find('[data-type="edit-mode"]').length === 0) {
            // Close All Inline Edit
            $('[data-type="edit-mode"]').each(function () {
                $(this).closest("span").html($(this).attr('data-val'));
            });

            let text = $(this).find('[data-action="inline-editable"]').text().trim();
            let fullText = ($(this).find('[data-action="inline-editable"]').attr('data-full-text') && $(this).find('[data-action="inline-editable"]').attr('data-full-text') != '') ? $(this).find('[data-action="inline-editable"]').attr('data-full-text').trim() : text;

            // Open Clicked Inline Edit
            switch ($(this).attr("data-content-type")) {
                case "text":
                case "password":
                case "url":
                case "email":
                    $(this).children("span").html("<textarea data-item-id='" + $(this).attr("data-item-id") + "' data-field='" + $(this).attr("data-field") + "' data-field-type='" + $(this).attr("data-field-type") + "' data-type='edit-mode' data-val='" + text + "'>" + fullText + "</textarea>").children("textarea").focus().select();
                    break;
                case "numeric":
                case "regular_price":
                case "sale_price":
                    $(this).children("span").html("<input type='number' min='-1' data-item-id='" + $(this).attr("data-item-id") + "' data-field='" + $(this).attr("data-field") + "' data-field-type='" + $(this).attr("data-field-type") + "' data-type='edit-mode' data-val='" + text + "' value='" + fullText.replaceAll(',', '') + "'>").children("input[type=number]").focus().select();
                    break;
            }
        }
    });

    // Discard Save
    $(document).on("click", function (e) {
        if ($(e.target).attr("data-action") !== "inline-editable" && $(e.target).attr("data-type") !== "edit-mode") {
            $('[data-type="edit-mode"]').each(function () {
                $(this).closest("span").html($(this).attr('data-val'));
            });
        }
    });

    $(document).on('click', '.iwbvel-reload-table', function () {
        iwbvelReloadProducts();
    });

    // Save Inline Edit By Enter Key
    $(document).on("keypress", '[data-type="edit-mode"]', function (event) {
        let iwbvelKeyCode = event.keyCode ? event.keyCode : event.which;
        if (iwbvelKeyCode === 13) {
            let productData = [];
            let productIds;
            let tdElement = $(this).closest('td');

            if (iwbvelSelectAllChecked() && $('#iwbvel-bind-edit').prop('checked') === true) {
                productIds = 'all_filtered';
            } else {
                if ($('#iwbvel-bind-edit').prop('checked') === true) {
                    productIds = iwbvelGetProductsChecked();
                } else {
                    productIds = [];
                }
                if ($.isArray(productIds)) {
                    productIds.push($(this).attr("data-item-id"));
                }
            }

            productData.push({
                name: tdElement.attr('data-name'),
                sub_name: (tdElement.attr('data-sub-name')) ? tdElement.attr('data-sub-name') : '',
                type: tdElement.attr('data-update-type'),
                value: $(this).val(),
                operation: 'inline_edit'
            });

            $(this).closest("span").html($(this).val());
            iwbvelProductEditAction(productIds, productData);
        }
    });

    $(document).on('input', '#iwbvel-meta-fields-manual_key_name', function () {
        let containerElement = $(this).closest('.iwbvel-meta-fields-manual-field');
        let errorMessageElement = containerElement.find('.iwbvel-add-meta-field-message');
        if ($(this).val() != '') {
            if ($.inArray($(this).val().toLowerCase(), IWBVEL_DATA.reserved_field_keys) === -1 && !$('input.iwbvel_meta_field_key_input[value="' + $(this).val().toLowerCase() + '"]').length) {
                $('#iwbvel-add-meta-field-manual').prop('disabled', false);
                containerElement.removeClass('iwbvel-add-meta-field-name-error');
                errorMessageElement.text('');
            } else {
                $('#iwbvel-add-meta-field-manual').prop('disabled', true);
                containerElement.addClass('iwbvel-add-meta-field-name-error');
                errorMessageElement.text('This name exists');
            }
        } else {
            $('#iwbvel-add-meta-field-manual').prop('disabled', true);
            containerElement.removeClass('iwbvel-add-meta-field-name-error');
            errorMessageElement.text('');
        }
    });

    // fetch product data by click to bulk edit button
    $(document).on("click", '[data-target="#iwbvel-float-side-modal-bulk-edit"]', function () {
        if (IWBVEL_DATA.iwbvel_settings.keep_filled_data_in_bulk_edit_form === "yes") {
            let productID = $("input.iwbvel-check-item:visible:checkbox:checked");
            if (productID.length === 1) {
                iwbvelGetProductData(productID.val());
            } else {
                iwbvelResetBulkEditForm();
            }
        }
    });

    $(document).on('click', '.iwbvel-inline-edit-color-action', function () {
        $(this).closest('td').find('input.iwbvel-inline-edit-action').trigger('change');
    });

    $(document).on("change", ".iwbvel-inline-edit-action", function (e) {
        let $this = $(this);
        setTimeout(function () {
            if ($('div.xdsoft_datetimepicker:visible').length > 0) {
                e.preventDefault();
                return false;
            }

            if ($this.hasClass('iwbvel-datepicker') || $this.hasClass('iwbvel-timepicker') || $this.hasClass('iwbvel-datetimepicker')) {
                if ($this.attr('data-val') == $this.val()) {
                    e.preventDefault();
                    return false;
                }
            }

            let productData = [];
            let productIds;
            let tdElement = $this.closest('td');
            if ($('#iwbvel-bind-edit').prop('checked') === true) {
                productIds = iwbvelGetProductsChecked();
            } else {
                productIds = [];
            }
            if ($.isArray(productIds)) {
                productIds.push($this.attr("data-item-id"));
            }

            let iwbvelValue;
            switch (tdElement.attr("data-content-type")) {
                case 'checkbox_dual_mode':
                case 'checkbox':
                    iwbvelValue = $this.prop("checked") ? "yes" : "no";
                    break;
                default:
                    iwbvelValue = $this.val();
                    break;
            }

            productData.push({
                name: tdElement.attr('data-name'),
                sub_name: (tdElement.attr('data-sub-name')) ? tdElement.attr('data-sub-name') : '',
                type: tdElement.attr('data-update-type'),
                value: iwbvelValue,
                operation: 'inline_edit'
            });

            iwbvelProductEdit(productIds, productData);
        }, 250)
    });

    $(document).on("click", ".iwbvel-inline-edit-clear-date", function () {
        let productData = [];
        let productIds;
        let tdElement = $(this).closest('td');

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr("data-item-id"));
        }

        productData.push({
            name: tdElement.attr('data-name'),
            sub_name: (tdElement.attr('data-sub-name')) ? tdElement.attr('data-sub-name') : '',
            type: tdElement.attr('data-update-type'),
            value: '',
            operation: 'inline_edit'
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on("click", ".iwbvel-modal-regular-price-apply-button", function () {
        let productId = $(this).attr("data-item-id");
        let productIds;
        let productData = [];

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push(productId);
        }

        productData.push({
            name: 'regular_price',
            sub_name: '',
            type: $(this).attr('data-update-type'),
            operator: $("#iwbvel-regular-price-calculator-operator").val(),
            value: $("#iwbvel-regular-price-calculator-value").val(),
            operator_type: $("#iwbvel-regular-price-calculator-type").val(),
            round: $("#iwbvel-regular-price-calculator-round").val()
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on("click", ".iwbvel-modal-sale-price-apply-button", function () {
        let productId = $(this).attr("data-item-id");
        let productIds;
        let productData = [];

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push(productId);
        }

        productData.push({
            name: 'sale_price',
            sub_name: '',
            type: $(this).attr('data-update-type'),
            operator: $("#iwbvel-sale-price-calculator-operator").val(),
            value: $("#iwbvel-sale-price-calculator-value").val(),
            operator_type: $("#iwbvel-sale-price-calculator-type").val(),
            round: $("#iwbvel-sale-price-calculator-round").val()
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on("click", ".iwbvel-bulk-edit-delete-action", function () {
        let deleteType = $(this).attr('data-delete-type');
        let productIds = iwbvelGetProductsChecked();

        if (!productIds.length && productIds != 'all_filtered' && deleteType != 'all') {
            swal({
                title: "Please select one product",
                type: "warning"
            });
            return false;
        }

        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelLoadingStart();
                iwbvelDeleteProduct(productIds, deleteType);
            }
        });
    });

    $(document).on("click", "#iwbvel-bulk-edit-duplicate-start", function () {
        let $this = $(this);
        $this.prop('disabled', true);
        let count = parseInt($("#iwbvel-bulk-edit-duplicate-number").val());
        let productIDs = $("input.iwbvel-check-item:visible:checkbox:checked").map(function () {
            if ($(this).attr('data-item-type') === 'variation') {
                swal({
                    title: iwbvelTranslate.duplicateVariationsDisabled,
                    type: "warning"
                });
                $this.prop('disabled', false);
                return false;
            }
            return $(this).val();
        }).get();

        if (!productIDs.length) {
            swal({
                title: "Please select one product",
                type: "warning"
            });
            $this.prop('disabled', false);
            return false;
        } else {
            iwbvelLoadingStart();
            iwbvelDuplicateProduct(productIDs, count);
        }
    });

    $(document).on("click", ".iwbvel-top-nav-duplicate-button", function () {
        let productIDs = $("input.iwbvel-check-item:visible:checkbox:checked").map(function () {
            if ($(this).attr('data-item-type') === 'variation') {
                swal({
                    title: iwbvelTranslate.duplicateVariationsDisabled,
                    type: "warning"
                });
            } else {
                return $(this).val();
            }
        }).get();

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

    $(document).on("click", "#iwbvel-create-new-item", function () {
        iwbvelLoadingStart();
        $(this).prop('disabled', true);
        iwbvelCreateNewProduct($("#iwbvel-new-item-count").val());
    });

    $(document).on("click", ".iwbvel-bulk-edit-show-variations-button", function () {
        if ($('#iwbvel-bulk-edit-show-variations').prop("checked") === true) {
            $(this).removeClass('selected');
            $('#iwbvel-bulk-edit-show-variations').prop("checked", false).change();
        } else {
            $(this).addClass('selected');
            $('#iwbvel-bulk-edit-show-variations').prop("checked", true).change();
        }
    });

    $(document).on("change", "#iwbvel-bulk-edit-show-variations", function () {
        if ($(this).prop("checked") === true) {
            iwbvelShowVariationSelectionTools();
        } else {
            iwbvelHideVariationSelectionTools();
        }

        setTimeout(function () {
            iwbvelReloadProducts();
        }, 30);
    });

    $(document).on("click", ".iwbvel-bulk-edit-select-all-variations-button", function () {
        if ($('#iwbvel-bulk-edit-select-all-variations').prop("checked") === true) {
            $(this).removeClass('selected')
            $('#iwbvel-bulk-edit-select-all-variations').prop("checked", false).change();
        } else {
            $(this).addClass('selected')
            $('#iwbvel-bulk-edit-select-all-variations').prop("checked", true).change();
        }
    });

    $(document).on("change", "#iwbvel-bulk-edit-select-all-variations", function () {
        if ($(this).prop("checked") === true) {
            $("input.iwbvel-check-item[data-item-type=variation]").prop("checked", true);
        } else {
            $("input.iwbvel-check-item[data-item-type=variation]").prop("checked", false);
        }
    });

    $(document).on("click", "#iwbvel-column-profiles-save-as-new-preset", function () {
        let presetKey = $("#iwbvel-column-profiles-choose").val();
        let items = $(".iwbvel-column-profile-fields input:checkbox:checked").map(function () {
            return $(this).val();
        }).get();
        iwbvelSaveColumnProfile(presetKey, items, "save_as_new");
    });

    $(document).on("click", "#iwbvel-column-profiles-update-changes", function () {
        let presetKey = $("#iwbvel-column-profiles-choose").val();
        let items = $(".iwbvel-column-profile-fields input:checkbox:checked").map(function () {
            return $(this).val();
        }).get();
        iwbvelSaveColumnProfile(presetKey, items, "update_changes");
    });

    $(document).on("click", ".iwbvel-bulk-edit-filter-profile-load", function () {
        iwbvelLoadFilterProfile($(this).val());

        $(".iwbvel-filter-profiles-items tr").removeClass("iwbvel-filter-profile-loaded");
        $(this).closest("tr").addClass("iwbvel-filter-profile-loaded");

        if (IWBVEL_DATA.iwbvel_settings.close_popup_after_applying == 'yes') {
            iwbvelCloseFloatSideModal();
        }
    });

    $(document).on("click", ".iwbvel-bulk-edit-filter-profile-delete", function () {
        let presetKey = $(this).val();
        let item = $(this).closest("tr");
        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelDeleteFilterProfile(presetKey);
                if (item.hasClass('iwbvel-filter-profile-loaded')) {
                    $('.iwbvel-filter-profiles-items tbody tr:first-child').addClass('iwbvel-filter-profile-loaded').find('input[type=radio]').prop('checked', true);
                    $('#iwbvel-bulk-edit-reset-filter').trigger('click');
                }
                if (IWBVEL_DATA.iwbvel_settings.close_popup_after_applying == 'yes') {
                    iwbvelCloseFloatSideModal();
                }
                item.remove();
            }
        });
    });

    $(document).on("change", "input.iwbvel-filter-profile-use-always-item", function () {
        iwbvelFilterProfileChangeUseAlways($(this).val());
    });

    $(document).on("click", ".iwbvel-filter-form-action", function (e) {
        let data = iwbvelGetCurrentFilterData();
        let page;
        let action = $(this).attr("data-search-action");
        if (action === "pagination") {
            page = $(this).attr("data-index");
        } else {
            page = 1;
        }
        if (action === "quick_search" && $('#iwbvel-quick-search-text').val() !== '') {
            iwbvelResetFilterForm();
        }
        if (action === "pro_search") {
            iwbvelResetQuickSearchForm();
        }
        iwbvelProductsFilter(data, action, [], page);
    });

    $(document).on("click", "#iwbvel-filter-form-reset", function () {
        $(this).prop('disabled', true);
        iwbvelResetFilters();
    });

    $(document).on("click", "#iwbvel-bulk-edit-reset-filter", function () {
        iwbvelResetFilters();
    });

    $(document).on("change", "#iwbvel-quick-search-field", function () {
        let options = $("#iwbvel-quick-search-operator option");
        switch ($(this).val()) {
            case "title":
            case "sku":
                options.each(function () {
                    $(this).closest("select").prop("selectedIndex", 0);
                    $(this).prop("disabled", false);
                });
                break;
            case "id":
                options.each(function () {
                    $(this).closest("select").prop("selectedIndex", 1);
                    if ($(this).attr("value") === "exact") {
                        $(this).prop("disabled", false);
                    } else {
                        $(this).prop("disabled", true);
                    }
                });
                break;
        }
    });

    // Quick Per Page
    $("#iwbvel-quick-per-page").on("change", function () {
        iwbvelChangeCountPerPage($(this).val());
    });

    $(document).on("click", ".iwbvel-edit-action-with-button", function () {
        let productIds;
        let productData = [];
        let modal = $(this).closest('.iwbvel-modal');

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr("data-item-id"));
        }

        let iwbvelValue;
        switch ($(this).attr("data-content-type")) {
            case "textarea":
                iwbvelValue = tinymce.get("iwbvel-text-editor").getContent();
                break;
            case "select_products":
                iwbvelValue = $('#iwbvel-select-products-value').val();
                break;
            case "multi_select":
                if (modal) {
                    iwbvelValue = modal.find('.iwbvel-modal-acf-taxonomy-multi-select-value').val();
                }
                break;
            case "select_files":
                let names = $('.iwbvel-inline-edit-file-name').map(function () {
                    return $(this).val();
                }).get();

                let urls = $('.iwbvel-inline-edit-file-url').map(function () {
                    return $(this).val();
                }).get();

                iwbvelValue = {
                    files_name: names,
                    files_url: urls,
                };
                break;
            case "file":
                iwbvelValue = $('#iwbvel-modal-file #iwbvel-file-id').val();
                break;
            case "image":
                iwbvelValue = $(this).attr("data-image-id");
                break;
            case "gallery":
                iwbvelValue = $("#iwbvel-modal-gallery-items input.iwbvel-inline-edit-gallery-image-ids").map(function () {
                    return $(this).val();
                }).get();
                break;
            case "custom_field_files":
                iwbvelValue = [];
                if ($('.iwbvel-modal-custom-field-file-item').length > 0) {
                    $('.iwbvel-modal-custom-field-file-item').each(function () {
                        let name = $(this).find('input.iwbvel-inline-edit-file-name').val();
                        let url = $(this).find('input.iwbvel-inline-edit-file-url').val();
                        if (url != '') {
                            iwbvelValue.push({
                                name: name,
                                url: url
                            });
                        }
                    })
                }
                break;
        }

        productData.push({
            name: $(this).attr('data-name'),
            sub_name: ($(this).attr('data-sub-name')) ? $(this).attr('data-sub-name') : '',
            type: $(this).attr('data-update-type'),
            value: iwbvelValue,
            operation: 'inline_edit'
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on("click", ".iwbvel-load-text-editor", function () {
        tinymce.get("iwbvel-text-editor").setContent('');

        let tdElement = $(this).closest('td');
        let productId = $(this).attr("data-item-id");
        let field = $(this).attr("data-field");
        let fieldType = $(this).attr("data-field-type");

        $('#iwbvel-modal-text-editor-item-title').text($(this).attr('data-item-name'));
        $("#iwbvel-text-editor-apply").attr("data-field", field).attr("data-field-type", fieldType).attr("data-item-id", productId).attr('data-update-type', tdElement.attr('data-update-type')).attr('data-name', tdElement.attr('data-name'));

        $.ajax({
            url: IWBVEL_DATA.ajax_url,
            type: "post",
            dataType: "json",
            data: {
                action: "iwbvel_get_text_editor_content",
                nonce: IWBVEL_DATA.ajax_nonce,
                product_id: productId,
                field: field,
                fetch_type: tdElement.attr('data-fetch-type')
            },
            success: function (response) {
                if (response.success && response.content !== '') {
                    tinymce.get("iwbvel-text-editor").setContent(response.content);
                    tinymce.execCommand('mceFocus', false, 'iwbvel-text-editor');
                }
            },
            error: function () { }
        });
    });

    $(document).on("click", "#iwbvel-create-new-product-taxonomy", function () {
        if ($("#iwbvel-new-product-category-name").val() !== "") {
            let taxonomyInfo = {
                name: $("#iwbvel-new-product-taxonomy-name").val(),
                slug: $("#iwbvel-new-product-taxonomy-slug").val(),
                parent: $("#iwbvel-new-product-taxonomy-parent").val(),
                description: $("#iwbvel-new-product-taxonomy-description").val(),
                product_id: $(this).attr("data-item-id"),
                modal_id: $(this).attr('data-closest-id')
            };
            iwbvelAddProductTaxonomy(taxonomyInfo, $(this).attr("data-field"), $(this).attr("data-item-id"));
        } else {
            swal({
                title: iwbvelTranslate.taxonomyNameRequired,
                type: "warning"
            });
        }
    });

    //Search
    $(document).on("keyup", ".iwbvel-search-in-list", function () {
        let iwbvelSearchValue = this.value.toLowerCase().trim();
        $($(this).attr("data-id") + " .iwbvel-product-items-list li").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(iwbvelSearchValue) > -1);
        });
    });

    $(document).on("click", "#iwbvel-create-new-product-attribute", function () {
        if ($("#iwbvel-new-product-attribute-name").val() !== "") {
            let attributeInfo = {
                name: $("#iwbvel-new-product-attribute-name").val(),
                slug: $("#iwbvel-new-product-attribute-slug").val(),
                description: $("#iwbvel-new-product-attribute-description").val(),
                product_id: $(this).attr("data-item-id")
            };
            iwbvelAddProductAttribute(attributeInfo, $(this).attr("data-field"));
        } else {
            swal({
                title: iwbvelTranslate.attributeNameRequired,
                type: "warning"
            });
        }
    });

    $(document).on('click', 'button[data-target="#iwbvel-modal-select-products"]', function () {
        let childrenIds = $(this).attr('data-children-ids').split(',');
        let tdElement = $(this).closest('td');
        $('#iwbvel-select-products-value').val('').change();
        $('#iwbvel-modal-select-products-item-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-select-products .iwbvel-edit-action-with-button').attr('data-item-id', $(this).attr('data-item-id')).attr('data-field', $(this).attr('data-field')).attr('data-field-type', $(this).attr('data-field-type')).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        iwbvelSetSelectedProducts(childrenIds);
    });

    $(document).on('click', '#iwbvel-modal-select-files-add-file-item', function () {
        iwbvelAddNewFileItem();
    });

    $(document).on('click', '#iwbvel-modal-custom-field-files-add-file-item', function () {
        iwbvelAddCustomFieldFileItem();
    });

    $(document).on('click', '#iwbvel-bulk-edit-custom-field-files-add-file-item', function () {
        iwbvelBulkEditAddCustomFieldFileItem();
    });

    $(document).on('click', 'button[data-toggle=modal][data-target="#iwbvel-modal-select-files"]', function () {
        $('.iwbvel-inline-select-files').html('');
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-select-files-apply').attr('data-item-id', $(this).attr('data-item-id')).attr('data-field', $(this).attr(('data-field'))).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        $('#iwbvel-modal-select-files-item-title').text($(this).closest('td').attr('data-col-title'));
        iwbvelGetProductFiles($(this).attr('data-item-id'));
    });

    $(document).on('click', 'button[data-toggle="modal"][data-target="#iwbvel-modal-custom-field-files"]', function () {
        $('.iwbvel-inline-custom-field-files').html('');
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-custom-field-files-apply').attr('data-item-id', $(this).attr('data-item-id')).attr('data-field', $(this).attr(('data-field'))).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        $('#iwbvel-modal-custom-field-files-item-title').text($(this).closest('td').attr('data-col-title'));
        iwbvelGetProductCustomFieldFiles($(this).attr('data-item-id'), tdElement.attr('data-name'));
    });

    $(document).on('click', '.iwbvel-inline-edit-file-remove-item', function () {
        $(this).closest('.iwbvel-modal-select-files-file-item').remove();
    });

    $(document).on('click', '.iwbvel-custom-field-file-remove-item', function () {
        $(this).closest('.iwbvel-modal-custom-field-file-item').remove();
    });

    $(document).on('click', '.iwbvel-bulk-edit-custom-field-file-remove-item', function () {
        $(this).closest('.iwbvel-bulk-edit-custom-field-file-item').remove();
    });

    if ($.fn.sortable) {
        let iwbvelSelectFiles = $(".iwbvel-inline-select-files");
        iwbvelSelectFiles.sortable({
            handle: ".iwbvel-select-files-sortable-btn",
            cancel: ""
        });
        iwbvelSelectFiles.disableSelection();

        let iwbvelCustomFieldFiles = $(".iwbvel-inline-custom-field-files");
        iwbvelCustomFieldFiles.sortable({
            handle: ".iwbvel-custom-field-files-sortable-btn",
            cancel: ""
        });
        iwbvelCustomFieldFiles.disableSelection();

        let iwbvelBulkEditCustomFieldFiles = $(".iwbvel-bulk-edit-custom-field-files");
        iwbvelBulkEditCustomFieldFiles.sortable({
            handle: ".iwbvel-bulk-edit-custom-field-files-sortable-btn",
            cancel: ""
        });
        iwbvelBulkEditCustomFieldFiles.disableSelection();

        // yikes custom tabs 
        let iwbvelTabItems = $("#iwbvel-modal-yikes-custom-tabs");
        iwbvelTabItems.sortable({
            handle: ".iwbvel-yikes-tab-item-sort",
            cancel: ""
        });
        iwbvelTabItems.disableSelection();
    }

    $(document).on("change", ".iwbvel-bulk-edit-form-variable", function () {
        let newVal = $(this).val() ? $(this).closest("div").find("input[type=text]").val() + "{" + $(this).val() + "}" : "";
        $(this).closest("div").find("input[type=text]").first().val(newVal).change();
    });

    $(document).on("change", 'select[data-field="operator"]', function () {
        let id = $(this).closest(".iwbvel-form-group").find("label").attr("for");
        let $this = $(this);

        if ($(this).val() === "text_replace") {
            $(this).closest(".iwbvel-form-group").append("<div class='iwbvel-bulk-edit-form-extra-field'>" +
                "<select id='" + id + "-sensitive' data-field='sensitive'>" +
                "<option value='yes'>" + iwbvelTranslate.sameCase + "</option>" +
                "<option value='no'>" + iwbvelTranslate.ignoreCase + "</option>" +
                "</select>" +
                "<input type='text' id='" + id + "-replace' data-field='replace' placeholder='" + iwbvelTranslate.enterText + "'>" +
                "<select class='iwbvel-bulk-edit-form-variable' title='" + iwbvelTranslate.selectVariable + "' data-field='variable'>" +
                "<option value=''>" + iwbvelTranslate.variable + "</option>" +
                "<option value='title'>" + iwbvelTranslate.title + "</option>" +
                "<option value='id'>" + iwbvelTranslate.id + "</option>" +
                "<option value='sku'>" + iwbvelTranslate.sku + "</option>" +
                "<option value='menu_order'>Menu Order</option>" +
                "<option value='parent_id'>" + iwbvelTranslate.parentId + "</option>" +
                "<option value='parent_title'>" + iwbvelTranslate.parentTitle + "</option>" +
                "<option value='parent_sku'>" + iwbvelTranslate.parentSku + "</option>" +
                "<option value='regular_price'>" + iwbvelTranslate.regularPrice + "</option>" +
                "<option value='sale_price'>" + iwbvelTranslate.salePrice + "</option>" +
                "</select>" +
                "</div>");
        } else if ($(this).val() === "number_round") {
            $(this).closest(".iwbvel-form-group").append('<div class="iwbvel-bulk-edit-form-extra-field"><select id="' + id + '-round-item"><option value="5">5</option><option value="10">10</option><option value="19">19</option><option value="29">29</option><option value="39">39</option><option value="49">49</option><option value="59">59</option><option value="69">69</option><option value="79">79</option><option value="89">89</option><option value="99">99</option></select></div>');
        } else {
            $(this).closest(".iwbvel-form-group").find(".iwbvel-bulk-edit-form-extra-field").remove();
        }
        if ($.inArray($(this).val(), ['number_clear', 'text_remove_duplicate', 'text_clear']) !== -1) {
            $(this).closest(".iwbvel-form-group").find('[data-field="value"]').val('').prop('disabled', true);
            $(this).closest(".iwbvel-form-group").find('select[data-field="variable"]').val('').prop('disabled', true);
        } else {
            $(this).closest(".iwbvel-form-group").find('[data-field="value"]').prop('disabled', false);
            $(this).closest(".iwbvel-form-group").find('select[data-field="variable"]').prop('disabled', false);
        }

        if (!$(this).closest('#iwbvel-variations-bulk-actions-modal').length) {
            setTimeout(function () {
                changedTabs($this);
            }, 150);
        }
    });

    $("#iwbvel-float-side-modal-bulk-edit, #iwbvel-float-side-modal-filter").on("change", '[data-field="value"], [data-field="from"], [data-field="to"]', function () {
        changedTabs($(this));
    });

    $(document).on("change", ".iwbvel-date-from", function () {
        let field_to = $('#' + $(this).attr('data-to-id'));
        let datepicker = true;
        let timepicker = false;
        let format = 'Y/m/d';

        if ($(this).hasClass('iwbvel-datetimepicker')) {
            timepicker = true;
            format = 'Y/m/d H:i'
        }

        if ($(this).hasClass('iwbvel-timepicker')) {
            datepicker = false;
            timepicker = true;
            format = 'H:i'
        }

        field_to.val("");
        field_to.datetimepicker("destroy");
        field_to.datetimepicker({
            format: format,
            datepicker: datepicker,
            timepicker: timepicker,
            minDate: $(this).val(),
        });
    });

    $(document).on("click", ".iwbvel-bulk-edit-form-remove-image", function () {
        $(this).closest("div").remove();
        $(".iwbvel-bulk-edit-form-product-image").val("");
    });

    $(document).on("click", ".iwbvel-bulk-edit-form-remove-gallery-item", function () {
        $(this).closest("div").remove();
        $("#iwbvel-bulk-edit-form-product-gallery input[value=" + $(this).attr("data-id") + "]").remove();
    });

    $(document).on('click', '.iwbvel-sortable-column', function () {
        let otherIcons = $('.iwbvel-sortable-column').not('[data-column-name="' + $(this).attr('data-column-name') + '"]').find('.iwbvel-sortable-column-icon i');
        if (otherIcons.length) {
            otherIcons.each(function () {
                $(this).closest('.iwbvel-sortable-column-icon').html(IWBVEL_DATA.icons.sortUpAndDown);
            });
        }

        let currentSortType = ($(this).attr('data-sort') === undefined) ? IWBVEL_DATA.iwbvel_settings.default_sort : $(this).attr('data-sort');
        if (currentSortType === 'DESC') {
            $(this).attr('data-sort', 'ASC');
            iwbvelSortByColumn($(this).attr('data-column-name'), 'ASC');
            $(this).find('.iwbvel-sortable-column-icon').html(IWBVEL_DATA.icons.sortDownToUp);
        } else {
            $(this).attr('data-sort', 'DESC');
            $(this).find('.iwbvel-sortable-column-icon').html(IWBVEL_DATA.icons.sortUpToDown);
            iwbvelSortByColumn($(this).attr('data-column-name'), 'DESC');
        }
    });

    $(document).on("click", ".iwbvel-column-manager-edit-field-btn", function () {
        $('#iwbvel-modal-column-manager-edit-preset .iwbvel-box-loading').show();
        let presetKey = $(this).val();
        $('#iwbvel-modal-column-manager-edit-preset .items').html('');
        $("#iwbvel-column-manager-edit-preset-key").val(presetKey);
        $("#iwbvel-column-manager-edit-preset-name").val($(this).attr("data-preset-name"));
        iwbvelColumnManagerFieldsGetForEdit(presetKey);
    });

    $(document).on("click", "#iwbvel-get-meta-fields-by-product-id", function () {
        $(".iwbvel-meta-fields-empty-text").hide();
        let input = $("#iwbvel-add-meta-fields-product-id");
        iwbvelAddMetaKeysByProductID(input.val());
        input.val("");
    });

    $(document).on("click", "#iwbvel-bulk-edit-undo", function () {
        $(this).prop('disabled', true);
        iwbvelHistoryUndo();
    });

    $(document).on("click", "#iwbvel-bulk-edit-redo", function () {
        $(this).prop('disabled', true);
        iwbvelHistoryRedo();
    });

    $(document).on("click", "#iwbvel-history-filter-apply", function () {
        let filters = {
            operation: $("#iwbvel-history-filter-operation").val(),
            author: $("#iwbvel-history-filter-author").val(),
            fields: $("#iwbvel-history-filter-fields").val(),
            date: {
                from: $("#iwbvel-history-filter-date-from").val(),
                to: $("#iwbvel-history-filter-date-to").val()
            }
        };
        iwbvelHistoryFilter(filters);
    });

    $(document).on("click", "#iwbvel-history-filter-reset", function () {
        $(".iwbvel-history-filter-fields input").val("");
        $(".iwbvel-history-filter-fields select").val("").change();
        iwbvelHistoryFilter();
    });

    $(document).on("click", '[data-target="#iwbvel-float-side-modal-history"]', function () {
        if ($(this).attr('data-loaded') == 'true') {
            return;
        } else {
            $(this).attr('data-loaded', 'true');
            $(".iwbvel-history-filter-fields input").val("");
            $(".iwbvel-history-filter-fields select").val("").change();
            iwbvelHistoryFilter(null, false);
        }
    });

    $(document).on("click", '[data-target="#iwbvel-float-side-modal-meta-fields"]', function () {
        if ($(this).attr('data-loaded') == 'true') {
            return;
        } else {
            $(this).attr('data-loaded', 'true');
            iwbvelMetaFieldsLoad();
        }
    });

    $(document).on("change", ".iwbvel-meta-fields-main-type", function () {
        let item = $(this).closest('.iwbvel-meta-fields-right-item');
        if ($(this).val() === "textinput") {
            item.find(".iwbvel-meta-fields-sub-type").show();
        } else {
            item.find(".iwbvel-meta-fields-sub-type").hide();
        }

        if ($.inArray($(this).val(), ['select', 'array', 'radio']) !== -1) {
            item.find(".iwbvel-meta-fields-key-value").show();
        } else {
            item.find(".iwbvel-meta-fields-key-value").hide();
        }
    });

    $("#iwbvel-column-manager-add-new-preset").on("submit", function (e) {
        if ($(this).find(".iwbvel-column-manager-added-fields .items .iwbvel-column-manager-right-item").length < 1) {
            e.preventDefault();
            swal({
                title: iwbvelTranslate.plzAddColumns,
                type: "warning"
            });
        }
    });

    $(document).on("click", "#iwbvel-bulk-edit-form-reset", function () {
        $(this).prop('disabled', true);
        iwbvelResetBulkEditForm();
    });

    $(document).on("click", "#iwbvel-filter-form-save-preset", function () {
        $(this).prop('disabled', true);
        let presetName = $("#iwbvel-filter-form-save-preset-name").val();
        if (presetName !== "") {
            if ($('[data-target="#iwbvel-float-side-modal-filter-profiles"]').attr('data-loaded') != 'true') {
                iwbvelFilterProfileLoad();
            }
            let data = iwbvelGetProSearchData();
            iwbvelSaveFilterPreset(data, presetName);
        } else {
            swal({
                title: iwbvelTranslate.presetNameRequired,
                type: "warning"
            });
            $(this).prop('disabled', false);
        }
    });

    $(document).on("click", '.iwbvel-bulk-edit-form-do-bulk-edit', function (e) {
        $(this).prop('disabled', true);
        iwbvelProductEdit(iwbvelGetProductsChecked(), iwbvelGetBulkEditData());
    });

    $(document).on('click', '[data-target="#iwbvel-modal-new-item"]', function () {
        $('#iwbvel-new-item-title').html(iwbvelTranslate.newProduct);
        $('#iwbvel-new-item-description').html(iwbvelTranslate.newProductNumber);
    });

    $(document).on('click', '[data-target="#iwbvel-modal-text-editor"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-text-editor-item-title').html($(this).attr(''));
        $('#iwbvel-text-editor-apply').attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
    });

    // keypress: Enter
    $(document).on("keypress", function (e) {
        if (e.keyCode === 13) {
            if ($('#iwbvel-quick-search-text').val() !== '' && $($('#iwbvel-last-modal-opened').val()).css('display') !== 'block' && $('.iwbvel-tabs-list a[data-content=bulk-edit]').hasClass('selected')) {
                iwbvelReloadProducts();
                $('#iwbvel-quick-search-reset').show();
                $('.iwbvel-quick-filter a').addClass('active');
            }
            if ($("#iwbvel-modal-new-product-taxonomy").css("display") === "block") {
                $("#iwbvel-create-new-product-taxonomy").trigger("click");
            }
            if ($("#iwbvel-modal-new-item").css("display") === "block") {
                if ($("#iwbvel-create-new-item").prop('disabled') === false) {
                    $("#iwbvel-create-new-item").trigger("click");
                }
            }
            if ($("#iwbvel-modal-item-duplicate").css("display") === "block") {
                if ($("#iwbvel-bulk-edit-duplicate-start").prop('disabled') === false) {
                    $("#iwbvel-bulk-edit-duplicate-start").trigger("click");
                }
            }

            let metaFieldManualInput = $("#iwbvel-meta-fields-manual_key_name");
            let metaFieldProductId = $("#iwbvel-add-meta-fields-product-id");
            if (metaFieldManualInput.val() !== "" && $('#iwbvel-add-meta-field-manual').prop('disabled') === false) {
                $(".iwbvel-meta-fields-empty-text").hide();
                iwbvelAddMetaKeysManual(metaFieldManualInput.val().toLowerCase());
                metaFieldManualInput.val("");
            }
            if (metaFieldProductId.val() !== "") {
                $(".iwbvel-meta-fields-empty-text").hide();
                iwbvelAddMetaKeysByProductID(metaFieldProductId.val());
                metaFieldProductId.val("");
            }

            // filter form
            if ($('#iwbvel-float-side-modal-filter:visible').length) {
                $('#iwbvel-float-side-modal-filter:visible').find('.iwbvel-filter-form-action').trigger('click');
            }
        }
    });

    $(document).on('click', '.iwbvel-bulk-edit-status-filter-item', function () {
        $('.iwbvel-top-nav-status-filter').hide();

        $('.iwbvel-bulk-edit-status-filter-item').removeClass('active');
        $(this).addClass('active');
        $('.iwbvel-status-filter-selected-name').text(' - ' + $(this).text());

        if ($(this).attr('data-status') === 'all') {
            $('#iwbvel-filter-form-reset').trigger('click');
        } else {
            $('#iwbvel-filter-form-product-status').val($(this).attr('data-status')).change();
            setTimeout(function () {
                $('#iwbvel-filter-form-get-products').trigger('click');
            }, 250);
        }
    });

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

    $(document).on("click", "#iwbvel-filter-form-get-products", function () {
        $(this).prop('disabled', true);
        iwbvelFilterFormCheckAttributes();
        iwbvelCheckResetFilterButton();
    });

    $(document).on("click", ".iwbvel-inline-edit-taxonomy-save", function () {
        let productData = [];
        let productIds;

        let value = $("#iwbvel-modal-product-taxonomy input:checkbox:checked").map(function () {
            return $(this).val();
        }).get();

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr("data-item-id"));
        }

        productData.push({
            name: $(this).attr('data-name'),
            sub_name: ($(this).attr('data-sub-name')) ? $(this).attr('data-sub-name') : '',
            type: $(this).attr('data-update-type'),
            value: value,
            operation: 'inline_edit'
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('click', '.iwbvel-product-attribute', function () {
        let modalId = $(this).attr('data-target');
        $(modalId).find('input.is-visible').prop('checked', ($(this).attr('data-is-variation') == 'true')).change();
        $(modalId).find('input.is-visible-prev').val(($(this).attr('data-is-visible') == 'true') ? 'yes' : 'no');
        $(modalId).find('input.is-variation').prop('checked', ($(this).attr('data-is-variation') == 'true')).change();
        $(modalId).find('input.is-variation-prev').val(($(this).attr('data-is-variation') == 'true') ? 'yes' : 'no');
    });

    $(document).on("click", ".iwbvel-inline-edit-attribute-save", function () {
        let productData = [];
        let productIds;
        let modal = $("#iwbvel-modal-product-attribute");
        let value = modal.find(".iwbvel-modal-product-attribute-terms-list input:checkbox:checked").map(function () {
            return $(this).val();
        }).get();

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr("data-item-id"));
        }

        productData.push({
            name: $(this).attr('data-name'),
            sub_name: ($(this).attr('data-sub-name')) ? $(this).attr('data-sub-name') : '',
            type: $(this).attr('data-update-type'),
            value: value,
            used_for_variations: (modal.find('input.is-variation').prop('checked') === true) ? 'yes' : 'no',
            used_for_variations_prev: modal.find('input.is-variation-prev').val(),
            attribute_is_visible: (modal.find('input.is-visible').prop('checked') === true) ? 'yes' : 'no',
            attribute_is_visible_prev: modal.find('input.is-visible-prev').val(),
            operation: 'inline_edit'
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on("click", ".iwbvel-inline-edit-add-new-taxonomy", function () {
        $("#iwbvel-create-new-product-taxonomy").attr("data-field", $(this).attr("data-field")).attr("data-item-id", $(this).attr("data-item-id")).attr('data-closest-id', $(this).attr('data-closest-id'));
        $('#iwbvel-modal-new-product-taxonomy-product-title').text($(this).attr('data-item-name'));
        iwbvelGetTaxonomyParentSelectBox($(this).attr("data-field"));
    });

    $(document).on("click", ".iwbvel-inline-edit-add-new-attribute", function () {
        $("#iwbvel-create-new-product-attribute").attr("data-field", $(this).attr("data-field")).attr("data-item-id", $(this).attr("data-item-id"));
        $('#iwbvel-modal-new-product-attribute-item-title').text($(this).attr('data-item-name'));
    });

    $(document).on("click", 'button.iwbvel-calculator[data-target="#iwbvel-modal-numeric-calculator"]', function () {
        let btn = $("#iwbvel-modal-numeric-calculator .iwbvel-edit-action-numeric-calculator");
        let tdElement = $(this).closest('td');
        btn.attr("data-item-id", $(this).attr("data-item-id"));
        btn.attr("data-field", $(this).attr("data-field"));
        btn.attr("data-name", tdElement.attr('data-name'));
        btn.attr("data-update-type", tdElement.attr('data-update-type'));
        btn.attr("data-field-type", $(this).attr("data-field-type"));
        if ($(this).attr('data-field') === 'download_limit' || $(this).attr('data-field') === 'download_expiry') {
            $('#iwbvel-modal-numeric-calculator #iwbvel-numeric-calculator-type').val('n').change().hide();
            $('#iwbvel-modal-numeric-calculator #iwbvel-numeric-calculator-round').val('').change().hide();
        } else {
            $('#iwbvel-modal-numeric-calculator #iwbvel-numeric-calculator-type').show();
            $('#iwbvel-modal-numeric-calculator #iwbvel-numeric-calculator-round').show();
        }
        $('#iwbvel-modal-numeric-calculator-item-title').text($(this).attr('data-item-name'));
    });

    $(document).on("click", ".iwbvel-edit-action-numeric-calculator", function () {
        let productId = $(this).attr("data-item-id");
        let productIds;
        let productData = [];

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push(productId);
        }

        productData.push({
            name: $(this).attr("data-name"),
            sub_name: ($(this).attr("data-name")) ? $(this).attr("data-name") : '',
            type: $(this).attr('data-update-type'),
            operator: $("#iwbvel-numeric-calculator-operator").val(),
            value: $("#iwbvel-numeric-calculator-value").val(),
            operator_type: ($("#iwbvel-numeric-calculator-type").val()) ? $("#iwbvel-numeric-calculator-type").val() : 'n',
            round: $("#iwbvel-numeric-calculator-round").val()
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('keyup', 'input[type=number][data-field=download_limit], input[type=number][data-field=download_expiry]', function () {
        if ($(this).val() < -1) {
            $(this).val(-1);
        }
    });

    $(document).on('click', '#iwbvel-quick-search-button', function () {
        if ($('#iwbvel-quick-search-text').val() !== '') {
            $('#iwbvel-quick-search-reset').show();
            $('.iwbvel-quick-filter a').addClass('active');
        }
    });

    $(document).on('click', '#iwbvel-quick-search-reset', function () {
        iwbvelResetFilters()
    });

    $(document).on('click', 'button[data-toggle="modal"][data-target="#iwbvel-modal-product-badges"]', function () {
        $('#iwbvel-modal-product-badges-item-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-product-badges-apply').attr('data-item-id', $(this).attr('data-item-id'));
        $('#iwbvel-modal-product-badge-items').val('').change();
        iwbvelGetProductBadges($(this).attr('data-item-id'));
    });

    $(document).on('click', 'button[data-toggle="modal"][data-target="#iwbvel-modal-ithemeland-badge"]', function () {
        let productId = $(this).attr('data-item-id');
        $('#iwbvel-modal-ithemeland-badge-item-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-ithemeland-badge-apply').attr('data-item-id', productId);
        $('.it_unique_nav_for_general').trigger('click');
        $('#_unique_label_type').val('none').change();
        iwbvelGetProductIthemelandBadge(productId);
    });

    $(document).on('click', 'button[data-toggle="modal"][data-target="#iwbvel-modal-yikes-custom-product-tabs"]', function () {
        $('#iwbvel-modal-yikes-custom-tabs').html('');
        let productId = $(this).attr('data-item-id');
        $('#iwbvel-modal-yikes-custom-product-tabs-item-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-yikes-custom-product-tabs-apply').attr('data-item-id', productId);
        iwbvelGetYikesCustomProductTabs(productId);
    });

    $(document).on('click', '#iwbvel-modal-product-badges-apply', function () {
        let productIds = [];
        let productData = [];
        productIds.push($(this).attr('data-item-id'));
        productData.push({
            name: "_yith_wcbm_product_meta",
            sub_name: "id_badge",
            type: "meta_field",
            operation: "inline_edit",
            value: $('#iwbvel-modal-product-badge-items').val(),
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('click', '#iwbvel-yikes-add-tab', function () {
        let newUniqueId = 'editor-' + Math.floor((Math.random() * 9999) + 1000);
        $('#iwbvel-modal-yikes-custom-product-tabs #duplicate-item').clone().appendTo('#iwbvel-modal-yikes-custom-tabs').ready(function () {
            let duplicated = $('#iwbvel-modal-yikes-custom-tabs').find('#duplicate-item');
            duplicated.find('.iwbvel-yikes-tab-content').attr('data-id', newUniqueId).find('textarea').attr('id', newUniqueId);
            duplicated.removeAttr('id');
            wp.editor.initialize(newUniqueId, iwbvelWpEditorSettings);
        });
    });

    $(document).on('click', '#iwbvel-modal-ithemeland-badge-apply', function () {
        let productIds;
        let productData = [];
        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr("data-item-id"));
        }

        $('#ithemeland-badge-form .ithemeland-badge-form-item[data-value-position="child"]').each(function () {
            let fieldName = $(this).attr('data-name');
            let value;
            switch ($(this).attr('data-type')) {
                case 'text':
                case 'dropdown':
                    value = $('input[name="' + fieldName + '"]').val();
                    break;
                case 'radio':
                case 'checkbox':
                    value = $('input[name="' + fieldName + '"]:checked').val();
                    break;
            }
            productData.push({
                name: fieldName,
                type: 'meta_field',
                value: value,
                operation: 'inline_edit'
            });
        });

        $('#ithemeland-badge-form .ithemeland-badge-form-item[data-value-position="self"]').each(function () {
            let value;
            if ($(this).attr('type') === 'checkbox') {
                value = ($(this).prop('checked') === true) ? 'yes' : 'no';
            } else {
                value = $(this).val()
            }
            productData.push({
                name: $(this).attr('name'),
                type: 'meta_field',
                value: value,
                operation: 'inline_edit'
            });
        });

        iwbvelProductEdit(productIds, productData);
    });

    $('#iwbvel-bulk-edit-select-all-variations').prop('checked', false);

    if (itemIdInUrl && itemIdInUrl > 0) {
        iwbvelResetFilterForm();
        setTimeout(function () {
            $('#iwbvel-filter-form-product-ids').val(itemIdInUrl);
            $('#iwbvel-filter-form-get-products').trigger('click');
        }, 500);
    }

    $(document).on('click', '.iwbvel-yikes-tab-item-header', function (e) {
        if ($.inArray($(e.target).attr('class'), ['iwbvel-yikes-tab-item-header', 'iwbvel-yikes-tab-item-header-title']) !== -1) {
            if ($(this).closest('div.iwbvel-yikes-tab-item').find('.iwbvel-yikes-tab-item-body:visible').length > 0) {
                $('.iwbvel-yikes-tab-item-body').slideUp(250);
            } else {
                $('.iwbvel-yikes-tab-item-body').slideUp(250);
                $(this).closest('div.iwbvel-yikes-tab-item').find('.iwbvel-yikes-tab-item-body').slideDown(250);
            }
        }
    });

    $(document).on('keyup', '.iwbvel-yikes-tab-title input', function () {
        $(this).closest('.iwbvel-yikes-tab-item').find('.iwbvel-yikes-tab-item-header strong').text($(this).val());
    });

    $(document).on('click', '.iwbvel-yikes-tab-item-remove', function () {
        $(this).closest('.iwbvel-yikes-tab-item').remove();
    });

    $(document).on('click', '#iwbvel-modal-yikes-custom-product-tabs-apply', function () {
        let productIds;
        let productData = [];
        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr("data-item-id"));
        }

        let tabs = [];
        let customProductTabsElement = $(this).closest('#iwbvel-modal-yikes-custom-product-tabs').find('#yikes-custom-product-tabs-form .iwbvel-yikes-tab-item');
        if (customProductTabsElement.length > 0) {
            customProductTabsElement.each(function () {
                let editorId = ($(this).find('.iwbvel-yikes-tab-content').attr('data-id'));
                tabs.push({
                    global_tab: $(this).find('input[name="global_tab"]').val(),
                    title: $(this).find('.iwbvel-yikes-tab-title input').val(),
                    content: tinymce.get(editorId).getContent()
                });
            })
        }

        productData.push({
            name: 'yikes_woo_products_tabs',
            type: 'meta_field',
            value: tabs
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('click', '#iwbvel-yikes-add-saved-tab', function () {
        $('#iwbvel-last-modal-opened').val('.iwbvel-yikes-saved-tabs');
        $(this).closest('#iwbvel-modal-yikes-custom-product-tabs').find('.iwbvel-yikes-saved-tabs').fadeIn(250);
    });

    $(document).on('click', '.iwbvel-yikes-saved-tabs-close-button', function () {
        $(this).closest('.iwbvel-yikes-saved-tabs').fadeOut(250);
        $('#iwbvel-last-modal-opened').val('#iwbvel-modal-yikes-custom-product-tabs');
    });

    $(document).on('click', '.iwbvel-yikes-saved-tab-add', function () {
        iwbvelAddYikesSavedTab($(this).attr('data-id'));
        $('.iwbvel-yikes-saved-tabs-close-button').trigger('click')
    });

    $(document).on('change', '.iwbvel-yikes-override-tab', function () {
        let tabItem = $(this).closest('.iwbvel-yikes-tab-item');
        let globalInput = tabItem.find('input[name="global_tab"]');
        if ($(this).prop('checked') === false) {
            globalInput.val(globalInput.attr('data-global-id'));
            tabItem.find('.iwbvel-yikes-tab-title input').prop('disabled', 'disabled');
            tabItem.find('.iwbvel-yikes-tab-content button').prop('disabled', 'disabled');
            tinyMCE.get(tabItem.find('.iwbvel-yikes-tab-content').attr('data-id')).getBody().setAttribute('contenteditable', false);
        } else {
            globalInput.val('');
            tabItem.find('.iwbvel-yikes-tab-title input').prop('disabled', false);
            tabItem.find('.iwbvel-yikes-tab-content button').prop('disabled', false);
            tinyMCE.get(tabItem.find('.iwbvel-yikes-tab-content').attr('data-id')).getBody().setAttribute('contenteditable', true);
        }
    });

    $(document).on('click', '[data-toggle="modal"][data-target="#iwbvel-modal-gallery"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-gallery #iwbvel-modal-gallery-items').html('');
        $('#iwbvel-modal-gallery #iwbvel-modal-gallery-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-gallery #iwbvel-modal-gallery-apply').attr('data-item-id', $(this).attr('data-item-id')).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        iwbvelGetProductGalleryImages($(this).attr('data-item-id'));
    });

    $(document).on('click', '.iwbvel-delete-item-btn', function () {
        let productIds = [];
        productIds.push($(this).attr('data-item-id'));
        let deleteType = $(this).attr('data-delete-type');
        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelDeleteProduct(productIds, deleteType);
            }
        });
    });

    $(document).on('click', '.iwbvel-restore-item-btn', function () {
        let productIds = [];
        productIds.push($(this).attr('data-item-id'));
        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelRestoreProduct(productIds);
            }
        });
    });

    $(document).on('change', '#iwbvel-filter-form-product-status', function () {
        if ($(this).val() == 'trash') {
            $('.iwbvel-nav-trash-button').find('div[data-page="general"]').hide();
            $('.iwbvel-nav-trash-button').find('div[data-page="trash"]').show();
        } else {
            $('.iwbvel-nav-trash-button').find('div[data-page="general"]').show();
            $('.iwbvel-nav-trash-button').find('div[data-page="trash"]').hide();
        }
    });

    $(document).on('click', '.iwbvel-trash-option-restore-selected-items', function () {
        let productIds = iwbvelGetProductsChecked();
        if (!productIds.length) {
            swal({
                title: "Please select one product",
                type: "warning"
            });
            return false;
        } else {
            swal({
                title: iwbvelTranslate.areYouSure,
                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) {
                    if (iwbvelSelectAllChecked()) {
                        productIds = 'all_filtered';
                    }
                    iwbvelLoadingStart();
                    iwbvelRestoreProduct(productIds);
                }
            });
        }
    });

    $(document).on('click', '.iwbvel-trash-option-restore-all', function () {
        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelRestoreProduct([]);
                iwbvelLoadingStart();
            }
        });
    });

    $(document).on('click', '.iwbvel-trash-option-delete-selected-items', function () {
        let productIds = iwbvelGetProductsChecked();
        if (!productIds.length) {
            swal({
                title: "Please select one product",
                type: "warning"
            });
            return false;
        } else {
            swal({
                title: iwbvelTranslate.areYouSure,
                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) {
                    if (iwbvelSelectAllChecked()) {
                        productIds = 'all_filtered';
                    }

                    iwbvelLoadingStart();
                    iwbvelDeleteProduct(productIds, 'permanently');
                }
            });
        }
    });

    $(document).on('click', '.iwbvel-trash-option-delete-all', function () {
        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelEmptyTrash();
                iwbvelLoadingStart();
            }
        });
    });

    $(document).on('click', '#iwbvel-bulk-edit-trash-empty', function () {
        swal({
            title: iwbvelTranslate.areYouSure,
            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) {
                iwbvelEmptyTrash();
            }
        });
    });

    $(document).on('click', '#iwbvel-bulk-edit-trash-restore', function () {
        let productIds = iwbvelGetProductsChecked();
        iwbvelRestoreProduct(productIds);
    });

    $(document).on('click', '[data-toggle="modal"][data-target="#iwbvel-modal-it-wc-dynamic-pricing-all-fields"]', function () {
        let tdElement = $(this).closest('td');
        let productType = $(this).attr('data-item-type');

        $('#iwbvel-modal-it-wc-dynamic-pricing-all-fields .iwbvel-modal-section').each(function () {
            let sectionType = $(this).attr('data-type').split(',');
            if ($.inArray(productType, sectionType) !== -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        })

        $('#iwbvel-modal-it-wc-dynamic-pricing-all-fields').find('input[type="number"]').val('').change();
        $('#iwbvel-modal-it-wc-dynamic-pricing-all-fields').find('select').val('').change();
        $('#iwbvel-modal-it-wc-dynamic-pricing-all-fields').find('input[type="checkbox"]').prop('checked', false);

        $('#iwbvel-modal-it-wc-dynamic-pricing-all-fields-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-it-wc-dynamic-pricing-all-fields-apply').attr('data-item-id', $(this).attr('data-item-id')).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        iwbvelGetItWcDynamicPricingAllFields($(this).attr('data-item-id'));
    });

    $(document).on('click', '[data-toggle="modal"][data-target="#iwbvel-modal-it-wc-dynamic-pricing"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-it-wc-dynamic-pricing').find('input[data-type="value"]').val('').change();
        $('#iwbvel-modal-it-wc-dynamic-pricing-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-it-wc-dynamic-pricing-apply').attr('data-item-id', $(this).attr('data-item-id')).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        iwbvelGetItWcRolePrices($(this).attr('data-item-id'));
    });

    $(document).on('click', '[data-toggle="modal"][data-target="#iwbvel-modal-it-wc-dynamic-pricing-select-roles"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-it-wc-dynamic-pricing-select-roles #iwbvel-user-roles').val('').change();
        $('#iwbvel-modal-it-wc-dynamic-pricing-select-roles-title').text($(this).attr('data-item-name'));
        $('#iwbvel-modal-it-wc-dynamic-pricing-select-roles-apply').attr('data-item-id', $(this).attr('data-item-id')).attr('data-name', tdElement.attr('data-name')).attr('data-update-type', tdElement.attr('data-update-type'));
        iwbvelGetItWcDynamicPricingSelectedRoles($(this).attr('data-item-id'), tdElement.attr('data-name'));
    });

    $(document).on('click', '#iwbvel-modal-it-wc-dynamic-pricing-apply', function () {
        let productIds;
        let productData = [];
        let values = [];

        $(this).closest('#iwbvel-modal-it-wc-dynamic-pricing').find('input[data-type="value"]').each(function () {
            if ($(this).val()) {
                values.push({
                    field: $(this).attr('data-name'),
                    amount: $(this).val()
                });
            }
        });

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr('data-item-id'));
        }

        productData.push({
            name: $(this).attr('data-name'),
            type: $(this).attr('data-update-type'),
            operation: "inline_edit",
            value: values,
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('click', '#iwbvel-modal-it-wc-dynamic-pricing-select-roles-apply', function () {
        let productIds;
        let productData = [];

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr('data-item-id'));
        }

        productData.push({
            name: $(this).attr('data-name'),
            type: $(this).attr('data-update-type'),
            operation: "inline_edit",
            value: $(this).closest('#iwbvel-modal-it-wc-dynamic-pricing-select-roles').find('#iwbvel-user-roles').val(),
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('click', '.iwbvel-acf-taxonomy-multi-select', function () {
        $('.iwbvel-modal-acf-taxonomy-multi-select-value').select2();
    })

    $(document).on('click', '#iwbvel-modal-it-wc-dynamic-pricing-all-fields-apply', function () {
        let productIds;
        let productData = [];

        let pricing_roles = [];

        $(this).closest('#iwbvel-modal-it-wc-dynamic-pricing-all-fields').find('#iwbvel-it-pricing-roles input[data-type="value"]').each(function () {
            if ($(this).val()) {
                pricing_roles.push({
                    field: $(this).attr('data-name'),
                    amount: $(this).val()
                });
            }
        });

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push($(this).attr('data-item-id'));
        }

        productData.push({
            name: $(this).attr('data-name'),
            type: $(this).attr('data-update-type'),
            operation: "inline_edit",
            value: {
                it_product_disable_discount: ($('#iwbvel-it-wc-dynamic-pricing-disable-discount').prop('checked') === true) ? 'yes' : 'no',
                it_product_hide_price_unregistered: ($('#iwbvel-it-wc-dynamic-pricing-hide-price-unregistered').prop('checked') === true) ? 'yes' : 'no',
                pricing_rules_product: pricing_roles,
                it_pricing_product_price_user_role: $('#iwbvel-select-roles-hide-price').val(),
                it_pricing_product_add_to_cart_user_role: $('#iwbvel-select-roles-hide-add-to-cart').val(),
                it_pricing_product_hide_user_role: $('#iwbvel-select-roles-hide-product').val(),
            },
        });

        iwbvelProductEdit(productIds, productData);
    });

    // Compatible with ithemeland badge

    // Only show the "remove image" button when needed
    if (!$('#_unique_label_image').val()) {
        $('.it_remove_image_button').hide();
        $('#_unique_label_image').val('http://wordpress.local/wp-content/plugins/woocommerce-advanced-product-labels/assets/admin/images/placeholder.png');
        $('.product-label img').css({
            "width": '50px'
        });
    }

    // Uploading files
    var file_frame;
    $(document).on('click', '.it_upload_image_button', function (event) {
        event.preventDefault();

        // If the media frame already exists, reopen it.
        if (file_frame) {
            file_frame.open();
            return;
        }

        // Create the media frame.
        file_frame = wp.media.frames.downloadable_file = wp.media({
            title: 'Choose an image',
            button: {
                text: 'Use image',
            },
            multiple: false
        });

        // When an image is selected, run a callback.
        file_frame.on('select', function () {
            attachment = file_frame.state().get('selection').first().toJSON();

            $('#_unique_label_image').val(attachment.url);
            $('#unique_thumbnail img').attr('src', attachment.url);
            $('.it_remove_image_button').show();
            if ($('.custom_label_pic').length < 1) {
                $('.product-label').wrapInner("<img class='custom_label_pic' style='width: auto;' src='" + attachment.url + "'/>");
            } else {
                $('.product-label img').attr('src', attachment.url);
            }
            $('.product-label img').css({
                "width": 'auto'
            });
        });

        // Finally, open the modal.
        file_frame.open();
    });

    $(document).on('click', '.it_remove_image_button', function (event) {
        $('#unique_thumbnail img').attr('src', 'http://wordpress.local/wp-content/plugins/woocommerce-advanced-product-labels/assets/admin/images/placeholder.png');
        $('.product-label img').attr('src', 'http://wordpress.local/wp-content/plugins/woocommerce-advanced-product-labels/assets/admin/images/placeholder.png');
        $('.product-label img').css({
            "width": '50px'
        });
        $('#_unique_label_image').val('');
        $('#_unique_label_image').val('http://wordpress.local/wp-content/plugins/woocommerce-advanced-product-labels/assets/admin/images/placeholder.png');
        $('.it_remove_image_button').hide();
        return false;
    });

    /**************Admin Panel's Setting Tab End Here****************/
    /*custom range*/
    var rangeSlider = function () {
        var slider = $('.range-slider'),
            range = $('.range-slider__range'),
            value = $('.range-slider__value');

        slider.each(function () {

            value.each(function () {
                var value = $(this).prev().attr('value');
                $(this).html(value);
            });

            range.on('input', function () {
                $(this).next(value).html(this.value);
            });
        });
    };

    rangeSlider();
    /*end custom range*/

    if ($(".color-picker").length > 0 && $.fn.wpColorPicker) {
        $(".color-picker").wpColorPicker();
    }

    $(document).on('click', '.iwbvel-history-pagination-item', function () {
        $('.iwbvel-history-pagination-loading').show();

        let filters = {
            operation: $("#iwbvel-history-filter-operation").val(),
            author: $("#iwbvel-history-filter-author").val(),
            fields: $("#iwbvel-history-filter-fields").val(),
            date: {
                from: $("#iwbvel-history-filter-date-from").val(),
                to: $("#iwbvel-history-filter-date-to").val()
            }
        };

        iwbvelHistoryChangePage($(this).attr('data-index'), filters);
    });

    if ($('#iwbvel-settings-show-only-filtered-variations').val() === 'yes') {
        $('#iwbvel-bulk-edit-show-variations').prop('checked', true).attr('disabled', 'disabled');
    }

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

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

    $(document).on('click', '.iwbvel-products-table-load-more-variations', function () {
        $(this).closest('td').find('.iwbvel-products-table-load-more-variations-loading').show();
        iwbvelLoadMoreVariations($(this).attr('data-variable-id'), $(this).attr('data-page'));
    });

    $(document).on('click', '[data-target="#iwbvel-float-side-modal-column-manager"]', function () {
        if ($(this).attr('data-loaded') != 'true') {
            iwbvelColumnManagerLoad();
        }
    });

    $(document).on('click', '[data-target="#iwbvel-float-side-modal-filter-profiles"]', function () {
        if ($(this).attr('data-loaded') != 'true') {
            iwbvelFilterProfileLoad();
        }
    });

    $(document).on('click', '[data-target="#iwbvel-float-side-modal-column-profiles"]', function () {
        if ($(this).attr('data-loaded') != 'true') {
            iwbvelColumnProfileLoad();
        }
    });

    $(document).on('change', '#iwbvel-top-nav-filters-go-to-page', function () {
        if (goToPageProcessing === false && $(this).val() != '') {
            goToPageProcessing = true;
            iwbvelProductsFilter(iwbvelGetCurrentFilterData(), 'pagination', [], $(this).val());
        }
    });

    $(document).on('click', '[data-target="#iwbvel-modal-regular-price"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-regular-price .iwbvel-modal-regular-price-apply-button').attr('data-item-id', tdElement.attr('data-item-id'));
        $('#iwbvel-modal-regular-price .iwbvel-modal-item-title').html(tdElement.attr('data-item-title'));
    });

    $(document).on('click', '[data-target="#iwbvel-modal-sale-price"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-sale-price .iwbvel-modal-sale-price-apply-button').attr('data-item-id', tdElement.attr('data-item-id'));
        $('#iwbvel-modal-sale-price .iwbvel-modal-item-title').html(tdElement.attr('data-item-title'));
    });

    $(document).on('click', '[data-target="#iwbvel-modal-select-author"]', function () {
        jQuery('#iwbvel-modal-select-author-input').html('');
        jQuery('.iwbvel-modal-select-author-loading').show();
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-select-author .iwbvel-modal-select-author-apply-button').attr('data-item-id', tdElement.attr('data-item-id'));
        $('#iwbvel-modal-select-author .iwbvel-modal-item-title').html(tdElement.attr('data-item-title'));

        iwbvelGetProductAuthor(tdElement.attr('data-item-id'));
    });

    $(document).on('click', '.iwbvel-modal-select-author-apply-button', function () {
        let productId = $(this).attr("data-item-id");
        let productIds;
        let productData = [];

        if ($('#iwbvel-bind-edit').prop('checked') === true) {
            productIds = iwbvelGetProductsChecked();
        } else {
            productIds = [];
        }
        if ($.isArray(productIds)) {
            productIds.push(productId);
        }

        productData.push({
            name: 'post_author',
            sub_name: '',
            type: 'wp_posts_field',
            value: $("#iwbvel-modal-select-author-input").val(),
        });

        iwbvelProductEdit(productIds, productData);
    });

    $(document).on('click', '[data-target="#iwbvel-modal-product-taxonomy"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-product-taxonomy .iwbvel-modal-item-title').html(tdElement.attr('data-item-title'));
        $('.iwbvel-inline-edit-taxonomy-save').attr('data-item-id', tdElement.attr('data-item-id')).attr('data-name', tdElement.attr('data-name'));
        $('.iwbvel-inline-edit-add-new-taxonomy').attr('data-item-id', tdElement.attr('data-item-id')).attr('data-field', tdElement.attr('data-name'));
        iwbvelGetProductTaxonomyTerms(tdElement.attr('data-item-id'), tdElement.attr('data-name'));
    });

    $(document).on('click', '[data-target="#iwbvel-modal-product-attribute"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-product-attribute .iwbvel-modal-item-title').html(tdElement.attr('data-item-title'));
        $('.iwbvel-inline-edit-attribute-save').attr('data-item-id', tdElement.attr('data-item-id')).attr('data-name', tdElement.attr('data-name'));
        $('.iwbvel-inline-edit-add-new-attribute').attr('data-item-id', tdElement.attr('data-item-id')).attr('data-field', tdElement.attr('data-name'));
        iwbvelGetProductAttributeTerms(tdElement.attr('data-item-id'), tdElement.attr('data-name'));
    });

    $(document).on('click', '[data-target="#iwbvel-modal-acf-multi-select"]', function () {
        let tdElement = $(this).closest('td');
        $('#iwbvel-modal-acf-multi-select .iwbvel-modal-item-title').html(tdElement.attr('data-item-title'));
        $('#iwbvel-modal-acf-multi-select .iwbvel-edit-action-with-button').attr('data-item-id', tdElement.attr('data-item-id')).attr('data-name', tdElement.attr('data-name'));
        iwbvelGetAcfTaxonomyTerms(tdElement.attr('data-item-id'), tdElement.attr('data-name'));
    });

    $(document).on('click', '.iwbvel-processing-loading-stop-button', function () {
        let $this = $(this);
        swal({
            title: "Do you want to stop the operation?",
            text: "Your changes have been applied to a number of rows.",
            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) {
                $this.hide();
                jQuery('.iwbvel-processing-loading span[data-type="message"]').html(IWBVEL_DATA.background_process.loading_messages.stopping);
                iwbvelBackgroundProcessForceStop();
            }
        });
    });

    $(document).on('click', '.iwbvel-bulk-edit-form-schedule-bulk-edit', function () {
        let container = $('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="set_schedule"]');

        container.find('.iwbvel-set-schedule-form .required:visible').each(function () {
            if ($(this).val() != '') {
                $(this).removeClass('error');
            } else {
                $(this).addClass('error');
            }
        }).promise().done(function () {
            if (container.find('.iwbvel-set-schedule-form').find('.error').length) {
                container.find('.iwbvel-tab-item[data-content="set_schedule"]').trigger('click');
                iwbvelLoadingError('Please fill the required fields');
                return;
            }

            iwbvelLoadingStart();

            let editItems = iwbvelGetBulkEditData();
            let productIds = iwbvelGetProductsChecked();
            let filterItems = ($.isArray(productIds) && productIds.length) ? { product_ids: productIds } : iwbvelGetCurrentFilterData();

            if (!editItems.length) {
                iwbvelLoadingError('Bulk edit form is empty !');
                return;
            }

            let dates = iwbvelScheduleGetDatesFromJobForm(container);

            setTimeout(function () {
                $.ajax({
                    url: IWBVEL_DATA.ajax_url,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        action: 'iwbvel_add_schedule_job',
                        nonce: IWBVEL_DATA.ajax_nonce,
                        label: container.find('.iwbvel-set-schedule-name').val(),
                        description: container.find('.iwbvel-set-schedule-description').val(),
                        run_at: container.find('.iwbvel-set-schedule-run-at').val(),
                        run_for: (container.find('.iwbvel-set-schedule-run-for:visible').length) ? container.find('.iwbvel-set-schedule-run-for').val() : null,
                        dates: dates,
                        filter_items: filterItems,
                        edit_items: editItems,
                        stop_date: (container.find('.iwbvel-set-schedule-stop-date-time:visible').length) ? container.find('.iwbvel-set-schedule-stop-date-time').val() : null,
                        revert_date: (container.find('.iwbvel-set-schedule-revert-date-time:visible').length) ? container.find('.iwbvel-set-schedule-revert-date-time').val() : null,
                    },
                    success: function (response) {
                        if (response.success) {
                            if (container.find('.iwbvel-set-schedule-run-at').val() === 'now') {
                                if (response.is_processing) {
                                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: 0, completed: 0 });
                                    iwbvelIsProcessing();
                                } else {
                                    $('.iwbvel-reload-table').trigger('click');
                                }
                            } else {
                                iwbvelLoadingSuccess();
                            }

                            iwbvelScheduleAwaitingCountUpdate(response.awaiting_count);
                        } else {
                            iwbvelLoadingError((response.message && response.message != '') ? response.message : 'Error !');
                        }

                        if (IWBVEL_DATA.iwbvel_settings.close_popup_after_applying == 'yes') {
                            iwbvelCloseFloatSideModal();
                        }
                        if (IWBVEL_DATA.iwbvel_settings.keep_filled_data_in_bulk_edit_form == 'no') {
                            iwbvelResetBulkEditForm();
                        }
                    },
                    error: function () {
                        iwbvelLoadingError();
                    }
                });
            }, 250);
        });
    });

    iwbvelGetDefaultFilterProfileProducts();
    iwbvelSelect2UsersInit();
    iwbvelSelect2ProductsInit();
    iwbvelSelect2Init();
    iwbvelBackgroundProcessingCheck();
});