/**
 * Combine scripts for Customizer Controls.
 *
 * @package Blogbuster
 */

( function( api ) {
/*--------------- Tabs Control ------------------*/

    // Tab Control
    api.Tabs = [];
    api.Tab = api.Control.extend({
        ready: function () {
            var control = this;
            control.container.find('li.section-tab-button').click(function (e) {
                var key = jQuery(this).data('tab');
                e.preventDefault();
                control.container.find('li.section-tab-button').removeClass('active');
                jQuery(this).addClass('active');
                control.toggleActiveControls(key);
            });
            api.Tabs.push(control.id);
        },
        toggleActiveControls: function (key) {
            var control = this,
                currentFields = control.params.choices[key].fields;

            _.each(control.params.fields, function (id) {
                var tabControl = api.control(id);
                if (undefined !== tabControl) {
                    if (tabControl.active() && jQuery.inArray(id, currentFields) >= 0) {
                        tabControl.toggle(true);
                    } else {
                        tabControl.toggle(false);
                    }
                }
            });
        }
    });

    jQuery.extend(api.controlConstructor, {
        'mt-tabs': api.Tab
    });

    api.bind('ready', function () {
        _.each(api.Tabs, function (id) {
            var control = api.control(id);
            var iniID = control.container.find('li.active').data('tab');
            control.toggleActiveControls(iniID);
        });
    });
    
/*--------------- Heading Toggle Control ------------------*/
    api.controlConstructor['mt-heading-toggle'] = api.Control.extend( {
        ready: function() {
            var control = this, container = control.container;
            // on trigger action
            container.on( "click", function() {
                var _this = jQuery(this);
                _this.find(".toggle-button .dashicons").toggleClass("dashicons-arrow-down-alt2 dashicons-arrow-up-alt2");
                _this.nextUntil( ".customize-control-mt-heading-toggle" ).slideToggle();
            })
        }
    });
    
/*--------------- Typography Control------------------------*/
    
    api.controlConstructor['mt-typography'] = api.Control.extend( {
        ready: function() {
            var control = this;
            control.container.on( 'change', '.typography-font-style select', function() {
                control.settings['style'].set( jQuery( this ).val() );
            });
            control.container.on( 'click', '.typography-font-transform input', function() {
                control.settings['transform'].set( jQuery( this ).val() );
            });
            control.container.on( 'change', '.typography-text-decoration select', function() {
                control.settings['text_decoration'].set( jQuery( this ).val() );
            });
        }
    } );

})(wp.customize);

jQuery(document).ready(function($) {

/*--------------- Custom controls extra -----------*/

    $('.customize-control-select2').select2({
        allowClear: true
    });

/*--------------- Repeater field ------------------*/
    /**
      * Function for repeater field
     */
    function blogbuster_refresh_repeater_values(){
        $(".mt-repeater-field-control-wrap").each(function(){
            
            var values = []; 
            var $this = $(this);
            
            $this.find(".mt-repeater-field-control").each(function(){
            var valueToPush = {};   

                $(this).find('[data-name]').each(function(){
                    if( $(this).attr('type') === 'checkbox'){
                        dataValue = ( $(this).is(':checked') ) ? 'on' : 'off';
                    } else {
                        var dataValue = $(this).val();
                    }
                    var dataName = $(this).attr('data-name');
                    valueToPush[dataName] = dataValue;
                });

                values.push(valueToPush);
            });

            $this.next('.mt-repeater-collector').val(JSON.stringify(values)).trigger('change');
        });
    }

    // expand the repeater fields wrap
    $('#customize-theme-controls').on('click','.mt-repeater-field-title.item-visible', function(){
        $(this).closest('.mt-repeater-field-control').find('.mt-repeater-fields').slideToggle();
        $(this).closest('.mt-repeater-field-control').toggleClass('expanded');
    });

    // close the repeater fields wrap
    $('#customize-theme-controls').on('click', '.mt-repeater-field-close', function(){
        $(this).closest('.mt-repeater-fields').slideUp();
        $(this).closest('.mt-repeater-field-control').toggleClass('expanded');
    });

    // show/hide repeater field
    $("#customize-theme-controls").on("click", ".field-display", function(){
        $(this).toggleClass( "dashicons-visibility dashicons-hidden" );
        $(this).closest('.mt-repeater-field-control').toggleClass( 'item-visible item-not-visible' );
        $(this).closest('.mt-repeater-field-control').find('.mt-repeater-field-title').toggleClass( 'item-visible item-not-visible' );
        var dataVal =  $(this).parents('.mt-repeater-field-control').find('input.repeater-field-visible-holder').val();
        if(dataVal == 'show') {
            if ($(this).closest('.mt-repeater-field-control').find('.mt-repeater-fields').is(':visible')) {
                $(this).closest('.mt-repeater-field-control').toggleClass('expanded');
                $(this).closest('.mt-repeater-field-control').find('.mt-repeater-fields').slideUp();
            }
            $(this).closest('.mt-repeater-field-control').find('input.repeater-field-visible-holder').val('hide');
        } else {
            $(this).closest('.mt-repeater-field-control').find('input.repeater-field-visible-holder').val('show');
        }
        blogbuster_refresh_repeater_values();
    });

    $("body").on("click",'.mt-repeater-add-control-field', function(){

        var fLimit = $(this).parent().find('.field-limit').val();
        var fCount = $(this).parent().find('.field-count').val();
        var fLimitInfo = $(this).parent().find('.field-limit').data('info');
        if( fCount < fLimit ) {
            fCount++;
            $(this).parent().find('.field-count').val(fCount);
        } else {
            $(this).before('<span class="mt-limit-msg"><em>Only '+fLimit+ ' ' +fLimitInfo+' shall be permitted for free version.</em></span>');
            return;
        }

        var $this = $(this).parent();
        
        if(typeof $this != 'undefined') {

            var field = $this.find(".mt-repeater-field-control:first").clone();
            if(typeof field != 'undefined'){
                
                field.find("input[type='text'][data-name]").each(function(){
                    var defaultValue = $(this).attr('data-default');
                    $(this).val(defaultValue);
                });

                field.find("textarea[data-name]").each(function(){
                    var defaultValue = $(this).attr('data-default');
                    $(this).val(defaultValue);
                });

                field.find("select[data-name]").each(function(){
                    var defaultValue = $(this).attr('data-default');
                    $(this).val(defaultValue);
                });

                field.find(".attachment-media-view").each(function(){
                    var defaultValue = $(this).find('input[data-name]').attr('data-default');
                    $(this).find('input[data-name]').val(defaultValue);
                    if(defaultValue){
                        $(this).find(".thumbnail-image").html('<img src="'+defaultValue+'"/>').prev('.placeholder').addClass('hidden');
                    }else{
                        $(this).find(".thumbnail-image").html('').prev('.placeholder').removeClass('hidden');   
                    }
                });
                
                field.find(".mt-repeater-icon-list").each(function(){
                    var defaultValue = $(this).next('input[data-name]').attr('data-default');
                    $(this).next('input[data-name]').val(defaultValue);
                    $(this).prev('.mt-repeater-selected-icon').children('i').attr('class','').addClass(defaultValue);
                    
                    $(this).find('li').each(function(){
                        var icon_class = $(this).find('i').attr('class');
                        if(defaultValue == icon_class ){
                            $(this).addClass('icon-active');
                        }else{
                            $(this).removeClass('icon-active');
                        }
                    });
                });

                field.find('.mt-repeater-fields').show();

                $this.find('.mt-repeater-field-control-wrap').append(field);

                field.addClass('expanded').find('.mt-repeater-fields').show(); 
                $('.accordion-section-content').animate({ scrollTop: $this.height() }, 1000);
                blogbuster_refresh_repeater_values();
            }

        }
        return false;
     });
    
    // remove the repeater field item
    $("#customize-theme-controls").on("click", ".mt-repeater-field-remove",function(){
        if( typeof  $(this).parent() != 'undefined'){
            $(this).closest('.mt-repeater-field-control').slideUp('normal', function(){
                $(this).remove();
                blogbuster_refresh_repeater_values();
            });
        }
        return false;
    });

    $("#customize-theme-controls").on('keyup change', '[data-name]', function(){
        blogbuster_refresh_repeater_values();
        return false;
    });

    /**
     * Drag and drop to change order
     */
    $(".mt-repeater-field-control-wrap").sortable({
        orientation: "vertical",
        update: function( event, ui ) {
            blogbuster_refresh_repeater_values();
        }
    });

    /**
     * Image upload
     */
    var frame;
    
    //Add image
    $('.customize-control-mt-repeater').on( 'click', '.mt-upload-button', function( event ){
        event.preventDefault();

        var imgContainer = $(this).closest('.mt-fields-wrap').find( '.thumbnail-image'),
        placeholder = $(this).closest('.mt-fields-wrap').find( '.placeholder'),
        imgIdInput = $(this).siblings('.upload-id');

        frame = wp.media({
            title: 'Select or Upload Image',
            button: {
                text: 'Use Image'
            },
            multiple: false  // Set to true to allow multiple files to be selected
        });

        frame.on( 'select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            imgContainer.html( '<img src="'+attachment.url+'" style="max-width:100%;"/>' );
            placeholder.addClass('hidden');
            imgIdInput.val( attachment.url ).trigger('change');
        });

        frame.open();
    });

    // DELETE IMAGE LINK
    $('.customize-control-mt-repeater').on( 'click', '.mt-delete-button', function( event ){
        event.preventDefault();
        var imgContainer = $(this).closest('.mt-fields-wrap').find( '.thumbnail-image'),
        placeholder = $(this).closest('.mt-fields-wrap').find( '.placeholder'),
        imgIdInput = $(this).siblings('.upload-id');
        imgContainer.find('img').remove();
        placeholder.removeClass('hidden');
        imgIdInput.val( '' ).trigger('change');
    });

    /**
     * Repeater icon selector
     */
    $('body').on('click', '.mt-repeater-icon-list li', function(){
        var icon_class = $(this).find('i').attr('class');
        $(this).addClass('icon-active').siblings().removeClass('icon-active');
        $(this).parent('.mt-repeater-icon-list').prev('.mt-repeater-selected-icon').children('i').attr('class','').addClass(icon_class);
        $(this).parent('.mt-repeater-icon-list').next('input').val(icon_class).trigger('change');
        blogbuster_refresh_repeater_values();
    });

    $('body').on('click', '.mt-repeater-selected-icon', function(){
        $(this).next().slideToggle();
    });

});

/*--------------- Radio Images Control ------------------------*/

    wp.customize.controlConstructor['mt-radio-image'] = wp.customize.Control.extend({
        ready: function() {
            'use strict';
            var control = this;

            // Change the value
            this.container.on( 'click', 'input', function() {
                control.setting.set( jQuery( this ).val() );
            });
        }
    });

/*--------------- Toggle Control ------------------------*/

    wp.customize.controlConstructor['mt-toggle'] = wp.customize.Control.extend({
        ready: function(){
            'use strict';
            var control = this,
                checkboxValue = control.setting._value;
            // Save the value
            this.container.on( 'change', 'input', function() {
                checkboxValue = ( jQuery( this ).is( ':checked' ) ) ? true : false;
                control.setting.set( checkboxValue );
            });
        }
    });

/*--------------- Buttonset Control ------------------------*/

    wp.customize.controlConstructor['mt-buttonset'] = wp.customize.Control.extend({

        ready: function() {

            'use strict';

            var control = this;

            // Change the value
            this.container.on( 'click', 'input', function() {
                control.setting.set( jQuery( this ).val() );
            });
        }

    });

/*--------------- Radio Icons Control ------------------------*/

    wp.customize.controlConstructor['mt-radio-icons'] = wp.customize.Control.extend({

        ready: function() {

            'use strict';

            var control = this;

            // Change the value
            this.container.on( 'change', 'input', function() {
                control.setting.set( jQuery( this ).val() );
            });

        }

    });