/*!
 * SearchFilterSort widgets 1.9.1
 */
(function($) {
    "use strict";

    let itemNum = sfswpWidgets.sfswpItemNum;
    //@todo fix Elementor
    //@todo Create minifined version
    $(document).ready(function (){
        // Sorting widget
        $(document).on('click', '.sfswp-sorting-item-title', function (){
            $(this).parent('.sfswp-sorting-item-top').toggleClass('sfswp-opened');
        });

        $(document).on('click', '.sfswp-sorting-item-remove', function (){

            let item        = $(this);
            let sorting     = item.parents('div.sfswp-sorting-list');
            let sfswpSortingItems = sorting.find('.sfswp-sorting-item-wrapper');
            if( sfswpSortingItems.length < 2 ){
                return;
            }

            let widget      = item.parents('div.widget');
            let inside      = widget.children('.widget-inside');
            let saveButton  = inside.find( '.widget-control-save' );
            let widgetId    = inside.find( '.widget-id' ).val();
            let toRemove    = item.parents('.sfswp-sorting-item-wrapper');

            toRemove.remove();

            sfswpSortingItemsOrder(sorting);

            window.wpWidgets.dirtyWidgets[ widgetId ] = true;
            widget.addClass( 'widget-dirty' );
            saveButton.prop( 'disabled', false ).val( wp.i18n.__( 'Save' ) );
        });

        $(document).on('change', '.sfswp-orderby-select', function(e){
            let select       = $(this);
            let itemWrapper = select.parents('.sfswp-sorting-item-inside');
            let metaKeyWrapper = itemWrapper.find('.sfswp-sorting-item-meta-key-wrapper');

            if( select.val() === 'm' || select.val() === 'n' ){
                metaKeyWrapper.addClass('sfswp-opened');
            }else{
                metaKeyWrapper.removeClass('sfswp-opened');
            }

            return true;
        });

        $(document).on('input change', '.sfswp-sorting-item-label', function (){
            let input       = $(this);
            let itemWrapper = input.parents('.sfswp-sorting-item-wrapper');
            let itemParent  = itemWrapper.parents('.sfswp-sorting-list'); //.find('.sfswp-sorting-item-wrapper').length;
            let itemTitle   = itemWrapper.find('.sfswp-sorting-item-title');

            if( input.val() === '' ){
                let itemCurPos = itemWrapper.index();
                itemTitle.text( itemTitle.data('title') + (itemCurPos + 1) );
            }else{
                cpaLiveWrite( input, itemTitle );
            }

        });

        $(document).on('widget-added widget-updated', function (){
            sfswpMakeSortItemsSortable();

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

        $(document).on('focus', '.sfswp-sorting-item-label', function (){
            let currentVal = $(this).val();
            let sfswpRegExp =  new RegExp("^" + itemNum + "[\\d]{1,100}$");
            let newVal = currentVal.replace(sfswpRegExp, '');
            $(this).val(newVal);
        });

        $(document).on('click', '.sfswp-add-sorting-item', function (e){
            e.preventDefault();
            let widgetContent = $(this).parents('.sfswp-add-sorting-item-wrapper').parent(); //('.widget-content');
            let sortingList   = widgetContent.find('.sfswp-sorting-list');
            let html          = widgetContent.find('.sfswp-new-sorting-item').html();
            let $el           = $(html);
            let label         = $el.find('.sfswp-sorting-item-title');
            let search        = 'sfswp_new_id';
            let replace       = (sortingList.find('.sfswp-sorting-item-wrapper').length + 1);

            let replaceAttr = function(i, value){
                return value.replace( search, replace );
            }

            $el.find('[id*="' + search + '"]').attr('id', replaceAttr);
            $el.find('[for*="' + search + '"]').attr('for', replaceAttr);
            $el.find('[name*="' + search + '"]').attr('name', replaceAttr);
            $el.find('[value*="' + search + '"]').attr('value', replaceAttr);
            //label.attr('data-title', replaceAttr);
            label.text(label.data('title') + replace);
            $el.attr('class', replaceAttr);
            $el.find('.sfswp-sorting-item-top').addClass('sfswp-opened');

            // Hack to make Save Button active
            $("input.sfswp-ballast").trigger('change');

            sortingList.append($el);
        });

        // Elementor compatibility
        if( typeof elementor !== 'undefined'){
            elementor.hooks.addAction( 'panel/widgets/wp-widget-sfswp_sorting_widget/controls/wp_widget/loaded', function( widget ) {
                // console.log( widget );
                // console.log( $( '.sfswp-sorting-list' ) );

                setTimeout(function() {
                    // console.log( $( '.sfswp-sorting-list' ) );
                    sfswpMakeSortItemsSortable();
                    $("input.sfswp-ballast").trigger('change');
                }, 500);
            } );
        }

        sfswpMakeSortItemsSortable();
        // End Sorting widget
    });

    function sfswpMakeSortItemsSortable(){

        $( '.sfswp-sorting-list' ).sortable({
            items: "> div.sfswp-sorting-item-wrapper",
            delay: 75,
            placeholder: "sfswp-filter-item-shadow",
            refreshPositions: true,
            cursor: 'move',
            handle: ".sfswp-sorting-item-handle",
            axis: 'y',
            update: function( event, ui ) {
                sfswpSortingItemsOrder(ui.item.parent('.sfswp-sorting-list'));
            },
            start: function ( event, ui ){
                let $this = ui.item,
                    head = ui.item.children('.sfswp-sorting-item-top'),
                    sfswpSortingItemHeight = (head.height() + 2);

                if (head.hasClass('sfswp-opened') ) {
                    head.removeClass('sfswp-opened')
                    $this.css('max-height', sfswpSortingItemHeight + 'px');
                    $(this).sortable('refreshPositions');
                }
            },
            stop: function ( event, ui ){
                ui.item.css('max-height', 'none');
            }
        });
    }

    function cpaLiveWrite( readFrom, writeTo ) {
        writeTo.text(readFrom.val());
    }

    function sfswpSortingItemsOrder( $el ){
        let sortingList = $el; //.parent('.sfswp-sorting-list');
        let itemTitles  =  sortingList.find('.sfswp-sorting-item-label');
        let titleVal    = '';
        let newTitleVal = '';
        let sfswpRegExp =  new RegExp("^" + itemNum + "[\\d]{1,100}$");

        if( itemTitles.length > 0 ){
            itemTitles.each( function ( index, element ) {
                titleVal = $(element).val();
                newTitleVal = titleVal.replace(sfswpRegExp, itemNum+(index+1) );
                $(element).val(newTitleVal)
                    .trigger('change');
            });
        }
    }

})(jQuery);