(function ($) {

    var utility = {
        //Checks if element as desired attribute
        HasAttr: function ($elm, attr) {
            return typeof $elm.attr(attr) != 'undefined';
        },
        GetAttr: function ($elm, attr, def) {
            return this.HasAttr($elm, attr) ? $elm.attr(attr) : def;
        }
    };

    //Show/hide fields based on selected value
    function FieldSelector() {
        $('.field-selector select').each(function () {
            var $select = $(this),
                $section = $select.parents('.section'),
                fieldList = utility.GetAttr($select, 'data-fields', ''),
                $fields = $section.find(fieldList);

            $select.change(function () {
                var $selected = $select.find('option:selected');

                if (!utility.HasAttr($selected, 'data-show')) {
                    $fields.slideUp('fast');
                    return;
                }

                var show = $selected.attr('data-show'),
                    $items = $section.find(show);

                $fields.not($items).slideUp('fast');
                $items.slideDown('fast');
            }).change();
        });
    }

    //Handles icon selector
    function iconSelect() {
        var iconSelectFunc = function() {
            var $rad_icons_container = $('.rad-icon-param-container').eq(0).clone();
            $rad_icons_container.addClass('rad-container-popup');
            $rad_icons_container.find('input,.selected-icon,.select-icon-text').remove();
            $('.rad-icon-params').remove();
            $('body').append($rad_icons_container);

            $(document).on('click','.select-icon-text',function() {
                var $this = $(this);

                if($('.rad-container-popup').length <= 0)
                {
                    $rad_icons_container = $('.rad-icon-param-container').eq(0).clone();
                    $rad_icons_container.addClass('rad-container-popup');
                    $rad_icons_container.find('input,.selected-icon,.select-icon-text').remove();
                    $('.rad-icon-params').remove();
                    $('body').append($rad_icons_container);
                }

                var $iconInput = $this.siblings('input'),
                    $SelectediconBox = $this.siblings('.selected-icon');

                $rad_icons_container.find('.rad-icon-param.selected').removeClass('selected');

                if ($iconInput.attr('value') !== '') {
                    var val = $inputval.split(":"),
                        name = val[0],
                        type = val[1];
                        
                    $rad_icons_container.find('.rad-icon-param[data-name=' + name + '][data-type=' + type + ']').addClass('selected');
                    setTimeout(function(){
                        //Scroll iconContainer to show the select icon
                        if ($rad_icons_container.find('.selected').length) {
                            var $rad_icons = $rad_icons_container.find('.rad-icon-params'),
                                $offset = $rad_icons.scrollTop() - $rad_icons.offset().top + $rad_icons.find('.selected').offset().top ;

                            if ($offset > 0) {
                                $rad_icons.stop().animate({
                                    scrollTop: $offset + "px"
                                }, 200);
                            }
                        }
                    },100)

                }

                $SelectediconBox.addClass('icon_container_owner');
                $rad_icons_container.addClass('show');


            });

            $(document).on('click','.rad-container-popup .rad-icon-param', function () {
                var $this = $(this),
                    $icon_owner = $('.icon_container_owner'),
                    $iconInput = $icon_owner.siblings('input');

                if ($this.is('.selected')) {
                    $this.removeClass('selected');
                    $iconInput.attr('value', '');
                    $icon_owner.removeClass('icon-' + $icon_owner.data('name'));
                    $icon_owner.data('name','');
                }
                else {
                    $iconInput.attr('value', $(this).attr('data-name') + ':' + $(this).attr('data-type'));
                    $this.siblings('.rad-icon-param').removeClass('selected');
                    
                    $icon_owner.removeClass('icon-' + $icon_owner.data('name'));
                    $icon_owner.addClass('icon-' + $(this).attr('data-name'));
                    $icon_owner.data('name',$(this).attr('data-name'));
                    $this.addClass('selected');
                }

            });

            $(document).on('click','.rad-icon-params .close,.rad-container-popup', function () {
                var $icon_owner = $('.icon_container_owner');

                $icon_owner.removeClass('icon_container_owner');
                $rad_icons_container.removeClass('show');
            });

        }

        iconSelectFunc();
        
    }

    function CSVInput() {

        $('.csv-input').each(function () {
            var $container = $(this),
                $hidden = $container.find('input[type="hidden"]'),
                $input = $container.find('input[type="text"]'),
                $addBtn = $container.find('.btn-add'),
                $list = $container.find('.list');

            var values = $hidden.val().length > 0 ? $hidden.val().split(',') : [];

            //Add current items to our list
            for (i = 0; i < values.length; i++) {
                var val = values[i],
                    text = val.replace('%666', ','),//Evil char 
                    $item = GetNewItem(val, text);

                $list.append($item);
                HandleCloseBtn($item);
            }

            AssembleList();

            //Handle add button
            $addBtn.click(function (e) {
                e.preventDefault();

                var val = $input.val();
                val = $.trim(val);
                $input.val('');//Clear

                if (val.length < 1)
                    return;

                var $item = GetNewItem(val.replace(",", "%666"), val);
                HandleCloseBtn($item);
                $item.hide();

                $list.prepend($item);

                AssembleList();

                $item.slideDown('fast', function () { $(window).resize(); });
            });

            function AssembleList() {
                $hidden.val('');//Clear the current list
                var vals = [];

                $list.find('.value').each(function () {
                    var value = $(this).attr('data-val');
                    vals.push(value);
                });

                $hidden.val(vals.join(','));
            }

            function HandleCloseBtn($item) {
                //Remove item on click
                $item.find('.btn-close').click(function (e) {
                    e.preventDefault();

                    $item.slideUp('fast', function () { $item.remove(); AssembleList(); $(window).resize(); });
                });
            }

            function GetNewItem(val, text) {
                return $('<div class="value" data-val="' + val + '"><span>' + text + '</span><a href="#" class="btn-close"></a></div>');
            }

        });


    }

    function ImageSelect() {
        var $controls = $('.imageSelect');

        $controls.each(function () {
            var $select = $(this),
                $input = $select.find('input'),
                $options = $select.find('a');
            if( !$select.find('.selected').length )
            {
                var $default = $select.find('a.default');
                if($default.length <= 0)
                {
                    $default = $select.find('a').eq(0);
                }
                $default.addClass('selected');
                $input.val($select.find('a').eq(0).attr('data-val'));
            }
            

            //Hide input control
            $input.hide();

            $options.click(function (e) {
                e.preventDefault();

                var $ctl = $(this);

                if ($ctl.hasClass('selected'))
                    return;

                $options.removeClass('selected');
                $ctl.addClass('selected');

                $input.val($ctl.attr('data-val'));
                $(this).trigger( "image_selected" );
            });
        });

       function advanced_image_select() {
            $('.rad-imageselect-container').each(function () {

                var $list = $(this),
                $input = $list.find('input'),
                $images = $list.find('.rad-image'),
                $inputval = $input.val();
               
                if ($inputval.length !== 0) {
                    $list.find("span.image-" + $inputval).addClass('selected');
                }
                else
                {
                    $list.find("span:first-child").addClass('selected');
                }

                $(document).on('click', '.rad-image',function () {
                   
                    if(!$(this).hasClass('selected'))
                    {
                        $(this).closest('span').siblings('input').val($(this).attr('data-name'));
                        $(this).siblings('.rad-image').removeClass('selected');
                        $(this).addClass('selected');
                    }
                    $input.trigger( "change" );
                });

            });
        }

        advanced_image_select();
    }

    function Chosen() {
        if (!$.fn.chosen)
            return;

        $('.chosen').chosen();
    }

    function Combobox() {
        $('.select').each(function () {
            var $this = $(this),
                $overlay = $this.find('div'),
                $select = $this.find('select');

            $select.change(function () {
                $overlay.html($select.find('option:selected').text());
            });

            $select.change();
        });
    }

    function ColorPicker() {
        if (!$.fn.wpColorPicker)
            return;

        $('.rad-main .colorinput, .rado-widget-attributes-table .colorinput, .widget-insta.colorinput,#menu-management ul.menu li .colorinput, .taxonomy-product_cat .colorinput,.rad-color-attr .colorinput').each(function () {
            $(this).wpColorPicker( { palettes : false});
        });

    }

    function Sliders() {
        if (!$.fn.noUiSlider)
            return;

        var $sliders = $('input[type="range"]');

        $sliders.each(function () {
            var $this = $(this),
                $parent = $this.parent(),
                $label = $('<span></span>'),
                min = 0,
                max = 100,
                start = 0,
                isSwitch = $this.hasClass('switch'),
                sliderCls = isSwitch ? 'switch' : 'slider',
                $slider = $('<div class="' + sliderCls + '"></div>'),
                $states = ['Off', 'On'],
                setupState = true;//For switches


            //Set label
            $parent.find('.label').prepend($label);

            if ('value' in this.attributes)
                $label.html(this.attributes['value'].value);

            //Set values
            if (isSwitch) {
                min = 0;
                max = 1;

                if ($this.attr('data-state0') !== undefined)
                    $states[0] = $this.attr('data-state0');

                if ($this.attr('data-state1') !== undefined)
                    $states[1] = $this.attr('data-state1');

            }
            else {

                if ($this.attr('min') !== undefined)
                    min = parseInt($this.attr('min'));

                if ($this.attr('max') !== undefined)
                    max = parseInt($this.attr('max'));

                if ($this.attr('step') !== undefined)
                    step = parseInt($this.attr('step'));
                else
                    step = 0.01;

            }

            if ('value' in this.attributes &&
                this.attributes['value'].value.length > 0)
                start = parseInt(this.attributes['value'].value);
            else
                start = min + max * 0.5;

            $this.hide();
            $slider.appendTo($parent);

            if (isSwitch) {
                $slider.noUiSlider({
                    start: start,
                    range: {
                        'min': [min],
                        'max': [max]
                    },
                    step: 1,
                    direction: "ltr",
                    behaviour: 'tap',
                    connect: "upper"
                });
            }
            else {
                $slider.noUiSlider({
                    start: [start],
                    range: {
                        'min': [min],
                        'max': [max]
                    },
                    step : step,
                    direction: "ltr",
                    behaviour: 'tap',
                });
            }

            $slider.on({
                slide: Handle_Change,
            });


            function Handle_Change(e) {
                var value = $slider.val();

                if (isNaN(value) || (setupState && isSwitch && start > 0 && start < 1))
                    value = min;

                if (isSwitch) {

                    $label.html($states[Math.ceil(value)]);
                }  
                else
                {
                    if(Math.ceil(step) == step && $.isNumeric(step)) 
                    {
                        $label.html(Math.ceil(value));
                        value = Math.ceil(value);
                    }
                    else
                    {
                        $label.html(value);
                    } 
                }

                $this.val(value);

                setupState = false;
            }

            var $midbar = $slider.find('.noUi-midBar'),
                left = $midbar.css('left'),
                right = $midbar.css('right');

            if (left == '0px' && right == '0px' && $slider.val() != max) {
                $midbar.css({ right: $this.width() });
            }

            var $sliderHandle = $slider.find('.noUi-handle');


            if (isSwitch) {

                Handle_Change();
            }


        });

    }

    function Tooltips() {


        $('.section-tooltip').each(function () {
            var $this = $(this),
                text = $this.html(),
                $icon = $('<a href="#"><span class="dashicons dashicons-warning"></span></a>'),
                $wrap = $('<div class="tip_wrapper"><div class="text">' + text + '</div>');

            $this.html('');
            $this.append($icon);
            $this.append($wrap);
            $wrap.css({ opacity: 0, display: 'none' });

            $icon.click(function (e) {
                e.preventDefault();
            });

            if ($.fn.hoverIntent)
                $this.hoverIntent(InHandler, OutHandler);
            else
                $this.hover(InHandler, OutHandler);

            function InHandler() {
                $wrap.css({ display: 'block' });
                $wrap.stop().animate({ opacity: 1 }, 200);
            }

            function OutHandler() {
                $wrap.stop().animate({ opacity: 0, }, { duration: 200, complete: function () { $wrap.css({ display: 'none' }); } });
            }

        });

    }

    function Save_Button() {
        var $btns = $('.rad-main .save-button'),
            $loadingIcons = $btns.find('.loading-icon'),
            $saveIcons = $btns.find('.save-icon'),
            $form = $('.rad-container'),
            $dummyData = $('.rad-main input[name="import_dummy_data"]');

        $btns.click(function (e) {
            var $btn = $(this);

            if ($btn.hasClass('loading')) {
                e.preventDefault();
                return;
            }

            var data = $form.find('input,textarea,select').serialize();

            $loadingIcons.css({ display: 'inline' });
            $saveIcons.hide();

            $btns.addClass('loading');


            //Todo: Save the settings
            //Test ajax call
            $.ajax({
                url: ajaxurl,
                type: 'post',
                data: data,
                success: function (data, textStatus, jqXHR) {
                    //TODO: Show proper saved message
                    OnSaveComplete();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    OnSaveComplete();

                    alert('Error occured in saving data');
                }
            });

            function OnSaveComplete() {
                $loadingIcons.hide();
                $saveIcons.css({ display: 'inline' });
                $btns.removeClass('loading');

                //Reload page if import dummy data option is selected
                if ($dummyData.length && $dummyData.val() == '1')
                    document.location.reload(true);
            }

            e.preventDefault();
        });


    }

    function Tabs() {
        var $tabs = $('.rad-tab a'),
            $active = $();

        $tabs.each(function () {
            var $this = $(this),
                href = $this.attr('href'),
                $container = $(href);

            $this.click(function (e) {
                e.preventDefault();

                if ($this.hasClass('active'))
                    return;

                $tabs.removeClass('active');
                $this.addClass('active');

                $active.fadeOut(100);
                $container.fadeIn(400);

                $active = $container;

                $(window).resize();

            });

            if ($this.hasClass('active')) {
                $this.removeClass('active');
                $this.click();
                $active = $container;
            }
            else {
                $container.fadeOut(100);
            }

        });

    }

    function Sidebar_Accordion() {
        var $head = $('#rad-sidebar-accordion > h3 a');

        var $active = $('#rad-sidebar-accordion > h3 a.active'),
            $target = $();

        if ($active.length > 0) {
            $target = $active.parent().next();
            $target.show();
        }


        $head.click(function (e) {
            var $this = $(this);
            e.preventDefault();

            $target = $this.parent().next();

            if (!$this.hasClass('active')) {
                var $prev = $('#rad-sidebar-accordion > h3 a.active').parent().next();

                $head.removeClass('active');

                $prev.hide('fast', 'easeOutQuad');
                $target.slideDown('fast', 'easeOutQuad');
                $this.addClass('active');
                $this.parent().next('div').find('li').eq(0).find('a').trigger('click');

            }

            e.preventDefault();
        });
    }

    function Thickbox() {
        $('body').on('click', '.upload-field .upload-button', function(e){
                e.preventDefault();
                var $button  = $(this),
                    $input    = $button.parent('.upload-field').find('input[type="hidden"]'),
                    $thumbs  = $button.parent('.upload-field').find('.upload-thumb'),
                    multiple_media = $button.parent('.upload-field').hasClass('multiple')? true:false,
                    custom_uploader = wp.media({
                title: $button.data('title'),
                library : {
                    // uncomment the next line if you want to attach image to the current post
                    //uploadedTo : wp.media.view.settings.post.id, 
                    type : 'image'
                },
                button: {
                    text: 'Use this image' // button label text
                },
                multiple: multiple_media // for multiple image selection set to true
            }).on('select', function() { // it also has "open" and "close" events 
                if(multiple_media)
                {
                    var attachments = custom_uploader.state().get('selection'),
                        attachment_ids = new Array(),
                        i = 0;
                    $thumbs.find('img').remove();
                    attachments.each(function(attachment) {
                        attachment_ids[i] = attachment['id'];
                        $thumbs.append('<img class="true_pre_image" src="' + attachment['attributes']['url'] + '"/>');
                        $thumbs.addClass('show');
                        i++;
                    });

                    $input.val(attachment_ids.join(','));
                }
                else
                {
                    var attachment = custom_uploader.state().get('selection').first().toJSON();
                    $thumbs.find('img').remove();
                    $thumbs.append('<img class="true_pre_image" src="' + attachment.url + '"/>');
                    $thumbs.addClass('show');
                    $input.val(attachment.id);
                    var url = attachment.url;
                    $(document).trigger('rad_upload', [{url:url, id:attachment.id},$input]);
                }
            }).open();
        });

        $(document).on('click','.upload-thumb .close',function (e) {
            $(this).parents('.upload-thumb').removeClass("show");
            $(this).parents('.upload-field').find('input').val('');
            $(this).parents('.upload-field').find('img').remove();
        });
    }

    function product_image_attributes() {
        $(document).on('rad_upload',function(e, data,$input) {
            var $attr_extra_input = $input.closest('.field-container').find('input[name^="attribute_extra_values"]');
            if($attr_extra_input.length > 0)
            {
                $attr_extra_input.val(data.id);
            }
            
        });
    }

    function ImageFields() {
        var $imageSec = $('.section-home-slides'),
            $fields = $imageSec.find('.upload-field'),
            $dupBtn = $('<a class="duplicate-button" href="#">Add Image</a>'),
            $remBtn = $('<span class="remove-button"><a class=" close" href="#"><span class="close-icon"></span></a></span>');

        //Click handler for remove button
        $remBtn.click(function (e) {
            e.preventDefault();

            var $this = $(this);

            $this.parent().remove();

            $fields = $imageSec.find('.upload-field');

            if ($fields.length < 2)
                //Remove the button
                $fields.find('.remove-button').remove();
        });


        //Add remove button if there is more than one image field
        if ($fields.length > 1)
            $fields.append($remBtn.clone(true));

        //Add duplicate button after last upload field
        $fields.filter(':last').after($dupBtn);

        $dupBtn.click(function (e) {
            e.preventDefault();

            //Don't try to reuse $fields var above ;)
            $fields = $imageSec.find('.upload-field');
            var $lastField = $fields.filter(':last'),
                $clone = $lastField.clone(true);

            //Clear the value (if any)
            $clone.find('input[type="text"]').val('');
            $clone.find('.upload-thumb').removeClass('show');
            $clone.find('img').attr('src','');

            $lastField.after($clone);

            //Refresh
            $fields = $imageSec.find('.upload-field');
            //Add 'remove' button to all fields
            //Rest of 'remove' buttons will get cloned
            if ($fields.length == 2)
                $fields.append($remBtn.clone(true));
        });
    }

    function preloader() {
        
        var display_logo_preloader = function(type) {
            $preloaderlogo = $('.section-preloader-logo');
            if (type == 'logo') {
                $preloaderlogo.slideDown('fast');
            } else {
               $preloaderlogo.slideUp('fast');
            }
        }

        var preloaderType = $('.section-preloader-type .imageSelect a.selected').text();
        display_logo_preloader(preloaderType);

        $(document).on('click', '.section-preloader-type .imageSelect a', function () {
            preloaderType = $(this).text();
            display_logo_preloader(preloaderType);
        });

    }

    function menu() {

        var $container = $('#menu'),

            // Header Position 
            $headerPosition = $container.find('.section-menu-align .imageList a.selected'),
            $headerPositionVal = $headerPosition.text();

            //HeaderTop Style
            $HeadertopStyle = $container.find('.section-menu-state .imageList a.selected'),
            $HeadertopStyleVal = $HeadertopStyle.text();
            
            // Header Color 
            $HeaderColor = $container.find('.section-menu-color');
            $HeaderTopIntialColor = $container.find('.section-initial-menu-color');
            // Header top Style 
            $headerStyle = $container.find('.section-menu-state');
            // Header menu container  styles container Or Fullwidth            
            $HeaderContainerStyle = $container.find('.section-menu-container');
            // submenu color - mega menu Option Disable in sidebars menu
            $submenu_color = $container.find('.section-submenu-color');
            
            if ($HeadertopStyleVal == "double-state") {

                $HeaderColor.slideDown('fast').show();
            
            } else {

                $HeaderColor.slideUp('fast').hide();
            }

        // menu top style 
        $(document).on('click', '.section-menu-state .imageList a', function () {

            var $select = $(this),
                val = $(this).text(),
                $selected = $('#menu').find('.section-' + val);
  
            if (val == 'single-state') {
                // Hide logo secoun
                $(".section-menu-color").slideUp('fast').hide();
                $(".section-logo").slideDown('fast').show();
                $(".section-initial-menu-color").slideDown('fast').show();

            } else {

                $(".section-logo , .section-initial-menu-color , .section-menu-color").slideDown('fast').show();

            }

        }).change();

    }

    function demo_importer() {
        $(document).on('click', 'a.import', function (e) {
            e.preventDefault();
            var $import_button = $(this);
            var demo = $(this).data('demo');
            $(this).parents('form').find('input#demo_name').val(demo);
            $(this).parents('form').submit();
        });
    }

    function setRowTypeIcon ()
    {
        $('span.row_type').each(function(){
            if($(this).html() == "parallax")
            {
                $(this).removeClass('video-type mouse_parallax-type').addClass('parallax-type'); 
            }
            else if($(this).html() == "video")
            {
                $(this).removeClass('parallax-type mouse_parallax-type').addClass('video-type');
            }
            else if($(this).html() == "mouse_parallax")
            {
                $(this).removeClass('parallax-type video-type').addClass('mouse_parallax-type');
            }
            else
            {
                $(this).removeClass('parallax-type video-type mouse_parallax-type');
            }
        })
    }

    function menuDependencies()
    {
        $(document).on('mouseup', 'li.menu-item .menu-item-handle' ,function(e){
            mega_menu_handel();
        });
        $(document).on('change',"input[name^='is-mega-menu']",function(e) {
            var $menuItem = $(this).parents("li.menu-item");
            e.stopPropagation();
            mega_menu_handel();
        });

        mega_menu_handel();

        function mega_menu_handel(){
            //Mega menu & upload field dependencies
            var $menu = $('ul.menu.ui-sortable');

            setTimeout(function(){
                $menu.find('li.menu-item').removeClass('enable-mega-menu-of-parent');

                $menu.find('li.menu-item.menu-item-depth-0').each(function() {
                    $this = $(this);
                    var $megamenu = $this.find("input[name^='is-mega-menu']");

                    if( $megamenu.prop('checked') )
                    {

                        $this.nextUntil( '.menu-item-depth-0','li.menu-item.menu-item-depth-1,li.menu-item.menu-item-depth-2').addClass("enable-mega-menu-of-parent");
                        $this.addClass('enable-mega-menu-of-parent');
                        
                    }
                    else
                    {
                        $this.nextUntil( '.menu-item-depth-0','li.menu-item.menu-item-depth-1,li.menu-item.menu-item-depth-2').removeClass("enable-mega-menu-of-parent");
                        $this.removeClass('enable-mega-menu-of-parent');
                    }
                });
            },500);
        }

        $('#menu-to-edit').on('click',"a.item-edit",menuInitOptionHandle);

        function menuInitOptionHandle () {
            ColorPicker();
        }
    }

    function product_variation()
    {

        $(document).on('click','.woocommerce_attribute_data .add_all_attr',function(e){
            e.preventDefault();
            var $fields_container = $(this).prev('.fields-container');
            $fields_container.find('div.field-container.hide-field').each(function(index,element){
                var $elem = $(element);
                //remove image saved in the attribute field
                $elem.find('.upload-thumb').removeClass("show");
                $elem.find('.upload-field').find('input').val('');
                $elem.removeClass('hide-field'); // show it

                var $value_field = $elem.find('input[name^="x_attribute_values"]'),
                    $extra_value_field = $elem.find('input[name^="x_attribute_extra_values"]');


                var $attr_value_name = $value_field.attr('name'),
                    $attr_extra_value_name = $extra_value_field.attr('name');

                //trick : add x to disable saving it's value ( instead of removing it completly, we can retrive it with just rename them)
                $attr_value_name = $attr_value_name.replace('x_attribute_values','attribute_values');
                $attr_extra_value_name = $attr_extra_value_name.replace('x_attribute_extra_values','attribute_extra_values');

                $value_field.attr('name',$attr_value_name);
                $extra_value_field.attr('name',$attr_extra_value_name);
            });
        });

        $(document).on('click','.woocommerce_attribute_data .field-container .attr_remove',function(){
            $(this).closest('.field-container').addClass('hide-field');

            var $value_field = $(this).closest('.field-container').find('input[name^="attribute_values"]'),
                $extra_value_field = $(this).closest('.field-container').find('input[name^="attribute_extra_values"]');

            var $attr_value_name = $value_field.attr('name'),
                $attr_extra_value_name = $extra_value_field.attr('name');

            //trick : add a prefix "x" to input names to  disable saving those values ( instead of removing them completly, we rename them and it's easy to retrive them)
            $attr_value_name = $attr_value_name.replace('attribute_values','x_attribute_values');
            $attr_extra_value_name = $attr_extra_value_name.replace('attribute_extra_values','x_attribute_extra_values');

            $value_field.attr('name',$attr_value_name);
            $extra_value_field.attr('name',$attr_extra_value_name);

        });

        $(document).on('click','.woocommerce_attribute_data .field-container .upload-thumb .close',function(e){
            $(this).parents('.upload-thumb').prev('.upload-button').trigger('click');
        });



        $( '.product_attributes' ).on( 'click', '.remove_row', function() {
            var $parent = $( this ).parent().parent();
            $parent.find( '.image-attr-field-container input[type=hidden]' ).val( '' );
        });



        // Add a new attribute (via ajax) : this function is a customized copy of function defined in woocommerce/assets/js/admin/meta-boxes-product.js
        $(document).on( 'click', 'a.add_new_attr', function(e) {
            e.preventDefault();

            $( '.product_attributes' ).block({
                message: null,
                overlayCSS: {
                    background: '#fff',
                    opacity: 0.6
                }
            });

            var $wrapper           = $( this ).closest( '.woocommerce_attribute' );
            var $fields_container  = $wrapper.find( '.fields-container' );
            var attribute          = $wrapper.data( 'taxonomy' );
            var attribute_number   = $( this ).siblings('.fields-container').find('.field-container').data( 'attr-number' ); // attr number
            var new_attribute_name = window.prompt( woocommerce_admin_meta_boxes.new_attribute_prompt );

            if ( new_attribute_name ) {

                var data = {
                    action:   'woocommerce_add_new_attribute',
                    taxonomy: attribute,
                    term:     new_attribute_name,
                    security: woocommerce_admin_meta_boxes.add_attribute_nonce
                };

                $.post( woocommerce_admin_meta_boxes.ajax_url, data, function( response ) {

                    if ( response.error ) {
                        // Error
                        window.alert( response.error );
                    } else if ( response.slug ) {

                        if( $fields_container.length <= 0)
                        {
                            $wrapper.find('.add_all_attr').before('<div class="fields-container"></div>');
                            $fields_container = $wrapper.find('.fields-container');
                        }

                        // get image for upload field
                            var new_attr = '<div class="field-container image-attr-field-container" data-attr-number=" '+ attribute_number + '">';
                            new_attr += '<a class="attr_remove"></a>';
                            new_attr += '<input type="hidden" name="attribute_values[' + attribute_number + '][]" value="' + response.term_id + '">';
                            new_attr += '<input type="hidden" name="attribute_extra_values[' + attribute_number + '][' + response.slug + ']" value="">';
                            new_attr += '<div class="field upload-field clear-after" data-title="Upload Image" data-referer="rad-attr-image">';
                            new_attr += '<label for="field-' + response.slug + '">' + response.name + '</label>';
                            new_attr += '<input type="hidden" id="field-' + response.slug + '" name="' + response.slug + '" value="">';
                            new_attr += '<a href="#" class="upload-button">Browse</a>';
                            new_attr += '<div class="upload-thumb">';
                            new_attr += '<div class="close"><span class="close-icon"></span></div>';
                            new_attr += '<img class="" src="" alt="' + response.slug + '">';
                            new_attr += '</div></div></div>';
                            $fields_container.append(new_attr);
    
                    }

                    $( '.product_attributes' ).unblock();
                });

            } else {
                $( '.product_attributes' ).unblock();
            }

            return false;
        });
    }


    function filter_widget_change_display_type() {
       // Add a new attribute (via ajax) : this function is a customized copy of function defined in woocommerce/assets/js/admin/meta-boxes-product.js
        $(document).on( 'change', 'p.display_type_container select, p.attribute_container select', function(e) {
            e.preventDefault();

            var $widget      = $(this).closest('.widget-content'),
                attribute    = $widget.find('p.attribute_container select').find('option:selected').val(),
                display_type = $widget.find('p.display_type_container select').find('option:selected').val(),
                id           = $widget.find('input[name="w_id"]').val(),
                id_base      = $widget.find('input[name="w_idbase"]').val(),
                number       = $widget.find('input[name="w_number"]').val(),
                ajax_nonce   = $widget.find('input[name="ajax_nonce"]').val(),
                $attr_table  = $widget.find('.rado-widget-attributes-table'),
                $hide_text  = $widget.find('.hide_text_container');

            if(display_type == 'image')
            {
                $hide_text.slideDown();
            }
            else
            {
                $hide_text.slideUp();
            }

            if ( attribute !== undefined &&  (display_type == 'color' || display_type == 'image') ) {

                var data = {
                    action:      'change_attribute_display_type',
                    attribute    : attribute,
                    display_type : display_type,
                    id           : id,
                    id_base      : id_base,
                    number       : number,
                    ajax_nonce   : ajax_nonce
                };
                $attr_table.slideDown();
                $attr_table.addClass('loading');
                $attr_table.find('.wc-loading').removeClass('hide');

                $.post( ajaxurl, data, function( response ) {
                    $attr_table.find('table, .no-term').remove();
                    $attr_table.prepend(response);
                    ColorPicker();
                    //wait a bit to add new elements
                    setTimeout(function() {
                        $attr_table.removeClass('loading');
                        $attr_table.find('.wc-loading').addClass('hide')
                    },100)

                });

            }
            else
            {
                $attr_table.slideUp();
            }

            return false;
        });
        
        //Run colorpicker aftar updating widget
        $( document ).on( 'widget-updated' , function( event, $widget ){
            ColorPicker();
        });
    }

    function video_widget_change_display_type() {
        var video_type_dependencies = function(video_display_type_container) {
            if(video_display_type_container == undefined) {
                video_display_type_container = '.video_display_type_container select';
            }

            var $video_display_type_container = $(video_display_type_container);

            $video_display_type_container.each(function(){
                var $widget      = $(this).closest('.rado-video-widget'),
                    display_type = $(this).find('option:selected').val();

                $widget.removeClass('local_video local_video_popup embeded_video_youtube embeded_video_youtube_popup embeded_video_vimeo embeded_video_vimeo_popup').addClass(display_type);
            });

        }

        video_type_dependencies();

        $( document ).on( 'change', '.video_display_type_container select', function(){
            video_type_dependencies(this);
        });

        $( document ).on( 'widget-updated' , function( event, $widget ) {
            video_type_dependencies();
        });
    }
    
     //Toggle Sections in theme settings with switch
     function toggle_rad_admin_sections($switch_element,$toggle_element1,$toggle_element2){
         
         if($switch_element=='undefined'){// To avoid error at the beginning when we have no $switch
             return;
         }
            $switch_element= $switch_element.next('.switch');

            if($toggle_element1)
            {
                $toggle_element1 = $toggle_element1.parent();
            }

            if($toggle_element2)
            {
                $toggle_element2 = $toggle_element2.parent();
            }

            //initial state
            if( $switch_element.find('.noUi-origin').hasClass("noUi-stacking"))
            {
                if($toggle_element1)
                {
                    $toggle_element1.slideUp('fast');
                    $toggle_element1.hide();
                }

                if($toggle_element2)
                {
                    $toggle_element2.slideDown('fast');
                    $toggle_element2.show();
                }
            }
            else
            {
                if($toggle_element1)
                {
                    $toggle_element1.show();
                    $toggle_element1.slideDown('fast');
                }

                if($toggle_element2)
                {
                    $toggle_element2.hide();
                    $toggle_element2.slideUp('fast');
                }
            }
            
            // when switch was clicked
            $switch_element.on('change', function(){
                if( $switch_element.find('.noUi-origin').hasClass("noUi-stacking"))
                    {
                        if($toggle_element1)
                        {
                            $toggle_element1.slideUp('fast');
                            $toggle_element1.hide();
                        }
                        
                        if($toggle_element2)
                        {
                            $toggle_element2.slideDown('fast');
                            $toggle_element2.show();
                        }
                    }
                else
                    {
                        if($toggle_element1)
                        {
                            $toggle_element1.slideDown('fast');
                            $toggle_element1.show();
                        }

                        if($toggle_element2)
                        {
                            $toggle_element2.hide();
                            $toggle_element2.slideUp('fast');
                        }
                    }
            });
      }
   
    function product_style_dependencies() {
        var $product_style = $('.imageSelect.shop-styles'),
            $product_rating = $('.product_rating');

        $product_style.find('a').on('click',function(){
            product_style_change_handler($(this));
        });

        product_style_change_handler($product_style.find('a.selected'));

        function product_style_change_handler($element)
        {
            $product_rating.slideDown();
        }
    }
	
	function upload_wc_cat_header_img() {
		// Only show the "remove image" button when needed
		if ( '0' === $( '#header_image_id' ).val() ) {
			$( '.remove_wc_cat_header_image_button' ).hide();
		}

		// Uploading files
		var file_frame;

		$( document ).on( 'click', '.upload_wc_cat_header_image_button', function( event ) {

			event.preventDefault();

			// If the media frame already exists, reopen it.
			if ( file_frame ) {
				file_frame.open();
				return;
			}

			// Create the media frame.
			file_frame = wp.media.frames.downloadable_file = wp.media({
				title: 'Choose an image',
				button: {
					text: 'Use image'
				},
				multiple: false
			});

			// When an image is selected, run a callback.
			file_frame.on( 'select', function() {
				var attachment           = file_frame.state().get( 'selection' ).first().toJSON();
				var attachment_thumbnail = attachment.sizes.thumbnail || attachment.sizes.full;

				$( '#cat-header-bg-image' ).val( attachment.id );
				$( '#product_cat_background_image' ).find( 'img' ).attr( 'src', attachment_thumbnail.url );
				$( '.remove_wc_cat_header_image_button' ).show();
			});

			// Finally, open the modal.
			file_frame.open();
		});

		$( document ).on( 'click', '.remove_wc_cat_header_image_button', function() {
			$( '#product_cat_background_image' ).find( 'img' ).attr( 'src', $( '#product_cat_background_image' ).data('default-img') );
			$( '#page-header-bg-image' ).val( '' );
			$( '.remove_wc_cat_header_image_button' ).hide();
			return false;
		});
		
		$( document ).ajaxComplete( function( event, request, options ) {
			if ( request && 4 === request.readyState && 200 === request.status && options.data && 0 <= options.data.indexOf( 'action=add-tag' ) ) {
				// Clear header image and color fields on submit
				$( '#product_cat_background_image' ).find( 'img' ).attr( 'src', $( '#product_cat_background_image' ).data('default-img') );
				$( '.term-header-color-wrap .wp-picker-clear' ).trigger('click');
			}
		});


	}

    function initEditorButtons () {
            var self = this;
            if(typeof tinymce === "undefined")
                    return;

                    var getCurrentColor = function (editor, format) {
                      var color;
                      editor.dom.getParents(editor.selection.getStart(), function (elm) {
                        var value;
                        if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
                          color = color ? color : value;
                        }
                      });
                      return color;
                    };
                    var mapColors = function (colorMap) {
                      var i;
                      var colors = [];
                      for (i = 0; i < colorMap.length; i += 2) {
                        colors.push({
                          text: colorMap[i + 1],
                          color: '#' + colorMap[i]
                        });
                      }
                      return colors;
                    };
                    var applyFormat = function (editor, format, values) {
                      editor.undoManager.transact(function () {
                        editor.focus();
                        var output = insertStyle(editor,format, values);
                        editor.execCommand('mceInsertContent', 0, output);

                        //editor.formatter.apply(format, { value: value });
                        editor.nodeChanged();
                      });
                    };
                    var removeFormat = function (editor, format, values) {
                      editor.undoManager.transact(function () {
                        editor.focus();
                        var output = removeStyle(editor, format, values);
                        //editor.formatter.remove(format, { value: null }, null);
                        editor.nodeChanged();
                      });
                    };
                    var TextColor = {
                      getCurrentColor: getCurrentColor,
                      mapColors: mapColors,
                      applyFormat: applyFormat,
                      removeFormat: removeFormat
                    };

                    var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');

                    var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');

                    var defaultColorMap = [
                      '000000','Black','993300','Burnt orange','333300','Dark olive','003300','Dark green','003366','Dark azure','000080','Navy Blue','333399','Indigo','333333','Very dark gray','800000','Maroon','FF6600','Orange','808000','Olive','008000','Green','008080','Teal','0000FF','Blue','666699','Grayish blue','808080','Gray','FF0000','Red','FF9900','Amber','99CC00','Yellow green','339966','Sea green','33CCCC','Turquoise','3366FF','Royal blue','800080','Purple','999999','Medium gray','FF00FF','Magenta','FFCC00','Gold','FFFF00','Yellow','00FF00','Lime','00FFFF','Aqua','00CCFF','Sky blue','993366','Red violet','FFFFFF','White','FF99CC','Pink','FFCC99','Peach','FFFF99','Light yellow','CCFFCC','Pale green','CCFFFF','Pale cyan','99CCFF','Light sky blue','CC99FF','Plum'
                    ];
                    var getTextColorMap = function (editor) {
                      return editor.getParam('textcolor_map', defaultColorMap);
                    };
                    var getForeColorMap = function (editor) {
                      return editor.getParam('forecolor_map', getTextColorMap(editor));
                    };
                    var getBackColorMap = function (editor) {
                      return editor.getParam('backcolor_map', getTextColorMap(editor));
                    };
                    var getTextColorRows = function (editor) {
                      return editor.getParam('textcolor_rows', 5);
                    };
                    var getTextColorCols = function (editor) {
                      return editor.getParam('textcolor_cols', 8);
                    };
                    var getForeColorRows = function (editor) {
                      return editor.getParam('forecolor_rows', getTextColorRows(editor));
                    };
                    var getBackColorRows = function (editor) {
                      return editor.getParam('backcolor_rows', getTextColorRows(editor));
                    };
                    var getForeColorCols = function (editor) {
                      return editor.getParam('forecolor_cols', getTextColorCols(editor));
                    };
                    var getBackColorCols = function (editor) {
                      return editor.getParam('backcolor_cols', getTextColorCols(editor));
                    };
                    var getColorPickerCallback = function (editor) {
                      return editor.getParam('color_picker_callback', null);
                    };
                    var hasColorPicker = function (editor) {
                      return typeof getColorPickerCallback(editor) === 'function';
                    };
                    var Settings = {
                      getForeColorMap: getForeColorMap,
                      getBackColorMap: getBackColorMap,
                      getForeColorRows: getForeColorRows,
                      getBackColorRows: getBackColorRows,
                      getForeColorCols: getForeColorCols,
                      getBackColorCols: getBackColorCols,
                      getColorPickerCallback: getColorPickerCallback,
                      hasColorPicker: hasColorPicker
                    };

                    var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');

                    var getHtml = function (cols, rows, colorMap, hasColorPicker) {
                      var colors, color, html, last, x, y, i, count = 0;
                      var id = global$1.DOM.uniqueId('mcearia');
                      var getColorCellHtml = function (color, title) {
                        var isNoColor = color === 'transparent';
                        return '<td class="mce-grid-cell' + (isNoColor ? ' mce-colorbtn-trans' : '') + '">' + '<div id="' + id + '-' + count++ + '"' + ' data-mce-color="' + (color ? color : '') + '"' + ' role="option"' + ' tabIndex="-1"' + ' style="' + (color ? 'background-color: ' + color : '') + '"' + ' title="' + global$3.translate(title) + '">' + (isNoColor ? '&#215;' : '') + '</div>' + '</td>';
                      };
                      colors = TextColor.mapColors(colorMap);
                      colors.push({
                        text: global$3.translate('No color'),
                        color: 'transparent'
                      });
                      html = '<table class="mce-grid mce-grid-border mce-colorbutton-grid" role="list" cellspacing="0"><tbody>';
                      last = colors.length - 1;
                      for (y = 0; y < rows; y++) {
                        html += '<tr>';
                        for (x = 0; x < cols; x++) {
                          i = y * cols + x;
                          if (i > last) {
                            html += '<td></td>';
                          } else {
                            color = colors[i];
                            html += getColorCellHtml(color.color, color.text);
                          }
                        }
                        html += '</tr>';
                      }
                      if (hasColorPicker) {
                        html += '<tr>' + '<td colspan="' + cols + '" class="mce-custom-color-btn">' + '<div id="' + id + '-c" class="mce-widget mce-btn mce-btn-small mce-btn-flat" ' + 'role="button" tabindex="-1" aria-labelledby="' + id + '-c" style="width: 100%">' + '<button type="button" role="presentation" tabindex="-1">' + global$3.translate('Custom...') + '</button>' + '</div>' + '</td>' + '</tr>';
                        html += '<tr>';
                        for (x = 0; x < cols; x++) {
                          html += getColorCellHtml('', 'Custom color');
                        }
                        html += '</tr>';
                      }
                      html += '</tbody></table>';
                      return html;
                    };
                    var ColorPickerHtml = { getHtml: getHtml };

                    var onButtonClick = function (editor) {
                      return function (e) {
                        var ctrl = e.control,
                            value_array;

                        if (ctrl._color) {
                            value_array = {
                                class : ctrl.settings.target_classname,
                                color : ctrl._color
                            }
                            
                        } else {
                            value_array = {
                                class : ctrl.settings.target_classname,
                                color : ''
                            }
                        }

                        editor.execCommand('rad_mceApplycolor', ctrl.settings.format,value_array);

                      };
                    };

                    var onPanelClick = function (editor, cols) {
                      return function (e) {

                        var buttonCtrl = this.parent();
                        var value;
                        var currentColor = TextColor.getCurrentColor(editor, buttonCtrl.settings.format);
                        var selectColor = function (value) {
                            var value_array = {
                                class : buttonCtrl.settings.target_classname,
                                color : value
                            }
                            editor.execCommand('rad_mceApplycolor', buttonCtrl.settings.format, value_array);
                            buttonCtrl.hidePanel();
                            buttonCtrl.color(value);
                        };
                        var resetColor = function () {
                            var value_array = {
                                class : buttonCtrl.settings.target_classname,
                            }
                          editor.execCommand('rad_mceRemovecolor', buttonCtrl.settings.format, value_array);
                          buttonCtrl.hidePanel();
                          buttonCtrl.resetColor();
                        };
                        value = e.target.getAttribute('data-mce-color');
                        if (value) {
                          if (this.lastId) {
                            global$1.DOM.get(this.lastId).setAttribute('aria-selected', 'false');
                          }
                          e.target.setAttribute('aria-selected', true);
                          this.lastId = e.target.id;
                          if (value === 'transparent') {
                            resetColor();
                          } else {
                            selectColor(value);
                          }
                        } else if (value !== null) {
                          buttonCtrl.hidePanel();
                        }
                      };
                    };

                    var renderColorPicker = function (editor, foreColor) {
                      return function () {
                        var cols = foreColor ? Settings.getForeColorCols(editor) : Settings.getBackColorCols(editor);
                        var rows = foreColor ? Settings.getForeColorRows(editor) : Settings.getBackColorRows(editor);
                        var colorMap = foreColor ? Settings.getForeColorMap(editor) : Settings.getBackColorMap(editor);
                        var hasColorPicker = Settings.hasColorPicker(editor);
                        return ColorPickerHtml.getHtml(cols, rows, colorMap, hasColorPicker);
                      };
                    };

            var TextFont = {
                applyFormat: applyFormat
            }

            tinymce.create('tinymce.plugins.RadoTypographPlugin', {
                init: function(ed, url){

                    ed.addCommand('rad_mceApplycolor', function (format, values) {
                        TextColor.applyFormat(ed, format, values);
                    });
                    ed.addCommand('rad_mceRemovecolor', function (format, values) {
                        TextColor.removeFormat(ed, format, values);
                    });
                    ed.addCommand('rad_mceApplyfont', function (values) {
                        TextFont.applyFormat(ed, 'font', values);
                    });
                    ed.addCommand('rad_mceApplyLineHeight', function (values) {
                        TextFont.applyFormat(ed, 'line-height', values);
                    });
                    ed.addCommand('rad_mceApplyLetterSpaing', function (values) {
                        TextFont.applyFormat(ed, 'letter-spacing', values);
                    });

                    ed.on('Change keyup AddEditor', function(e) {
                        var content = ed.getContent();
                        if(ed.id == "wpb_tinymce_content") // fire rad_editor_change just on VC editor
                        {
                            //tinymce.ui.FloatPanel.prototype.moveRel($('.rad_editor'),'br-tl');
                            
                            $('body').trigger('rad_editor_change',[{content : content}]);
                        }
                        
                    });

                    ed.addButton('rad_underline1',
                    {
                        type: 'colorbutton',
                        name: 'rad-underline1',
                        image: url + '/../img/tinymce/underline.png',
                        format : 'linecolor',
                        tooltip : 'Underline style1',
                        target_classname: 'rad-underline1',
                        classes: 'rad-underline1-button rad-editor-btn',
                        panel: {
                          role: 'application',
                          ariaRemember: true,
                          html: renderColorPicker(ed, true),
                          onclick: onPanelClick(ed, Settings.getForeColorCols(ed))
                        },
                        onclick: onButtonClick(ed),
                        onPostRender: function() {
                            var _this = this;   // reference to the button itself
                            ed.on('NodeChange', function(e) {
                                _this.active(e.element.className == 'rad-underline1');

                            })
                        }

                    });

                    ed.addButton('rad_underline2',
                    {
                        type: 'colorbutton',
                        name: 'rad-underline2',
                        image: url + '/../img/tinymce/underline.png',
                        format : 'linecolor',
                        tooltip : 'Underline style2',
                        target_classname: 'rad-underline2',
                        classes: 'rad-underline2-button rad-editor-btn',
                        panel: {
                          role: 'application',
                          ariaRemember: true,
                          html: renderColorPicker(ed, true),
                          onclick: onPanelClick(ed, Settings.getForeColorCols(ed))
                        },
                        onclick: onButtonClick(ed),
                        onPostRender: function() {
                            var _this = this;   // reference to the button itself
                            ed.on('NodeChange', function(e) {
                                _this.active(e.element.className == 'rad-underline2');

                            })
                        }
                    });

                    ed.addButton('rad_underline3',
                    {
                        type: 'colorbutton',
                        name: 'rad-underline3',
                        image: url + '/../img/tinymce/underline.png',
                        tooltip : 'Underline style3',
                        format : 'linecolor',
                        target_classname: 'rad-underline3',
                        classes: 'rad-underline3-button rad-editor-btn',
                        panel: {
                          role: 'application',
                          ariaRemember: true,
                          html: renderColorPicker(ed, true),
                          onclick: onPanelClick(ed, Settings.getForeColorCols(ed))
                        },
                        onclick: onButtonClick(ed),
                        onPostRender: function() {
                            var _this = this;   // reference to the button itself
                            ed.on('NodeChange', function(e) {
                                _this.active(e.element.className == 'rad-underline3');

                            })
                        }
                    });

                    ed.addButton('rad_interactive_underline',
                    {
                        type: 'colorbutton',
                        name: 'rad-interactive-underline',
                        image: url + '/../img/tinymce/underline-interactive.png',
                        tooltip : 'Interactive Underline',
                        format : 'linecolor',
                        target_classname: 'rad-interactive-underline',
                        classes: 'rad-interactive-underline-button rad-editor-btn',
                        panel: {
                          role: 'application',
                          ariaRemember: true,
                          html: renderColorPicker(ed, true),
                          onclick: onPanelClick(ed, Settings.getForeColorCols(ed))
                        },
                        onclick: onButtonClick(ed),
                        onPostRender: function() {
                            var _this = this;   // reference to the button itself
                            ed.on('NodeChange', function(e) {
                                _this.active(e.element.className == 'rad-interactive-underline');

                            })
                        }
                    });

                    ed.addButton('rad_background',
                    {
                        type: 'colorbutton',
                        name: 'rad-background',
                        format : 'backcolor',
                        image: url + '/../img/tinymce/background.png',
                        //text: 'Background',
                        tooltip : 'Background',
                        target_classname: 'rad-background',
                        classes: 'rad-background-button rad-editor-btn',
                        panel: {
                          role: 'application',
                          ariaRemember: true,
                          html: renderColorPicker(ed, true),
                          onclick: onPanelClick(ed, Settings.getForeColorCols(ed))
                        },
                        onclick: onButtonClick(ed),
                        onPostRender: function() {
                            var _this = this;   // reference to the button itself
                            ed.on('NodeChange', function(e) {
                                _this.active(e.element.className == 'rad-background');

                            })
                        }
                    });

                    if(RADData.fonts_collection != '')
                    {

                        var rad_fonts = JSON.parse(RADData.fonts_collection);
                        
                        ed.addButton('rad_font', {
                          type: 'listbox',
                          format: 'font',
                          text: 'Font',
                          icon: false,
                          name: 'rad-font',
                          classes: 'rad-font-button rad-editor-btn',
                          onselect: function(e) {
                            tinymce.execCommand('rad_mceApplyfont',this.value());
                          },
                          values: rad_fonts,
                        });
                    }


                    ed.addButton('rad_lineheight', {
                      type: 'listbox',
                      format: 'line-height',
                      text: 'Line height',
                      icon: false,
                      name: 'rad-line-height',
                      classes: 'rad-line-height-button rad-editor-btn',
                      onselect: function(e) {
                        tinymce.execCommand('rad_mceApplyLineHeight',this.value());
                      },
                      values: [
                          { text : "10px", value : "10px"},
                          { text : "11px", value : "11px"},
                          { text : "12px", value : "12px"},
                          { text : "13px", value : "13px"},
                          { text : "14px", value : "14px"},
                          { text : "15px", value : "15px"},
                          { text : "16px", value : "16px"},
                          { text : "17px", value : "17px"},
                          { text : "18px", value : "18px"},
                          { text : "19px", value : "19px"},
                          { text : "20px", value : "20px"},
                          { text : "21px", value : "21px"},
                          { text : "22px", value : "22px"},
                          { text : "23px", value : "23px"},
                          { text : "24px", value : "24px"},
                          { text : "25px", value : "25px"},
                          { text : "26px", value : "26px"},
                          { text : "27px", value : "27px"},
                          { text : "28px", value : "28px"},
                          { text : "29px", value : "29px"},
                          { text : "30px", value : "30px"},
                          { text : "31px", value : "31px"},
                          { text : "32px", value : "32px"},
                          { text : "33px", value : "33px"},
                          { text : "34px", value : "34px"},
                          { text : "35px", value : "35px"},
                          { text : "36px", value : "36px"},
                          { text : "37px", value : "37px"},
                          { text : "38px", value : "38px"},
                          { text : "39px", value : "39px"},
                          { text : "40px", value : "40px"},
                          { text : "41px", value : "41px"},
                          { text : "42px", value : "42px"},
                          { text : "43px", value : "43px"},
                          { text : "44px", value : "44px"},
                          { text : "45px", value : "45px"},
                          { text : "46px", value : "46px"},
                          { text : "47px", value : "47px"},
                          { text : "48px", value : "48px"},
                          { text : "49px", value : "49px"},
                          { text : "50px", value : "50px"},
                          { text : "51px", value : "51px"},
                          { text : "52px", value : "52px"},
                          { text : "53px", value : "53px"},
                          { text : "54px", value : "54px"},
                          { text : "55px", value : "55px"},
                          { text : "56px", value : "56px"},
                          { text : "57px", value : "57px"},
                          { text : "58px", value : "58px"},
                          { text : "59px", value : "59px"},
                          { text : "60px", value : "60px"},
                          { text : "61px", value : "61px"},
                          { text : "62px", value : "62px"},
                          { text : "63px", value : "63px"},
                          { text : "64px", value : "64px"},
                          { text : "65px", value : "65px"},
                          { text : "66px", value : "66px"},
                          { text : "67px", value : "67px"},
                          { text : "68px", value : "68px"},
                          { text : "69px", value : "69px"},
                          { text : "70px", value : "70px"},
                          { text : "71px", value : "71px"},
                          { text : "72px", value : "72px"},
                          { text : "73px", value : "73px"},
                          { text : "74px", value : "74px"},
                          { text : "75px", value : "75px"},
                          { text : "76px", value : "76px"},
                          { text : "77px", value : "77px"},
                          { text : "78px", value : "78px"},
                          { text : "79px", value : "79px"},
                          { text : "80px", value : "80px"},
                      ],

                    });

                    ed.addButton('rad_letterspacing', {
                      type: 'listbox',
                      format: 'letter-spacing',
                      text: 'Letter spacing',
                      icon: false,
                      name: 'rad-letter-spacing',
                      classes: 'rad-letter-spacing-button rad-editor-btn',
                      onselect: function(e) {
                        tinymce.execCommand('rad_mceApplyLetterSpaing',this.value());
                      },
                      values: [
                          { text : "Default", value : "default"},
                          { text : "0px", value : "0px"},
                          { text : "1px", value : "1px"},
                          { text : "2px", value : "2px"},
                          { text : "3px", value : "3px"},
                          { text : "4px", value : "4px"},
                          { text : "5px", value : "5px"},
                          { text : "6px", value : "6px"},
                          { text : "7px", value : "7px"},
                          { text : "8px", value : "8px"},
                          { text : "9px", value : "9px"},
                          { text : "10px", value : "10px"},
                          { text : "11px", value : "11px"},
                          { text : "12px", value : "12px"},
                          { text : "13px", value : "13px"},
                          { text : "14px", value : "14px"},
                          { text : "15px", value : "15px"},
                          { text : "16px", value : "16px"},
                          { text : "17px", value : "17px"},
                          { text : "18px", value : "18px"},
                          { text : "19px", value : "19px"},
                          { text : "20px", value : "20px"},
                      ],

                    });

                    

                    
                    
                },
                getInfo: function() {
                  return {
                    longname : 'Aventa plugin - editor buttons',
                    author : 'Rado-studio',
                    authorurl : 'https://www.Rado-studio.com',
                    version : "1.0"
                  };
                }
              });
              tinymce.PluginManager.add( 'RadoTypographExtenssion', tinymce.plugins.RadoTypographPlugin );
        }

        function get_font_variant_attribute(variant) {
            if($.isNumeric(variant))
            {
                return 'font-weight:' + variant + ';';
            }
            else if (variant == 'regular') {
                return 'font-weight:normal;';
            }
            else if (variant == 'italic') {
                return 'font-style:italic;';
            }
            else if (variant.indexOf("italic") >= 0) {
                return 'font-style:italic;font-weight:' + variant.replace('italic','') + ';';
            }

            return '';
        }

        function is_typographycal_tag(elem_type,$elem,selected_text)
        {
            if(elem_type == 'SPAN' || elem_type == 'P' || elem_type == 'H1' || elem_type == 'H2' || elem_type == 'H3' || elem_type == 'H4' || elem_type == 'H5' || elem_type == 'H6')
            {
                if(selected_text == $elem.html())
                {
                    return true;
                }               
            }

            return false;
        }

        function insertStyle (ed, format, values) {

            var output = '',
                selected_text = ed.selection.getContent(), // Get selected element
                $elem = $(ed.selection.getNode()),// Get selected element
                elem_type = ed.selection.getNode().nodeName; // Get element type
                

            if(format == 'linecolor')
            {
                var className = values.class,
                    value = values.color;

                if(is_typographycal_tag(elem_type,$elem,selected_text))
                {
                    if($elem.hasClass(className))
                    {

                        if($elem.css('border-color') != value)
                        {
                            $elem.css('border-color', value);
                            $elem.attr('data-mce-style',$elem.attr('style'));
                            output = $elem.get(0).outerHTML;
                        }
                        else
                        {
                            output = selected_text;
                        }

                    }
                    else
                    {

                        $elem.removeClass('rad-underline1 rad-underline2 rad-underline3 rad-interactive-underline')
                        $elem.addClass(className).css('border-color', value);
                        $elem.attr('data-mce-style',$elem.attr('style'));
                        output = $elem.get(0).outerHTML;
                    }

                    
                }
                else
                {
                    
                    output =  '<span class="' + className +'" data-mce-style="border-color:'+ value +'" style="border-color:'+ value +'">' + selected_text +'</span>';
                }
            }
            else if(format == 'backcolor')
            {
                var className = values.class,
                    value = values.color;

                if(is_typographycal_tag(elem_type,$elem,selected_text))
                {
                    if($elem.hasClass(className))
                    {

                        if($elem.css('background-color') != value)
                        {
                            $elem.css('background-color', value);
                            $elem.attr('data-mce-style',$elem.attr('style'));
                            output = $elem.get(0).outerHTML;
                        }
                        else
                        {
                            output = selected_text;
                        }

                    }
                    else
                    {
                        $elem.addClass(className).css('background-color', value);
                        $elem.attr('data-mce-style',$elem.attr('style'));
                        output = $elem.get(0).outerHTML;
                    }
                }
                else
                {   
                    output =  '<span class="' + className +'" data-mce-style="background-color:'+ value +'" style="background-color:'+ value +'">' + selected_text +'</span>';
                }
            }
            else if(format == 'font')
            {
                var values_array = values.split(':'),
                    font = values_array[0],
                    font_variant = values_array[1];

                if(font == 'theme_default' || font == 'theme_default_medium' || font == 'theme_default_bold')
                {
                    font = 'inherit';
                }

                if(is_typographycal_tag(elem_type,$elem,selected_text))
                {
                    if(font == 'inherit')
                    {
                        $elem.css('font-family', '');
                    }
                    else
                    {
                        $elem.css('font-family', font);
                    }

                    if(font_variant == 'regular')
                    {
                        $elem.css('font-weight', '');
                    }
                    else
                    {
                        var new_variant = get_font_variant_attribute(font_variant);
                        new_variant_arr = new_variant.split(';');
                        $.each(new_variant_arr,function(index, value ){
                            var css = value.split(":");
                            $elem.css(css[0], css[1]);
                        });
                    }
                    
                    $elem.attr('data-mce-style',$elem.attr('style'));
                    output = $elem.get(0).outerHTML;
                    
                }
                else
                {
                    if(font == 'inherit' && font_variant == 'normal')
                    {
                        output =  selected_text;
                    }
                    else if(font == 'inherit' && font_variant == '700')
                    {
                        output =  '<span style="font-weight:700;">' + selected_text +'</span>';

                    }
                    else
                    {
                        var new_variant = get_font_variant_attribute(font_variant);
                        new_variant_arr = new_variant.split(';');
                        
                        output =  '<span style="font-family:'+ font +';';
                        var font_styles = '';
                        $.each(new_variant_arr,function(index, value){
                            var css = value.split(":");
                            font_styles += css[0] + ":"+ css[1] + ";";
                        });
                        output += font_styles + '" data-mce-style="font-family:'+ font +';' + font_styles +'" >' + selected_text +'</span>';
                    }
                }
            }
            else if(format == 'line-height')
            {
                if(values == 'default')
                {
                    values = '';
                }

                if(is_typographycal_tag(elem_type,$elem,selected_text))
                {
                    $elem.css('line-height', values);
                    //$elem.attr('data-mce-style',$elem.attr('style'));
                    output = $elem.get(0).outerHTML;
                    
                }
                else
                {
                    if(values == '')
                    {
                        output =  selected_text;
                    }
                    else
                    {
                        //data-mce-style="line-height:'+ values +';"
                        output =  '<span style="line-height:'+ values +';">' + selected_text +'</span>';
                    }
                }
            }
            else if(format == 'letter-spacing')
            {
                if(values == 'default')
                {
                    values = '';
                }

                if(is_typographycal_tag(elem_type,$elem,selected_text))
                {

                    $elem.css('letter-spacing', values);
                    //$elem.attr('data-mce-style',$elem.attr('style'));
                    output = $elem.get(0).outerHTML;
                    
                }
                else
                {
                    if(values == '')
                    {
                        output =  selected_text;
                    }
                    else
                    {
                        //data-mce-style="letter-spacing:'+ values +';"
                        output =  '<span style="letter-spacing:'+ values +';">' + selected_text +'</span>';
                    }
                }
            }
            
            return output;
        }

        function removeStyle (ed, format, values) {
            var output = '',
                node = ed.selection.getNode(),
                $elem = $(node),// Get selected element
                selected_text = $elem.html(), // Get selected element
                elem_type = ed.selection.getNode().nodeName, // Get element type
                className = values.class;                

            if(format == 'linecolor')
            {
                if(elem_type == 'SPAN')
                {
                    if(className == 'rad-underline1')
                        $elem.removeClass(' rad-underline1')
                    else if(className == 'rad-underline2')
                        $elem.removeClass(' rad-underline2')
                    else if(className == 'rad-underline3')
                        $elem.removeClass(' rad-underline3')
                    else
                        $elem.removeClass('rad-interactive-underline');


                    if(!$elem.hasClass('rad-underline1') && !$elem.hasClass('rad-underline2') && !$elem.hasClass('rad-underline3') && !$elem.hasClass('rad-interactive-underline'))
                    {
                        var style = $elem.attr('style'),
                            mce_style = $elem.attr('data-mce-style');

                        if(mce_style  == style)
                        {
                            $elem.css('border-color', '');
                            $elem.data('mce-style', '');
                        }
                    }

                    if($elem.attr('class') == '' && $elem.data('mce-style') == '')
                    {
                        output =  selected_text;
                    }
                    else
                    {
                        output = $elem.get(0).outerHTML;
                    }
                    
                }
                else
                {
                    output =  selected_text;
                }
            }
            else if(format == 'backcolor')
            {
                if(elem_type == 'SPAN')
                {
                    var style = $elem.attr('style'),
                        mce_style = $elem.attr('data-mce-style');

                    $elem.css('background-color', '');

                    if(mce_style  == style)
                    {
                        $elem.removeAttr('data-mce-style');
                    }


                    $elem.removeClass('rad-background').css('background-color', '');

                    if($elem.attr('class') == '' && !node.hasAttribute("data-mce-style"))
                    {
                        $elem.removeAttr('class');
                        $elem.removeAttr('style');
                        output =  selected_text;
                    }
                    else
                    {
                        output = $elem.get(0).outerHTML;
                    }
                    
                }
                else
                {
                    output =  selected_text;
                }
            }
            
            $elem.replaceWith(output);
            return output;
        }

    function section_tabs()
    {
        var $tabs = $('.section-tabs li');
        $tabs.on('click',function(){
            var $this = $(this),
                key = $(this).data('class');
            $this.siblings('.active').removeClass('active');
            $this.addClass('active');
            $this.parent('ul').siblings('.section').removeClass('active');
            $this.parent('ul').siblings('.' + key).addClass('active');
        })
    }

    $(document).ready(function () {
        section_tabs();
        initEditorButtons();
        FieldSelector();
        CSVInput();
        ImageSelect();
        Save_Button();
        Thickbox();
        Tooltips();
        Sliders();
        ColorPicker();
        Combobox();
        Chosen();
        Tabs();
        Sidebar_Accordion();
        ImageFields();
        menu();
        iconSelect();
        demo_importer();
        preloader();
        product_variation();
        product_style_dependencies();
        filter_widget_change_display_type();
        video_widget_change_display_type();
		upload_wc_cat_header_img();
        product_image_attributes();


        toggle_rad_admin_sections($('input[name="rss"]'),$('#field-social'),$('#field-social_rss_url'));//Toggle RSS & '#field-social' this is for making switch to work, such element don't exist
        toggle_rad_admin_sections($('input[name="related_product"]'),null,$('input[name="related_product_display"],[name="related_product_width"]'));//woocommerce related product mode
        toggle_rad_admin_sections($('input[name="catalog_mode"]'),null,$('input[name="catalog_mode_price"]'));//woocommerce catalog mode
        toggle_rad_admin_sections($('input[name="social_share_display"]'),null,$('input[name="social_share_google"],[name="social_share_facebook"],[name="social_share_mail"],[name="social_share_twitter"],[name="social_share_pinterest"]'));//social share 

        setTimeout(function(){
            setRowTypeIcon();
        },800);
        menuDependencies();


        $('#vc_ui-panel-edit-element span.vc_ui-button-action').on('click',function(){
            setTimeout(function(){
                setRowTypeIcon();
            },200);
        });

        
        if(typeof window.VcBackendTtaTabsView != "undefined")
        {

        
            window.RADBackendTtaTabsView = window.VcBackendTtaTabsView.extend({
                addSection : function(prepend) {
                        var params;
                        return params = {
                            shortcode: "rad_tta",
                            params: {
                                title: this.defaultSectionTitle
                            },
                            parent_id: this.model.get("id"),
                            order: _.isBoolean(prepend) && prepend ? vc.add_element_block_view.getFirstPositionIndex() : vc.shortcodes.getNextOrder(),
                            prepend: prepend
                        }, vc.shortcodes.create(params)
                }
            });

            RADBackendTtaTourView = window.VcBackendTtaTourView.extend({
                addSection : function(prepend) {
                    var params;
                    return params = {
                        shortcode: "rad_tta",
                        params: {
                            title: this.defaultSectionTitle
                        },
                        parent_id: this.model.get("id"),
                        order: _.isBoolean(prepend) && prepend ? vc.add_element_block_view.getFirstPositionIndex() : vc.shortcodes.getNextOrder(),
                        prepend: prepend
                    }, vc.shortcodes.create(params)
                }
            });

            RADBackendTtaAccordionView = window.VcBackendTtaAccordionView.extend({
                addSection : function(prepend) {
                    var params;
                    return params = {
                        shortcode: "rad_tta",
                        params: {
                            title: this.defaultSectionTitle
                        },
                        parent_id: this.model.get("id"),
                        order: _.isBoolean(prepend) && prepend ? vc.add_element_block_view.getFirstPositionIndex() : vc.shortcodes.getNextOrder(),
                        prepend: prepend
                    }, vc.shortcodes.create(params)
                }
            });

            RADBackendTtaCarouselGalleryView = window.VcBackendTtaAccordionView.extend({
                addSection : function(prepend) {
                        var params;
                        return params = {
                            shortcode: "rad_gallery_item",
                            params: {
                                title: RADData.carousel_gallery_new_item
                            },
                            parent_id: this.model.get("id"),
                            order: _.isBoolean(prepend) && prepend ? vc.add_element_block_view.getFirstPositionIndex() : vc.shortcodes.getNextOrder(),
                            prepend: prepend
                        }, vc.shortcodes.create(params)
                }
            });

            RADBackendTtaTestimonialView = window.VcBackendTtaAccordionView.extend({
                addSection : function(prepend) {
                        var params;
                        return params = {
                            shortcode: "rad_testimonial_item",
                            params: {
                                name: RADData.testimonial_new_item
                            },
                            parent_id: this.model.get("id"),
                            order: _.isBoolean(prepend) && prepend ? vc.add_element_block_view.getFirstPositionIndex() : vc.shortcodes.getNextOrder(),
                            prepend: prepend
                        }, vc.shortcodes.create(params)
                }
            });

            RADBackendTtaSlideshowView = window.VcBackendTtaAccordionView.extend({
                addSection : function(prepend) {
                    var params;
                    return params = {
                        shortcode: "rad_slideshow_item",
                        params: {
                            title: RADData.carousel_gallery_new_item
                        },
                        parent_id: this.model.get("id"),
                        order: _.isBoolean(prepend) && prepend ? vc.add_element_block_view.getFirstPositionIndex() : vc.shortcodes.getNextOrder(),
                        prepend: prepend
                    }, vc.shortcodes.create(params)
                }
            });
        }


    });

})(jQuery);