/*!
 * SearchFilterSort set admin 1.9.1
 */
(function($) {
    "use strict";
    let filtersFormValid = false;
    let postTypesTaxList = sfswpSetVars.postTypesTaxList;
    let numFieldNoTaxes  = sfswpSetVars.numFieldNoTaxes;
    let numFieldAttrs    = sfswpSetVars.numFieldAttrs;

    function validateFiltersForm( $el )
    {
        let $spinner = $('#publishing-action .spinner');
        let requestParams          = {};

        $spinner.addClass( 'is-active' );
        /**
         * @todo checkboxes does not validates correctly because they send the same value !!! IMPORTANT
         * independently from checked status
         */

        requestParams.validateData = sfswpSerialize( $el );

        wp.ajax.post( 'sfswp-validate-filters', requestParams )
            .always( function() {
                $spinner.removeClass( 'is-active' );
            })
            .done( function( response ) {
                filtersFormValid = true;
                $el.submit();
            })
            .fail( function( response ) {

                let notices = [];
                let filterContainer = '';

                if( typeof response.errors !== 'undefined' ){
                    $.each( response.errors, function ( index, error ){

                        if( typeof error.id !== 'undefined'){
                            addFieldError( error.id, error.message );

                            // Open filter container to show error
                            filterContainer = $('#'+error.id).parents('.sfswp-filter-item');
                            openFilter(filterContainer);

                            // Open additional fields if errors are there
                            if( $('#'+error.id).parents('.sfswp-filter-additional-fields').length > 0 ){
                                openAdditional(filterContainer);
                            }
                        }else{
                            notices.push( error.message );
                        }

                    });

                    if( notices.length < 1 ){
                        notices.push( 'Error: Set was not saved.' );
                    }

                    addNotice( notices );
                }
            });

        return false;
    }

    function removeElement($el)
    {
        $el.fadeTo(100, 0, function() {
            $el.slideUp(100, function() {
                $el.remove();
            });
        });
    }

    function addFieldError( fieldId, message )
    {
        let target = $('#'+fieldId);
        let html = '<div class="sfswp-field-notice sfswp-field-notice-error"><p>'+message+'</p></div>';
        if( typeof target !== 'undefined' ){
            target.before( html );
        }
    }

    function addNotice( messages )
    {
        let target = $('form#post');
        let text   = '';
        $.each( messages, function ( index, message ) {
            text += '<p>' + message + '</p>';
        });

        let html = '<div id="message" class="error notice notice-error is-dismissible">'
            + text +
            '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>' +
            '</div>';
        if( typeof target !== 'undefined' ){
            if( $("#message").length > 0 ){
                $("#message").remove();
            }
            target.before( html );
        }
    }

    function openFilter($el)
    {
        let head = $el.find('.sfswp-filter-head'),
            body = head.next('.sfswp-filter-body');
        head.addClass('sfswp-opened');
        body.slideDown({
            duration: 200,
            complete: function (){
                body.addClass('sfswp-opened');
            }
        });
    }

    function closeFilter($el)
    {
        let head = $el.find('.sfswp-filter-head'),
            body = head.next('.sfswp-filter-body');

        head.removeClass('sfswp-opened');
        body.slideUp({
            duration: 200,
            complete: function (){
                body.removeClass('sfswp-opened');
            }
        });
    }

    function closeAdditional($el)
    {
        $el.find('.sfswp-filter-additional-fields').slideUp({
            duration: 200,
            complete: function (){
                $(this).removeClass('sfswp-opened');
            }
        });
    }

    function openAdditional($el)
    {
        $el.find('.sfswp-filter-additional-fields').slideDown({
            duration: 200,
            complete: function (){
                $(this).addClass('sfswp-opened');
            }
        });
    }

    /**
     * Creates array with taxonomies that do not belong to the Post type
     * selected in SFS Set
     * @returns {[]|*[]}
     */
    function getForbiddenTaxes()
    {
        if( typeof sfswpSetVars.postTypesTaxList !== 'undefined'){
            let postType = $('#sfswp_set_fields-post_type').val();
            let allowedTaxes   = [];
            let forbiddenTaxes = [];

            if( typeof sfswpSetVars.postTypesTaxList[postType] !== 'undefined' ){
                $.each( sfswpSetVars.postTypesTaxList[postType], function ( iNdex, taxProps ){
                    allowedTaxes.push(taxProps['name']);
                });
            }

            $.each( sfswpSetVars.postTypesTaxList, function ( pType, taxesArray ){
                if( pType !== postType ){
                    $.each( taxesArray, function ( index, theTax ){
                        if( allowedTaxes.includes(theTax['name']) === false ){
                            forbiddenTaxes.push(theTax['name']);
                        }
                    } )
                }
            });

            return forbiddenTaxes;
        }

        return [];
    }

    /**
     * Retrieves already selected filter entities to disable double using of them
     * @param $inputs - select tags, where we collect used entities. Usually .sfswp-field-entity
     * @param excludeInput
     * @returns {boolean|[]}
     */
    function getUsedEntities( $inputs, excludeInput )
    {
        let usedEntities = [];
        let currentVal   = '';
        // Pass through these entities
        let doNotInclude = ['post_meta', 'post_meta_num', 'post_meta_exists', 'tax_numeric'];

        if ( $inputs.length > 0 ) {
            $inputs.each( function(){
                currentVal = $(this).val();

                // Continue
                if( $(this).attr('id') == excludeInput.attr('id') ){
                    return;
                }

                if( doNotInclude.includes( currentVal ) ){
                    return;
                }
                if( currentVal ) {
                    usedEntities.push( currentVal );
                }
            });

            return usedEntities;
        }
        return false;
    }

    /**
     * Pass through new filter entity options and set as disabled already used taxonomies
     * @param $theSelect - the select element with options to set. Usually it is .sfswp-field-entity
     * @param dropdownClass - class of the select element where we have to set option status
     * @param noChange
     * @returns {boolean}
     */
    function setAvailableEntities( $theSelect, noChange )
    {   // .sfswp-field-entity
        let currentVal      = '';
        let selectClass     = $theSelect.attr('class');
        let exclude         = getUsedEntities( $( '.'+selectClass ), $theSelect ); // Entities already selected in other filters
        let forbiddenTaxes  = getForbiddenTaxes(); // Entities that do not belong to the Post type

        $theSelect.find('option').each( function (){
            currentVal = $(this).val();

            if( currentVal === 'post_meta_exists' && ( sfswpSetVars.filtersPro < 1 ) ) {
                return;
            }
            if( currentVal === 'tax_numeric' && ( sfswpSetVars.filtersPro < 1 ) ) {
                return;
            }

            if( exclude.includes( currentVal ) || forbiddenTaxes.includes( currentVal ) ){
                $(this).attr( 'disabled', 'disabled' );
            }else{
                $(this).removeAttr( 'disabled' );
            }
        } );

        // If currently selected option is disabled, make first available option selected.
        let disabled = $theSelect.find('option:selected').attr('disabled');
        // if noChange === false this works
        if( disabled === 'disabled' && ! noChange ){
            $theSelect.find('option:not([disabled]):first').prop('selected', true)
                .trigger('change');
        }

        return true;
    }

    function handleShowTerms( select )
    {
        let currentVal = select.val();
        let currentFid = select.parents('.sfswp-filter-item').data('fid');
        currentVal     = sfswpShortenEname( currentVal );

        let $formTable  = $( "#sfswp-filter-id-"+currentFid+" .sfswp-form-fields-table" );
        if ( sfswpSetVars.swatchesTaxonomies.includes( currentVal ) ){
            $formTable.addClass("taxonomy-has-swatches");
        } else {
            $formTable.removeClass("taxonomy-has-swatches");
        }

        if ( sfswpSetVars.brandEntities.includes( currentVal ) ){
            $formTable.addClass("sfswp-filter-has-brands");
        } else {
            $formTable.removeClass("sfswp-filter-has-brands");
        }

        if ( sfswpSetVars.ratingTaxonomies.includes( currentVal ) ){
            $formTable.addClass("selected-and-above-show");
        } else {
            $formTable.removeClass("selected-and-above-show");
        }
    }

    function passNewEntities( select )
    {
        let time = 0;

        $('.sfswp-new-filter-item .sfswp-field-entity').each( function () {
            let select   = $(this);
            let noChange = false;
            // Do not change current select tag
            if( $(this).attr('id') == select.attr('id') ) {
                noChange = true;
            }

            setTimeout( function(){ setAvailableEntities( select, noChange ); }, time);
            time += 100;
        });
    }

    $.fn.getCursorPosition = function() {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if ('selectionStart' in input) {
            // Standard-compliant browsers
            return input.selectionStart;
        } else if (document.selection) {
            // IE
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            return sel.text.length - selLen;
        }
    }

    $(document).ready(function (){

        $('form#post').on('submit', function(e){

            // Clear all errors
            removeElement( $('.sfswp-field-notice') );

            // Clear Notice
            removeElement( $('#message') );

            // Close All Filters
            closeFilter( $(".sfswp-filter-item") );

            if( ! filtersFormValid ){
                e.preventDefault();
                // Validate form. We will submit it from validation method
                validateFiltersForm($(this));
            }
        });

        $('.sfswp-add-filter').on('click', function (e){
            e.preventDefault();
            let html = $('#sfswp-new-filter').html();
            let $el = $(html);
            let search = 'sfswp_new_id';
            let replace = uniqId('filter_');
            let replaceAttr = function(i, value){
                return value.replace( search, replace );
            }

            let filtersListContainer = $('#sfswp-filters-list');

            $el.find('[id*="' + search + '"]').attr('id', replaceAttr);
            $el.find('[for*="' + search + '"]').attr('for', replaceAttr);
            $el.find('[name*="' + search + '"]').attr('name', replaceAttr);
            $el.find('[class*="' + search + '"]').attr('class', replaceAttr);
            $el.data('fid', replace);
            $el.attr('id', 'sfswp-filter-id-'+replace);

            let latestElem = $(".sfswp-filter-item").last();
            if ( latestElem.hasClass('sfswp-filter-not-listed') ) {
                let prevLatestElem = latestElem.prev('.sfswp-filter-item');
                if ( prevLatestElem.hasClass('sfswp-filter-not-listed') ) {
                    prevLatestElem.before($el);
                } else {
                    latestElem.before($el);
                }
            } else {
                filtersListContainer.append($el);
            }

            let select = $el.find('.sfswp-field-entity');

            syncEntityWithPrefix(select);
            handleMetaKeyField(select);
            setEntityTableClass(select);
            syncEntityWithView(select);
            syncEntityWithSortTerms(select);

            // Make already used entities unavailable to selection
            setAvailableEntities( select );
            handleHierarchyField( select );
            handleShowTerms( select );
            // handleUsedForVariationsField( select );

            $el.find('.sfswp-field-exclude').select2({
                width: '100%',
                placeholder: sfswpSetVars.excludePlaceholder,
            });

            // Fire this event to load exclude terms for first filter
            if( $(".sfswp-filter-item:not(.sfswp-filter-not-listed)").length === 1 ){
                select.trigger('change');
            }

            $('.sfswp-help-tip').tipTip({
                'attribute': 'data-tip',
                'fadeIn':    50,
                'fadeOut':   50,
                'delay':     200,
                'keepAlive': true,
                'maxWidth': "220px",
            });

            openFilter($el);

            renderMenuOrder();
            handleNoFiltersMessage();

            // Update Parent filter dropdown
            sfswpAddNewFilterToParentList();

            /**
             * @todo There is problem with down arrow when we adding new filter !!! IMPORTANT
             */

        });

        $('.sfswp-form-fields-table:not(.sfswp-filter-tax_numeric) .sfswp-field-exclude, .sfswp-form-fields-table:not(.sfswp-filter-post_meta_num) .sfswp-field-exclude, .sfswp-form-fields-table:not(.sfswp-filter-post_meta_exists) .sfswp-field-exclude').select2({
            width: '100%',
            placeholder: sfswpSetVars.excludePlaceholder
        });

        $('body').on('click', '.notice-dismiss', function(e){
            e.preventDefault();
            removeElement( $('#message') );
        });

        // Show delete buttons
        $('body').on('click', '.sfswp-button-link-delete', function(e){
            e.preventDefault();
            $(this).parents('.sfswp-filter-label-td')
                .next('.sfswp-sfs-field-td')
                .children('.sfswp-filter-delete-wrapper').css('visibility', 'visible');
        });

        $('body').on('click', '.sfswp-filter-delete-cancel', function(e){
            e.preventDefault();
            removeElement( $('.sfswp-field-notice') );
            $(this).parents('.sfswp-filter-delete-wrapper').css('visibility', 'hidden');
        });

        $('body').on('click', '.sfswp-done-action', function(e){
            $(this).parents('.sfswp-filter-body').slideToggle(200)
                    .toggleClass('sfswp-opened')
                .children('.sfswp-filter-additional-fields').removeClass('sfswp-additional-opened')
                    .hide();
            $(this).parents('.sfswp-filter-body').prev('.sfswp-filter-head').toggleClass('sfswp-opened');
            // Hide delete buttons
            $(this).parents('.sfswp-sfs-field-td')
                .next('.sfswp-sfs-field-td')
                .find('.sfswp-filter-delete-wrapper').css('visibility', 'hidden');
        });

        $('body').on('click', '.sfswp-advice-head', function(e){
            // let body = $(this).next('.sfswp-advice-body');
            $(this).toggleClass('sfswp-opened');
            // body.slideToggle(200)
            // body.toggle(200)
            //     body.toggleClass('sfswp-opened');
        });

        $('body').on('click', '.sfswp-title-action', function(e){
            let head = $(this).parent('.sfswp-filter-head'),
                body = head.next('.sfswp-filter-body');
            head.toggleClass('sfswp-opened');
            body.slideToggle(200)
                    .toggleClass('sfswp-opened')
                .children('.sfswp-filter-additional-fields').removeClass('sfswp-additional-opened')
                    .hide();
            body.find('.sfswp-filter-delete-wrapper').css('visibility', 'hidden');

            let moreOptions = body.find('.sfswp-more-options-toggle');
            if( moreOptions.hasClass('sfswp-opened') ){
                moreOptions.trigger('click');
            }
        });

        $('body').on('click', '.sfswp-more-options-toggle', function(e){
            e.preventDefault();

            let moreText = $(this).text();

            if( moreText === sfswpSetVars.moreOptions ){
                $(this).text( sfswpSetVars.lessOptions);
            }else{
                $(this).text( sfswpSetVars.moreOptions);
            }

            $(this).toggleClass('sfswp-opened');
            $(this).parents('.sfswp-filter-body').find('.sfswp-filter-additional-fields').slideToggle(200)
            .toggleClass('sfswp-additional-opened');
        });

        $('body').on('change', 'select.sfswp-field-ename', function(e){
            let time = 0;
            // let fid = $(this).parents('.sfswp-filter-item').data('fid');

            $( $('.sfswp-new-filter-item select.sfswp-field-ename').get().reverse() ).each( function () {
                let eNameSelect = $(this);

                setTimeout( function(){ setAvailableEntities( eNameSelect, false ); }, time);
                time += 100;
            });
        });

        $('body').on('change', '.sfswp-field-entity', function(e){
            let thisSelect = $(this);
            let theTitle = '';

            // Set available entities again
            passNewEntities(thisSelect);
            syncEntityWithPrefix(thisSelect);
            handleMetaKeyField(thisSelect);
            handleLogicField(thisSelect);
            setEntityTableClass(thisSelect);
            syncEntityWithView(thisSelect);
            syncEntityWithSortTerms(thisSelect);

            handleHierarchyField(thisSelect);
            handleShowTerms( thisSelect );
            // handleUsedForVariationsField(select);

            // Load terms for exclude
            let entity = $(this).val();
            let fid    = $(this).parents('.sfswp-filter-item').data('fid');

            if ( entity === 'tax_numeric' ) {
                $('#sfswp_filter_fields-'+fid+'-e_name').trigger('change');
            }

            // replace with includes
            if ( [ 'tax_numeric', 'post_meta', 'post_meta_num', 'post_meta_exists', 'post_date' ].includes(entity) ) {
                let target = $('#sfswp_filter_fields-'+fid+'-exclude');
                target.select2({
                    disabled: true,
                    width: '100%'
                });
            }else{
                loadExcludeItems(entity, fid);
            }

            let entityLabel = $(this).find('option:selected').text();
            let target      = $(this).parents('.sfswp-filter-item').find('.sfswp-filter-head li.sfswp-filter-entity');
            target.text(entityLabel);

            theTitle = $("#sfswp_filter_fields-"+fid+"-label").val();

            if( ! theTitle ){
                theTitle = sfswpSetVars.newFilter;
            }

            $(".sfswp-field-parent-filter option[value='"+fid+"'").each(function (index, element){
                $(this).text( theTitle + " (" +sfswpShortenEname( entity )+ ")" );
                if( entity === 'post_meta_num' || entity === 'tax_numeric' || entity === 'taxonomy_product_visibility' ){
                    $(this).attr('disabled', 'disabled');
                }else{
                    $(this).removeAttr('disabled');
                }
            });
        });

        // Try to prepend slug if it already exists
        $('body').on('input change', '.sfswp-field-ename', function(){
                let ename = $(this).val();
                let fid = $(this).parents('.sfswp-filter-item').data('fid');
                let entity = $('#sfswp_filter_fields-'+fid+'-entity').val();
                let val = '';
                let slugs = sfswpSetVars.filterSlugs;

                if ( entity === 'post_meta_num' ) {
                    val = 'post_meta_num_' + ename;
                } else if ( entity === 'tax_numeric' ) {
                    val = 'tax_numeric_' + ename;
                } else if ( entity === 'post_meta_exists' ) {
                    val = 'post_meta_exists_' + ename;
                } else {
                    val = 'post_meta_' + ename;
                }

                if( typeof slugs[val] !== 'undefined' ){
                    $('#sfswp_filter_fields-'+fid+'-slug').val( slugs[val] )
                        .trigger('input');

                    // Do not load exclude terms for Post Meta Num and Tax Numeric
                    if( entity !== 'post_meta_num' && entity !== 'tax_numeric'){
                        loadExcludeItems(entity, fid, ename);
                    }

                }else{
                    $('#sfswp_filter_fields-'+fid+'-slug').val('')
                        .trigger('input');
                    $('#sfswp_filter_fields-'+fid+'-exclude').select2({
                        disabled: true,
                        width: '100%',
                    });
                }
        });

        $('body').on('input', '.sfswp-field-value-step', function (){
            $(this).val( $(this).val().replace(/,/g, '.') );
            $(this).val( $(this).val().replace(/[^\d\.]/g, '') );
        });

        $('body').on('input keydown', '#sfswp_set_fields-apply_button_text', function (){
            let target = $("#sfswp-filter-id-apply-button").find('.sfswp-button-apply');
            cpaLiveWrite( $(this), target );
        });

        $('body').on('input keydown', '#sfswp_set_fields-reset_button_text', function (){
            let target = $("#sfswp-filter-id-apply-button").find('.sfswp-button-reset');
            cpaLiveWrite( $(this), target );
        });

        $('body').on('input keydown', '#sfswp_set_fields-search_field_placeholder', function (){
            let target = $("#sfswp-filter-id-search-field").find('.sfswp-text-input-search');
            target.attr('placeholder', $(this).val());
        });

        $('body').on('input keydown', '#sfswp_set_fields-search_field_label', function (){
            let target = $("#sfswp-filter-id-search-field").find('.sfswp-filter-label');
            cpaLiveWrite( $(this), target );
            // target.attr('placeholder', $(this).val());
        });

        $('body').on('input keydown', '.sfswp-field-slug', function (){
            let target = $(this).parents('.sfswp-filter-item').find('.sfswp-filter-head li.sfswp-filter-slug');
            cpaLiveWrite( $(this), target );
        });

        $('body').on('input keydown', '.sfswp-field-label', function (){
            let target = $(this).parents('.sfswp-filter-item').find('.sfswp-filter-head li.sfswp-filter-label');
            cpaLiveWrite( $(this), target );

            let fid   = $(this).parents(".sfswp-filter-item").data('fid');
            let eName = $("#sfswp_filter_fields-"+fid+"-entity").val();
            eName = sfswpShortenEname( eName );
            let theTitle = $(this).val();

            $(".sfswp-field-parent-filter option[value='"+fid+"'").each(function (index, element){
                $(this).text( theTitle + " (" + eName + ")" );
            });
        });

        $('body').on('change', '.sfswp-field-view', function(){
            let optionName = $(this).find('option:selected').text();
            let optionVal  = $(this).find('option:selected').val();
            let $divFilterItem = $(this).parents('.sfswp-filter-item');
            let target = $divFilterItem.find('.sfswp-filter-head li.sfswp-filter-view');
            let allowedViews = ['checkboxes', 'radio', 'labels'];
            target.text(optionName);

            if( allowedViews.includes(optionVal) ){
                $divFilterItem.find('.sfswp-field-search-tr').show();
                $divFilterItem.find('.sfswp-field-more-less-tr').show();
            }else{
                $divFilterItem.find('.sfswp-field-search-tr').hide();
                $divFilterItem.find('.sfswp-field-more-less-tr').hide();
            }

            let $fieldsTable = $divFilterItem.find('.sfswp-form-fields-table');
            $fieldsTable.removeClass('selected-and-above-show');
            if( optionVal === 'checkboxes' ) {
                $fieldsTable.addClass('sfswp-view-checkboxes');
                $fieldsTable.removeClass('sfswp-view-dropdown');
                $fieldsTable.removeClass('sfswp-view-rating');
            } else if( optionVal === 'rating' ){
                $fieldsTable.addClass('selected-and-above-show');
                $fieldsTable.addClass('sfswp-view-rating');
                $fieldsTable.removeClass('sfswp-view-checkboxes');
                $fieldsTable.removeClass('sfswp-view-dropdown');
            }else if( optionVal === 'dropdown' ){
                $fieldsTable.addClass('sfswp-view-dropdown');
                $fieldsTable.removeClass('sfswp-view-checkboxes');
                $fieldsTable.removeClass('sfswp-view-rating');
            } else {
                $fieldsTable.removeClass('sfswp-view-checkboxes');
                $fieldsTable.removeClass('sfswp-view-dropdown');
                $fieldsTable.removeClass('sfswp-view-rating');
                $fieldsTable.removeClass('selected-and-above-show');
            }
        });

        $( '.sfswp-sfs-set-wrapper .sfswp-filters-list' ).sortable({
            items: "> div.sfswp-filter-item",
            delay: 150,
            placeholder: "sfswp-filter-item-shadow",
            refreshPositions: true,
            cursor: 'move',
            handle: ".sfswp-filter-order",
            axis: 'y',
            update: function( event, ui ) {
                renderMenuOrder();
            },
            start: function ( event, ui ){
                let head = ui.item.children('.sfswp-filter-head'),
                    inside = ui.item.children('.sfswp-filter-body');

                if ( inside.hasClass('sfswp-opened') ) {
                    inside.removeClass('sfswp-opened')
                        .hide();
                    head.removeClass('sfswp-opened');
                    $(this).sortable('refreshPositions');
                }

                $('.sfswp-filter-item-shadow').css('min-height', head.height() + 'px');
            }

        });

        $('.sfswp-sfs-set-wrapper .sfswp-filters-list').keydown(function(e){
            if (e.keyCode == 65 && (e.ctrlKey || e.metaKey) ) {
                e.target.select()
            }
        })

        $( ".sfswp-filters-list" ).disableSelection();

        // Deleter filter
        $('body').on('click', '.sfswp-filter-delete', function (){
            removeElement( $('.sfswp-field-notice') );
            let $spinner = $(this).prev('.spinner');
            $spinner.addClass( 'is-active' );
            let requestParams          = {};
            requestParams._wpnonce = $("#sfswp_set_nonce").val();
            requestParams.fid   = $(this).data('fid');

            // @feature localize this var
            if( requestParams.fid === 'sfswp_new_id' ){
                let $filterItem = $(this).parents('.sfswp-filter-item');
                $filterItem.slideUp({
                    duration: 200,
                    complete: function (){
                        $(this).remove();
                        renderMenuOrder();
                        handleNoFiltersMessage();
                    }
                })
            }

            // Remove current filter from Parent filters list
            let dataFid = $(this).parents('.sfswp-filter-item').data('fid');
            sfswpDeleteFilterFromParentList( dataFid );

            wp.ajax.post( 'sfswp-delete-filter', requestParams )
                .always( function() {
                    $spinner.removeClass( 'is-active' );
                })
                .done( function( response ) {

                    if( typeof response !== 'undefined' && typeof response.fid !== 'undefined' ){
                        $("#sfswp-filter-id-"+response.fid).slideUp({
                            duration: 200,
                            complete: function (){
                                $(this).remove();
                                renderMenuOrder();
                                handleNoFiltersMessage();

                                // Set available entities again
                                // @todo doesn't work properly if there are several new filters exists on a page !!! IMPORTANT
                                // doesn't make some entities available, but should.
                                passNewEntities();

                            }
                        })
                    }
                })

                .fail( function(response) {
                    if( typeof response !== 'undefined'){
                        addFieldError( 'sfswp-filter-delete-wrapper-'+response.fid, response.message );
                    }
                });
        });

        // Get set location fields
        let selected_link = $('#sfswp_set_fields-post_type option:selected').data('link');
        if(selected_link != ''){
            $('.sfswp-location-preview-not-pro').removeClass('display-none');
        }

        $('body').on('change', '#sfswp_set_fields-post_type', function (){

            let postType = $(this).val();
            $("#sfswp-filters-list").attr('data-posttype', postType );
            let link = $('option:selected', this).data('link');
            $('.sfswp-location-preview-not-pro').attr('href', link);

            if(link != ''){
                $('.sfswp-location-preview-not-pro').removeClass('display-none');
            }else{
                $('.sfswp-location-preview-not-pro').addClass('display-none');
            }


            if( sfswpSetVars.filtersPro < 1 ){
                return true;
            }
            setAvailableEntities( $('.sfswp-new-filter-item .sfswp-field-entity') );

            removeElement( $('.sfswp-field-notice') );

            // Update Post type related location terms
            let selected = $('#sfswp_set_fields-wp_page_type').val();
            if( typeof selected !== 'undefined' /*&& selected === 'common:common'*/ ){
                sfswpGetLocationTerms( selected );
            }

            // Change options in all select.sfswp-field-ename
            let eNameSelect = $("select.sfswp-field-ename");
            if( eNameSelect.length > 0 ) {
                fillTaxNumSelect( eNameSelect, postType );
            }

        });

        // Filtered WP_Query location
        $('body').on('change', '#sfswp_set_fields-wp_page_type', function(){
            sfswpGetLocationTerms( $(this).val() );
        });

        // Apply button location
        $('body').on('change', '#sfswp_set_fields-apply_button_page_type', function(){
            sfswpGetApplyLocationTerms( $(this).val() );
        });

        $('body').on('change', '#sfswp_set_fields-post_name', function (e){
            let filterPagelink = $('option:selected', this).data('link');

            if( typeof filterPagelink !== 'undefined'){
                sfswpGetWpQueries( filterPagelink );
            }
        });

        $('body').on( 'change', '.sfswp-date-format', function (e){
            let otherFieldName = $(this).attr('name');
            let $customField = $( '.sfswp-date-custom-format[name="'+otherFieldName+'"]' );
            if ( $(this).attr('value') === 'other' ) {
                $customField.removeAttr('disabled');
            } else {
                $customField.val( $(this).val() );
                $customField.attr('disabled', 'disabled');
            }
        });

        $('body').on('change', '.sfswp-date-type', function (e){

            let dataFid = $(this).parents('.sfswp-filter-item').data('fid');

            let $spinner = $( '.sfswp_filter_fields-'+dataFid+'-date_format-wrap' ).children( '.spinner' );
            $spinner.addClass( 'is-active' );

            // Set up AJAX request
            let requestParams           = {};
            //requestParams._wpnonce  = $("#sfswp_set_nonce").val();
            requestParams.setId         = $("#post_ID").val();
            requestParams.dateType      = $("#sfswp_filter_fields-"+dataFid+"-date_type").val();
            requestParams.fid           = dataFid;

            wp.ajax.post( 'sfswp_get_date_formats', requestParams )
                .always( function() {
                    $spinner.removeClass( 'is-active' );
                })
                .done( function( response ) {
                    if ( typeof response.html !== 'undefined' ) {
                        let setDefault  = true;
                        let radioList   = $(response.html).find('ul');

                        $.each( radioList.find('input.sfswp-date-format'), function( key, value ){
                            let theOption = $(this);
                            if( theOption.is(':checked') ){
                                setDefault = false;
                                return;
                            }
                        });

                        if( setDefault === true ) {
                            radioList.find('input.sfswp-date-format:first').attr('checked', 'checked');
                        }

                        $( '.sfswp_filter_fields-'+dataFid+'-date_format-wrap ul' ).replaceWith(radioList);
                    }
                })
                .fail( function(response) {
                    // {"success":false}
                });
        });

        $('body').on('change', '.sfswp-field-parent-filter', function (){
            let parentNo    = ['no', '-1'];
            let parentVal   = $(this).val();
            let fid         = $(this).parents('.sfswp-filter-item').data('fid');
            let hideTr      = $("#sfswp-filter-id-"+fid+" .sfswp-field-hide-until-parent-tr");

            if( parentNo.includes(parentVal) ){
                hideTr.removeClass('sfswp-opened');
            }else{
                hideTr.addClass('sfswp-opened');
            }
        });

        $('body').on('click', '#sfswp_set_fields-use_apply_button', function (){
            let applyButtonChecked = $(this).prop( "checked" );

            if( applyButtonChecked ){
                $("#sfswp-filter-id-apply-button").addClass('sfswp-opened');
                $(".sfswp-field-apply-button-text-tr").addClass('sfswp-opened');
                $(".sfswp-field-apply-button-page-type-tr").addClass('sfswp-opened');
                $(".sfswp-field-reset-button-text-tr").addClass('sfswp-opened');
                $('.sfswp-no-filters').hide();
            }else{
                $("#sfswp-filter-id-apply-button").removeClass('sfswp-opened');
                $(".sfswp-field-apply-button-text-tr").removeClass('sfswp-opened');
                $(".sfswp-field-apply-button-page-type-tr").removeClass('sfswp-opened');
                $(".sfswp-field-reset-button-text-tr").removeClass('sfswp-opened');

                if( $(".sfswp-filter-item:visible").length < 1 ){
                    $('.sfswp-no-filters').show();
                }
            }
        });

        $('body').on('click', '#sfswp_set_fields-use_search_field', function (){
            let searchFieldChecked = $(this).prop( "checked" );

            if( searchFieldChecked ){
                $("#sfswp-filter-id-search-field").addClass('sfswp-opened');

                $(".sfswp-search-field-placeholder-tr").addClass('sfswp-opened');
                $(".sfswp-search-field-label-tr").addClass('sfswp-opened');

                $('.sfswp-no-filters').hide();
            }else{
                $("#sfswp-filter-id-search-field").removeClass('sfswp-opened');

                $(".sfswp-search-field-placeholder-tr").removeClass('sfswp-opened');
                $(".sfswp-search-field-label-tr").removeClass('sfswp-opened');

                if( $(".sfswp-filter-item:visible").length < 1 ){
                    $('.sfswp-no-filters').show();
                }
            }
        });
        $('body').on('click', '#sfswp_set_fields-use_sort_option', function (){
            let searchFieldChecked = $(this).prop( "checked" );

            if( searchFieldChecked ){
                $("#sfswp-filter-id-sort-field").addClass('sfswp-opened');

                $(".sfswp-sort-field-placeholder-tr").addClass('sfswp-opened');
                $(".sfswp-sort-field-label-tr").addClass('sfswp-opened');

                $('.sfswp-no-filters').hide();
                $('.sfswp-sfs-set-sorting-options-settings-wrapper').show();
            }else{
                $("#sfswp-filter-id-sort-field").removeClass('sfswp-opened');

                $(".sfswp-sort-field-placeholder-tr").removeClass('sfswp-opened');
                $(".sfswp-sort-field-label-tr").removeClass('sfswp-opened');

                if( $(".sfswp-filter-item:visible").length < 1 ){
                    $('.sfswp-no-filters').show();
                }
                $('.sfswp-sfs-set-sorting-options-settings-wrapper').hide();
            }
        });

        $('body').on('focus keypress blur', '.sfswp-field-min-num-label, .sfswp-field-max-num-label', function (e){
            let sfswpPosition = $(this).getCursorPosition();
            $(this).data('caret', sfswpPosition);
        });

        $('body').on('click', '.sfswp-variable-inserter', function (e){
            let wrapper = $(this).parents('.sfswp-sfs-field-min-max-labels-wrap');
            $.each( wrapper.find('input[type="text"]'), function( i, field ){
                let inputField =  $( field );
                let valueVar = '{value}';
                let caretPos   = inputField.data('caret');

                if( caretPos === 0 ){
                    valueVar = valueVar+' ';
                }else if( caretPos === inputField.val().length ){
                    valueVar = ' '+valueVar;
                }else{
                    // Undefined or position in the end
                    valueVar = ' '+valueVar+' ';
                }

                insertAtCaret( inputField, valueVar, caretPos );
            } );

        });


        let filterPagelink = $('option:selected', $('#sfswp_set_fields-post_name')).data('link');
        $('.sfswp-location-preview').addClass('display-none');

        if( typeof filterPagelink !== 'undefined' && filterPagelink ){
            $('.sfswp-location-preview').removeClass('display-none');
            sfswpGetWpQueries( filterPagelink );
        }

        let notProfilterPagelink = $('option:selected', $('#sfswp_set_fields-post_type')).data('link');
        if( typeof notProfilterPagelink !== 'undefined' && notProfilterPagelink ){
            $('.sfswp-location-preview-not-pro').attr('href', notProfilterPagelink);
            $('.sfswp-location-preview-not-pro').removeClass('display-none');
        }
    });

    function sfswpShortenEname( eName ){
        let shortenName = eName;

        if( eName.includes( 'taxonomy_' ) ){
            if( eName.slice(0, 9) === 'taxonomy_' ){
                shortenName = eName.slice(9);
            }
        }else if( eName.includes( 'author_' ) ){
            if( eName.slice(0, 7) === 'author_' ){
                shortenName = eName.slice(7);
            }
        }

        return shortenName;
    }

    function sfswpAddNewFilterToParentList(){
        let allIds = {};
        let theFid = 0;
        let theTitle = ''
        let theEname = '';
        let theNoVal = false;
        let possibleOption = false;
        let newOption      = false;

        $(".sfswp-filter-item:not(.sfswp-filter-not-listed)").each( function ( index, elem ){
            theFid      = $(this).data('fid');
            theTitle    = $("#sfswp_filter_fields-"+theFid+"-label").val();

            if( ! theTitle ){
                theTitle = sfswpSetVars.newFilter;
            }

            theEname = $("#sfswp_filter_fields-"+theFid+"-entity").val();
            // theEname = sfswpShortenEname(theEname);

            allIds[theFid] = { 'id' : theFid.toString(), 'title': theTitle, 'ename': theEname};
        } );

        // In case if there is only single filter in Set
        if( Object.keys(allIds).length < 2 ){
            //console.log('Less than 2');
            return;
        }

        // If there are 2 or more filters
        $.each( allIds, function ( index, elem ){

            theNoVal = $( "#sfswp_filter_fields-"+elem['id']+"-parent_filter > option[value='no']");
            if( theNoVal.length > 0 ){
                theNoVal.val( '-1' );
                theNoVal.text( sfswpSetVars.selectFilter );
            }

            $.each( allIds, function ( inindex, inelem ){
                if( elem['id'] === inindex ){
                    return;
                }

                possibleOption = $( "#sfswp_filter_fields-"+elem['id']+"-parent_filter > option[value='"+inindex+"']");
                if( possibleOption.length < 1 ){
                    newOption = $('<option>', {
                        value: inindex,
                        text: inelem['title']+" ("+sfswpShortenEname( inelem['ename'] )+")"
                    });

                    if( inelem['ename'] === 'post_meta_num' || inelem['ename'] === 'tax_numeric' ){
                        newOption.attr("disabled", "disabled");
                    }

                    $( "#sfswp_filter_fields-"+elem['id']+"-parent_filter").append( newOption );
                }
            });
        });
    }

    function sfswpDeleteFilterFromParentList( filterId )
    {
        let theOption = false;

        $(".sfswp-field-parent-filter option[value='"+filterId+"'").each(function (index, element){
            theOption = $(this);
            let theSelect = theOption.parents("select");

            if( theOption.is(':selected') ){
                theSelect.val( theSelect.find("option:first").val() );
            }

            theOption.remove();

            if( theSelect.find("option").length === 1 ){
                theOption = theSelect.find("option:first");
                theOption.val('no');
                theOption.text(sfswpSetVars.addFilter);
                theSelect.val('no');
            }

        });
    }

    function sfswpGetWpQueries( filterPagelink ){
        if( sfswpSetVars.filtersPro < 1){
            return true;
        }

        if( filterPagelink === '' ){
            return true;
        }

        removeElement( $('.sfswp-field-notice') );
        // 1 Get current Post type to try to find its query

        // let selected = $('#sfswp_set_fields-post_type').val();
        let $spinner = $( '.sfswp_set_fields-wp_filter_query-wrap' ).children( '.spinner' );
        let postType = $("#sfswp_set_fields-post_type").val();

        // Set up AJAX request
        let requestParams          = {};
        requestParams._wpnonce      = $("#sfswp_set_nonce").val();
        requestParams.wpPageType    = $('#sfswp_set_fields-wp_page_type').val();
        requestParams.postType      = postType;
        requestParams.postId        = $("#post_ID").val();
        requestParams.action        = 'sfswp_get_wp_queries';


        $.ajax({
            'method': 'POST',
            'data': requestParams,
            'url': filterPagelink,
            'dataType': 'html',
            beforeSend: function () {
                $spinner.addClass( 'is-active' );
                $(".sfswp-location-preview").attr('href', filterPagelink);
            },
            complete: function () {
                $spinner.removeClass( 'is-active' );
            },
            success: function (response) {
                let sfswpWpQueriesSelect = $(response).find('#sfswp_set_fields-wp_filter_query');
                let sfswpWpQueriesHidden = $(response).find('#sfswp_query_vars');

                if( sfswpWpQueriesSelect !== '' && sfswpWpQueriesSelect.length > 0 ){
                    $("#"+sfswpSetVars.wPQuerySelectId).replaceWith(sfswpWpQueriesSelect);
                }

                if( sfswpWpQueriesHidden.length > 0 ){
                    $('#sfswp_query_vars').replaceWith(sfswpWpQueriesHidden);
                }
            },

            error: function (response) {
                //
            }
        });
    }

    function sfswpGetApplyLocationTerms( selected ){

        let $spinner = $( '.sfswp_set_fields-apply_button_post_name-wrap' ).children( '.spinner' );
        $spinner.addClass( 'is-active' );
        // Clear all errors
        removeElement( $('.sfswp-field-notice') );
        let postType = $("#sfswp_set_fields-post_type").val();

        // Set up AJAX request
        let requestParams          = {};
        requestParams._wpnonce = $("#sfswp_set_nonce").val();
        requestParams.wpPageType = selected;
        requestParams.postType   = postType;
        requestParams.postId     = $("#post_ID").val();
        requestParams.fieldKey   = 'apply_button_post_name';

        wp.ajax.post( 'sfswp-get-set-location-terms', requestParams )
            .always( function() {
                $spinner.removeClass( 'is-active' );
            })
            .done( function( response ) {
                //
                let locationTermsSelect = $(response.html).find('#sfswp_set_fields-apply_button_post_name');
                $( '#sfswp_set_fields-apply_button_post_name' ).replaceWith(locationTermsSelect);
            })

            .fail( function(response) {
                // {"success":false}
                if( typeof response !== 'undefined'){
                    addFieldError('sfswp_set_fields-apply_button_post_name', response.message);
                }
            });
    }

    function sfswpGetLocationTerms( selected ){

        let $spinner = $( '.sfswp_set_fields-post_name-wrap' ).children( '.spinner' );
        $spinner.addClass( 'is-active' );
        // Clear all errors
        removeElement( $('.sfswp-field-notice') );
        let postType = $("#sfswp_set_fields-post_type").val();

        // Set up AJAX request
        let requestParams          = {};
        requestParams._wpnonce = $("#sfswp_set_nonce").val();
        requestParams.wpPageType = selected;
        requestParams.postType   = postType;
        requestParams.postId     = $("#post_ID").val();

        wp.ajax.post( 'sfswp-get-set-location-terms', requestParams )
            .always( function() {
                $spinner.removeClass( 'is-active' );
            })
            .done( function( response ) {
                //
                let locationTermsSelect = $(response.html).find('#sfswp_set_fields-post_name');
                $( '#sfswp_set_fields-post_name' ).replaceWith(locationTermsSelect);

                let filterPagelink = $('option:selected', $('#sfswp_set_fields-post_name') ).data('link');
                if( typeof filterPagelink !== 'undefined'){
                    sfswpGetWpQueries( filterPagelink );
                }
            })

            .fail( function(response) {
                // {"success":false}
                if( typeof response !== 'undefined'){
                    addFieldError('sfswp_set_fields-post_name', response.message);
                }
            });
    }

    function cpaLiveWrite( readFrom, writeTo ) {
        let cpaText;
        // readFrom.on('input', function() {
            cpaText = readFrom.val(); //$(this).val();
            writeTo.text(cpaText);
        // });
    }

    /**
     * Calculates correct menu order in accordance with filter position in list
     */
    function renderMenuOrder()
    {
        $(".sfswp-filter-item").each( function ( index, element ) {
            var num = index + 1;
            $(element).find('.sfswp-menu-order-field').attr( 'value', num );
            $(element).find('.sfswp-filter-order').attr( 'title', num );
        });
    }

    function handleNoFiltersMessage()
    {
        if( $(".sfswp-filter-item:not(.sfswp-filter-not-listed)").length > 0 ){
            $('.sfswp-no-filters').hide();
        }else{
            if ( $(".sfswp-filter-not-listed").hasClass('sfswp-opened') === false ){
                $('.sfswp-no-filters').show();
            }
        }
    }

    function setEntityTableClass( entitySelect )
    {
        let val = entitySelect.val();
        let fid = entitySelect.parents('.sfswp-filter-item').data('fid');
        let additionalClass = '';

        if( val.startsWith('taxonomy_pa_') ){
            additionalClass = ' taxonomy-product-attribute';
        }

        if( val.indexOf('taxonomy') !== -1 ){
            val = 'taxonomy';
        }

        $("#sfswp-filter-id-"+fid+" .sfswp-form-fields-table").attr('class', 'sfswp-form-fields-table sfswp-filter-'+val+additionalClass);
    }

    function syncEntityWithPrefix( entitySelect )
    {
        let val = entitySelect.val();
        let fid = entitySelect.parents('.sfswp-filter-item').data('fid');

        if( typeof sfswpSetVars.filterSlugs[val] !== 'undefined'){
            let prefix = sfswpSetVars.filterSlugs[val];
            $('#sfswp_filter_fields-'+fid+'-slug').val(prefix)
                .attr('readonly', 'readonly')
                .trigger('input');
        } else {
            $('#sfswp_filter_fields-'+fid+'-slug').val('')
                .removeAttr('readonly')
                .trigger('input');
        }

    }

    function syncEntityWithSortTerms( entitySelect ){
        let val = entitySelect.val();
        let fid = entitySelect.parents('.sfswp-filter-item').data('fid');

        if( ! val.includes('taxonomy_pa') ) {
            $('#sfswp_filter_fields-'+fid+'-orderby option[value="menuasc"]').attr('disabled', 'disabled');
            $('#sfswp_filter_fields-'+fid+'-orderby option[value="menudesc"]').attr('disabled', 'disabled');
        }else{
            $('#sfswp_filter_fields-'+fid+'-orderby option[value="menuasc"]').removeAttr('disabled');
            $('#sfswp_filter_fields-'+fid+'-orderby option[value="menudesc"]').removeAttr('disabled');
        }
    }

    function syncEntityWithView( entitySelect ){
        let val = entitySelect.val();
        let fid = entitySelect.parents('.sfswp-filter-item').data('fid');
        if( val === 'post_meta_num' || val === 'tax_numeric' ) {
            $('#sfswp_filter_fields-' + fid + '-view option:not([value="range"])').attr('disabled', 'disabled');
            $('#sfswp_filter_fields-' + fid + '-view option[value="range"]').removeAttr('disabled')
                .prop('selected', true);
            $('#sfswp_filter_fields-' + fid + '-view').trigger('change');
        } else if ( val === 'taxonomy_product_visibility' ) {
            $('#sfswp_filter_fields-' + fid + '-view option[value="rating"]').removeAttr('disabled')
                .prop('selected', true);
            $('.sfswp-form-fields-table').addClass('sfswp-view-rating');
        }
        else if ( val === 'post_date' ) {
            $('#sfswp_filter_fields-' + fid + '-view option:not([value="date"])').attr('disabled', 'disabled');
            $('#sfswp_filter_fields-' + fid + '-view option[value="date"]').removeAttr('disabled')
                .prop('selected', true);
            $('#sfswp_filter_fields-' + fid + '-view').trigger('change');
        }else{
            $('#sfswp_filter_fields-'+fid+'-view option').removeAttr('disabled')
            $('#sfswp_filter_fields-'+fid+'-view option:not([disabled]):first').prop('selected', true);
            $('#sfswp_filter_fields-'+fid+'-view option[value="range"]').attr('disabled', 'disabled');
            $('#sfswp_filter_fields-'+fid+'-view option[value="rating"]').attr('disabled', 'disabled');
            $('#sfswp_filter_fields-'+fid+'-view option[value="date"]').attr('disabled', 'disabled');
            $('#sfswp_filter_fields-'+fid+'-view').trigger('change');
        }
    }


    function handleLogicField( entitySelect )
    {
        let val = entitySelect.val();
        let fid = entitySelect.parents('.sfswp-filter-item').data('fid');

        if ( val === 'author_author' || val === 'post_meta_exists' || val === 'taxonomy_product_visibility' ) {
            $( '#sfswp_filter_fields-' + fid + '-logic option[value="and"]' ).attr( 'disabled', 'disabled' );
            $( '#sfswp_filter_fields-' + fid + '-logic option[value="or"]' ).prop( 'selected', true );
        } else if ( val === 'post_meta_num' || val === 'tax_numeric' || val === 'post_date' ) {
            // If filter is numeric logic can be AND only
            $( '#sfswp_filter_fields-' + fid + '-logic option[value="or"]' ).attr( 'disabled', 'disabled' );
            $( '#sfswp_filter_fields-' + fid + '-logic option[value="and"]' ).prop( 'selected', true );
        } else {
            $( '#sfswp_filter_fields-'+fid+'-logic option[value="and"]' ).removeAttr( 'disabled' );
            $( '#sfswp_filter_fields-'+fid+'-logic option[value="or"]' ).removeAttr( 'disabled' );
        }

        return true;
    }

    function handleHierarchyField( entitySelect )
    {
        let val = entitySelect.val();
        let $divFilterItem = entitySelect.parents('.sfswp-filter-item');

        if( val.indexOf('taxonomy') !== -1 ){
            $.each( sfswpSetVars.postTypesTaxList, function ( pType, taxesArray ){
                $.each( taxesArray, function ( index, theTax ){
                    if( theTax['name'] === val ){
                        if( theTax['hierarchical'] ){
                            $divFilterItem.find('.sfswp-form-fields-table').addClass('taxonomy-hierarchical');
                        }else{
                            $divFilterItem.find('.sfswp-form-fields-table').removeClass('taxonomy-hierarchical');
                        }
                    }
                });
            });
        } else {
            $divFilterItem.find('.sfswp-form-fields-table').removeClass('taxonomy-hierarchical');
        }
    }

    function handleMetaKeyField( entitySelect )
    {
        let val = entitySelect.val();
        let fid = entitySelect.parents('.sfswp-filter-item').data('fid');

        if ( val === 'post_meta' || val === 'post_meta_num' || val === 'post_meta_exists' ) {
            let eNameTag = $('#sfswp_filter_fields-'+fid+'-e_name');

            if ( eNameTag.prop("tagName").toLowerCase() === 'select' ) {
                let eNameInput = $('<input>');
                let postType = $("#sfswp_set_fields-post_type").val();

                eNameInput.attr( 'class', eNameTag.attr('class') )
                    .attr( 'type', 'text' )
                    .attr( 'name', eNameTag.attr('name') )
                    .attr( 'id', eNameTag.attr('id') );

                eNameTag.val('');
                eNameTag.removeAttr('readonly');
                eNameTag.replaceWith(eNameInput);

                eNameInput.parents('.sfswp-field-ename-tr').show();
            } else {
                eNameTag.val('');
                eNameTag.parents('.sfswp-field-ename-tr').show();
            }

            $('#sfswp-filter-id-'+fid+' .sfswp-field-ename-tr p.sfswp-field-description').text( numFieldAttrs['post_meta_num']['description'] );
            $('#sfswp-filter-id-'+fid+' .sfswp-field-ename-tr label.sfswp-filter-label span.sfswp-label-text').text( numFieldAttrs['post_meta_num']['label'] );
            $('#sfswp-filter-id-'+fid+' .sfswp-field-ename-tr p.description').css('visibility', 'visible');

        } else if ( val === 'tax_numeric' ) {
            let eNameTag = $('#sfswp_filter_fields-'+fid+'-e_name');
            let postType = $("#sfswp_set_fields-post_type").val();

            if ( eNameTag.prop("tagName").toLowerCase() === 'input' ) {
                let eNameSelect = $('<select>');

                eNameSelect.attr( 'class', eNameTag.attr('class') )
                    .attr( 'name', eNameTag.attr('name') )
                    .attr( 'id', eNameTag.attr('id') );

                eNameTag.removeAttr( 'readonly' );
                eNameTag.replaceWith( eNameSelect );
                //@todo - if already existing tax_numeric slug presents, it should be inserted as usual
                //@todo - if filter by this tax numeric entity exists, it should be deactivated in the Tax num dropdown
                fillTaxNumSelect( eNameSelect, postType );
                eNameSelect.parents('.sfswp-field-ename-tr').show();
            } else {
                fillTaxNumSelect( eNameTag, postType );
                eNameTag.parents('.sfswp-field-ename-tr').show();
            }

            $('#sfswp-filter-id-'+fid+' .sfswp-field-ename-tr p.sfswp-field-description').text( numFieldAttrs['tax_numeric']['description'] );
            $('#sfswp-filter-id-'+fid+' .sfswp-field-ename-tr label.sfswp-filter-label span.sfswp-label-text').text( numFieldAttrs['tax_numeric']['label'] );
            $('#sfswp-filter-id-'+fid+' .sfswp-field-ename-tr p.description').css('visibility', 'hidden');

        } else {
            $('#sfswp_filter_fields-'+fid+'-e_name').parents('.sfswp-field-ename-tr').hide();
        }

        // Numeric values can not be in URL path
        if( val === 'post_meta_num' || val === 'tax_numeric' || val === 'post_date' ){
            $('#sfswp_filter_fields-'+fid+'-in_path').prop( "checked", false );
            // $('#sfswp_filter_fields-'+fid+'-show_chips').prop( "checked", false );
        }else{
            $('#sfswp_filter_fields-'+fid+'-in_path').prop( "checked", true );
            // $('#sfswp_filter_fields-'+fid+'-show_chips').prop( "checked", true );
        }
    }

    function loadExcludeItems( entity, fid, ename )
    {
        removeElement( $('.sfswp-field-notice') );
        let requestParams          = {};
        let target              = $('#sfswp_filter_fields-'+fid+'-exclude');
        requestParams._wpnonce  = $("#sfswp_set_nonce").val();
        requestParams.fid       = fid;
        requestParams.entity    = entity;

        if( typeof ename !== 'undefined' ){
            requestParams.ename = ename;
        }

        let $spinner = target.parent('.sfswp-after-spinner-container').prev( '.spinner' );
        $spinner.addClass( 'is-active' );

        wp.ajax.post( 'sfswp-load-exclude-terms', requestParams )
            .always( function() {
                $spinner.removeClass( 'is-active' );
            })
            .done( function( response ) {
                if( typeof response.fid !== 'undefined' ){
                    target.select2('destroy');
                    target.html('');
                    target.select2({
                        width: '100%',
                        placeholder: sfswpSetVars.excludePlaceholder,
                        data: response.terms,
                        disabled: false
                    })
                }
            })

            .fail( function(response) {
                // if( typeof response !== 'undefined'){
                //     addFieldError( 'sfswp_filter_fields-'+response.fid+'-exclude', response.message );
                // }
            });

    }

    function sfswpSerialize( $el ){

        var obj = {};
        var inputs = $el.find('select, textarea, input').serializeArray();

        for( var i = 0; i < inputs.length; i++ ) {
            sfswpBuildObject( obj, inputs[i].name, inputs[i].value );
        }
        return obj;
    };

    function sfswpBuildObject( obj, name, value ){
        name = name.replace('[]', '[%%index%%]');

        var keys = name.match(/([^\[\]])+/g);
        if( !keys ) return;
        var length = keys.length;
        var ref = obj;

        for( var i = 0; i < length; i++ ) {
            var key = String( keys[i] );
            if( i == length - 1 ) {
                if( key === '%%index%%' ) {
                    ref.push( value );
                } else {
                    ref[ key ] = value;
                }
            } else {
                if( keys[i+1] === '%%index%%' ) {
                    if( !sfswpIsArray(ref[ key ]) ) {
                        ref[ key ] = [];
                    }
                } else {
                    if( !sfswpIsObject(ref[ key ]) ) {
                        ref[ key ] = {};
                    }
                }
                ref = ref[ key ];
            }
        }
    };

    function sfswpIsArray( a ){
        return Array.isArray(a);
    };

    function sfswpIsObject( a ){
        return ( typeof a === 'object' );
    }

    /**
     * Fills Tax Num Select with options
     * @param $el (object) The select element
     * @param postType Post type selected to filter
     */
    function fillTaxNumSelect( $el, postType ) {
        $el.find('option')
            .remove()
            .end();

        if ( postType in postTypesTaxList ) {
            $( postTypesTaxList[ postType ] ).each( function() {
                $el.append( $("<option>").attr('value', this.name ).text( this.label ) );
            });
        } else {
            $el.append( $("<option>").attr('value', -1 ).text( numFieldNoTaxes ) );
        }
    }

})(jQuery);

function insertAtCaret( target, text, caretPos )
{
    let textAreaTxt = target.val();
    let result = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
    result = result.replace(/ +(?= )/g,'');
    target.val(result);

    return true;
}

// Important!!!
// When field Filter by is selected, it is required to make AJAX request to find the same
// entity in filters already. And if it is exists, to predefine field "slug" defined in previous
// selection of

function uniqId (prefix, moreEntropy) {
    //  discuss at: https://locutus.io/php/uniqid/
    // original by: Kevin van Zonneveld (https://kvz.io)
    //  revised by: Kankrelune (https://www.webfaktory.info/)
    //      note 1: Uses an internal counter (in locutus global) to avoid collision
    //   example 1: var $id = uniqid()
    //   example 1: var $result = $id.length === 13
    //   returns 1: true
    //   example 2: var $id = uniqid('foo')
    //   example 2: var $result = $id.length === (13 + 'foo'.length)
    //   returns 2: true
    //   example 3: var $id = uniqid('bar', true)
    //   example 3: var $result = $id.length === (23 + 'bar'.length)
    //   returns 3: true

    if (typeof prefix === 'undefined') {
        prefix = '';
    }

    var retId;
    var _formatSeed = function (seed, reqWidth) {
        seed = parseInt(seed, 10).toString(16); // to hex str
        if (reqWidth < seed.length) {
            // so long we split
            return seed.slice(seed.length - reqWidth);
        }
        if (reqWidth > seed.length) {
            // so short we pad
            return Array(1 + (reqWidth - seed.length)).join('0') + seed;
        }
        return seed;
    }

    var $global = (typeof window !== 'undefined' ? window : global);
    $global.$locutus = $global.$locutus || {}
    var $locutus = $global.$locutus;
    $locutus.php = $locutus.php || {}

    if (!$locutus.php.uniqidSeed) {
        // init seed with big random int
        $locutus.php.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
    }
    $locutus.php.uniqidSeed++;

    // start with prefix, add current milliseconds hex string
    retId = prefix;
    retId += _formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
    // add seed hex string
    retId += _formatSeed($locutus.php.uniqidSeed, 5);
    if (moreEntropy) {
        // for more entropy we add a float lower to 10
        retId += (Math.random() * 10).toFixed(8).toString();
    }

    return retId;
}