/*!
 * SearchFilterSort seo rules admin 1.9.1
 */
(function($) {
    "use strict";
    let seoRulesFormValid = false;

    function validateSeoRulesForm( $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-seo-rules', requestParams )
            .always( function() {
                $spinner.removeClass( 'is-active' );
            })
            .done( function( response ) {
                seoRulesFormValid = true;
                $el.submit();
            })
            .fail( function( response ) {

                let notices = [];

                if( typeof response.errors !== 'undefined' ){
                    $.each( response.errors, function ( index, error ){
                        notices.push( error.message );
                    });

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

                    addNotice( notices );
                }
            });

        return false;
    }

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

        let html = '<div id="message" class="sfswp-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 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 );
        }
    }

    $.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;
        }
    }

    $.fn.createSeoVarsList = function( seoVars )
    {
        let html = '<ul class="sfswp-seo-vars-list">';

        if( Object.keys(seoVars).length > 0 ){
            $.each( seoVars, function ( slug, label ){
                html += '<li data-seovar="{'+slug+'}">'+label+'</li>';
            });
        }else{
            html += '<li>'+sfswpSeoVars.noSeoVarsMsg+'</li>';
        }

        html += '</ul>';
        $(this).replaceWith(html);
        return true;
    }

    $(document).mouseup(function(e)
    {
        let $sfswpContainer = $('.sfswp-vars-container');
        if( $sfswpContainer.length > 0 ){
            // var container = $('.sfswp-vars-container');
            // if the target of the click isn't the container nor a descendant of the container
            if (! $sfswpContainer.is(e.target) && $sfswpContainer.has(e.target).length === 0)
            {
                $sfswpContainer.hide();
            }
        }
    });

    $(document).ready(function (){

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

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

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

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

        $('.sfswp-seo-vars-list').createSeoVarsList( sfswpSeoVars.seovars );

        $('body').on('click', '.sfswp-open-container', function (e){
            e.preventDefault();
            let link = $(this);
            let fieldId = link.data('field');
            let sfswpContainer = $('#sfswp-vars-container-'+fieldId );
            $('#sfswp_seo_rules-'+fieldId).focus();
            sfswpContainer.toggle();
        });

        $('body').on('focus keypress blur', '.sfswp-vars-insertable', function (e){
            let sfswpPosition = $(this).getCursorPosition();
            $(this).data('caret', sfswpPosition);
        });

        $('body').on('click', '.sfswp-seo-vars-list li', function (){
            let seoVar = $(this).data('seovar');

            let sfswpContainer = $(this).parents('.sfswp-vars-container');

            if( typeof seoVar !== 'undefined' ){
                let inputField = $('#sfswp_seo_rules-'+sfswpContainer.data('container'));
                let caretPos   = inputField.data('caret');

                if( caretPos === '' ){
                    caretPos = inputField.val().length;
                }

                if( caretPos === 0 ){
                    seoVar = seoVar+' ';
                }else if( caretPos === inputField.val().length ){
                    seoVar = ' '+seoVar;
                }else{
                    seoVar = ' '+seoVar+' ';
                }

                insertAtCaret( inputField, seoVar, caretPos );
            }

            sfswpContainer.hide();
        });

        $('body').on('change', '#sfswp_seo_rules-rule_post_type', function (){
            removeElement( $('.sfswp-field-notice') );
            let selected = $(this).val();
            let $spinner = $( '.sfswp-intersection-fields-wrapper' ).children( '.spinner' );
            $spinner.addClass( 'is-active' );
            let requestParams          = {};
            requestParams._wpnonce = $("#sfswp_seo_rule_nonce").val();
            requestParams.postType = selected;
            requestParams.postId   = $("#post_ID").val();

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

                    $( '#sfswp-intersections-table' ).replaceWith( response.html );
                    $('.sfswp-seo-vars-list').createSeoVarsList( response.seovars );
                })

                .fail( function(response) {
                    if( typeof response !== 'undefined'){
                        addFieldError( 'sfswp-intersection-fields-container', 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' );
    }

})(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;
}