/**
 * Main jQuery elements controller for the table settings page
 *
 * Binds the jQuery control elements for manipulating the config object, binds jQuery plugins
 *
 * @author Alexander Gilmanov
 * @since 16.09.2016
 */

(function ($) {
    let customMediaUploader;

    $(function () {

        /**
         * Enable Source file path input and Browse button when source file selectbox option is selected
         */
        $('#wdt-add-data-source-input').attr('disabled', 'disabled');
        $('#wdt-add-data-browse-button').attr('disabled', 'disabled');

        function updateSourceFileDataSelected() {
            if (sourceFileDataSelected()) {
                $('#wdt-add-data-source-input').removeAttr('disabled');
                $('#wdt-add-data-browse-button').removeAttr('disabled');
            } else {
                $('#wdt-add-data-source-input').attr('disabled', 'disabled');
                $('#wdt-add-data-browse-button').attr('disabled', 'disabled');
            }
        }

        function sourceFileDataSelected() {
            return $('#wdt-source-file-data').val() !== '';
        }

        $('#wdt-source-file-data').change(updateSourceFileDataSelected);

        /**
         * Change table type
         */
        $('#wdt-table-type').change(function (e) {
            wpdatatable_config.setTableType($(this).val());
        });

        /**
         * Change file location
         */
        $('#wdt-file-location').change(function (e) {
            wpdatatable_config.setFileLocation($(this).val());
        });

        /**
         * Toggle server-side processing
         */
        $('.wdt-server-side').change(function (e) {
            wpdatatable_config.setServerSide($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Change table name
         */
        $('#wdt-table-title-edit').change(function (e) {
            wpdatatable_config.setTitle($(this).val());
        });
        /**
         * Change table description
         */
        $('#wdt-table-description-edit').change(function (e) {
            wpdatatable_config.setDescription($(this).val());
        });
        /**
         * Change auto-refresh
         */
        $('#wdt-auto-refresh').change(function (e) {
            wpdatatable_config.setAutoRefresh($(this).val());
        });

        /**
         * Change URL
         */
        $('#wdt-input-url').bind('input change', function (e) {
            wpdatatable_config.setContent($(this).val());
        });

        /**
         * Toggle Table Tools selection dropdown
         */
        $('#wdt-table-tools').change(function (e) {
            wpdatatable_config.setShowTableTools($(this).is(':checked') ? 1 : 0, {});
        });

        /**
         * Toggle Table Tools Include HTML option
         */
        $('#wdt-table-tools-include-html').change(function (e) {
            wpdatatable_config.setTableToolsIncludeHTML($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Table Tools Include table title option
         */
        $('#wdt-table-tools-include-title').change(function (e) {
            wpdatatable_config.setTableToolsIncludeTitle($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Responsiveness
         */
        $('#wdt-responsive').change(function (e) {
            wpdatatable_config.setResponsive($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set pagination layout
         */
        $('#wdt-responsive-action').change(function (e) {
            wpdatatable_config.setResponsiveAction($(this).val());
        });

        /**
         * Toggle Scrollable
         */
        $('#wdt-scrollable').change(function (e) {
            wpdatatable_config.setScrollable($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Vertical scroll
         */
        $('#wdt-vertical-scroll').change(function (e) {
            wpdatatable_config.setVerticalScroll($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Hide until loaded
         */
        $('#wdt-hide-until-loaded').change(function (e) {
            wpdatatable_config.setHideBeforeLoad($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Limit Width
         */
        $('#wdt-limit-layout').change(function (e) {
            wpdatatable_config.setLimitLayout($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Word Wrap
         */
        $('#wdt-word-wrap').change(function (e) {
            wpdatatable_config.setWordWrap($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle show title
         */
        $('#wdt-show-title').change(function (e) {
            wpdatatable_config.setShowTitle($(this).is(':checked') ? 1 : 0);
        });
        /**
         * Toggle show description
         */
        $('#wdt-show-description').change(function (e) {
            wpdatatable_config.setShowDescription($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Change display length
         */
        $('#wdt-rows-per-page').change(function (e) {
            if ($(this).data('suppress-change')) return;

            wpdatatable_config.setDisplayLength($(this).val());
        });

        /**
         * Toggle "Show X entries"
         */
        $('#wdt-show-rows-per-page').change(function (e) {
            wpdatatable_config.setShowRowsPerPage($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Change display info block
         */
        $('#wdt-info-block').change(function (e) {
            wpdatatable_config.setInfoBlock($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Enable to go on the top of the table after clicking the pagination buttons
         */
        $('#wdt-pagination-top').change(function (e) {
            wpdatatable_config.setPaginationOnTop($(this).is(':checked') ? 1 : 0);
        });
        /**
         * Enable pagination
         */
        $('#wdt-pagination').change(function (e) {
            wpdatatable_config.setPagination($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set pagination alignment
         */
        $('#wdt-pagination-align').change(function (e) {
            wpdatatable_config.setPaginationAlign($(this).val());
        });

        /**
         * Set pagination layout
         */
        $('#wdt-pagination-layout').change(function (e) {
            wpdatatable_config.setPaginationLayout($(this).val());
        });

        /**
         * Set pagination layout for mobile devices
         */
        $('#wdt-pagination-layout-mobile').change(function (e) {
            wpdatatable_config.setPaginationLayoutMobile($(this).val());
        });

        /**
         * Toggle simple responsive
         */
        $('#wdt-simple-responsive').change(function (e) {
            wpdatatable_config.setSimpleResponsive($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle simple header
         */
        $('#wdt-simple-header').change(function (e) {
            wpdatatable_config.setSimpleHeader($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle stripe table
         */
        $('#wdt-stripe-table').change(function (e) {
            wpdatatable_config.setStripeTable($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set cell padding for simple table
         */
        $('#wdt-cell-padding').change(function (e) {
            wpdatatable_config.setCellPadding($(this).val());
        });

        /**
         * Set cell padding for simple table
         */
        $('#wdt-vertical-scroll-height').change(function (e) {
            wpdatatable_config.setVerticalScrollHeight($(this).val());
        });

        /**
         * Toggle remove borders for simple table
         */
        $('#wdt-remove-borders').change(function (e) {
            wpdatatable_config.setRemoveBorders($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set border collapse for simple table
         */
        $('#wdt-border-collapse').change(function (e) {
            wpdatatable_config.setBorderCollapse($(this).val());
        });

        /**
         * Set border spacing for simple table
         */
        $('#wdt-border-spacing').change(function (e) {
            wpdatatable_config.setBorderSpacing($(this).val());
        });

        /**
         * Toggle Advanced filter
         */
        $('#wdt-advanced-filter').change(function (e) {
            wpdatatable_config.setAdvancedFiltering($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Sorting
         */
        $('#wdt-global-sorting').change(function (e) {
            wpdatatable_config.setSorting($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Global Search
         */
        $('#wdt-global-search').change(function (e) {
            wpdatatable_config.setGlobalSearch($(this).is(':checked') ? 1 : 0);
        });
        /**
         * Toggle cache source data
         */
        $('#wpdt-cache-source-data').change(function (e) {
            wpdatatable_config.setCacheSourceData($(this).is(':checked') ? 1 : 0);
        });
        /**
         * Toggle auto update cache
         */
        $('#wpdt-auto-update-cache').change(function (e) {
            wpdatatable_config.setAutoUpdateCache($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Filters in form
         */
        $('#wdt-filter-in-form').change(function (e) {
            wpdatatable_config.setFilteringForm($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Clear Filters
         */
        $('#wdt-clear-filters').change(function (e) {
            wpdatatable_config.setClearFilters($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Editable
         */
        $('#wdt-editable').change(function (e) {
            wpdatatable_config.setEditable($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle Popover Tools
         */
        $('#wdt-popover-tools').change(function (e) {
            wpdatatable_config.setPopoverTools($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle inline editing
         */
        $('#wdt-inline-editable').change(function (e) {
            wpdatatable_config.setInlineEditing($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set MySQL table name
         */
        $('#wdt-mysql-table-name').change(function (e) {
            wpdatatable_config.setMySQLTableName($(this).val());
        });

        /**
         * Set ID editing column
         */
        $('#wdt-id-editing-column').change(function (e) {
            wpdatatable_config.setIdEditingColumn($(this).val());
        });

        /**
         * Set editor roles
         */
        $('#wdt-editor-roles').change(function (e) {
            wpdatatable_config.setEditorRoles($(this).val());
        });

        /**
         * Set buttons displayed on front-end
         */
        $('#wdt-edit-buttons-displayed').change(function (e) {
            wpdatatable_config.setEditButtonsDisplayed($(this).val());
        });

        /**
         * Toggle duplicate button
         */
        $('#wdt-enable-duplicate-button').on('change', function (e) {
            wpdatatable_config.setEnableDuplicateButton($(this).is(':checked') ? 1 : 0);
            updateEditButtons($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Toggle edit only own rows
         */
        $('#wdt-edit-only-own-rows').change(function (e) {
            wpdatatable_config.setEditOwnRows($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set User ID Column
         */
        $('#wdt-user-id-column').change(function (e) {
            wpdatatable_config.setUserIdColumn($(this).val());
        });

        /**
         * Toggle Show All rows
         */
        $('#wdt-show-all-rows').change(function (e) {
            wpdatatable_config.setShowAllRows($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set Table Tools config
         */
        $('#wdt-table-tools-config').change(function (e) {
            var tableToolsConfig = {};
            var tableToolsSelection = $(this).val();
            for (var i in tableToolsSelection) {
                tableToolsConfig[tableToolsSelection[i]] = 1;
            }

            // Show/hide PDF export options
            if (tableToolsSelection.includes('pdf')) {
                if (!$('div.pdf-export-options').is(":visible")) {
                    $('div.pdf-export-options').animateFadeIn();
                }
            } else {
                $('div.pdf-export-options').animateFadeOut();
                wpdatatable_config.setPdfPaperSize('A4');
                wpdatatable_config.setPdfPageOrientation('portrait');
            }

            if ($(this).val() == null) {
                wpdatatable_config.setShowTableTools(0, []);
            }
            wpdatatable_config.setTableToolsConfig(tableToolsConfig);
        });

        /**
         * Set PDF export paper size
         */
        $('#wdt-pdf-paper-size').change(function (e) {
            wpdatatable_config.setPdfPaperSize($(this).val());
        });

        /**
         * Set PDF export page orientation
         */
        $('#wdt-pdf-page-orientation').change(function (e) {
            wpdatatable_config.setPdfPageOrientation($(this).val());
        });

        $('#wdt-custom-rows-per-page').change(function (e) {
            var isValidFormat = /^(-1|0|[1-9]\d*)(,(?!$)|,(?:-1|0|[1-9]\d*(?<!0))(?:(?!,,)(?<!0)\d*)*)*$/.test($(this).val());
            if (isValidFormat || $(this).val() === "") {
                var newOptions = $(this).val().split(',');
                wpdatatable_config.setCustomDisplayLengthPerRow($(this).val());
                var displayoption = $(this).val() === "" ? 10 : parseInt(newOptions[0]);
                $('#wdt-rows-per-page').val(displayoption).selectpicker('refresh');
                wpdatatable_config.setDisplayLength(displayoption);
            } else {
                $('#wdt-error-modal .modal-body').html(wpdatatables_frontend_strings.customDisplayError_wpdatatables);
                $('#wdt-error-modal').modal('show');
            }
        });
        /**
         * Set Placeholder VAR 1
         */
        $('#wdt-var1-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar1($(this).val());
        });

        /**
         * Set Placeholder VAR 2
         */
        $('#wdt-var2-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar2($(this).val());
        });

        /**
         * Set Placeholder VAR 3
         */
        $('#wdt-var3-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar3($(this).val());
        });

        /**
         * Set Placeholder VAR 4
         */
        $('#wdt-var4-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar4($(this).val());
        });

        /**
         * Set Placeholder VAR 5
         */
        $('#wdt-var5-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar5($(this).val());
        });

        /**
         * Set Placeholder VAR 6
         */
        $('#wdt-var6-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar6($(this).val());
        });

        /**
         * Set Placeholder VAR 7
         */
        $('#wdt-var7-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar7($(this).val());
        });

        /**
         * Set Placeholder VAR 8
         */
        $('#wdt-var8-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar8($(this).val());
        });

        /**
         * Set Placeholder VAR 9
         */
        $('#wdt-var9-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderVar9($(this).val());
        });

        /**
         * Set Placeholder Current User ID
         */
        $('#wdt-user-id-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentUserId($(this).val());
        });

        /**
         * Set Placeholder Current User Login
         */
        $('#wdt-user-login-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentUserLogin($(this).val());
        });

        /**
         * Set Placeholder Current Post ID
         */
        $('#wdt-post-id-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentPostId($(this).val());
        });

        /**
         * Set Placeholder wpdb
         */
        $('#wdt-wpdb-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderWpdb($(this).val());
        });

        /**
         * Set Placeholder Current User Display Name
         */
        $('#wdt-user-display-name-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentUserDisplayName($(this).val());
        });

        /**
         * Set Placeholder Current User First Name
         */
        $('#wdt-user-first-name-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentUserFirstName($(this).val());
        });

        /**
         * Set Placeholder Current User Last Name
         */
        $('#wdt-user-last-name-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentUserLastName($(this).val());
        });

        /**
         * Set Placeholder Current User Email
         */
        $('#wdt-user-email-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentUserEmail($(this).val());
        });
        /**
         * Set Placeholder Current Date
         */
        $('#wdt-date-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentDate($(this).val());
        });
        /**
         * Set Placeholder Current DateTime
         */
        $('#wdt-datetime-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentDateTime($(this).val());
        });
        /**
         * Set Placeholder Current Time
         */
        $('#wdt-time-placeholder').change(function (e) {
            wpdatatable_config.setPlaceholderCurrentTime($(this).val());
        });

        /**
         * Change language on select change for table - "Interface language"
         */
        $('#wdt-table-interface-language').change(function (e) {
            wpdatatable_config.setLanguage($(this).val());
        });

        /**
         * Change table skin
         */
        $('#wdt-table-base-skin').change(function (e) {
            wpdatatable_config.setTableSkin($(this).val());
        });
        $('#wdt-wcag').change(function (e) {
            wpdatatable_config.setWCAG($(this).is(':checked') ? 1 : 0);
        });
        $('#wdt-loader-visibility').change(function (e) {
            wpdatatable_config.setLoaderVisibility($(this).is(':checked') ? 1 : 0);
        });
        /**
         * Change table font
         */
        $('#wdt-table-font').change(function (e) {
            wpdatatable_config.setTableFontColorSettings($(this).data('name'), $(this).val());
        });

        /**
         * Change table font size
         */
        $('#wdt-table-font-size').change(function (e) {
            wpdatatable_config.setTableFontColorSettings($(this).data('name'), $(this).val());

        });

        /**
         * Change table font color
         */
        $('.wdt-color-picker').change(function (e) {
            wpdatatable_config.setTableFontColorSettings($(this).find('.cp-value').data('name'), $(this).find('input').val());
        });

        /**
         * Change table inner border size
         */
        $('#wdt-table-inner-border-size').change(function (e) {
            wpdatatable_config.setTableFontColorSettings($(this).data('name'), $(this).val());

        });

        /**
         * Change table outer border size
         */
        $('#wdt-table-outer-border-size').change(function (e) {
            wpdatatable_config.setTableFontColorSettings($(this).data('name'), $(this).val());

        });

        /**
         * Remove borders from table
         */
        $('#wdt-table-remove-borders').change(function (e) {
            wpdatatable_config.setTableBorderRemoval($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Remove borders from header
         */
        $('#wdt-table-remove-borders-header').change(function (e) {
            wpdatatable_config.setTableBorderRemovalHeader($(this).is(':checked') ? 1 : 0);
        });

        /**
         * Set Custom CSS - "Custom wpDataTables CSS"
         */
        $('#wdt-table-custom-css').change(function (e) {
            if (aceEditorTableCSS.getValue().length > 0) {
                wpdatatable_config.setTableCustomCss(aceEditorTableCSS.getValue());
            } else {
                wpdatatable_config.setTableCustomCss('');
            }

        });

        /**
         * Remove decimal place if value is negative or 0 for int
         * and if value is negative for formula
         */
        $('#wdt-column-decimal-places').change(function (e) {
            var comparisonNumber = wpdatatable_config.currentOpenColumn.type == 'formula' ? -1 : 0;
            if ($('#wdt-column-decimal-places').val() <= comparisonNumber) {
                $('#wdt-column-decimal-places').val('');
            }
        });

        /**
         * Apply syntax highlighter for SQL
         */
        createAceEditor('wdt-mysql-query');

        /**
         * Apply syntax highlighter for custom table CSS
         */
        createAceEditor('wdt-table-custom-css');

        /**
         * Show "Reset options" when "Customize settings" tab is active
         */
        $('.wdt-main-menu a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            var target = $(e.target).attr("href");
            if (target == '#customize-table-settings') {
                $('.wdt-reset-customize-options').show();
            } else {
                $('.wdt-reset-customize-options').hide();
            }
        });

        /**
         * Reset customize options
         */
        $('.wdt-reset-customize-options').click(function (e) {
            e.preventDefault();
            $('#customize-table-settings input.cp-value').val('').change();
            $('#customize-table-settings .wpcolorpicker-icon i').css('background', '#fff');
            wpdatatable_config.tableFontColorSettings = _.mapObject(
                wpdatatable_config.tableFontColorSettings,
                function (color) {
                    return '';
                }
            );
            wpdatatable_config.setTableCustomCss('');
            wpdatatable_config.setLanguage('');
            wpdatatable_config.setTableSkin('');
            $('#wdt-table-remove-borders').prop('checked', false).change();
            $('#wdt-table-remove-borders-header').prop('checked', false).change();
        });

        /**
         * Close column settings
         */
        $('button.wdt-cancel-column-settings').click(function (e) {
            e.preventDefault();
            wpdatatable_config.currentOpenColumn.hide();
        });

        $('#wdt-rows-per-page').on('show.bs.select', function (e) {
            e.preventDefault();
            var customValue = $('#wdt-custom-rows-per-page').val(),
                originalValue = $('#wdt-rows-per-page').data('original-data-length'), newOptions;

            $(this).empty();
            if (customValue !== '') {
                newOptions = customValue.split(',');
            } else {
                newOptions = originalValue.split(',')
            }
            for (var i = 0; i < newOptions.length; i++) {
                var value = newOptions[i];
                var displayText = (value === '-1') ? wpdatatables_frontend_strings.all_wpdatatables : newOptions[i];

                $(this).append($('<option>', {
                    value: value,
                    text: displayText,
                    selected: wpdatatable_config.display_length == value ? true : false
                }));
            }

            $(this).selectpicker('refresh');
        });
        /**
         * Collapse and expand the Table Settings widget
         */
        $('button.wdt-collapse-table-settings').click(function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            if ($(this).hasClass('expanded')) {
                $(this).find('i').removeClass('wpdt-icon-angle-up').addClass('wpdt-icon-angle-down');
                $(this).closest('.card').find('div.card-body').slideUp();
                $(this).removeClass('expanded').addClass('collapsed');
            } else {
                $(this).find('i').addClass('wpdt-icon-angle-up').removeClass('wpdt-icon-angle-down');
                $(this).closest('.card').find('div.card-body').slideDown();
                $(this).addClass('expanded').removeClass('collapsed');
            }
        });

        /**
         * Reset column values
         */
        $('#wdt-column-values-reset').click(function (e) {
            e.preventDefault();
            $('#wdt-column-values-list')
                .tagsinput('removeAll');
        });

        /**
         * Configure column values
         */
        $('#wdt-column-values').change(function (e) {
            e.preventDefault();

            $('select#wdt-column-editor-input-type').find('option')
                .prop('disabled', false);

            $('#wdt-possible-values-ajax')
                .prop('disabled', false);

            if ($(this).val() === 'read') {
                $('div.wdt-manual-list-enter-block').hide();
                $('div.wdt-foreign-key-block').hide();
                $('.wdt-possible-values-ajax-block').show();
                $('.wdt-possible-values-foreign-keys-block').hide();
            } else if ($(this).val() === 'list') {
                $('div.wdt-manual-list-enter-block').show();
                $('div.wdt-foreign-key-block').hide();
                $('.wdt-possible-values-ajax-block').show();
                $('.wdt-possible-values-foreign-keys-block').hide();
            } else if ($(this).val() === 'foreignkey') {
                if ($.inArray(wpdatatable_config.currentOpenColumn.filter_type, ['select', 'checkbox']) !== -1) {
                    $('#wdt-column-exact-filtering').prop('checked', 1).change();
                    $('#wdt-column-range-slider').prop('checked', 1).change();
                }
                $('div.wdt-manual-list-enter-block').hide();
                $('div.wdt-foreign-key-block').show();
                $('div.wdt-foreign-rule-display').show();
                $('.wdt-possible-values-ajax-block').hide();
                $('.wdt-and-logic-block').hide();
                $('#wdt-and-logic').prop('checked', false);
                if (wpdatatable_config.edit_only_own_rows == 1) {
                    $('.wdt-possible-values-foreign-keys-block').show();
                } else {
                    $('.wdt-possible-values-foreign-keys-block').hide();
                }

                $('select#wdt-column-editor-input-type').find('option')
                    .not('[value=selectbox]')
                    .not('[value=none]')
                    .prop('disabled', true);
                if ($('select#wdt-column-editor-input-type').val() == null) {
                    $('select#wdt-column-editor-input-type').selectpicker('val', 'none');
                }
            } else {
                $('div.wdt-possible-values-options-block').hide();
            }

            $('select#wdt-column-editor-input-type').selectpicker('refresh');

            if (wpdatatable_config.currentOpenColumn.foreignKeyRule == null) {
                $('#wdt-column-foreign-table').selectpicker('val', 0).trigger('change');

                $('.wdt-foreign-rule-display #wdt-connected-table-name').text('-');
                $('.wdt-foreign-rule-display #wdt-connected-table-show-column').text('-');
                $('.wdt-foreign-rule-display #wdt-connected-table-value-column').text('-');
            }

        });

        /**
         * Show columns list modal
         */
        $('#wdt-open-columns-list').click(function (e) {
            e.preventDefault();
            $('#wdt-columns-list-modal').modal('show');
        });

        /**
         * Show Foreign Key config modal
         */
        $('#wdt-foreign-key-open').click(function (e) {
            e.preventDefault();
            $('#wdt-configure-foreign-key-modal').modal('show');
            if (wpdatatable_config.currentOpenColumn.foreignKeyRule) {
                $('#wdt-column-foreign-table')
                    .selectpicker('val', wpdatatable_config.currentOpenColumn.foreignKeyRule.tableId).trigger('change');
            }
        });

        /**
         * Apply Dragula within columns list modal
         */
        dragula([$('div.wdt-columns-container').get(0)])
            .on('dragend', function (el) {
                $('#wdt-columns-list-modal div.wdt-column-block:not(.select-all)').each(function () {
                    wpdatatable_config
                        .getColumnByHeader($(this).data('orig_header'))
                        .setPos($(this).index())
                });
            });

        /**
         * Open formula editor
         */
        $('button.wdt-add-formula-column,button.wdt-open-formula-editor').click(function (e) {
            e.preventDefault();
            if (wpdatatable_config.currentOpenColumn !== null) {
                $('#wdt-formula-editor-modal textarea').val(wpdatatable_config.currentOpenColumn.formula);
            } else {
                $('#wdt-formula-editor-modal textarea').val('');
            }
            $('div.wdt-formula-result-preview').addClass('hidden');
            $('#wdt-formula-editor-modal').modal('show');
        });

        /*
         * Open add column modal
         */
        $('button.wdt-add-column').click(function (e) {
            e.preventDefault();
            $('#wdt-add-column-modal').modal('show');
        });

        /*
         * Open remove column modal
         */
        $('button.wdt-remove-column').click(function (e) {
            e.preventDefault();
            $('#wdt-remove-column-modal').modal('show');
        });

        /**
         * Delete conditional formatting rule
         */
        $(document).on('click', 'button.wdt-delete-conditional-formatting-rule', function (e) {
            var $block = $(this).closest('div.wdt-conditional-formatting-rule');
            $block.remove();
        });

        $('#wdt-column-type').change(function (e) {

            /**
             * Remove foreign key rules for non-string columns
             */
            if ($(this).val() !== 'string' && wpdatatable_config.currentOpenColumn.foreignKeyRule) {
                delete wpdatatable_config.currentOpenColumn.foreignKeyRule;
            }


            /**
             * Show/hide different settings for different column types
             */
            if ($(this).val() == 'hidden') {
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-skip-thousands-separator-block').hide();
                $('div.wdt-numeric-column-block').hide();
                $('div.wdt-float-column-block').hide();
                $('div.wdt-date-input-format-block').hide();
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                $('div.wdt-numeric-column-block.wdt-skip-thousands-separator-block').hide();
            } else if ($(this).val() == 'formula') {
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-formula-column-block').show();
                $('div.wdt-skip-thousands-separator-block').hide();
                $('div.wdt-numeric-column-block').show();
                $('div.wdt-float-column-block').show();
                $('div.wdt-date-input-format-block').hide();
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                $('div.wdt-numeric-column-block.wdt-skip-thousands-separator-block').hide();
            } else if (['int', 'float'].indexOf($(this).val()) !== -1) {
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-numeric-column-block').show();
                $('div.wdt-date-input-format-block').hide();
                if ($(this).val() == 'float') {
                    $('div.wdt-skip-thousands-separator-block').hide();
                    $('div.wdt-float-column-block').show();
                } else {
                    $('div.wdt-float-column-block').hide();
                    $('div.wdt-skip-thousands-separator-block').show();
                }
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                if ($('#wdt-column-filter-type').val() === 'number-range') {
                    $('div.wdt-number-range-slider').show();
                }
            } else if ($(this).val() == 'string') {
                $('div.wdt-possible-values-type-block').show();
                $('div.wdt-possible-values-options-block').show();
                $('div.wdt-numeric-column-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-date-input-format-block').hide();
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                $('div.wdt-number-range-slider').hide();
            } else if (['date', 'datetime'].indexOf($(this).val()) !== -1
                && $.inArray(wpdatatable_config.table_type, ['xls', 'csv', 'google_spreadsheet', 'json', 'nested_json', 'xml', 'serialized']) !== -1) {
                $('div.wdt-date-input-format-block').show();
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-numeric-column-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                $('div.wdt-number-range-slider').hide();
            } else if ($(this).val() == 'link') {
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-numeric-column-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-date-input-format-block').hide();
                $('div.wdt-link-target-attribute-block').show();
                $('div.wdt-link-nofollow-attribute-block').show();
                $('div.wdt-link-noreferrer-attribute-block').show();
                $('div.wdt-link-sponsored-attribute-block').show();
                if ($('#wdt-link-button-attribute').is(':checked')) {
                    $('div.wdt-link-button-label-block').show();
                    $('div.wdt-link-button-class-block').show();
                }
                $('div.wdt-link-button-attribute-block').show();
                $('div.wdt-number-range-slider').hide();
            } else if ($(this).val() == 'select' || $(this).val() == 'cart') {
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-skip-thousands-separator-block').hide();
                $('div.wdt-numeric-column-block').hide();
                $('div.wdt-float-column-block').hide();
                $('div.wdt-date-input-format-block').hide();
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                $('div.wdt-numeric-column-block.wdt-skip-thousands-separator-block').hide();
            } else {
                $('div.wdt-possible-values-type-block').hide();
                $('div.wdt-possible-values-options-block').hide();
                $('div.wdt-numeric-column-block').hide();
                $('div.wdt-formula-column-block').hide();
                $('div.wdt-date-input-format-block').hide();
                $('div.wdt-link-target-attribute-block').hide();
                $('div.wdt-link-nofollow-attribute-block').hide();
                $('div.wdt-link-noreferrer-attribute-block').hide();
                $('div.wdt-link-sponsored-attribute-block').hide();
                $('div.wdt-link-button-attribute-block').hide();
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
                $('div.wdt-number-range-slider').hide();
            }
        });

        /**
         * Show different Default Value(s) input(s) for different filter types
         */
        $('#wdt-column-filter-type').change(function (e) {
            var filterType = $(this).val();
            var $filterInput = $('#wdt-filter-default-value');
            var $filterInputBlock = $('.wdt-filter-default-value-block');
            var $filterInputFrom = $('#wdt-filter-default-value-from');
            var $filterInputFromBlock = $('.wdt-filter-default-value-from-block');
            var $filterInputTo = $('#wdt-filter-default-value-to');
            var $filterInputToBlock = $('.wdt-filter-default-value-to-block');
            var $filterInputSelectpicker = $('#wdt-filter-default-value-selectpicker');
            var $filterInputSelectpickerBlock = $('.wdt-filter-default-value-selectpicker-block');
            var $renderCheckboxesInModal = $('.wdt-checkboxes-in-modal-block #wdt-checkboxes-in-modal');
            var $andLogic = $('.wdt-and-logic-block #wdt-and-logic');
            var $renderSearchInSelectBox = $('.wdt-search-in-selectbox-block #wdt-search-in-selectbox');
            var $renderCheckboxesInModalBlock = $('.wdt-checkboxes-in-modal-block');
            var $renderSearchInSelectBoxBlock = $('.wdt-search-in-selectbox-block');
            let $rangeSliderMaxBlock = $('.wdt-range-max-value');
            let $rangeSliderCustomMaxBlock = $('.wdt-range-max-value-custom');
            let columnType = $('#wdt-column-type').val();
            var $andLogicBlock = $('.wdt-and-logic-block');
            var $useAndLogicBlock = $('#wdt-column-type').val() === 'string' && $('#wdt-column-values').val() !== 'foreignkey';
            var typeAttr = 'text';
            let $foreignKeyFilteringNotice = $('.wdt-foreign-key-filter-alert');

            $renderCheckboxesInModal.prop('checked', 0);
            $andLogic.prop('checked', 0);
            if ($.inArray(filterType, ['text', 'number']) != -1) {
                $('div.wdt-exact-filtering-block').show();
                $('div.wdt-number-range-slider').hide();
                $rangeSliderMaxBlock.hide();
                $rangeSliderCustomMaxBlock.hide();
                if (filterType === 'number')
                    typeAttr = 'number';
                $filterInput.attr('type', typeAttr);
                $filterInputBlock.show();
                $filterInputFromBlock.hide();
                $filterInputToBlock.hide();
                $filterInputSelectpickerBlock.hide();
                $filterInputFrom.val('');
                $filterInputTo.val('');
                $filterInputSelectpicker.selectpicker('deselectAll');
                $renderCheckboxesInModalBlock.hide();
                $renderSearchInSelectBoxBlock.hide();
                $andLogicBlock.hide();
                if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'foreignkey') {
                    $foreignKeyFilteringNotice.removeClass('hidden').show();
                } else {
                    $foreignKeyFilteringNotice.addClass('hidden').hide();
                }
            } else if ($.inArray(filterType, ['number-range', 'date-range', 'datetime-range', 'time-range']) != -1) {
                $('div.wdt-exact-filtering-block').hide();
                $('div.wdt-number-range-slider').hide();
                $rangeSliderMaxBlock.hide();
                $rangeSliderCustomMaxBlock.hide();
                $filterInputBlock.hide();
                $filterInputFromBlock.show();
                $filterInputToBlock.show();
                $filterInputSelectpickerBlock.hide();
                $filterInputFrom.val('');
                $filterInputTo.val('');
                $filterInputSelectpicker.selectpicker('deselectAll');
                $renderCheckboxesInModalBlock.hide();
                $renderSearchInSelectBoxBlock.hide();
                $andLogicBlock.hide();
                if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'foreignkey') {
                    $foreignKeyFilteringNotice.removeClass('hidden').show();
                } else {
                    $foreignKeyFilteringNotice.addClass('hidden').hide();
                }

                if ($filterInputFrom.data('DateTimePicker') != undefined)
                    $filterInputFrom.data('DateTimePicker').destroy();

                if ($filterInputTo.data('DateTimePicker') != undefined)
                    $filterInputTo.data('DateTimePicker').destroy();

                if (filterType == 'number-range' && $.inArray(columnType, ['float', 'int']) !== -1) {
                    $('div.wdt-number-range-slider').show();
                    typeAttr = 'number';

                    if ($('#wdt-column-range-slider').is(':checked')) {
                        $rangeSliderMaxBlock.show();
                        $('#wdt-max-value-display').trigger('change');
                    }
                }


                $filterInputFrom
                    .attr('type', typeAttr)
                    .removeClass('wdt-datepicker wdt-datetimepicker wdt-timepicker');
                $filterInputTo
                    .attr('type', typeAttr)
                    .removeClass('wdt-datepicker wdt-datetimepicker wdt-timepicker');

                if (filterType != 'number-range') {
                    $filterInputFrom
                        .addClass('wdt-' + filterType.substring(0, filterType.indexOf('-')) + 'picker');
                    $filterInputTo
                        .addClass('wdt-' + filterType.substring(0, filterType.indexOf('-')) + 'picker')
                }
            } else {
                $('div.wdt-exact-filtering-block').show();
                $('div.wdt-number-range-slider').hide();
                $rangeSliderMaxBlock.hide();
                $rangeSliderCustomMaxBlock.hide();
                $filterInputBlock.hide();
                $filterInputFromBlock.hide();
                $filterInputToBlock.hide();
                $filterInputSelectpickerBlock.show();
                $renderCheckboxesInModalBlock.hide();
                $renderSearchInSelectBoxBlock.hide();
                $andLogicBlock.hide();
                $foreignKeyFilteringNotice.addClass('hidden').hide();

                // Must recreate selectpicker block because Ajax Selectpicker
                $filterInputSelectpickerBlock.html('<div class="fg-line"><div class="select"><select class="selectpicker" id="wdt-filter-default-value-selectpicker" data-none-selected-text="' + wpdatatables_frontend_strings.nothingSelected_wpdatatables + '" data-live-search="true" title="' + wpdatatables_frontend_strings.nothingSelected_wpdatatables + '"></select></div></div>');
                $filterInputSelectpicker = $('#wdt-filter-default-value-selectpicker');
                $filterInputSelectpicker.html('');

                if (filterType === 'checkbox' || filterType === 'multiselect') {
                    $filterInputSelectpicker.attr('multiple', 'multiple');
                } else {
                    // $filterInputSelectpicker.prepend('<option value="" data-empty="true" selected="selected"></option>');
                    $filterInputSelectpicker.removeAttr('multiple');
                }

                if (filterType === 'checkbox') {
                    if (wpdatatable_config.filtering_form)
                        $renderCheckboxesInModalBlock.show();

                    if ($useAndLogicBlock)
                        $andLogicBlock.show();
                }
                if (filterType === 'multiselect' || filterType === 'select') {
                    $renderSearchInSelectBoxBlock.show();
                    if (filterType === 'multiselect' && $useAndLogicBlock) {
                        $andLogicBlock.show();
                    } else {
                        $andLogicBlock.hide();
                    }

                    if (wpdatatable_config.currentOpenColumn.possibleValuesAjax === -1) {
                        $renderSearchInSelectBox.prop('checked', 0);
                    } else {
                        $renderSearchInSelectBox.prop('checked', 1);
                    }
                }

                if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'foreignkey') {
                    $('#wdt-column-exact-filtering').prop('checked', 1).change();
                    $('#wdt-column-range-slider').prop('checked', 1).change();
                }

                var options = '';

                if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'read' || wpdatatable_config.currentOpenColumn.possibleValuesType === 'foreignkey') {
                    if (wpdatatable_config.currentOpenColumn.filterDefaultValue) {
                        if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'read') {
                            var defaultValues = wpdatatable_config.currentOpenColumn.filterDefaultValue.split('|');

                            $.each(defaultValues, function (index, value) {
                                if (value) {
                                    options += '<option selected value="' + value + '">' + value + '</option>'
                                }
                            });
                        } else {
                            if ($.isArray(wpdatatable_config.currentOpenColumn.filterDefaultValue)) {
                                $.each(wpdatatable_config.currentOpenColumn.filterDefaultValue, function (index, value) {
                                    if (value) {
                                        options += '<option selected value="' + value.value + '">' + value.text + '</option>'
                                    }
                                });
                            } else {
                                options += '<option selected value="' + wpdatatable_config.currentOpenColumn.filterDefaultValue.value + '">' + wpdatatable_config.currentOpenColumn.filterDefaultValue.text + '</option>'
                            }
                        }

                        $filterInputSelectpicker.append(options);
                    }

                    $filterInputSelectpicker.selectpicker('destroy').selectpicker('render')
                        .ajaxSelectPicker({
                            ajax: {
                                url: ajaxurl,
                                method: 'POST',
                                data: {
                                    wdtNonce: $('#wdtNonce').val(),
                                    action: 'wpdatatables_get_column_possible_values',
                                    tableId: wpdatatable_config.id,
                                    originalHeader: wpdatatable_config.currentOpenColumn.orig_header
                                }
                            },
                            cache: false,
                            preprocessData: function (data) {
                                if ($filterInputSelectpicker.attr('multiple') !== 'multiple')
                                    data.unshift({value: ''});
                                return data
                            },
                            preserveSelected: true,
                            emptyRequest: true,
                            preserveSelectedPosition: 'before',
                            locale: {
                                emptyTitle: wpdatatables_frontend_strings.nothingSelected_wpdatatables,
                                statusSearching: wpdatatables_frontend_strings.sLoadingRecords_wpdatatables,
                                currentlySelected: wpdatatables_frontend_strings.currentlySelected_wpdatatables,
                                errorText: wpdatatables_frontend_strings.errorText_wpdatatables,
                                searchPlaceholder: wpdatatables_frontend_strings.search_wpdatatables,
                                statusInitialized: wpdatatables_frontend_strings.statusInitialized_wpdatatables,
                                statusNoResults: wpdatatables_frontend_strings.statusNoResults_wpdatatables,
                                statusTooShort: wpdatatables_frontend_strings.statusTooShort_wpdatatables
                            }
                        });

                    $filterInputSelectpicker.trigger('change').data('AjaxBootstrapSelect').list.cache = {};
                    $filterInputSelectpicker.on('show.bs.select', function (e) {
                        $filterInputSelectpickerBlock.find('.bs-searchbox .form-control').val('').trigger('keyup');
                    });

                    if (filterType === 'multiselect') {
                        $foreignKeyFilteringNotice.removeClass('hidden').show();
                    } else {
                        $foreignKeyFilteringNotice.addClass('hidden').hide();
                    }
                } else {
                    if (wpdatatable_config.currentOpenColumn.valuesList !== null && !$.isArray(wpdatatable_config.currentOpenColumn.valuesList)) {
                        var defaultValuesData = wpdatatable_config.currentOpenColumn.valuesList.split('|');
                    }

                    if ($filterInputSelectpicker.attr('multiple') !== 'multiple')
                        options += '<option value="" data-empty="true" selected="selected"></option>'

                    $.each(defaultValuesData, function (index, value) {
                        if (value) {
                            options += '<option value="' + value + '">' + value + '</option>'
                        }
                    });

                    $filterInputSelectpicker.append(options);
                    $filterInputSelectpicker.selectpicker('destroy').selectpicker('render')
                }
            }

        });

        /**
         * Show/hide sorting direction block on 'default sorting' switch toggle
         */
        $('#wdt-column-default-sort').change(function (e) {
            if ($(this).is(':checked')) {
                $('div.wdt-column-default-sorting-direction-block').show();
            } else {
                $('div.wdt-column-default-sorting-direction-block').hide();
            }
        });

        /**
         * Show/hide predefined input for hidden fields (post-meta, query-param and acf-data)
         */
        $(document).on('change', '#wdt-editing-hidden-default-value-selectpicker', function (e) {
            $('.wdt-editing-hidden-query-param-value-block').hide()
            $('.wdt-editing-hidden-post-meta-value-block').hide()
            $('.wdt-editing-hidden-acf-data-value-block').hide()
            if ($.inArray($(this).val(), ['query-param', 'post-meta', 'acf-data']) != -1) {
                $('.wdt-editing-hidden-' + $(this).val() + '-value-block').show()
            }
        });


        /**
         * Show/hide editing blocks when 'none' is selected as editor input type.
         * Change 'Predefined value(s)' input type based on editor input type.
         */
        $('#wdt-column-editor-input-type').change(function (e) {

            $('div.wdt-editing-enabled-block').show();
            $('div.wdt-dynamic-editing-predefined-block').hide();
            var editorInputType = $(this).val();
            var $defaultValueInput = $('#wdt-editing-default-value');
            var $defaultValueInputBlock = $('.wdt-editing-default-value-block');
            var $defaultValueSelectpicker = $('#wdt-editing-default-value-selectpicker');
            var $defaultValueSelectpickerBlock = $('.wdt-editing-default-value-selectpicker-block');
            var $searchInSelectBoxEditingBlock = $('.wdt-search-in-selectbox-editing-block');
            var $searchInSelectBoxEditing = $('#wdt-search-in-selectbox-editing');

            if ($.inArray(editorInputType, ['text', 'textarea', 'mce-editor', 'link', 'email', 'attachment']) != -1) {
                $defaultValueInputBlock.show();
                $defaultValueSelectpickerBlock.hide();
                $searchInSelectBoxEditingBlock.hide();

                if ($defaultValueInput.data('DateTimePicker') != undefined)
                    $defaultValueInput.data('DateTimePicker').destroy();

                $defaultValueInput
                    .removeClass('wdt-datepicker wdt-datetimepicker wdt-timepicker');

            } else if ($.inArray(editorInputType, ['date', 'datetime', 'time']) != -1) {
                $defaultValueInputBlock.show();
                $defaultValueSelectpickerBlock.hide();
                $searchInSelectBoxEditingBlock.hide();

                if ($defaultValueInput.data('DateTimePicker') != undefined)
                    $defaultValueInput.data('DateTimePicker').destroy();

                $defaultValueInput
                    .removeClass('wdt-datepicker wdt-datetimepicker wdt-timepicker');

                $defaultValueInput
                    .addClass('wdt-' + editorInputType + 'picker');

            } else if ($.inArray(editorInputType, ['selectbox', 'multi-selectbox']) != -1) {
                $defaultValueInputBlock.hide();
                $defaultValueSelectpickerBlock.show();
                $searchInSelectBoxEditingBlock.show();
                if (wpdatatable_config.currentOpenColumn.possibleValuesAjax === -1) {
                    $searchInSelectBoxEditing.prop('checked', 0);
                } else {
                    $searchInSelectBoxEditing.prop('checked', 1);
                }
                $defaultValueInput.val('');

                $defaultValueSelectpickerBlock.html('<div class="fg-line"><div class="select"><select class="selectpicker" id="wdt-editing-default-value-selectpicker" data-none-selected-text="' + wpdatatables_frontend_strings.nothingSelected_wpdatatables + '" data-live-search="true"></select></div></div>');
                $defaultValueSelectpicker = $('#wdt-editing-default-value-selectpicker');
                $defaultValueSelectpicker.html('');

                if (editorInputType === 'multi-selectbox') {
                    $defaultValueSelectpicker.attr('multiple', 'multiple');
                } else {
                    $defaultValueSelectpicker.removeAttr('multiple');
                }

                var options = '';
                if (wpdatatable_config.currentOpenColumn.editingDefaultValue) {
                    if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'read' || wpdatatable_config.currentOpenColumn.possibleValuesType === 'list') {
                        if (!$.isArray(wpdatatable_config.currentOpenColumn.editingDefaultValue))
                            var defaultValues = wpdatatable_config.currentOpenColumn.editingDefaultValue.split('|');

                        $.each(defaultValues, function (index, value) {
                            if (value) {
                                options += '<option selected value="' + value + '">' + value + '</option>'
                            }
                        });
                    } else if (wpdatatable_config.currentOpenColumn.possibleValuesType === 'foreignkey') {
                        if ($.isArray(wpdatatable_config.currentOpenColumn.editingDefaultValue)) {
                            $.each(wpdatatable_config.currentOpenColumn.editingDefaultValue, function (index, value) {
                                if (value) {
                                    options += '<option selected value="' + value.value + '">' + value.text + '</option>'
                                }
                            });
                        } else {
                            options += '<option selected value="' + wpdatatable_config.currentOpenColumn.editingDefaultValue.value + '">' + wpdatatable_config.currentOpenColumn.editingDefaultValue.text + '</option>'
                        }
                    }
                }

                $defaultValueSelectpicker.append(options);

                $defaultValueSelectpicker.selectpicker('destroy').selectpicker('render')
                    .ajaxSelectPicker({
                        ajax: {
                            url: ajaxurl,
                            method: 'POST',
                            data: {
                                wdtNonce: $('#wdtNonce').val(),
                                action: 'wpdatatables_get_column_possible_values',
                                tableId: wpdatatable_config.id,
                                originalHeader: wpdatatable_config.currentOpenColumn.orig_header
                            }
                        },
                        cache: false,
                        preprocessData: function (data) {
                            if ($defaultValueSelectpicker.attr('multiple') !== 'multiple')
                                data.unshift({value: ''});
                            return data
                        },
                        preserveSelected: true,
                        emptyRequest: true,
                        preserveSelectedPosition: 'before',
                        locale: {
                            emptyTitle: wpdatatables_frontend_strings.nothingSelected_wpdatatables,
                            statusSearching: wpdatatables_frontend_strings.sLoadingRecords_wpdatatables,
                            currentlySelected: wpdatatables_frontend_strings.currentlySelected_wpdatatables,
                            errorText: wpdatatables_frontend_strings.errorText_wpdatatables,
                            searchPlaceholder: wpdatatables_frontend_strings.search_wpdatatables,
                            statusInitialized: wpdatatables_frontend_strings.statusInitialized_wpdatatables,
                            statusNoResults: wpdatatables_frontend_strings.statusNoResults_wpdatatables,
                            statusTooShort: wpdatatables_frontend_strings.statusTooShort_wpdatatables
                        }
                    });

                $defaultValueSelectpicker.trigger('change').data('AjaxBootstrapSelect').list.cache = {};
                $defaultValueSelectpicker.on('show.bs.select', function (e) {
                    $defaultValueSelectpickerBlock.find('.bs-searchbox .form-control').val('').trigger('keyup');
                });
            } else if (editorInputType == 'hidden') {
                if (wpdatatable_config.currentOpenColumn.editingDefaultValue) {
                    $('div.wdt-editing-enabled-block').hide();
                    $('div.wdt-dynamic-editing-predefined-block').show();
                    if (wpdatatable_config.currentOpenColumn.editingDefaultValue.indexOf("query-param:") != -1) {
                        var queryParam = wpdatatable_config.currentOpenColumn.editingDefaultValue.replace('query-param:', '')
                        $('#wdt-editing-hidden-default-value-selectpicker').selectpicker('val', 'query-param');
                        $('.wdt-editing-hidden-query-param-value-block').show()
                        $('.wdt-editing-hidden-query-param-value').val(queryParam)
                        $('.wdt-editing-hidden-acf-data-value-block').hide()
                        $('.wdt-editing-hidden-acf-data-value').val('')
                        $('.wdt-editing-hidden-post-meta-value-block').hide()
                        $('.wdt-editing-hidden-post-meta-value').val('')
                    } else if (wpdatatable_config.currentOpenColumn.editingDefaultValue.indexOf("post-meta:") != -1) {
                        var postMeta = wpdatatable_config.currentOpenColumn.editingDefaultValue.replace('post-meta:', '')
                        $('#wdt-editing-hidden-default-value-selectpicker').selectpicker('val', 'post-meta');
                        $('.wdt-editing-hidden-post-meta-value-block').show()
                        $('.wdt-editing-hidden-post-meta-value').val(postMeta)
                        $('.wdt-editing-hidden-query-param-value-block').hide()
                        $('.wdt-editing-hidden-query-param-value').val('')
                        $('.wdt-editing-hidden-acf-data-value-block').hide()
                        $('.wdt-editing-hidden-acf-data-value').val('')
                    } else if (wpdatatable_config.currentOpenColumn.editingDefaultValue.indexOf("acf-data:") != -1) {
                        var acfData = wpdatatable_config.currentOpenColumn.editingDefaultValue.replace('acf-data:', '')
                        $('#wdt-editing-hidden-default-value-selectpicker').selectpicker('val', 'acf-data');
                        $('.wdt-editing-hidden-acf-data-value-block').show()
                        $('.wdt-editing-hidden-acf-data-value').val(acfData)
                        $('.wdt-editing-hidden-post-meta-value-block').hide()
                        $('.wdt-editing-hidden-post-meta-value').val('')
                        $('.wdt-editing-hidden-query-param-value-block').hide()
                        $('.wdt-editing-hidden-query-param-value').val('')
                    } else {
                        $('#wdt-editing-hidden-default-value-selectpicker').selectpicker('val', wpdatatable_config.currentOpenColumn.editingDefaultValue);
                        $('.wdt-editing-hidden-query-param-value-block').hide()
                        $('.wdt-editing-hidden-query-param-value').val('')
                        $('.wdt-editing-hidden-post-meta-value-block').hide()
                        $('.wdt-editing-hidden-post-meta-value').val('')
                        $('.wdt-editing-hidden-acf-data-value-block').hide()
                        $('.wdt-editing-hidden-acf-data-value').val('')
                    }
                    $('#wdt-editing-hidden-default-value-selectpicker').selectpicker('refresh');
                } else {
                    $('#wdt-editing-hidden-default-value-selectpicker').selectpicker('val', wpdatatable_config.currentOpenColumn.editingDefaultValue);
                    $('.wdt-editing-hidden-query-param-value-block').hide()
                    $('.wdt-editing-hidden-query-param-value').val('')
                    $('.wdt-editing-hidden-post-meta-value-block').hide()
                    $('.wdt-editing-hidden-post-meta-value').val('')
                    $('.wdt-editing-hidden-acf-data-value-block').hide()
                    $('.wdt-editing-hidden-acf-data-value').val('')
                }
            } else {
                $defaultValueInput.val('');
                $('div.wdt-editing-enabled-block').hide();
            }

        });

        /**
         * Add a conditional formatting rule
         */
        $('button.wdt-column-add-conditional-formatting-rule').click(function (e) {
            if (wpdatatable_config.currentOpenColumn == null) {
                return;
            }
            wpdatatable_config.currentOpenColumn.renderConditionalFormattingBlock({
                ifClause: 'eq',
                cellVal: '',
                action: 'setCellColor',
                setVal: ''
            });
        });

        /**
         * Show/hide the filter selection block on 'enable filtering' switch toggle
         */
        $('#wdt-column-enable-filter').change(function (e) {
            if ($(this).is(':checked')) {
                $('div.wdt-filtering-enabled-block').show();
                $('#wdt-column-filter-type').trigger('change');
            } else {
                $('div.wdt-filtering-enabled-block').hide();
            }
        });

        /**
         * Show/hide all filtering settings and enable/disable filtering on 'global search'  toggle
         */
        $('#wdt-column-enable-global-search').change(function (e) {
            let columnEnableFilter = $('#wdt-column-enable-filter');
            if (!$(this).is(':checked')) {
                columnEnableFilter.prop('checked', 0).change().attr('disabled', true);
            } else {
                columnEnableFilter.attr('disabled', false).prop('checked', 1).change();
            }
        });

        /**
         * Show/hide number range settings and on 'range slider'  toggle
         */
        $('#wdt-column-range-slider').change(function (e) {
            let $rangeSliderMaxBlock = $('.wdt-range-max-value');
            let $rangeSliderCustomMaxBlock = $('.wdt-range-max-value-custom');
            if ($(this).is(':checked')) {
                $rangeSliderMaxBlock.show();
            } else {
                $('#wdt-max-value-display').val('default').selectpicker('refresh');
                $rangeSliderMaxBlock.hide();
                $rangeSliderCustomMaxBlock.hide();
            }
        });

        /**
         * Show/hide number range settings and on 'range slider'  toggle
         */
        $('#wdt-max-value-display').change(function (e) {
            let $rangeSliderCustomMaxBlock = $('.wdt-range-max-value-custom');
            if ($(this).val() === 'custom_text') {
                $rangeSliderCustomMaxBlock.show();
            } else {
                $('#wdt-custom-max-value').val('');
                $rangeSliderCustomMaxBlock.hide();
            }
        });

        /**
         * Show/hide button label in Url link column
         */
        $('#wdt-link-button-attribute').change(function (e) {
            if ($(this).is(':checked')) {
                $('div.wdt-link-button-label-block').show();
                $('div.wdt-link-button-class-block').show();

            } else {
                $('div.wdt-link-button-label-block').hide();
                $('div.wdt-link-button-class-block').hide();
            }
        });

        /**
         * Open WordPress media uploader
         */
        $('#wdt-add-data-browse-button').click(function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            e.preventDefault();
            openCustomMediaUploader(customMediaUploader);
        });

        /**
         * Checks if save changes should be continued when adding data from source
         */
        $('#wdt-backend-save-button').click(function (e) {
            e.preventDefault();
            continueSaveChanges();
            $('#wdt-backend-save-modal').modal('hide');
        });


        /**
         * Apply all column changes on "Apply" click in column block
         */
        $('button.wdt-column-apply').click(function (e) {
            e.preventDefault();
            wpdatatable_config.currentOpenColumn.applyChanges();
            // Trigger table's Apply action
            $('button.wdt-apply:eq(0)').click();
        });

        /**
         * Apply all changes on "Apply" click
         */
        $(document).on('click', 'button.wdt-apply', function (e) {

            if ($('#wdt-add-data-source-input').val() && $('#wdt-source-file-data').val()) {
                let selectedFileSourceOption = $('#wdt-source-file-data').val();
                let alertSaveMessage;
                switch (selectedFileSourceOption) {
                    case 'replaceTableData':
                        alertSaveMessage = wpdatatables_edit_strings.selected_replace_data_option_common;
                        break;
                    case 'addDataToTable':
                        alertSaveMessage = wpdatatables_edit_strings.selected_add_data_option_common;
                        break;
                    case 'replaceTable':
                        alertSaveMessage = wpdatatables_edit_strings.selected_replace_table_option_common;
                        break;
                }
                let alertMessageDiv = document.getElementById('wdt-save-table-message');
                alertMessageDiv.innerHTML = alertSaveMessage;

                $('#wdt-backend-save-modal').modal('show');
                return false;
            }

            continueSaveChanges();
        });

        function continueSaveChanges() {

            if (wpdatatable_config.table_type == 'gravity' ||
                wpdatatable_config.table_type == 'formidable') return;

            if (wpdatatable_config.table_type === 'wp_posts_query' || wpdatatable_config.table_type === 'woo_commerce') {
                wpdatatable_config.updatePostQueryParameters();
                let taxField = document.querySelector('.wdt-wp-query-tax-field');
                let taxTerms = document.querySelector('.wdt-wp-query-tax-terms');
                let taxonomy = document.querySelector('.wdt-wp-query-taxonomy');

                if (taxField || taxTerms || taxonomy) {
                    if (taxField.value.trim() === '' || taxTerms.value.trim() === '' || taxonomy.value.trim() === '') {
                        wdtNotify(wpdatatables_frontend_strings.error_wpdatatables, wpdatatables_frontend_strings.emtyfields_woo_front, 'danger');
                        return;
                    }
                }
            }
            if (!wpdatatable_config.title) {
                wdtNotify(wpdatatables_edit_strings.error_common, wpdatatables_edit_strings.tableNameEmpty_common, 'danger');
                return;
            }
            if (wpdatatable_config.masterDetail && wpdatatable_config.masterDetailSender == 'get') {
                if ($.inArray(wpdatatable_config.masterDetailSendTableType, ['childTable', 'childTableRender']) !== -1) {
                    if (wpdatatable_config.masterDetailSendChildTableColumnIDName == '' || wpdatatable_config.masterDetailSendParentTableColumnIDName == '') {
                        wdtNotify(wpdatatables_edit_strings.error_common, wpdatatables_edit_strings.masterdetail_error_common, 'danger');
                        return;
                    }
                }
                if (wpdatatable_config.masterDetailSendTableType == 'existingTable') {
                    if (wpdatatable_config.masterDetailSendParentTableColumnIDName == '') {
                        wdtNotify(wpdatatables_edit_strings.error_common, wpdatatables_edit_strings.masterdetailParentId_error_common, 'danger');
                        return;
                    }
                }
            }
            if (wpdatatable_config.editable) {
                if ($('#wdt-mysql-table-name').val() == '') {
                    $('#wdt-error-modal .modal-body').html('MySQL table name for front-end editing is not set!');
                    $('#wdt-error-modal').modal('show');
                    return;
                }
            }
            if ((wpdatatable_config.table_type === 'csv' || wpdatatable_config.table_type === 'xls')
                && wpdatatable_config.file_location == '') {
                wpdatatable_config.file_location = 'wp_media_lib'
            }
            if (wpdatatable_config.server_side == 1) {
                for (var i in wpdatatable_config.columns) {
                    wpdatatable_config.columns[i].groupColumn = 0;
                    if (wpdatatable_config.columns[i].type == 'formula') {
                        wpdatatable_config.columns[i].calculateTotal = wpdatatable_config.columns[i].calculateTotal;
                        wpdatatable_config.columns[i].calculateAvg = wpdatatable_config.columns[i].calculateAvg;
                        wpdatatable_config.columns[i].calculateMin = wpdatatable_config.columns[i].calculateMin;
                        wpdatatable_config.columns[i].calculateMax = wpdatatable_config.columns[i].calculateMax;
                    }
                    if (wpdatatable_config.columns[i].possibleValuesType == 'foreignkey') {
                        wpdatatable_config.columns[i].possibleValuesAjax = -1;
                    }
                }
            }

            wpdatatable_config.connection = $('#wdt-table-connection').val();
            let file_source_action = $('#wdt-source-file-data').val();
            let file = ($('#wdt-add-data-source-input').val() ? $('#wdt-add-data-source-input').val() : 0)

            if (wpdatatable_config.table_type === 'nested_json') {

                wpdatatable_config.jsonAuthParams = {
                    url: $('#wdt-nested-json-url').val(),
                    method: $('#wdt-nested-json-get-type').selectpicker('val'),
                    authOption: $('#wdt-nested-json-auth-option').selectpicker('val'),
                    username: $('#wdt-nested-json-username').val(),
                    password: $('#wdt-nested-json-password').val(),
                    customHeaders: wpdatatable_config.compileCustomHeadersRow(),
                    root: $('#wdt-nested-json-root').val(),
                };

                if (wpdatatable_config.jsonAuthParams.root === '') {
                    wdtNotify(wpdatatables_edit_strings.error_common, 'JSON roots can not be empty. Please set proper JSON roots or insert proper JSON params and click on Fetch JSON button again to get valid roots from JSON URL.', 'danger');
                    return;
                }
                if (wpdatatable_config.jsonAuthParams.url === '') {
                    $('.wdt-table-settings #wdt-nested-json-root').html('').selectpicker('refresh');
                    $('.wdt-table-settings .nested-json-roots').addClass('hidden');
                    wdtNotify(wpdatatables_edit_strings.error_common, 'JSON URL can not be empty', 'danger');
                    return;
                }
                if (wpdatatable_config.jsonAuthParams.authOption !== '') {
                    if (wpdatatable_config.jsonAuthParams.username === '' || wpdatatable_config.jsonAuthParams.password === '') {
                        wdtNotify(wpdatatables_edit_strings.error_common, 'Credentials can not be empty', 'danger');
                        return;
                    }
                }
            }

            $('.wdt-preload-layer').animateFadeIn();

            $.ajax({
                url: ajaxurl,
                method: 'POST',
                dataType: 'json',
                data: {
                    wdtNonce: $('#wdtNonce').val(),
                    action: 'wpdatatables_save_table_config',
                    table: JSON.stringify(wpdatatable_config.getJSON()),
                    file: file,
                    fileSourceAction: file_source_action
                },
                success: function (data) {

                    if (typeof data.error != 'undefined') {
                        // Show error if returned
                        $('#wdt-error-modal .modal-body').html(data.error);
                        $('#wdt-error-modal').modal('show');
                        $('.wdt-preload-layer').animateFadeOut();
                        return;
                    } else {
                        // Reinitialize table with returned data
                        wpdatatable_config.initFromJSON(data.table);
                        wpdatatable_config.setTableHtml(data.wdtHtml);
                        wpdatatable_config.setDataTableConfig(data.wdtJsonConfig);
                        if ($('.wpExcelTable').length) {
                            location.reload();
                        } else {
                            wpdatatable_config.renderTable();
                        }
                        // Show editing tab
                        if ((data.table.table_type == 'mysql' || data.table.table_type == 'manual')
                            && !jQuery('.editing-settings-tab').is(':visible')) {
                            $('.editing-settings-tab').animateFadeIn();
                        }
                        // Add url to "Switch View" buttons for MySQL tables
                        if (data.table.table_type == 'mysql') {
                            $('.wdt-edit-buttons a')
                                .attr('href', window.location.pathname + '?page=wpdatatables-constructor&source&table_id=' + data.table.id + '&table_view=excel')
                        }

                        if (file_source_action === 'replaceTable' && file != 0) location.reload();

                        // Show success message
                        wdtNotify(
                            wpdatatables_edit_strings.success_common,
                            wpdatatables_edit_strings.tableSaved_common,
                            'success'
                        );
                    }
                    if (window.location.href.indexOf("table_id=") === -1) {
                        window.history.replaceState(null, null, window.location.pathname + "?page=wpdatatables-constructor&source&table_id=" + data.table.id);
                    }

                    $('#wdt-add-data-source-input').val('');
                    $('#wdt-source-file-data').selectpicker('val', '');
                    $('#wdt-add-data-source-input').attr('disabled', 'disabled');
                    $('#wdt-add-data-browse-button').attr('disabled', 'disabled');
                },
                error: function (data) {
                    $('#wdt-error-modal .modal-body').html('There was an error while trying to save the table!' + data.statusText + '<br>' + data.responseText);
                    $('#wdt-error-modal').modal('show');
                    $('.wdt-preload-layer').animateFadeOut();
                    $('#wdt-add-data-source-input').val('');
                    $('#wdt-source-file-data').selectpicker('val', '');
                    $('#wdt-add-data-source-input').attr('disabled', 'disabled');
                    $('#wdt-add-data-browse-button').attr('disabled', 'disabled');
                }
            });
        }

        /**
         * Empty the save changes with data modal after closing
         */
        $('#wdt-backend-save-modal').on('hidden.bs.modal', function () {
            $(this).find("#wdt-save-table-message").empty();
        });

        /**
         * Switch tabs in table settings
         */
        $('.wdt-datatables-admin-wrap .wdt-table-settings .tab-nav a').on('click', function (e) {
            e.preventDefault();

            // Logic for the main tab switching, excluding Customize and Data Source
            if (!$(this).closest('ul').hasClass('customize-table-settings-ul') &&
                !$(this).closest('ul').hasClass('main-wp-posts-settings-ul') &&
                !$(this).closest('ul').hasClass('main-wdt-woo-settings-ul')) {
                $('.wdt-datatables-admin-wrap .wdt-table-settings .tab-content .tab-pane,' +
                    '.wdt-datatables-admin-wrap .wdt-table-settings .customize-table-settings-ul li,' +
                    '.wdt-datatables-admin-wrap .wdt-table-settings .main-wp-posts-settings-ul li' +
                    '.wdt-datatables-admin-wrap .wdt-table-settings .main-wdt-woo-settings-ul li').removeClass(' fade active in');
                $('.wdt-datatables-admin-wrap .wdt-table-settings .tab-content .tab-pane.main-customize-table-settings,' +
                    '.wdt-datatables-admin-wrap .wdt-table-settings .tab-content .customize-table-settings-ul .main-customize-table-settings-tab,' +
                    '.wdt-datatables-admin-wrap .wdt-table-settings .tab-content .main-wp-posts-settings-ul .general-settings-tab' +
                    '.wdt-datatables-admin-wrap .wdt-table-settings .tab-content .main-wdt-woo-settings-ul .general-settings-tab').addClass('active');
                $($(this)[0].hash).addClass('active');
                if ($(this).closest('ul').hasClass('wdt-main-menu'))
                    $('#general-settings-tab').addClass('active in');
            }

            // Logic for the Customize tab switching
            else if ($(this).closest('ul').hasClass('customize-table-settings-ul')) {
                if (!$(this)[0].hash === '#customize-table-settings') {
                    $('.wdt-datatables-admin-wrap .wdt-table-settings .tab-content.wdt-main-child .tab-pane').removeClass(' fade active in');
                }
                $($(this)[0].hash).addClass('active in');
            }

            // Logic for the WP Posts and WooCommerce Data Source tab switching
            else if ($(this).closest('ul').hasClass('main-wp-posts-settings-ul') || $(this).closest('ul').hasClass('main-wdt-woo-settings-ul')) {
                if (!$(this)[0].hash === '#main-table-settings') {
                    $('.wdt-datatables-admin-wrap .wdt-table-settings .tab-content.wdt-main-child .tab-pane').removeClass(' fade active in');
                }
                $($(this)[0].hash).addClass('active in');
            }
        });

        /**
         * Switch tabs in column settings
         */
        $('.wdt-datatables-admin-wrap .column-settings-panel .tab-nav a').on('click', function (e) {
            e.preventDefault();
            $('.wdt-datatables-admin-wrap .column-settings-panel .tab-content .tab-pane:not(.main-customize-table-settings)').removeClass(' fade active in');
            $($(this)[0].hash).addClass('active in');
        });

        /**
         * Fill possible values list on "Read From Table" button
         */
        $('button#wdt-column-values-read-from-table').click(function (e) {
            e.preventDefault();

            if (wpdatatable_config.table_type == 'mysql' || wpdatatable_config.table_type == 'manual') {
                var data = {};
                data.action = 'wpdatatable_get_column_distinct_values';
                data.tableId = wpdatatable_config.id;
                data.columnId = wpdatatable_config.currentOpenColumn.id;

                $.ajax({
                    type: 'post',
                    url: ajaxurl,
                    data: data,
                    dataType: 'json',
                    success: function (distValues) {
                        if (!(distValues instanceof Array)) {
                            return;
                        }
                        wdtFillPossibleValuesList(distValues);
                    }
                });
            } else {
                var distValues = wpdatatable_config.dataTable.columns(wpdatatable_config.currentOpenColumn.pos).data().eq(0).sort().unique().toArray();
                wdtFillPossibleValuesList(distValues);
            }

        });

        /**
         * Apply foreign key rule and save for current column
         */
        $('button.wdt-save-foreign-key-rule').click(function (e) {
            $('#wdt-configure-foreign-key-modal').modal('hide');
            if (wpdatatable_config.currentOpenColumn == null) {
                return;
            }
            wpdatatable_config.currentOpenColumn.foreignKeyRule = {
                tableId: $('#wdt-column-foreign-table').val(),
                tableName: $('#wdt-column-foreign-table').selectpicker('val') != 0 ? $('#wdt-column-foreign-table option:selected').html() : '',
                displayColumnId: $('#wdt-foreign-column-display-value').val(),
                displayColumnName: $('#wdt-foreign-column-display-value option:selected').data('orignal_header'),
                storeColumnId: $('#wdt-foreign-column-store-value').val(),
                storeColumnName: $('#wdt-foreign-column-store-value option:selected').data('orignal_header'),
                allowAllPossibleValuesForeignKey: $('#wdt-possible-values-foreign-keys').val()
            };
            if (wpdatatable_config.currentOpenColumn.foreignKeyRule.tableId != 0) {
                $('.wdt-foreign-rule-display #wdt-connected-table-name').text($('#wdt-column-foreign-table option:selected').html());
                $('.wdt-foreign-rule-display #wdt-connected-table-show-column').text($('#wdt-foreign-column-display-value option:selected').html());
                $('.wdt-foreign-rule-display #wdt-connected-table-value-column').text($('#wdt-foreign-column-store-value option:selected').html());
            } else {
                $('.wdt-foreign-rule-display #wdt-connected-table-name').text('-');
                $('.wdt-foreign-rule-display #wdt-connected-table-show-column').text('-');
                $('.wdt-foreign-rule-display #wdt-connected-table-value-column').text('-');
            }
        });

        /**
         * Replace span with input for column name and vice versa
         */
        $(document).on('keyup', '.wdt-column-display-header-edit', function (e) {
            e.preventDefault();
            wpdatatable_config
                .getColumnByHeader($(this).closest('.wdt-column-block').data('orig_header'))
                .setDisplayHeader($(this).val());
        });

        /**
         * Apply changes for column settings on enter
         */
        $(document).on('keyup', '#column-display-settings input[type="text"]', function (e) {
            if (e.which == 13) {
                $('button.wdt-column-apply:eq(0)').click();
            }
        });

        /**
         * Load the tables for foreign key when a table is chosen in dropdown
         */
        $('#wdt-column-foreign-table').change(function (e) {
            if ($(this).val() != '') {
                wpdatatable_config.getForeignColumns(
                    $(this).val(),
                    wpdatatable_config.currentOpenColumn.foreignKeyRule ? wpdatatable_config.currentOpenColumn.foreignKeyRule.displayColumnId : null,
                    wpdatatable_config.currentOpenColumn.foreignKeyRule ? wpdatatable_config.currentOpenColumn.foreignKeyRule.storeColumnId : null
                )
            }
        });

        /**
         * Apply the changes to column in the quickaccess modal
         */
        $('#wdt-apply-columns-list').click(function (e) {
            $('#wdt-columns-list-modal').modal('hide');
            $('button.wdt-apply:eq(0)').click();
        });

        /**
         * Add column to formula on click
         */
        $(document).on('click', '#wdt-formula-editor-modal div.wdt-column-block', function (e) {
            $('#wdt-formula-editor-modal textarea').insertAtCaret($(this).data('orig_header'));
        });

        $(document).on('click', '.transform-value-shortcodes-container div.wdt-column-block', function (e) {
            $('#wdt-column-transform-value').insertAtCaret('{' + $(this).data('orig_header') + '.value}');
        });

        /**
         * Add operator to formula on click
         */
        $(document).on('click', '#wdt-formula-editor-modal div.wdt-formula-operators button', function (e) {
            $('#wdt-formula-editor-modal textarea').insertAtCaret($(this).text());
        });

        /**
         * Preview formula result
         */
        $('button.wdt-preview-formula').click(function (e) {
            $('#wdt-formula-editor-modal .wdt-preload-layer').animateFadeIn();
            $.ajax({
                url: ajaxurl,
                method: 'POST',
                data: {
                    action: 'wpdatatables_preview_formula_result',
                    table_id: wpdatatable_config.id,
                    formula: $('#wdt-formula-editor-modal textarea').val()
                },
                success: function (data) {
                    $('div.wdt-formula-result-preview').html(data);
                    if (!$('div.wdt-formula-result-preview').is(':visible')) {
                        $('div.wdt-formula-result-preview').fadeInDown();
                    }
                    $('#wdt-formula-editor-modal .wdt-preload-layer').animateFadeOut();
                }
            })
        });

        /**
         * Save formula
         */
        $('button.wdt-save-formula').click(function (e) {
            $.ajax({
                url: ajaxurl,
                method: 'POST',
                data: {
                    action: 'wpdatatables_check_formula_result',
                    table_id: wpdatatable_config.id,
                    formula: $('#wdt-formula-editor-modal textarea').val()
                },
                success: function (data) {
                    if (data.includes("Unable to calculate")) {
                        $('div.wdt-formula-result-preview').html(data);
                        if (!$('div.wdt-formula-result-preview').is(':visible')) {
                            $('div.wdt-formula-result-preview').fadeInDown();
                        }
                        $('#wdt-formula-editor-modal .wdt-preload-layer').animateFadeOut();
                    } else {
                        if (wpdatatable_config.currentOpenColumn == null) {
                            // Adding a new column
                            var columnName = wpdatatable_config.generateFormulaName();
                            wpdatatable_config.addColumn(
                                new WDTColumn(
                                    {
                                        type: 'formula',
                                        orig_header: columnName,
                                        display_header: columnName,
                                        pos: wpdatatable_config.columns.length,
                                        formula: $('#wdt-formula-editor-modal textarea').val(),
                                        parent_table: wpdatatable_config
                                    }
                                )
                            );
                            $('button.wdt-apply:eq(0)').click();
                            $('#wdt-formula-editor-modal').modal('hide');
                        } else {
                            //Updating existing column
                            wpdatatable_config.currentOpenColumn.formula = $('#wdt-formula-editor-modal textarea').val();
                        }
                        $('#wdt-formula-editor-modal').modal('hide');
                    }
                },
                error: function (data) {
                    $('div.wdt-formula-result-preview').html(data);
                    if (!$('div.wdt-formula-result-preview').is(':visible')) {
                        $('div.wdt-formula-result-preview').fadeInDown();
                    }
                    $('#wdt-formula-editor-modal .wdt-preload-layer').animateFadeOut();
                }
            })

        });

        /**
         * Load the table for edit page
         */
        if (typeof wpdatatable_init_config !== 'undefined') {
            wpdatatable_config.initFromJSON(wpdatatable_init_config);

            // Fix for multiple DataTables when there's a wpdt shortcode inside a cell in an imported file
            while ($('#wpdatatable-preview-container table.wpDataTable').length > 1) {
                $('#wpdatatable-preview-container table.wpDataTable')[1].remove();
            }
            wpdatatable_config.dataTable = $('#wpdatatable-preview-container table.wpDataTable').DataTable();
            $('div.column-settings').removeClass('hidden');
            wpdatatable_config.drawColumnSettingsButtons($('#wpdatatable-preview-container table'));

            if (wpdatatable_config.table_type !== "simple" && !wpdatatable_config.server_side) {
                if (wpdatatable_config.fixed_header) {
                    wpdatatable_config.dataTable.fixedHeader.enable();
                    wpdatatable_config.dataTable.fixedHeader.adjust();
                }
                if (wpdatatable_config.fixed_columns && !wpdatatable_config.filtering_form) {
                    wpdatatable_config.dataTable.fixedColumns().left(wpdatatable_config.fixed_left_columns_number);
                    wpdatatable_config.dataTable.fixedColumns().right(wpdatatable_config.fixed_right_columns_number);
                }
            }
        }
        /**
         * Open WordPress media uploader
         */
        $('#wdt-browse-button').click(function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            e.preventDefault();

            var mediaType;

            if ($('#wdt-table-type').val() == 'xls') {
                mediaType = 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            } else if ($('#wdt-table-type').val() == 'csv') {
                mediaType = 'text/csv';
            }

            // Extend the wp.media object
            custom_uploader = wp.media.frames.file_frame = wp.media({
                title: wpdatatables_edit_strings.selectExcelCsv_common,
                button: {
                    text: wpdatatables_edit_strings.choose_file_common
                },
                multiple: false,
                library: {
                    type: mediaType
                }
            });

            // When a file is selected, grab the URL and set it as the text field value
            custom_uploader.on('select', function () {
                attachment = custom_uploader.state().get('selection').first().toJSON();
                $('#wdt-input-url').val(attachment.url).trigger('change');
            });

            //Open the uploader dialog
            custom_uploader.open();

        });
        /**
         * Change JSON Auth option
         */
        $('#wdt-nested-json-auth-option').change(function (e) {
            let type = $(this).val();
            switch (type) {
                case 'basic_auth':
                    jQuery('.wdt-table-settings .nested-json-basic-auth-inputs').removeClass('hidden');
                    break;
                default:
                    jQuery('.wdt-table-settings .nested-json-basic-auth-inputs').addClass('hidden');
                    jQuery('#wdt-nested-json-username').val('');
                    jQuery('#wdt-nested-json-password').val('');
                    break;
            }
            jQuery('#wdt-nested-json-auth-option').val(type).selectpicker('refresh');
        });

        /**
         * Get Nested JSON roots
         */
        $('#wdt-get-nested-json-roots').click(function (e) {
            e.stopImmediatePropagation();
            let url = $('#wdt-nested-json-url').val(),
                authOption = $('#wdt-nested-json-auth-option').selectpicker('val'),
                username = $('#wdt-nested-json-username').val(),
                password = $('#wdt-nested-json-password').val(),
                customHeaders = wpdatatable_config.compileCustomHeadersRow(),
                params = {
                    method: $('#wdt-nested-json-get-type').selectpicker('val')
                };

            if (url === '') {
                $('.wdt-table-settings #wdt-nested-json-root').html('').selectpicker('refresh');
                $('.wdt-table-settings .nested-json-roots').addClass('hidden');
                wdtNotify(wpdatatables_edit_strings.error_common, 'JSON URL can not be empty', 'danger');
                return;
            }
            params.url = url;
            params.customHeaders = customHeaders;
            if (authOption !== '') {
                params.authOption = authOption;
                if (username === '' || password === '') {
                    wdtNotify(wpdatatables_edit_strings.error_common, 'Credentials can not be empty', 'danger');
                    return;
                }
                params.username = username;
                params.password = password;
            }

            // Add custom loader
            let loader = document.createElement("div");
            loader.classList.add("nested-json-loader");
            $('#main-table-settings').css('opacity', '0.5').append(loader)

            $.ajax({
                url: ajaxurl,
                method: 'POST',
                data: {
                    action: 'wpdatatables_get_nested_json_roots',
                    wdtNonce: $('#wdtNonce').val(),
                    params: JSON.stringify(params),
                    tableConfig: JSON.stringify(wpdatatable_config.getJSON())
                },
                success: function (data) {
                    if (data.success) {
                        var options = '';
                        $.each(data.data.roots, function (i, name) {
                            options += '<option value="' + name + '">' + name + '</option>';
                        });
                        $('.wdt-table-settings #wdt-nested-json-root').html(options).selectpicker('refresh');
                        $('.wdt-table-settings .nested-json-roots').removeClass('hidden');
                        $('#main-table-settings .nested-json-loader').remove();
                        $('#main-table-settings').css('opacity', '1')
                        jQuery('button.wdt-apply').prop('disabled', '');
                        wdtNotify(
                            wpdatatables_edit_strings.success_common,
                            wpdatatables_edit_strings.getJsonRoots_common,
                            'success'
                        );
                    } else {
                        $('.wdt-table-settings #wdt-nested-json-root').html('').selectpicker('refresh');
                        $('.wdt-table-settings .nested-json-roots').addClass('hidden');
                        $('#main-table-settings .nested-json-loader').remove();
                        $('#main-table-settings').css('opacity', '1')
                        $('button.wdt-apply').prop('disabled', 'disabled');
                        wdtNotify('Error!', wpdatatables_edit_strings.errorText_common, 'danger');
                    }
                },
                error: function (xhr, status, error) {
                    $('.wdt-table-settings #wdt-nested-json-root').html('').selectpicker('refresh');
                    $('.wdt-table-settings .nested-json-roots').addClass('hidden');
                    $('#main-table-settings .nested-json-loader').remove();
                    $('#main-table-settings').css('opacity', '1')
                    $('button.wdt-apply').prop('disabled', 'disabled');
                    let message = xhr.responseText;
                    wdtNotify('Error!', message, 'danger');
                }
            })

        });

        /**
         * Add custom headers row
         */
        $('.wdt-add-nested-json-custom-headers-row').on('click', function (e) {
            wpdatatable_config.renderCustomHeadersRow({
                setKeyName: '',
                setKeyValue: ''
            });

        });

        /**
         * Delete custom headers row
         */
        $(document).on('click', '.wdt-delete-custom-headers-row-rule', function (e) {
            var $block = $(this).closest('div.wdt-custom-headers-row-rule');
            $block.remove();
        });

        /**
         * Apply tagsinput
         */
        $('#wdt-column-values-list').tagsinput({
            delimiterRegex: '|',
            tagClass: 'label label-primary'
        });


        var hash = window.location.hash;

        // On page load
        activateTabByHash(hash);

        // On hashchange
        window.addEventListener('hashchange', function () {
            activateTabByHash(window.location.hash);
        }, false);

        // Update hash when any tab is clicked
        $('.wdt-datatables-admin-wrap').on('click', '.wdt-table-settings .tab-nav a[data-toggle="tab"]', function (e) {
            e.preventDefault();
            var targetHash = this.hash;
            if (targetHash) {
                var scrollmem = $('body').scrollTop();
                window.location.hash = targetHash;
                $('html,body').scrollTop(scrollmem);
            }

            // Show tab (Bootstrap behavior)
            $(this).wdtBootstrapTabs('show');
        });

        function activateTabByHash(hash) {
            if (!hash) return;

            // First, try matching a top-level tab
            var $topLevelTab = $('.wdt-datatables-admin-wrap .wdt-table-settings ul.tab-nav a[href="' + hash + '"]');

            if ($topLevelTab.length && typeof $.fn.wdtBootstrapTabs !== 'undefined') {
                $topLevelTab.wdtBootstrapTabs('show');
            }
            // If not found, try nested tabs under #customize-table-settings
            var $nestedTab = $('.customize-table-settings-ul a[href="' + hash + '"]');

            if ($nestedTab.length) {
                // First, make sure parent tab is shown
                var $customizeTab = $('.wdt-datatables-admin-wrap .wdt-table-settings ul.tab-nav a[href="#customize-table-settings"]');
                if ($customizeTab.length) {
                    $customizeTab.wdtBootstrapTabs('show');
                }

                // Then show the nested tab
                setTimeout(function () {
                    $nestedTab.wdtBootstrapTabs('show');
                }, 100); // slight delay in case parent tab needs time to render
            }
        }

        function updateEditButtons(enableDuplicateButton) {
            var editButtonsSelect = $('#wdt-edit-buttons-displayed');
            if (!enableDuplicateButton) {
                $('select#wdt-edit-buttons-displayed option[value="duplicate"]').remove();
            } else if (enableDuplicateButton && $("#wdt-edit-buttons-displayed option[value='duplicate']").length <= 0) {
                editButtonsSelect.append('<option value="duplicate">Duplicate</option>');
                $('select#wdt-edit-buttons-displayed option[value="duplicate"]')
                    .prop('selected', $('#wdt-edit-buttons-displayed option:selected').val() !== undefined);
            }
            editButtonsSelect.selectpicker('refresh');
            editButtonsSelect.trigger('change');
        }

    });

})(jQuery);