/*!
 * SearchFilterSort 1.9.1
 */
(function ($) {
    "use strict";
    let sfswpAjax                     = sfswpFilterFront.sfswpAjaxEnabled;
    let sfswpStatusCookieName         = sfswpFilterFront.sfswpStatusCookieName;
    let sfswpMoreLessCookieName       = sfswpFilterFront.sfswpMoreLessCookieName;
    let sfswpWidgetStatusCookieName   = sfswpFilterFront.sfswpWidgetStatusCookieName;
    let sfswpHierachyListCookieName   = sfswpFilterFront.sfswpHierarchyListCookieName;
    let sfswpMobileWidth              = sfswpFilterFront.sfswpMobileWidth;
    let sfswpPostContainers           = sfswpFilterFront.sfswpPostContainers;
    let sfswpAutoScroll               = sfswpFilterFront.sfswpAutoScroll;
    let sfswpAutoScrollOffset         = sfswpFilterFront.sfswpAutoScrollOffset;
    let sfswpWaitCursor               = sfswpFilterFront.sfswpWaitCursor;
    let sfswpPostsPerPage             = sfswpFilterFront.sfswpPostsPerPage;
    let sfswpUseSelect2               = sfswpFilterFront.sfswpUseSelect2;
    let sfswpDateFilters              = sfswpFilterFront.sfswpDateFilters;
    let sfswpDateFiltersLocale        = sfswpFilterFront.sfswpDateFiltersLocale;
    let sfswpDateFiltersL10n          = sfswpFilterFront.sfswpDateFiltersL10n;
    let sfswpPopupCompatMode          = sfswpFilterFront.sfswpPopupCompatMode;
    let sfswpApplyButtonSets          = sfswpFilterFront.sfswpApplyButtonSets;
    let sfswpQueryOnThePageSets       = sfswpFilterFront.sfswpQueryOnThePageSets;
    let noPostsContainerMsg         = sfswpFilterFront.sfswpNoPostsContainerMsg;
    let sfswpWidgetContainer          = '.sfswp-filters-main-wrap';
    let sfswpIsMobile                 = false;
    let toReplaceSEO                = true;
    let prevState                   = false; // Contains SEO Rule availability on a page
    let currentState                = false; // Contains SEO Rule availability on a page

    let seoRuleId = $('#sfswp-seo-rule-id').data( 'seoruleid' );
    if ( seoRuleId > 0 ) {
        prevState = true;
    }

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

    $(document).on('click', '.sfswp-filter-content input[type="radio"],.sfswp-filter-content input[type="checkbox"]', function (e) {
        let sfswpLink = $(this).data('sfswp-link');
        let $el     = $(this).parents(sfswpWidgetContainer);
        let setId   = $el.data('set');
        let applyButtonMode = false;

        if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes(setId) ){
            applyButtonMode = true;
        }

        if( sfswpAjax || applyButtonMode ){
            e.preventDefault();
            sfswpSendFilterRequest( sfswpLink, $el, applyButtonMode );
        }else{
            location.href = sfswpLink;
        }
    });

    $(document).on('change', '.sfswp-orderby-select', function (){
        let sfswpSortingForm = $(this).parents('form.sfswp-sorting-form');
        // let sfswpSortingVal  = $(this).val();
        let search = '';
        //@todo bug on mobile force AJAX
        search = '?' + sfswpSortingForm.serialize();

        let sfswpLink = sfswpSortingForm.attr('action') + search;

        if( sfswpFilterFront.sfswpAjaxEnabled ) {
            $('.sfswp-filters-main-wrap').each(function (index, element) {
                let $el = $(element);
                sfswpSendFilterRequest(sfswpLink, $el, false);
            });
        }else{
            sfswpSortingForm.attr('action', sfswpLink);
            // window.location.href = sfswpLink;
            sfswpSortingForm.submit();
        }
    });

    $(document).on('change', '.sfswp-filter-content select', function (e) {
        var sfswpLink = $(this).find('option:selected').data('sfswp-link');
        let $el     = $(this).parents(sfswpWidgetContainer);
        let setId   = $el.data('set');
        let applyButtonMode = false;

        if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes(setId) ){
            applyButtonMode = true;
        }

        if( sfswpAjax || applyButtonMode ){
            e.preventDefault();
            sfswpSendFilterRequest( sfswpLink, $el, applyButtonMode );
        }else{
            location.href = sfswpLink;
        }
    });

    $(document).on('click', '.sfswp-filter-chip a', function (e){
        let sfswpLink = $(this).attr('href');
        let setId   = $(this).parents('.sfswp-filter-chips-list').data('set');
        let $el     = $('.sfswp-sfs-set-'+setId);
        let applyButtonMode = false;

        if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes(setId) ){
            if( $(this).parents('.sfswp-sfs-set-'+setId).length > 0 ){
                applyButtonMode = true;
            }
        }

        if( sfswpAjax || applyButtonMode ) {
            e.preventDefault();
            sfswpSendFilterRequest( sfswpLink, $el, applyButtonMode );
        }else{
            return true;
        }
    });

    $(document).on('click', 'a.sfswp-filters-submit-button', function (e){

        if( $(this).hasClass('on-hold') ){
            if( $(this).data('last') !== 'sfswp-search-field' ){
                e.preventDefault();
                return false;
            }
        }

        let sfswpLink = $(this).attr('href');
        let setId   = $(this).parents('.sfswp-filters-main-wrap').data('set');
        let $el     = $('.sfswp-sfs-set-'+setId);

        if( sfswpAjax && sfswpQueryOnThePageSets.includes( setId ) ) {
            e.preventDefault();
            sfswpSendFilterRequest( sfswpLink, $el, false );
        }else{
            return true;
        }
    });

    $(document).on('click', 'a.sfswp-search-clear-icon', function (e){
        let sfswpLink = $(this).attr('href');
        let setId   = $(this).parents('.sfswp-filters-main-wrap').data('set');
        let $el     = $('.sfswp-sfs-set-'+setId);
        let applyButtonMode = false;

        if( sfswpAjax ) {
            e.preventDefault();
            sfswpSendFilterRequest( sfswpLink, $el, applyButtonMode );
            return false;
        }else{
            return true;
        }
    });

    $(document).on( 'change', '.sfswp-search-field', function (e) {
        let form = $(this).parents(".sfswp-filter-search-form");

        let $el = form.parents(sfswpWidgetContainer);
        let setId = $el.data('set');
        let applyButtonMode = false;

        if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes(setId) ){
            applyButtonMode = true;
            // return false;
        }

        if( sfswpAjax || applyButtonMode ){
            let search  = form.serialize();
            let sfswpLink = form.attr('action') + '?' + search;
            sfswpSendFilterRequest( sfswpLink, $el, applyButtonMode );
            return false;
        } else {
            form.submit();
        }
    });

    $(document).on('submit', '.sfswp-filter-search-form', function (e) {
        let form = $(this);

        let $el = form.parents(sfswpWidgetContainer);
        let setId = $el.data('set');
        let applyButtonMode = false;

        if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes(setId) ){
            applyButtonMode = true;
        }

        if( sfswpAjax || applyButtonMode ){
            let search  = form.serialize();
            let sfswpLink = form.attr('action') + '?' + search;
            sfswpSendFilterRequest( sfswpLink, $el, applyButtonMode );
            return false;
        } else {
            return true;
            // form.submit();
        }

    });

    $(document).on('click', 'a.sfswp-filters-reset-button', function (e){

        if( $(this).hasClass('on-hold') ){
            e.preventDefault();
            return false;
        }

        let sfswpLink = $(this).attr('href');
        let setId   = $(this).parents('.sfswp-filters-main-wrap').data('set');
        let $el     = $('.sfswp-sfs-set-'+setId);

        if( sfswpAjax ) {
            e.preventDefault();
            if( sfswpQueryOnThePageSets.includes( setId ) ){
                sfswpSendFilterRequest( sfswpLink, $el, false );
            }else{
                sfswpSendFilterRequest( sfswpLink, $el, true );
            }
        }else{
            return true;
            // sfswpSendFilterRequest( sfswpLink, $el, true );
        }
    });

    $(document).on('click', 'i.sfswp-toggle-children-list', function (){
        let tid = $(this).data('tid');
        let $targetLi = $(this).parent(".sfswp-term-item-content-wrapper").parent('li');
        let $targetFilter = $(this).parents('.sfswp-filters-section');

        if ( $targetLi.hasClass( 'sfswp-opened' ) ) {
            $targetLi.removeClass( 'sfswp-opened' )
                .addClass( 'sfswp-closed' );
            setStatusCookie( -tid, sfswpHierachyListCookieName );
        } else if ( $targetLi.hasClass( 'sfswp-closed' ) ) {
            $targetLi.removeClass( 'sfswp-closed' )
                .addClass( 'sfswp-opened' );
            setStatusCookie( tid, sfswpHierachyListCookieName );
        } else {
            if ( $targetFilter.hasClass( 'sfswp-filter-hierarchy-reverse' ) ) {
                $targetLi.removeClass( 'sfswp-opened' ) // For any case
                    .addClass( 'sfswp-closed' );
                setStatusCookie( -tid, sfswpHierachyListCookieName );
            } else {
                $targetLi.removeClass( 'sfswp-closed' ) // For any case
                    .addClass( 'sfswp-opened' );
                setStatusCookie( tid, sfswpHierachyListCookieName );
            }
        }
    });

    $(document).on('click', '.sfswp-filters-overlay', function (){
        let setId = $('body').data('set');
        sfswpCloseFiltersContainer(setId);
    })

    $(document).on('change', '.sfswp-filter-range-form input[type="number"]', function (event) {
        let form = $(this).parents('.sfswp-filter-range-form');
        processRangeForm( event, form );
    });

    $(document).on( 'click','.sfswp-open-close-filters-button', function (e){
        e.preventDefault();
        let openCloseButton = $(this);
        let sfswpSetId        = openCloseButton.data('wid');
        let widgetContent   = $('.sfswp-sfs-set-'+sfswpSetId+' .sfswp-filters-widget-content');

        if( widgetContent.is(':visible') ){
            widgetContent.slideUp({
                duration: 100,
                complete: function (){
                    $(this).addClass('sfswp-closed')
                        .removeClass('sfswp-opened');
                    openCloseButton.removeClass('sfswp-opened');
                    sfswpSetCookie(sfswpWidgetStatusCookieName, null, {path: '/', 'max-age': 2592000});
                }
            });
        }else{
            widgetContent.slideDown({
                duration: 100,
                complete: function (){
                    $(this).addClass('sfswp-opened')
                        .removeClass('sfswp-closed');
                    openCloseButton.addClass('sfswp-opened');
                    sfswpSetCookie(sfswpWidgetStatusCookieName, sfswpSetId, {path: '/', 'max-age': 2592000});
                }
            });
        }
    });

    $(document).on('click', '.sfswp-widget-close-icon', function (e){
        e.preventDefault();
        let $wrapper    = $( this ).parents( sfswpWidgetContainer );
        let setId       = $wrapper.data( 'set' );
        sfswpCloseFiltersContainer(setId);
    });

    $(document).on('click', '.sfswp-filters-apply-button', function (e){
        e.preventDefault();
        let $wrapper    = $( this ).parents( sfswpWidgetContainer );
        let setId       = $wrapper.data( 'set' );
        let $content    = $( '.sfswp-sfs-set-'+setId+' .sfswp-filters-widget-content' );
        let href        = $(this).attr( 'href' );
        let sfswpReload   = ! $(this).hasClass('sfswp-posts-loaded');
        let sfswpZindex   = '';
        let $currentTag = false;

        $wrapper.removeClass('sfswp-container-opened');
        $('html').removeClass('sfswp-overlay-visible');
        $content.removeClass('sfswp-filters-widget-opened');
        $('.sfswp-open-button-'+setId+' .sfswp-filters-open-widget').removeClass('sfswp-opened');

        if( sfswpPopupCompatMode ) {
            setTimeout(() => {
                $content.parents().each(function (index, tag) {
                    $currentTag = $(tag);
                    sfswpZindex = $currentTag.data('sfswpzindex');

                    // Saved z-index for
                    if (sfswpZindex !== 'undefined') {
                        $currentTag.css('z-index', sfswpZindex);
                    }

                    if ($currentTag.hasClass('sfswp-force-visibility')) {
                        $currentTag.removeClass('sfswp-force-visibility');
                    }
                });

                setTimeout(() => {
                    $(".sfswp-was-invisible").css('opacity', '1')
                        .removeClass('sfswp-was-invisible');
                }, 300);

            }, 260);
        }

        if( sfswpReload ) {
            location.href = href;
        }
    });

    $(document).on('submit', '.sfswp-filter-range-form', function (e) {
        submitSliderForm(e, $(this));
    });

    $(document).on('keydown', '.sfswp-filters-range-from,.sfswp-filters-range-to', function (event){
        if ( event.which == 13 ) {
            let fid = $(this).data('fid');
            processRangeForm( event, $("#sfswp-filter-date-range-form-"+ fid ) );
        }
    });

    $(document).on('click', '.sfswp-filter-content a', function (e) {
        e.preventDefault();
        let sfswpInputId = $(this).closest('label').attr('for');
        $(this).closest('label').parent('.sfswp-term-item-content-wrapper').parent('.sfswp-term-item').find('#'+sfswpInputId).trigger('click');
    });

    $(document).on('click', '.sfswp-filters-open-widget', function (e) {
        e.preventDefault();
        let setId = $(this).data('wid');
        sfswpOpenContainer( setId );
    });

    $(document).on('click', '.sfswp-filters-close-button', function (e) {
        e.preventDefault();
        let wrapper = $(this).parents(sfswpWidgetContainer);
        let setId   = wrapper.data('set');

        if( sfswpAjax && sfswpFilterFront.sfswpAjaxEnabled ){
            let cancelLink      = $(this).attr('href');
            let applyLink       = $('.sfswp-sfs-set-'+setId+' .sfswp-filters-apply-button').attr('href');

            if( cancelLink !== applyLink ){
                sfswpSendFilterRequest( cancelLink, wrapper, false,'sfswpCloseFiltersContainer' );
                return;
            }
        }

        sfswpCloseFiltersContainer(setId);
    });

    $(document).on('click', 'a.sfswp-toggle-a', function (e){
        e.preventDefault();
        let fid            = $(this).data('fid');
        let $filterSection = $( ".sfswp-filters-section-" + fid );
        //$( ".sfswp-filters-section-" + fid ).toggleClass( 'sfswp-show-more' );

        if ( $filterSection.hasClass('sfswp-show-more' ) ) {
            $filterSection.removeClass( 'sfswp-show-more' )
                .addClass( 'sfswp-show-less' );
            setStatusCookie( -fid, sfswpMoreLessCookieName );
        } else if ( $filterSection.hasClass('sfswp-show-less' ) ) {
            $filterSection.removeClass( 'sfswp-show-less' )
                .addClass( 'sfswp-show-more' );
            setStatusCookie( fid, sfswpMoreLessCookieName );
        } else {
            // No status class detected
            if( $filterSection.hasClass( 'sfswp-filter-has-selected' ) || $filterSection.hasClass( 'sfswp-show-more-reverse' ) ) {
                $filterSection.removeClass( 'sfswp-show-more' ) // For any case
                    .addClass( 'sfswp-show-less' );
                setStatusCookie( -fid, sfswpMoreLessCookieName );
            } else {
                $filterSection.removeClass( 'sfswp-show-less' ) // For any case
                    .addClass( 'sfswp-show-more' );
                setStatusCookie( fid, sfswpMoreLessCookieName );
            }
        }
    });

    $(document).on('click', '.sfswp-filters-main-wrap input', function (e) {
        let lastInputClass = $(this).attr('class');
        if ( typeof lastInputClass !== 'undefined' ){
            $('.sfswp-filters-submit-button').data('last', lastInputClass);
        }
    });

    $(document).on('click', '.sfswp-filter-title button', function (e) {
        e.preventDefault();
        let $filterSection = $(this).parents('.sfswp-filters-section');
        let filterId       = $filterSection.data( 'fid' );

        if ( $filterSection.hasClass( 'sfswp-opened' ) ) {
            $filterSection.removeClass( 'sfswp-opened' )
                .addClass( 'sfswp-closed' );
            setStatusCookie( -filterId, sfswpStatusCookieName );
        } else if ( $filterSection.hasClass( 'sfswp-closed' ) ) {
            $filterSection.removeClass( 'sfswp-closed' )
                .addClass( 'sfswp-opened' );
            setStatusCookie( filterId, sfswpStatusCookieName );
        } else {
           if( $filterSection.hasClass( 'sfswp-filter-has-selected' ) || $filterSection.hasClass( 'sfswp-filter-collapsible-reverse' ) ) {
                $filterSection.removeClass( 'sfswp-opened' )
                    .addClass( 'sfswp-closed' );
               setStatusCookie( -filterId, sfswpStatusCookieName );
           } else {
               $filterSection.removeClass( 'sfswp-closed' )
                   .addClass( 'sfswp-opened' );
               setStatusCookie( filterId, sfswpStatusCookieName );
           }
        }
    });

    $( window ).resize(function() {
        if( window.innerWidth <= sfswpMobileWidth ){
            sfswpIsMobile = true;
            if( sfswpFilterFront.showBottomWidget === 'yes' ) {
                sfswpAjax = true;
            }
        }else{
            sfswpAjax     = sfswpFilterFront.sfswpAjaxEnabled;
            sfswpIsMobile = false;
        }

        if ( ! sfswpSsMobileBrowser() ){
            if( sfswpUseSelect2 === 'yes' ){
                $(sfswpWidgetContainer).each( function ( index, widget ){
                    let widgetSet = $(widget).data('set');
                    let widgetClass = 'sfswp-sfs-set-'+widgetSet;
                    sfswpInitSelect2(widgetClass);
                });
            }
        }

    });

    if ($.support.pjax) {
        $(document).on('pjax:end', function() {
            setTimeout(() => {
                sfswpInitiateAll();
            }, 300);
        });
    }

    $(document).ready(function (){
        sfswpInitiateAll();
    });

    $(document).on('input', '.sfswp-search-field',function (e){
        let $section    = $(this).parents('.sfswp-filters-section');
        let searchOrig  = $(this).val();
        let $search     = searchOrig.toLowerCase();
        let $submitBtn = $(".sfswp-filters-submit-button");
        let theHref    = $submitBtn.attr('href');

        if ( typeof theHref !== 'undefined' ){
            let url     = new URL(theHref);
            url.searchParams.set( 'srch', searchOrig);
            $submitBtn.attr( 'href', url.href );

            if( $search !== '' ){
                $section.addClass('sfswp-search-active');
            }else{
                $section.removeClass('sfswp-search-active');
            }
        }

    });

    $(document).on('input', '.sfswp-filter-search-field',function (e){
        let $search  = $(this).val().toString().toLowerCase();
        let $section = $(this).parents('.sfswp-filters-section');
        let fid      = $section.data('fid');

        if( $search !== '' ){
            $(".sfswp-filter-search-wrapper-"+fid+" .sfswp-search-clear").show();
            $section.addClass('sfswp-search-active');
        }else{
            $(".sfswp-filter-search-wrapper-"+fid+" .sfswp-search-clear").hide();
            $section.removeClass('sfswp-search-active');
        }

        $(".sfswp-filters-list-"+fid+" li").each(function( index, value ) {
            let $li = $(value);
            let $termName = $(value).find('label a').text().toLowerCase();
            if ($termName.indexOf($search) > -1) {
                $li.addClass('showli');
            } else {
                $li.removeClass('showli');
            }
        });
    });

    $(document).on( 'click', '.sfswp-search-clear', function (e){
        e.preventDefault();
        let $searchField = $(this).parent(".sfswp-filter-search-wrapper").find(".sfswp-filter-search-field");
        $searchField.val('')
            .trigger('input');
    })


    function isDonePressed( inst ) {
        return ( ( $('#ui-datepicker-div .ui-datepicker-close.ui-state-hover').length > 0 ) && !inst._keyEvent );
    }

    function sfswpInitiateAll(){
        $('.sfswp-filter-range-form').each( function ( index, form ){
            $.fn.sfswpInitSlider( $(form) );
        });

        if (window.innerWidth <= sfswpMobileWidth) {
            sfswpIsMobile = true;
            if( sfswpFilterFront.showBottomWidget === 'yes' ) {
                sfswpAjax = true;
            }
        }

        if( sfswpUseSelect2 === 'yes' ){
            $(sfswpWidgetContainer).each( function ( index, widget ){
                let widgetSet = $(widget).data('set');
                let widgetClass = 'sfswp-sfs-set-'+widgetSet;
                sfswpInitSelect2(widgetClass);
            });
        }

        if ( sfswpDateFilters !== '' ) {

            $.datepicker.regional[sfswpDateFiltersLocale] = sfswpDateFiltersL10n;
            $.datepicker.setDefaults(sfswpDateFiltersL10n);

            const updatedProperties = {
                _selectDate : function( id, dateStr ) {
                    var onSelect,
                        target = $( id ),
                        inst = this._getInst( target[ 0 ] );

                    dateStr = ( dateStr != null ? dateStr : this._formatDate( inst ) );
                    if ( inst.input ) {
                        inst.input.val( dateStr );
                    }
                    this._updateAlternate( inst );

                    onSelect = this._get( inst, "onSelect" );
                    if ( onSelect ) {
                        onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );  // trigger custom callback
                    } else if ( inst.input ) {
                        inst.input.trigger( "change" ); // fire the change event
                    }

                    if ( inst.inline || this._curInst.id.includes( 'sfswp-filters-alt-date' ) ) {
                        this._updateDatepicker( inst );
                    } else {
                        this._hideDatepicker();
                        this._lastInput = inst.input[ 0 ];
                        if ( typeof( inst.input[ 0 ] ) !== "object" ) {
                            inst.input.trigger( "focus" ); // restore focus
                        }
                        this._lastInput = null;
                    }
                }
            };

            Object.assign( $.datepicker, updatedProperties );

            $.each( sfswpDateFilters, function ( fid, dateFilter ) {

                if ( $("#sfswp-filters-date-from-"+ fid).length < 1 ) {
                    return false;
                }
                let pickerOptions = {};
                let timeFormat = dateFilter['time_format'].includes('s') ? 'HH.mm.ss' : 'HH.mm.00';
                if ( dateFilter['date_type'] === 'date' ) {
                    let yearMin = $("#sfswp-filters-date-from-"+ fid).data('from').slice(0,4);
                    let yearMax = $("#sfswp-filters-date-to-"+ fid).data('to').slice(0,4);

                    pickerOptions = {
                        dateFormat: dateFilter['date_format'], // will be shown in visible field
                        altFieldTimeOnly: false,
                        altField: '#sfswp-filters-date-from-' + fid,
                        altFormat: 'yy-mm-dd',
                        changeYear: true,
                        yearRange: yearMin+':'+yearMax,
                        changeMonth: true,
                        showButtonPanel: true,
                        onClose: function( dateText, inst ){
                            if( isDonePressed( inst ) ) {
                                processRangeForm( event, $("#sfswp-filter-date-range-form-"+ fid ) );
                            }
                        },
                        beforeShow: function(input, inst) {
                            $('#ui-datepicker-div').addClass('sfswp-filter-datepicker');
                        }
                    };

                    $( "#sfswp-filters-alt-date-from-" + fid  ).datepicker( pickerOptions );
                    pickerOptions.altField = '#sfswp-filters-date-to-' + fid;
                    $( "#sfswp-filters-alt-date-to-" + fid ).datepicker( pickerOptions );

                } else if ( dateFilter['date_type'] === 'datetime' ) {
                    $.timepicker.regional[sfswpDateFiltersLocale] = sfswpDateFiltersL10n;
                    $.timepicker.setDefaults(sfswpDateFiltersL10n);
                    let yearMin = $("#sfswp-filters-date-from-"+ fid).data('from').slice(0,4);
                    let yearMax = $("#sfswp-filters-date-to-"+ fid).data('to').slice(0,4);

                    pickerOptions = {
                        dateFormat: dateFilter['date_format'],
                        timeFormat: dateFilter['time_format'], // Depends from localization
                        altFieldTimeOnly: false,
                        altField: '#sfswp-filters-date-from-' + fid,
                        altFormat: 'yy-mm-dd',
                        altTimeFormat: timeFormat, // Depends from format HH.mm.ss or HH.mm.00
                        altSeparator: 't',
                        changeYear: true,
                        yearRange: yearMin+':'+yearMax,
                        changeMonth: true,
                        showButtonPanel: true,
                        controlType: 'select',
                        oneLine: true,
                        onClose: function( dateText, inst ){
                            if( isDonePressed( inst ) ) {
                                processRangeForm( event, $("#sfswp-filter-date-range-form-"+ fid ) );
                            }
                        },
                        beforeShow: function(input, inst) {
                            $('#ui-datepicker-div').addClass('sfswp-filter-datepicker');
                        }
                    };

                    $( "#sfswp-filters-alt-date-from-" + fid ).datetimepicker( pickerOptions );
                    pickerOptions.altField = '#sfswp-filters-date-to-' + fid;
                    $( "#sfswp-filters-alt-date-to-" + fid ).datetimepicker( pickerOptions );

                } else if ( dateFilter['date_type'] === 'time' ) {
                    $.timepicker.regional[sfswpDateFiltersLocale] = sfswpDateFiltersL10n;
                    $.timepicker.setDefaults(sfswpDateFiltersL10n);

                    pickerOptions = {
                        timeFormat: dateFilter['time_format'],
                        altField: '#sfswp-filters-date-from-' + fid,
                        altFieldTimeOnly: false,
                        altTimeFormat: timeFormat,
                        controlType: 'select',
                        oneLine: true,
                        onClose: function( dateText, inst ){
                            if( isDonePressed( inst ) ) {
                                processRangeForm( event, $("#sfswp-filter-date-range-form-"+ fid ) );
                            }
                        },
                        beforeShow: function(input, inst) {
                            $('#ui-datepicker-div').addClass('sfswp-filter-datepicker');
                        }
                    };

                    $( "#sfswp-filters-alt-date-from-" + fid  ).timepicker( pickerOptions );
                    pickerOptions.altField = '#sfswp-filters-date-to-' + fid;
                    $( "#sfswp-filters-alt-date-to-" + fid ).timepicker( pickerOptions );

                }
            });
        }

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

    function sfswpSsMobileBrowser() {
        const userAgent = navigator.userAgent || navigator.vendor || window.opera;
        const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);

        return isMobile;
    }

    function sfswpIsDesktopSafari() {
        const userAgent = navigator.userAgent;
        const isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(userAgent);
        const isNotMobile = !/Mobile|iPhone|iPad|iPod/i.test(userAgent);

        return isSafari && isNotMobile;
    }

    function sfswpInitSelect2( widgetClass ) {
        if( typeof $.fn.select2 === 'undefined'){
            return;
        }

        let sfswpUserAgent = navigator.userAgent.toLowerCase();
        let sfswpIsAndroid = sfswpUserAgent.indexOf("android") > -1;

        let sfswpAllowSearchField = 0;
        if( sfswpIsAndroid ) {
            sfswpAllowSearchField = Infinity;
        }

        if( sfswpIsDesktopSafari() ){
            sfswpAllowSearchField = 10;
        }

        $('.sfswp-filters-widget-select').select2({
            dropdownCssClass: 'sfswp-search-filter-sort-dropdown',
            dropdownParent: $('.'+widgetClass+' .sfswp-filters-widget-content'),
            templateResult: function( data ) {
                return sfswpSelect2Template( data );
            },
            templateSelection: function( data ) {
                return sfswpSelect2Template( data );
            },
            minimumResultsForSearch: sfswpAllowSearchField,
        });

        $('.sfswp-orderby-select').select2({
            dropdownCssClass: 'sfswp-search-filter-sort-dropdown',
            dropdownParent: $('.sfswp-after-sorting-form'),
            templateResult: function(data) {
                // We only really care if there is an element to pull classes from
                if (!data.element) {
                    return data.text;
                }
                let $dr_element = $(data.element);
                let $dr_wrapper = $('<span></span>');
                $dr_wrapper.addClass($dr_element[0].className);
                $dr_wrapper.text(data.text);

                return $dr_wrapper;
            },
            minimumResultsForSearch: Infinity
        });
    }

    function sfswpSelect2Template( data ) {
        // We only really care if there is an element to pull classes from
        if ( ! data.element ) {
            return data.text;
        }

        let theImageSrc = $(data.element).data('image');
        let brandImageSrc = $(data.element).data('brand');
        let theColor = $(data.element).data('color');
        let starRating = $(data.element).data('starRating');
        let innerHtml = data.text;
        let postsCount = $(data.element).data('count');
        let additionalClass = '';

        if ( typeof theImageSrc !== 'undefined' ) {

            additionalClass = 'sfswp-item-has-swatch';
            innerHtml = $('<span class="sfswp-term-swatch-wrapper sfswp-term-swatch-image"><img src="'+theImageSrc+'" class="sfswp-term-image" /></span><span class="sfswp-term-name">'+data.text+'</span>');

        } else if ( typeof theColor !== 'undefined'  ) {

            additionalClass = 'sfswp-item-has-swatch';

            let swatch = '<span class="sfswp-term-swatch-wrapper">';
            if ( theColor === 'none' ){
                swatch += '<span class="sfswp-term-swatch sfswp-no-swatch-yet">';
            } else {
                swatch += '<span class="sfswp-term-swatch" style="background-color:'+theColor+'">';
            }
            swatch += '</span></span><span class="sfswp-term-name">'+data.text+'</span>';

            innerHtml = $( swatch );

        } else if ( typeof brandImageSrc !== 'undefined' ) {

            additionalClass = 'sfswp-item-has-brand';
            innerHtml = $('<span class="sfswp-term-image-wrapper"><img src="'+brandImageSrc+'"/></span><span class="sfswp-term-name">'+data.text+'</span>');

        } else if ( typeof starRating !== 'undefined' &&  starRating > 0) {
            additionalClass = 'sfswp-item-has-star-rating';
            innerHtml = $(data.element.innerHTML);
        }

        let $dr_element = $(data.element);
        let $dr_wrapper = $('<span></span>');
        $dr_wrapper.addClass($dr_element[0].className);
        if ( additionalClass !== '' ){
            $dr_wrapper.addClass( additionalClass );
        }
        $dr_wrapper.html( innerHtml );
        if ( typeof postsCount !== 'undefined' ){
            $dr_wrapper.append( '<span class="sfswp-term-count"><span class="sfswp-term-count-brackets-open">(</span><span class="sfswp-term-count-value">'+postsCount+'</span><span class="sfswp-term-count-brackets-close">)</span></span>' );
        }

        return $dr_wrapper;
    }

    function sfswpGetCookie(name) {
        var matches = document.cookie.match(new RegExp(
            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
        ))
        return matches ? decodeURIComponent(matches[1]) : undefined
    }

    //Example: sfswpSetCookie('user', 'John', {secure: true, 'max-age': 3600});
    function sfswpSetCookie(name, value, props) {
        props = props || {}
        let exp = props.expires
        if (typeof exp == "number" && exp) {
            let d = new Date()
            d.setTime(d.getTime() + exp*1000)
            exp = props.expires = d
        }

        if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
        value = encodeURIComponent(value)

        let updatedCookie = name + "=" + value
        for(let propName in props){
            updatedCookie += "; " + propName
            let propValue = props[propName]
            if(propValue !== true){ updatedCookie += "=" + propValue }
        }
        document.cookie = updatedCookie
    }

    function setStatusCookie( fid, sfswpListCookieName )
    {
        let status = sfswpGetCookie(sfswpListCookieName);
        let _fids  = new Array();

        fid = fid.toString();

        // In case there is no Cookies yet
        if( typeof status === 'undefined' ){
            status = '';
        }else{
            status = status.trim();
            _fids = status.split(',');
        }

        // Filter from empty elements
        _fids = _fids.filter(function (el) {
            return el != '';
        });

        // Remove possible existing closed/opened to avoid double commands e.g. 151 and -151
        let reversal = -fid;
        let pos = _fids.indexOf( reversal.toString() );

        if ( pos !== -1 ) {
            _fids.splice(pos, 1);
        }

        if( _fids.indexOf(fid) === -1 ){
            _fids.push(fid);

            let newStatus = '';

            if( _fids.length === 0 ){
                newStatus = fid;
            }else{
                newStatus = _fids.join();
            }

            sfswpSetCookie( sfswpListCookieName, newStatus, {path: '/', 'max-age': 2592000} )
        }

    }

    function sfswpCloseFiltersContainer(setId)
    {
        let $wrapper = $('.sfswp-sfs-set-'+setId);
        let $content = $('.sfswp-sfs-set-'+setId+' .sfswp-filters-widget-content');
        $('.sfswp-open-button-'+setId+' .sfswp-filters-open-widget').removeClass('sfswp-opened');
        $('html').removeClass('sfswp-overlay-visible');
        $content.removeClass('sfswp-filters-widget-opened');

        if( sfswpPopupCompatMode ) {
            setTimeout(() => {

                let sfswpZindex = '';
                let $currentTag = false;

                $content.parents().each(function (index, tag) {
                    $currentTag = $(tag);
                    sfswpZindex = $currentTag.data('sfswpzindex');
                    // Saved z-index for
                    if (sfswpZindex !== 'undefined') {
                        $currentTag.css('z-index', sfswpZindex);
                    }

                    if ($currentTag.hasClass('sfswp-force-visibility')) {
                        $currentTag.removeClass('sfswp-force-visibility');
                    }
                });

                setTimeout(() => {
                    $(".sfswp-was-invisible").css('opacity', '1')
                        .removeClass('sfswp-was-invisible');
                }, 300);

            }, 260);
        }

        $wrapper.removeClass('sfswp-container-opened');
    }

    function sfswpOpenFiltersContainer(setId)
    {
        let $wrapper    = $('.sfswp-sfs-set-'+setId);
        let $content    = $('.sfswp-sfs-set-'+setId+' .sfswp-filters-widget-content');
        let sfswpZindex   = '';
        let sfswpVisibility = '';
        let sfswpTransform = '';
        let $currentTag = false;

        if( $content.length < 1 ){
            return true;
        }

        if( sfswpPopupCompatMode ) {
            $content.parents().each(function (index, tag) {
                $currentTag     = $(tag);
                sfswpZindex       = $currentTag.css('z-index');
                sfswpVisibility   = $currentTag.is(":visible");
                sfswpTransform    = $currentTag.css('transform');

                // Save current z-index for future
                if (sfswpZindex !== 'auto') {
                    $currentTag.data('sfswpzindex', sfswpZindex);
                }

                $currentTag.css('z-index', 'auto');

                // Save current display, opacity and visibility values
                if (!sfswpVisibility || sfswpTransform !== 'none') {
                    if (!$currentTag.hasClass('widget_sfswp_filters_widget')
                        &&
                        !$currentTag.hasClass('sfswp-filters-main-wrap')
                    ) {
                        $currentTag.css('opacity', '0');
                        $currentTag.addClass('sfswp-force-visibility sfswp-was-invisible');
                    }
                }
            });

            if( sfswpUseSelect2 === 'yes' ){
                sfswpInitSelect2( 'sfswp-sfs-set-'+setId );
            }
        }

        $('.sfswp-open-button-'+setId+' .sfswp-filters-open-widget').addClass('sfswp-opened');
        $('html').addClass('sfswp-overlay-visible');
        $('body').data('set', setId);

        $content.addClass('sfswp-filters-widget-opened');
        $wrapper.addClass('sfswp-container-opened');
        $('.sfswp-sfs-set-'+setId+' .sfswp-filters-close-button').attr('href', window.location.href);

    }

    function sfswpOpenContainer( setId ) {
        let $wrapper = $( '.sfswp-sfs-set-'+setId );

        if( $wrapper.length < 1 ){
            alert('There is no filter widget with ID '+setId+' on this page');
            return;
        }

        if( $wrapper.hasClass('sfswp-container-opened') ){
            sfswpCloseFiltersContainer(setId);
        }else{
            sfswpOpenFiltersContainer(setId);
        }
    }

    function sfswpLockApplyButton( setId )
    {
        $(".sfswp-sfs-set-"+setId).addClass('is-active');
        // We have only to check what the element was last focused
        // if( $('.sfswp-search-field').length < 1 ){
            $(".sfswp-sfs-set-"+setId+" .sfswp-filters-submit-button").addClass('on-hold');
            $(".sfswp-sfs-set-"+setId+" .sfswp-filters-reset-button").addClass('on-hold');
        // }
    }

    function sfswpUnlockApplyButton( setId )
    {
        $(".sfswp-sfs-set-"+setId).removeClass('is-active');
        $(".sfswp-sfs-set-"+setId+" .sfswp-filters-submit-button").removeClass('on-hold');
        $(".sfswp-sfs-set-"+setId+" .sfswp-filters-reset-button").removeClass('on-hold');
    }

    function sfswpShowSpinner()
    {
        $('.sfswp-spinner, html').addClass('is-active');
    }

    function sfswpHideSpinner()
    {
        $('.sfswp-spinner, html').removeClass('is-active');
    }

    $.fn.sfswpInitSlider = function ( form ) {

        // Default valued at start
        let $min = form.find('.sfswp-filters-range-min');
        let $max = form.find('.sfswp-filters-range-max');
        let $slider = form.find('.sfswp-filters-range-slider-control');
        let step = parseFloat( $min.attr('step') );

        let initialMinVal = parseFloat( $min.data('min') );
        let initialMaxVal = parseFloat( $max.data('max') );

        // Values after applying filter
        let curMinVal = parseFloat( $min.val() );
        let curMaxVal = parseFloat( $max.val() );

        // Setting value into form inputs when slider is moving
        $slider.slider({
            min: initialMinVal,
            max: initialMaxVal,
            values: [curMinVal, curMaxVal],
            range: true,
            step: step,
            slide: function (event, elem) {
                let instantMinVal = elem.values[0];
                let instantMaxVal = elem.values[1];

                $min.val(instantMinVal);
                $max.val(instantMaxVal);
            },
            change: function (event) {
                // It is better always to submit slider automatically to avoid empty intersection occurrence
                submitSliderForm(event, form);
            }
        });

        form.submit(function (e) {
            //Remove ? sign if form is empty
            if (($(this).serialize().length === 0)) {
                e.preventDefault();
                window.location.assign(window.location.pathname);
            }
        });
    }

    function submitSliderForm(event, form) {
        if (event.originalEvent) {
            processRangeForm( event, form );
        }
    }

    function processRangeForm( event, form ){
        let low_suffix  = 'min';
        let high_suffix = 'max';

        if ( form.hasClass('sfswp-filter-date-range-form') ) {
            low_suffix  = 'from';
            high_suffix = 'to';
        }

        let $min = form.find( '.sfswp-filters-range-' + low_suffix );
        let $max = form.find( '.sfswp-filters-range-' + high_suffix );

        if ( low_suffix === 'min' && high_suffix ===  'max' ) {
            var curMinVal = parseFloat( $min.val() );
            var curMaxVal = parseFloat( $max.val() );
        } else {
            var curMinVal = $min.val().toString();
            var curMaxVal = $max.val().toString();
        }

        var initialMin = $min.data( low_suffix );
        var initialMax = $max.data( high_suffix );

        // The form has slider
        if( form.hasClass('sfswp-form-has-slider') ){
            let $slider = form.find('.sfswp-filters-range-slider-control');
            // in Case of e.type === 'change' we have to set slider values
            if ( event.type === 'change' ){
                $slider.slider("option", "values", [curMinVal, curMaxVal]);
            }
        }

        if (curMinVal === initialMin) {
            $min.attr('disabled', true);
        }

        if (curMaxVal === initialMax) {
            $max.attr('disabled', true);
        }

        let $el = form.parents(sfswpWidgetContainer);
        let setId = $el.data('set');
        let applyButtonMode = false;

        if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes( setId ) ){
            applyButtonMode = true;
        }

        if ( sfswpAjax || applyButtonMode ) {
            event.preventDefault();
            let search  = form.serialize();
            let questionParam = '?'
            if(!search){
                questionParam = '';
            }
            let sfswpLink = form.attr('action') + questionParam + search;

            sfswpSendFilterRequest(sfswpLink, $el, applyButtonMode);

            $min.attr('disabled', true);
            $max.attr('disabled', true);

        } else {
            form.trigger('submit');
        }
    }

    function sfswpSendFilterRequest( link, widget, applyButtonMode, onComplete ){

        onComplete = (typeof onComplete !== 'undefined') ? onComplete : false;
        removeElement($('.sfswp-front-error'));
        
        let requestParams               = {};
        requestParams.sfs_ajax_link    = link;
        requestParams.sfswpAjaxAction     = 'filter';
        let setId                       = widget.data('set');
        let widgetClass                 = 'sfswp-sfs-set-'+setId;
        let targetPostsContainer        = sfswpPostContainers['default'];

        if( typeof sfswpPostContainers[setId] !== "undefined" ){
            targetPostsContainer = sfswpPostContainers[setId];
        }

        // Disable Apply button for Pop-up widget as its behavior is the same
        if( applyButtonMode ){
            if( $("body").hasClass("sfswp_show_bottom_widget") ){
                if( window.innerWidth <= sfswpMobileWidth ){
                    applyButtonMode = false;
                }
            }
        }

        $.ajax({
            'method': 'POST',
            'data': requestParams,
            'url': link,
            'dataType': 'html',
            beforeSend: function () {
                if( sfswpWaitCursor ){
                    $('html, body').css("cursor", "wait");
                }

                let $a_el = $(widget).find('.sfswp-filters-apply-button');

                $a_el.removeClass('sfswp-posts-loaded');

                let oldLink = $a_el.attr('href');

                $a_el.attr('href', link);
                $a_el.data('href', oldLink);

                // $(".sfswp-filters-section-"+setId).find(".sfswp-filters-submit-button").attr('href', link);

                if( applyButtonMode ){
                    sfswpLockApplyButton( setId );
                }else{
                    sfswpShowSpinner();
                }
            },
            complete: function () {
                if(onComplete !== false){
                    eval(onComplete+'(setId)');
                }
                if( sfswpWaitCursor ) {
                    $('html, body').css("cursor", "auto");
                }

                sfswpInitiateAll();

                if( applyButtonMode){
                    sfswpUnlockApplyButton(setId);
                }else{
                    sfswpHideSpinner();
                }

            },
            success: function ( response ) {
                if ( typeof response !== 'undefined' ) {
                    
                    // Products
                    // Wrap response to allow .find method search inner elements.
                    response                    = '<div class="responseWrapper">'+response+'</div>';
                    let $response               = $(response);
                    let $responsePostsContainer = $response.find(targetPostsContainer);
                    let currentSeoRuleId        = $response.find('#sfswp-seo-rule-id').data('seoruleid');
                    let isFilterRequest         = $response.find('.sfswp-filters-main-wrap').hasClass('sfswp-filter-request');

                    if ( currentSeoRuleId > 0 ) {
                        currentState = true;
                    } else {
                        currentState = false;
                    }

                    if ( ! currentState && ! prevState ) {
                        toReplaceSEO = false;
                    } else {
                        toReplaceSEO = true;
                    }

                    if( applyButtonMode ){
                        // Sorting widget
                        sfswpReloadSorting( $response );
                        // Filters Widget
                        sfswpReloadFiltersWidget( $response, widgetClass );
                        return;
                    }

                    if( ( $responsePostsContainer.length > 0 ) && sfswpFilterFront.sfswpAjaxEnabled && sfswpQueryOnThePageSets.includes( setId ) ){

                        if( isFilterRequest ) {
                            $("body").addClass('sfswp_is_filter_request');
                        } else {
                            $("body").removeClass('sfswp_is_filter_request');
                        }

                        // But this works on TV also
                        $(targetPostsContainer).html( $responsePostsContainer.html() );
                        // sfswpPostsWereLoaded = true;

                        // Mark the "Show" button to not reload content
                        $(widget).find('.sfswp-filters-apply-button').addClass('sfswp-posts-loaded');

                        //@todo update selected terms if them outside of posts container

                        if ( toReplaceSEO ) {
                            let responseTitle     = $response.find('title').text();
                            let responseCanonical = $response.find('link[rel="canonical"]').attr('href');

                            // If h1 outside of posts container
                            if( $responsePostsContainer.find('h1').length < 1 ){
                                if( $response.find('h1').length > 0){
                                    $('h1')[0].replaceWith( $response.find('h1')[0] );
                                }
                            }

                            // If seoText container is outside from posts container
                            if( $responsePostsContainer.find('.sfswp-page-seo-description').length < 1 ){
                                let sfswpSeoTextContainer = $response.find('.sfswp-page-seo-description');
                                let originalSeoTextContainer = $('.sfswp-page-seo-description');
                                if( sfswpSeoTextContainer.length > 0 && originalSeoTextContainer.length > 0){
                                    $('.sfswp-page-seo-description')[0].replaceWith( sfswpSeoTextContainer[0] );
                                }
                            }

                            // Replace title
                            if( typeof responseTitle !== 'undefined' && responseTitle !== '' ){
                                $(document).attr( 'title', responseTitle );
                            }

                            // Handle <meta name="description" /> tag
                            handleMetaTag('description', response);

                            // Handle <meta name="robots" /> tag
                            handleMetaTag('robots', response);

                            // Handle Canonical
                            if( typeof responseCanonical !== 'undefined' && responseCanonical !== '' ){
                                // Replace content if tag exists
                                if( $('link[rel="canonical"]').length > 0 ){
                                    $('link[rel="canonical"]').attr('href', responseCanonical );
                                } else {
                                    // Append meta tag
                                    $('head').append('<link rel="canonical" href="'+responseCanonical+'" />');
                                }
                            }else{
                                if( $('link[rel="canonical"]').length > 0 ){
                                    $('link[rel="canonical"]').remove();
                                }
                            }
                        }

                        // If Filters open button outside of posts container
                        if( $responsePostsContainer.find('.sfswp-open-button-'+setId).length < 1 ) {
                            let sfswpButtonInnerContent = $response.find('.sfswp-open-button-'+setId+' .sfswp-button-inner');

                            if( sfswpButtonInnerContent.length > 0 ) {
                                $('.sfswp-open-button-'+setId).each( function ( bIndex, bUtton ) {
                                    if ( $(this).parent('div').hasClass('sfswp-filters-main-wrap') ){
                                        return true;
                                    }
                                    $(this).find(".sfswp-button-inner").replaceWith( sfswpButtonInnerContent[0] );
                                } );
                            }
                        }

                        window.history.pushState({sfswpHandler: 'sfswpSearchFilterSort'}, null, link);

                        prevState = currentState;
                    } else {
                        if ( $(targetPostsContainer).length === 0 && sfswpFilterFront.sfswpAjaxEnabled ) {
                            alert( noPostsContainerMsg );
                        }
                    }

                    let sfswpPostsFound   = $response.find('.'+widgetClass).find('.sfswp-posts-found').data('found');
                    sfswpPostsFound       = parseFloat( sfswpPostsFound );

                    // Chips
                    sfswpReloadChips( $response );

                    // Sorting widget
                    sfswpReloadSorting( $response );

                    // Filters Widget. It modifies $response so it is better to fire it in the end
                    sfswpReloadFiltersWidget( $response, widgetClass );

                    //trigger events
                    $(document).trigger( 'ready' );
                    $(window).trigger( 'scroll' );
                    $(window).trigger( 'resize' );

                    // a3 Lazy Load support
                    $(window).trigger( 'lazyshow' );

                    sfswpFixWoocommerceOrder();

                    //check rating stars
                    sfsStarCheck();

                    let applyButtonSFSSet = false;
                    if( setId > 0 && sfswpApplyButtonSets.length > 0 && sfswpApplyButtonSets.includes( setId ) ){
                        applyButtonSFSSet = true;
                    }

                    if( ! sfswpIsMobile && sfswpAutoScroll && ( sfswpPostsFound < sfswpPostsPerPage[setId] || applyButtonSFSSet ) ){
                        if( $(targetPostsContainer).length > 0 ){
                            $('body, html').animate({ scrollTop:$(targetPostsContainer).offset().top - sfswpAutoScrollOffset });
                        }
                    }

                    // Re-init Elementor actions
                    if( typeof( elementorFrontend ) !== 'undefined' ){
                        if( $responsePostsContainer.hasClass('elementor-element') ){
                            $(targetPostsContainer+'.elementor-element').each(
                                function() {
                                    elementorFrontend.elementsHandler.runReadyTrigger($(this));
                                }
                            );
                        } else {
                            $(targetPostsContainer+' .elementor-element').each(
                                function() {
                                    elementorFrontend.elementsHandler.runReadyTrigger($(this));
                                }
                            );
                        }
                    }
                }
            },

            error: function (response) {
                sfswpHideSpinner();
                let $a_el = $(widget).find('.sfswp-filters-apply-button');
                let oldLink = $a_el.data('href');
                $a_el.attr('href', oldLink );
            }
        });

    }

    function handleMetaTag( tagName, response )
    {

        let tagContent = $(response).find('meta[name="'+tagName+'"]').attr('content');
        if( typeof tagContent !== 'undefined' ){
            // Replace content if tag exists
            if( $('meta[name="'+tagName+'"]').length > 0 ){
                $('meta[name="'+tagName+'"]').attr('content', tagContent );
            } else {
                // Append meta tag
                $('head').append('<meta name="'+tagName+'" content="'+tagContent+'" />');
            }
        }else{
            if( $('meta[name="'+tagName+'"]').length > 0 ){
                $('meta[name="'+tagName+'"]').remove();
            }
        }
    }

    function sfswpFixWoocommerceOrder() {
        $('.woocommerce-ordering').on('change', 'select.orderby', function () {
            $(this).closest('form').submit();
        });
    }

    function sfswpReloadFiltersWidget( $response, widgetClass ){
                
        // Replace parts
        // let targetWidget = '.'+widgetClass;
        // let $response    = $response;
        // It seems we need to reload all widgets available on the page
        
        if( sfswpIsMobile === true && ( sfswpFilterFront.showBottomWidget === 'yes' ) ){

            $(sfswpWidgetContainer).each( function ( index, widget ){
                let widgetSet = $(widget).data('set');
                let widgetClass = '.sfswp-sfs-set-'+widgetSet;

                // .sfswp-filters-scroll-container
                // .sfswp-filters-widget-containers-wrapper
                let newWidget       = $response.find(widgetClass+' .sfswp-filters-scroll-container');
                let newPostsFound   = $response.find(widgetClass+' .sfswp-filters-found-posts');

                // Replace all filters and chips
                if( newWidget.length > 0 ){
                    let sortingData = [];
                    // === SAVE SORTING ===
                    let $oldWidget = $(widgetClass);    
                    
                    $oldWidget.find('.sfswp-sorting-form').each(function(){
                        sortingData.push({
                            html: $(this).prop('outerHTML')
                        });
                    });
                    
                    $(widgetClass).find('.sfswp-filters-scroll-container').replaceWith( newWidget );
                    
                    let $newWidget = $(widgetClass);
                    sortingData.forEach(function(sortItem){

                        let $wrapper   = $newWidget.find('.sfswp-filters-widget-wrapper');
                        let $afterSort = $wrapper.find('.sfswp-after-sorting-form');

                        let $sortingEl = $(sortItem.html);
                        
                        // Remove ?ordr= from action
                        let actionUrl = $sortingEl.attr('action');
                        if (actionUrl) {
                            let cleanUrl = actionUrl.replace(/([?&])ordr=[^&]*(&)?/, function(match, p1, p2){
                                return p2 ? p1 : '';
                            }).replace(/[?&]$/, '');

                            $sortingEl.attr('action', cleanUrl);
                        }

                        if ($afterSort.length) {
                            $sortingEl.insertBefore($afterSort);
                        } else {
                            $wrapper.append($sortingEl);
                        }
                    }); 
                
                }
                // Replace found posts number
                if( newPostsFound.length > 0  ){
                    $(widgetClass).find('.sfswp-filters-found-posts').html( newPostsFound.html() );
                }

                if( sfswpApplyButtonSets.includes( widgetSet ) ){
                    let applyLink = $(widgetClass+" .sfswp-filters-submit-button").attr('href');
                    if( applyLink !== '' ){
                        $(".sfswp-filters-widget-controls-container .sfswp-filters-submit-button").attr('href', applyLink);
                    }
                }
            });

        } else {
            $(sfswpWidgetContainer).each( function ( index, widget ) {
                let widgetSet = $(widget).data('set');
                let widgetClass = '.sfswp-sfs-set-'+widgetSet;

                let newWidget = $response.find(widgetClass);
                if (newWidget.length > 0) {
                    
                    let sortingData = [];
                    if(sfswpFilterFront.sfswpAjaxEnabled === '1' || (sfswpFilterFront.sfswpAjaxEnabled !== '1' && sfswpFilterFront.sfswpApplyButtonSets.length > 0 ) ){
                        // === SAVE SORTING ===
                        let $oldWidget = $(widgetClass);                    

                        $oldWidget.find('.sfswp-sorting-form').each(function(){
                            sortingData.push({
                                html: $(this).prop('outerHTML')
                            });
                        });
                    }

                    // === ORIGINAL REPLACE (UNCHANGED) ===
                    $(widgetClass).replaceWith(newWidget);

                    // === RESTORE SORTING ===
                    let $newWidget = $(widgetClass);
                    
                    if(sfswpFilterFront.sfswpAjaxEnabled === '1' || (sfswpFilterFront.sfswpAjaxEnabled !== '1' && sfswpFilterFront.sfswpApplyButtonSets.length > 0 ) ){
                        
                        sortingData.forEach(function(sortItem){

                            let $wrapper   = $newWidget.find('.sfswp-filters-widget-wrapper');
                            let $afterSort = $wrapper.find('.sfswp-after-sorting-form');

                            let $sortingEl = $(sortItem.html);

                            // Remove ?ordr= from action
                            let actionUrl = $sortingEl.attr('action');
                            if (actionUrl) {
                                let cleanUrl = actionUrl.replace(/([?&])ordr=[^&]*(&)?/, function(match, p1, p2){
                                    return p2 ? p1 : '';
                                }).replace(/[?&]$/, '');

                                $sortingEl.attr('action', cleanUrl);
                            }

                            if ($afterSort.length) {
                                $sortingEl.insertBefore($afterSort);
                            } else {
                                $wrapper.append($sortingEl);
                            }

                        });
                    }
                }
            });
        }
    }

    function sfswpReloadSorting( $response ){
        let sfswpSortingForms   = $response.find('.sfswp-sorting-form');
        
        if ( sfswpSortingForms.length < 1 ) {
            return;
        }
        let originalSortingForms = $(".sfswp-sorting-form");
        
        if( sfswpSortingForms.length > 0 ){
            sfswpSortingForms.each( function ( index, elem ){
                originalSortingForms[index].replaceWith(elem);
            });
        }
    }

    function sfswpReloadChips( $response ){
        let $chips = $(".sfswp-filter-chips-list");
        if ( $chips.length < 1 ) {
            return;
        }

        $chips.each( function ( index, chipsWidget ) {

            if( ( sfswpIsMobile === true && ( sfswpFilterFront.showBottomWidget !== 'yes' ) ) || sfswpIsMobile === false ){
                // Do not replace Chips inside Filters widget
                if ( $(this).parent('div').hasClass('sfswp-inner-widget-chips-wrapper') ){
                    return true;
                }
            }

            let chipsSetCount       = $(chipsWidget).data('setcount');
            let chipsWidgetClass    = '.sfswp-filter-chips-'+chipsSetCount;
            let newChipsInstance    = $response.find(chipsWidgetClass);

            if ( newChipsInstance.length > 0 ) {
                // Do not use $(this) because reloaded widget kills it
                $(chipsWidgetClass).replaceWith( newChipsInstance );
            }
        });
    }

    window.addEventListener( 'popstate', function ( e ) {
        // @todo the last history step sometimes doesn't reload
        if( e.state !== null && e.state.hasOwnProperty('sfswpHandler') ){
            if( e.state.sfswpHandler === 'sfswpSearchFilterSort' ){
                window.location.reload(true);
            }
        }
    });

    //check rating stars after upload
    function sfsStarCheck(){
        if($('label.sfs-star-label-checked').length > 0){
            $('#sfs-sfswp-term-count').removeClass('sfs-change-blocked');
            let ratingNumChecked =  $('label.sfs-star-label-checked').data('ratingNum');
            let selectedAndAbove =  $('.sfs-stars-sfswp-filter-content').data('selectedAndAbove');
            sfsGetRatingTermCount($('label.sfs-star-label-checked'))
            $('label.sfs-star-label').each(function( index ) {
                index += 1;
                if(!selectedAndAbove && index <= ratingNumChecked){
                    $('label.sfs-rating-numb-' + index).addClass('sfs-star-label-hover');
                }else if(selectedAndAbove && index >= ratingNumChecked) {
                    $('label.sfs-rating-numb-' + index).addClass('sfs-star-label-hover');
                }
            });
        }
    }
   sfsStarCheck();

    $(document).on('mouseenter', 'label.sfs-star-label', function() {
        if(!$('#sfs-sfswp-term-count').hasClass('sfs-change-blocked')) {
            let ratingNum = $(this).data('ratingNum');
            let selectedAndAbove = $('.sfs-stars-sfswp-filter-content').data('selectedAndAbove');
            $('label.sfs-remove-star-check').removeClass('sfs-star-label-not-checked');
            sfsGetRatingTermCount($(this));
            for (let i = 0; i <= 5; i++) {
                if (!selectedAndAbove && i <= ratingNum) {
                    $('label.sfs-rating-numb-' + i).addClass('sfs-star-label-hover');
                } else if (selectedAndAbove && i >= ratingNum) {
                    $('label.sfs-rating-numb-' + i).addClass('sfs-star-label-hover');
                } else {
                    $('label.sfs-rating-numb-' + i).removeClass('sfs-star-label-hover');
                }
            }
        }
    });

    $(document).on('click', 'label.sfs-star-label', function() {
        $('#sfs-sfswp-term-count').addClass('sfs-change-blocked');
        let ratingNum =  $(this).data('ratingNum');
        let selectedAndAbove =  $('.sfs-stars-sfswp-filter-content').data('selectedAndAbove');
        $('label.sfs-remove-star-check').removeClass('sfs-star-label-not-checked');
        sfsGetRatingTermCount($(this));
        for (let i = 0; i <= 5; i++) {
            if(!selectedAndAbove && i <= ratingNum){
                $('label.sfs-rating-numb-' + i).addClass('sfs-star-label-hover');
            }if(selectedAndAbove && i >= ratingNum){
                $('label.sfs-rating-numb-' + i).addClass('sfs-star-label-hover');
            }
        }

    });

    $(document).on('mouseleave', '.sfs-stars-filter', function() {
        if(!$('#sfs-sfswp-term-count').hasClass('sfs-change-blocked')){
            if($('label.sfs-star-label-checked').length > 0){
                let ratingNumChecked =  $('label.sfs-star-label-checked').data('ratingNum');
                let selectedAndAbove =  $('.sfs-stars-sfswp-filter-content').data('selectedAndAbove');
                sfsGetRatingTermCount($('label.sfs-star-label-checked'))
                $('label.sfs-remove-star-check').addClass('sfs-star-label-not-checked');
                for (let i = 0; i <= 5; i++) {
                    if(!selectedAndAbove && i <= ratingNumChecked){
                        $('label.sfs-rating-numb-' + i).addClass('sfs-star-label-hover');
                    }else if(selectedAndAbove && i >= ratingNumChecked){
                        $('label.sfs-rating-numb-' + i).addClass('sfs-star-label-hover');
                    }else{
                        $('label.sfs-rating-numb-' + i).removeClass('sfs-star-label-hover');
                    }
                }
            }else{
                $('#sfs-sfswp-term-count').text('');
                for (let i = 1; i <= 5; i++) {
                    $('label.sfs-rating-numb-' + i).removeClass('sfs-star-label-hover');
                }
            }
        }
    });


    function sfsGetRatingTermCount(el){
        if(!$('#sfs-sfswp-term-count').hasClass('sfs-change-blocked')){
            let sfswpTermCount = el.data('sfswpTermCount');
            let selectedAndAbove =  $('.sfs-stars-sfswp-filter-content').data('selectedAndAbove');
            let showTermCount =  $('.sfs-stars-sfswp-filter-content').data('showTermCount');
            if(showTermCount) {
                if(selectedAndAbove){
                    let ratingNum =  el.data('ratingNum');
                    let totalTerms = 0;
                    for (let i = ratingNum; i <= 5; i++) {
                        let showTermCount = $('label.sfs-rating-numb-' + i).data('sfswpTermCount');
                        totalTerms += showTermCount;
                    }
                    $('#sfs-sfswp-term-count').text(totalTerms);
                }else{
                    $('#sfs-sfswp-term-count').text(sfswpTermCount);
                }
            }
        }
    }

    $.fn.tipTip = function(options) {
        var defaults = {
            activation: "hover",
            keepAlive: false,
            maxWidth: "200px",
            edgeOffset: 3,
            defaultPosition: "bottom",
            delay: 400,
            fadeIn: 200,
            fadeOut: 200,
            attribute: "title",
            content: false, // HTML or String to fill TipTIp with
            enter: function(){},
            exit: function(){}
        };
        var opts = $.extend(defaults, options);

        // Setup tip tip elements and render them to the DOM
        if($("#tiptip_holder").length <= 0){
            var tiptip_holder = $('<div id="tiptip_holder" style="max-width:'+ opts.maxWidth +';"></div>');
            var tiptip_content = $('<div id="tiptip_content"></div>');
            var tiptip_arrow = $('<div id="tiptip_arrow"></div>');
            $("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('<div id="tiptip_arrow_inner"></div>')));
        } else {
            var tiptip_holder = $("#tiptip_holder");
            var tiptip_content = $("#tiptip_content");
            var tiptip_arrow = $("#tiptip_arrow");
        }

        return this.each(function(){
            var org_elem = $(this);
            if(opts.content){
                var org_title = opts.content;
            } else {
                var org_title = org_elem.attr(opts.attribute);
            }
            if(org_title != ""){
                if(!opts.content){
                    org_elem.removeAttr(opts.attribute); //remove original Attribute
                }
                var timeout = false;

                if(opts.activation == "hover"){
                    org_elem.hover(function(){
                        active_tiptip();
                    }, function(){
                        if(!opts.keepAlive || !tiptip_holder.is(':hover')){
                            deactive_tiptip();
                        }
                    });
                    if(opts.keepAlive){
                        tiptip_holder.hover(function(){}, function(){
                            deactive_tiptip();
                        });
                    }
                } else if(opts.activation == "focus"){
                    org_elem.focus(function(){
                        active_tiptip();
                    }).blur(function(){
                        deactive_tiptip();
                    });
                } else if(opts.activation == "click"){
                    org_elem.click(function(){
                        active_tiptip();
                        return false;
                    }).hover(function(){},function(){
                        if(!opts.keepAlive){
                            deactive_tiptip();
                        }
                    });
                    if(opts.keepAlive){
                        tiptip_holder.hover(function(){}, function(){
                            deactive_tiptip();
                        });
                    }
                }

                function active_tiptip(){
                    opts.enter.call(this);
                    tiptip_content.html(org_title);
                    tiptip_holder.hide().removeAttr("class").css("margin","0");
                    tiptip_arrow.removeAttr("style");

                    var top = parseInt(org_elem.offset()['top']);
                    var left = parseInt(org_elem.offset()['left']);
                    var org_width = parseInt(org_elem.outerWidth());
                    var org_height = parseInt(org_elem.outerHeight());
                    var tip_w = tiptip_holder.outerWidth();
                    var tip_h = tiptip_holder.outerHeight();
                    var w_compare = Math.round((org_width - tip_w) / 2);
                    var h_compare = Math.round((org_height - tip_h) / 2);
                    var marg_left = Math.round(left + w_compare);
                    var marg_top = Math.round(top + org_height + opts.edgeOffset);
                    var t_class = "";
                    var arrow_top = "";
                    var arrow_left = Math.round(tip_w - 12) / 2;

                    if(opts.defaultPosition == "bottom"){
                        t_class = "_bottom";
                    } else if(opts.defaultPosition == "top"){
                        t_class = "_top";
                    } else if(opts.defaultPosition == "left"){
                        t_class = "_left";
                    } else if(opts.defaultPosition == "right"){
                        t_class = "_right";
                    }

                    var right_compare = (w_compare + left) < parseInt($(window).scrollLeft());
                    var left_compare = (tip_w + left) > parseInt($(window).width());

                    if((right_compare && w_compare < 0) || (t_class == "_right" && !left_compare) || (t_class == "_left" && left < (tip_w + opts.edgeOffset + 5))){
                        t_class = "_right";
                        arrow_top = Math.round(tip_h - 13) / 2;
                        arrow_left = -12;
                        marg_left = Math.round(left + org_width + opts.edgeOffset);
                        marg_top = Math.round(top + h_compare);
                    } else if((left_compare && w_compare < 0) || (t_class == "_left" && !right_compare)){
                        t_class = "_left";
                        arrow_top = Math.round(tip_h - 13) / 2;
                        arrow_left =  Math.round(tip_w);
                        marg_left = Math.round(left - (tip_w + opts.edgeOffset + 5));
                        marg_top = Math.round(top + h_compare);
                    }

                    var top_compare = (top + org_height + opts.edgeOffset + tip_h + 8) > parseInt($(window).height() + $(window).scrollTop());
                    var bottom_compare = ((top + org_height) - (opts.edgeOffset + tip_h + 8)) < 0;

                    if(top_compare || (t_class == "_bottom" && top_compare) || (t_class == "_top" && !bottom_compare)){
                        if(t_class == "_top" || t_class == "_bottom"){
                            t_class = "_top";
                        } else {
                            t_class = t_class+"_top";
                        }
                        arrow_top = tip_h;
                        marg_top = Math.round(top - (tip_h + 5 + opts.edgeOffset));
                    } else if(bottom_compare | (t_class == "_top" && bottom_compare) || (t_class == "_bottom" && !top_compare)){
                        if(t_class == "_top" || t_class == "_bottom"){
                            t_class = "_bottom";
                        } else {
                            t_class = t_class+"_bottom";
                        }
                        arrow_top = -12;
                        marg_top = Math.round(top + org_height + opts.edgeOffset);
                    }

                    if(t_class == "_right_top" || t_class == "_left_top"){
                        marg_top = marg_top + 5;
                    } else if(t_class == "_right_bottom" || t_class == "_left_bottom"){
                        marg_top = marg_top - 5;
                    }
                    if(t_class == "_left_top" || t_class == "_left_bottom"){
                        marg_left = marg_left + 5;
                    }
                    tiptip_arrow.css({"margin-left": arrow_left+"px", "margin-top": arrow_top+"px"});
                    tiptip_holder.css({"margin-left": marg_left+"px", "margin-top": marg_top+"px"}).attr("class","tip"+t_class);

                    if (timeout){ clearTimeout(timeout); }
                    timeout = setTimeout(function(){ tiptip_holder.stop(true,true).fadeIn(opts.fadeIn); }, opts.delay);
                }

                function deactive_tiptip(){
                    opts.exit.call(this);
                    if (timeout){ clearTimeout(timeout); }
                    tiptip_holder.fadeOut(opts.fadeOut);
                }
            }
        });
    }

})(jQuery);