(function( api, $ ) {
    const { ajaxUrl, _wpnonce, custom_callback: customCallback, custom } = customizerExtrasObject

    // contextual
    $.each( customCallback, function( controlId, controlValue ) {
        wp.customize( controlId, function( value ) {
            value.bind( function( to ) {
                $.each( controlValue, function( index, toToggle ){
                    if( JSON.stringify( to ) == index ) {
                        $.each( toToggle, function( key, val ){
                            wp.customize.control( val ).activate()
                        })
                    } else {
                        $.each( toToggle, function( key, val ){
                            wp.customize.control( val ).deactivate()
                        })
                    }
                })
                if( to in controlValue ) {
                    $.each( controlValue[to], function( key, val ){
                        wp.customize.control( val ).activate()
                    })
                }
            });
        });    
    })

    // ajax call
    $(document).on( "click", ".customize-info-box-action-control .info-box-button", function() {
        var _this = $(this), action = _this.data("action"), html = _this.html();
        $.ajax({
            method: 'post',
            url: ajaxUrl,
            data: ({
                'action': action,
                '_wpnonce': _wpnonce,
            }),
            beforeSend: function(response) {
                _this.html( 'Processing' )
                _this.attr( 'disabled', true )
            },
            success: function(response) {
                _this.html( html );
            },
            complete: function() {
                window.location.reload();
            }
        })
    })

    // Change the previewed URL to the selected page when changing the page_for_posts.
    $.each( custom, function( key, val ) {
        if( [ 'news_event_blog_post_archive_panel', 'news_event_single_panel' ].includes( key ) ) {
            api.panel( key, function ( panel ) {
                panel.expanded.bind(function ( isExpanded ) {
                    if ( isExpanded ) api.previewer.previewUrl.set( val );
                });
            });
        } else {
            api.section( key, function ( section ) {
                section.expanded.bind(function ( isExpanded ) {
                    const { id } = section
                    if( id === 'news_event_blog_post_archive_panel' && api.previewer.previewUrl() === val ) return
                    if ( isExpanded ) api.previewer.previewUrl.set( val )
                });
            });
        }
    })
})( wp.customize, jQuery )