(function($){
    "use strict";

    $.fn.pixeColumn = function(){
        var editor = $(this);
        $.pixeColumn.bindToolbar(editor);
        $.pixeColumn.bindColumnWidthResize(editor);
        $.pixeColumn.bindColumnPaddingResize(editor);

        // column size
        editor.on('mouseenter', '.pixe-column', function(){
            var column = $(this);
            var columnWidth = $(this).outerWidth();
            if( columnWidth < 130 ){
                column.attr('data-size', 's');
            }else if( columnWidth < 190 ){
                column.attr('data-size', 'm');
            }else if( columnWidth < 305 ){
                column.attr('data-size', 'l');
            }else{
                column.removeAttr('data-size');
            }

            var breakpoint = 300;
            if( $.pixeEditor.viewport != 'desktop' ){
                breakpoint = 180;
            }
            if( column.offset().left + breakpoint > window.innerWidth ){
                column.addClass('pixe-right-toolbar');
            }else{
                column.removeClass('pixe-right-toolbar');
            }
        });
    };

    $.pixeColumn = {

        minimizeSize: 15,
        defaultPadding: { top: '15px', bottom: '15px' },

        getPercentSizes: function(size){
            var sizeP = $.pixeColumnSize.percent;
            var sizeC = $.pixeColumnSize.column;
            return sizeP[sizeC.indexOf(size)];
        },
        getColSizes: function(size, step = 0){
            var sizeP = $.pixeColumnSize.percent;
            var sizeC = $.pixeColumnSize.column;

            var index;
            var diff = 100;

            // loop to find nearest size
            for( var i in sizeP ){
                if( Math.abs(sizeP[i] - size) < diff ){     
                    index = i;
                    diff = Math.abs(sizeP[i] - size);
                }
            }

            // increase step
            if( step > 0 ){
                if( sizeP[index] - 1 <= size && sizeP[parseInt(index) + 1] ){
                    index++;
                }
            }else if( step < 0 ){
                if( sizeP[index] + 1 >= size && index > 0 ){
                    index--;
                }
            }
            
            return sizeC[index];
        },

        create: function(settings = {}, render = true, preview = false, container){
            settings = $.extend({
                _type: 'column'
            }, settings);

            var t = this;
            var column = $('<div class="pixe-column" ></div>');
            column.data('settings', settings);
            if( container ){
                container.append(column);
            }

            if( preview ){
                column.data('preview', true);
            }
            column.append('<style></style>');

            // set column id
            if( settings._id ){ column.attr('data-id', settings._id); }
            if( settings.id ){ column.attr('id', settings.id); }

            // init width
            if( !settings.width ){ settings.width = '1/1'; }

            // settings
            if( settings._subtype ){ 
                column.attr('data-type', settings._subtype); 

                if( settings._subtype == 'query' ){
                    column.addClass('pixe-query-' + pixeData.templateLayout);
                }
            }

            // toolbar
            if( !preview ){
                column.append(t.getToolbar(column));
            }

            // extra class before initiate inner elements
            t.renderStyle(column, 'propagate-hover', undefined, false);

            // content area & background
            var columnContent = $('<div class="pixe-column-content" ></div>');
            columnContent.appendTo(column);
            columnContent.append('<div class="pixe-bg-style" ></div>');
            if( settings._elements ){
                $.pixeEditor.render(settings._elements, true, preview, columnContent);
            }

            if( !preview ){
                
                // area
                column.append('<div class="pixe-column-area"></div>');

                // resize bar
                if( settings._subtype == 'carousel' ){
                    // do nothing
                }else{
                    var resize = $('<div class="pixe-column-resize" ></div>');
                    resize.append('<input class="pixe-size-text" type="text" ></div>');
                    resize.append('<div class="pixe-handler" ></div>');
                    resize.append('<div class="pixe-new" ><div class="pixe-svg-preset pixe-svg-column-new" ></div></div>');
                    column.append(resize);

                    // padding resize
                    var html  = '<div class="pixe-settings" >';
                        html += '<input type="text" />';
                        html += '</div>';
                    var topHandler = $('<div class="pixe-column-padding-resize pixe-top" ></div>');
                    topHandler.append(html);
                    topHandler.appendTo(column);
                    var bottomHandler = $('<div class="pixe-column-padding-resize pixe-bottom" ></div>');
                    bottomHandler.append(html);
                    bottomHandler.appendTo(column);
                }
            }

            // style for this element;
            if( render ){ t.render(column); }
            
            return column;
        },
        render: function(column, type){
            if( !column.data('settings') ) return;
            
            var t = this;
            if( type ){
                t.renderStyle(column, type);
                return;
            }

            // render styles
            t.renderStyle(column, 'item', undefined, true);
        },
        renderStyle: function(column, type, subtype, renderCss = true){
            if( !column.data('settings') ) return;
            
            var t = this;

            // check css for pro featured
            if( !t.proRenderStyle || !t.proRenderStyle(column, type, subtype) ){
                switch(type){
                    case 'class':
                    case 'id':
                    case 'responsive':
                        $.pixeSetAdvanceStyle(column, type);
                        break;
                    case 'shape-divider':
                    case 'shape-divider-top':
                    case 'shape-divider-bottom':
                    case 'tablet-shape-divider-top':
                    case 'tablet-shape-divider-bottom':
                    case 'mobile-shape-divider-top':
                    case 'mobile-shape-divider-bottom':
                        $.pixeShapeDividerStyle(column, '.pixe-column-content');
                        break;
                    case 'padding':
                    case 'tablet-padding':
                    case 'mobile-padding':
                    case 'margin':
                    case 'tablet-margin':
                    case 'mobile-margin':
                        t.setSpacingStyle(column);
                        break;
                    case 'bg-media':
                        $.pixeSetBackgroundMedia(column, '.pixe-column-content', subtype);
                        break;
                    case 'bg-style':
                        t.setBackgroundStyle(column);
                        break;
                    case 'width':
                    case 'tablet-width':
                    case 'mobile-width':
                        t.setWidthStyle(column);
                        t.setWidthText(column);
                        break;
                    case 'animation':
                    case 'tablet-animation':
                    case 'mobile-animation':
                        $.pixeSetAnimationStyle(column);
                        break;
                    case 'scroll-motion':
                    case 'tablet-scroll-motion':
                    case 'mobile-scroll-motion':
                        $.pixeSetScrollMotionStyle(column);
                        break;
                    case 'hover-animation':
                        $.pixeSetHoverAnimationStyle(column);
                        break;
                    case 'propagate-hover':
                        var settings = column.data('settings');
                        if( settings['propagate-hover'] ){
                            column.addClass('pixe-hover-target');
                        }else{
                            column.removeClass('pixe-hover-target');
                        }
                        $.pixeRenderElementStyles(column.find('.pixe-column, .pixe-item'));
                        break;
                    case 'extend-background':
                    case 'tablet-extend-background':
                    case 'mobile-extend-background':
                        var settings = column.data('settings');
                        column.removeClass('pixe-bgext-left pixe-bgext-right pixe-bgext-none');
                        column.removeClass('pixe-tbgext-left pixe-tbgext-right pixe-tbgext-none');
                        column.removeClass('pixe-mbgext-left pixe-mbgext-right pixe-mbgext-none');
                        if( settings['extend-background'] ){
                            column.addClass('pixe-bgext-' + settings['extend-background']);
                        }
                        if( settings['tablet-extend-background'] ){
                            column.addClass('pixe-tbgext-' + settings['tablet-extend-background']);
                        }
                        if( settings['mobile-extend-background'] ){
                            column.addClass('pixe-mbgext-' + settings['mobile-extend-background']);
                        }
                        break;
                    default:
                        if( type == 'item' ){
                            t.renderStyle(column, 'id', undefined, false);
                            t.renderStyle(column, 'class', undefined, false);
                            t.renderStyle(column, 'responsive', undefined, false);
                            t.renderStyle(column, 'width', undefined, false);
                            t.renderStyle(column, 'padding', undefined, false);
                            t.renderStyle(column, 'bg-media', undefined, false);
                            t.renderStyle(column, 'bg-style', undefined, false);
                            t.renderStyle(column, 'shape-divider', undefined, false);
                            t.renderStyle(column, 'animation', undefined, false);
                            t.renderStyle(column, 'hover-animation', undefined, false);
                            t.renderStyle(column, 'extend-background', undefined, false);
                            t.renderStyle(column, 'pro', undefined, false);
                        }
                        
                        t.setDefaultCss(column);
                        break;
                }
            }

            if( renderCss ){
                t.renderCss(column);
            } 
        },
        renderCss: function(column){
            if( !column.hasClass('pixe-column') ) return;
            
            var style = column.data('style');
            var styleTag = column.children('style');
            var bgMedia = column.children('.pixe-column-content').children('.pixe-bg-style');
            $.pixeRenderCss(styleTag, style);
            
            // parallax background
            bgMedia.pixeParallaxBackground();

            // background size
            $.pixeVideo.resizePortrait(column);

            // iframe api ( start - end time )
            $.pixeVideo.initMedia(bgMedia);
        },

        // default css
        setDefaultCss: function(column){
            var settings = column.data('settings');
            var id = '[data-id="' + settings._id + '"]';

            function getCss(deviceSlug = ''){
                var css = '';

                // wrap area
                var wrapCss = {
                    'transform': settings[deviceSlug + 'transform'],
                    'align-self': settings[deviceSlug + 'align-self'],
                    'flex-basis': settings[deviceSlug + 'flex-basis'],
                    'flex-grow': settings[deviceSlug + 'flex-grow'],
                    'flex-shrink': settings[deviceSlug + 'flex-shrink'],
                    'order': settings[deviceSlug + 'flex-order'],
                    'position': settings[deviceSlug + 'position'],
                    'z-index': settings[deviceSlug + 'z-index']
                };
                
                if( settings['scroll-motion'] && settings['scroll-motion']['enable'] ){
                    if( !deviceSlug ){
                        wrapCss['position'] = 'absolute';
                        wrapCss['top'] = settings['top']? settings['top']: '0px';
                        wrapCss['right'] = settings['right']
                        wrapCss['left'] = settings['left'];
                        if( !wrapCss['left'] && !wrapCss['right'] ){
                            wrapCss['left'] = '0px';
                        }
                    }else{
                        delete wrapCss['position'];
                        wrapCss['top'] = settings[deviceSlug + 'top'];
                        wrapCss['right'] = settings[deviceSlug + 'right'];
                        wrapCss['left'] = settings[deviceSlug + 'left'];
                    }

                    $.pixeSetScrollMotionStyle(column);
                }else if( settings[deviceSlug + 'position'] == 'absolute' || settings[deviceSlug + 'position'] == 'fixed' ){
                    wrapCss['top'] = settings[deviceSlug + 'top'];
                    wrapCss['right'] = settings[deviceSlug + 'right'];
                    wrapCss['bottom'] = settings[deviceSlug + 'bottom'];
                    wrapCss['left'] = settings[deviceSlug + 'left'];
                }

                if( settings[deviceSlug + 'height'] ){
                    if( settings[deviceSlug + 'height'] == 'full-screen' ){
                        if( settings[deviceSlug + 'full-screen-offset'] ){
                            wrapCss['min-height'] = 'calc(100vh - ' + settings[deviceSlug + 'full-screen-offset'] + ')';
                        }else{
                            wrapCss['min-height'] = '100vh';
                        }
                    }else if( settings[deviceSlug + 'height'] == 'min-height' ){
                        wrapCss['min-height'] = settings[deviceSlug + 'min-height'];
                    }else{
                        wrapCss['min-height'] = 'auto';
                    }
                }
                css += $.pixeSetCss(id, wrapCss);

                // wrap hover area
                css += $.pixeSetCss($.pixeGetHoverSelector(id + ':hover', column), {
                    'transform': settings[deviceSlug + 'transform-hover']
                });

                // content area
                var contentCss = {
                    'flex-direction': settings[deviceSlug + 'flex-direction'],
                    'justify-content': settings[deviceSlug + 'justify-content'],
                    'align-items': settings[deviceSlug + 'align-items'],
                    'align-content': settings[deviceSlug + 'align-content'],
                    'flex-wrap': settings[deviceSlug + 'flex-wrap'],
                    'gap': {
                        'x': settings[deviceSlug + 'column-gap'],
                        'y': settings[deviceSlug + 'row-gap']
                    },
                    'overflow': settings[deviceSlug + 'overflow']
                };
                if( settings[deviceSlug + 'content-width'] == 'boxed' ){
                    contentCss['width'] = settings[deviceSlug + 'boxed-content-width'];
                }
                css += $.pixeSetCss(id + ' > .pixe-column-content', contentCss);

                // content item
                if( settings[deviceSlug + 'flex-direction'] == 'row' || settings[deviceSlug + 'flex-direction'] == 'row-reverse' ){
                    css += $.pixeSetCss(id + ' > .pixe-column-content > .pixe-item', {'width': 'auto'});
                }

                return css;
            }

            // apply css
            $.pixeAddCss(column, 'default', getCss());
            $.pixeAddCss(column, 'default', getCss('tablet-'), 'tablet');
            $.pixeAddCss(column, 'default', getCss('mobile-'), 'mobile');
        },

        // spacing
        setSpacingStyle: function(column){
            var t = this;
            var settings = column.data('settings');
            $.pixeSetSpacingStyle(column, settings);

            // padding handler
            function getSpace(pos, type = 'padding'){
                switch($.pixeEditor.viewport){
                    case 'mobile':
                        if( settings['mobile-' + type] && settings['mobile-' + type][pos] ){
                            return settings['mobile-' + type][pos];
                        }
                    case 'tablet':
                        if( settings['tablet-' + type] && settings['tablet-' + type][pos] ){
                            return settings['tablet-' + type][pos];
                        }
                    case 'desktop':
                        if( settings[type] && settings[type][pos] ){
                            return settings[type][pos];
                        }
                    default:
                        if( type == 'padding' && settings._subtype != 'query' ){
                            return t.defaultPadding[pos];
                        }else{
                            return '0px';
                        }
                }
            }

            // handler
            var topHandler = column.children('.pixe-column-padding-resize.pixe-top');
            var topPadding = getSpace('top', 'padding');
            var topPaddingVar = $.pixeGetVariable(topPadding);
            if( topPadding ){
                topHandler.css({'padding-top': topPadding});
                if( topPaddingVar ){
                    topHandler.find('input').val(topPaddingVar);
                }else{
                    topHandler.find('input').val(topPadding);
                }
                if( parseInt(topPadding) < t.minimizeSize ){
                    topHandler.addClass('pixe-minimize');
                }else{
                    topHandler.removeClass('pixe-minimize');
                }
            }else{
                topHandler.css({'padding-top': 0});
                topHandler.find('input').val('-');
                topHandler.addClass('pixe-minimize');
            }
            topHandler.css({'margin-top': getSpace('top', 'margin')});

            var bottomHandler = column.children('.pixe-column-padding-resize.pixe-bottom');
            var bottomPadding = getSpace('bottom', 'padding');
            var bottomPaddingVar = $.pixeGetVariable(bottomPadding);
            if( bottomPadding ){
                bottomHandler.css({'padding-bottom': bottomPadding});
                if( bottomPaddingVar ){
                    bottomHandler.find('input').val(bottomPaddingVar);
                }else{
                    bottomHandler.find('input').val(bottomPadding);
                }
                if( parseInt(bottomPadding) < t.minimizeSize ){
                    bottomHandler.addClass('pixe-minimize');
                }else{
                    bottomHandler.removeClass('pixe-minimize');
                }
            }else{
                bottomHandler.css({'padding-bottom': 0});
                bottomHandler.find('input').val('-');
                bottomHandler.addClass('pixe-minimize');
            }
            bottomHandler.css({'margin-bottom': getSpace('bottom', 'margin')});
        },

        // background
        setBackgroundStyle: function(column){
            var settings = column.data('settings');
            delete settings['bg-style-display'];

            var value = settings['bg-style'];
            if( !value ){
                $.pixeAddCss(column, 'bg-style', '');
                $.pixeAddCss(column, 'bg-style', '', 'tablet');
                $.pixeAddCss(column, 'bg-style', '', 'mobile');
                return;
            }

            var id = '[data-id="' + settings._id + '"]';

            function getCss(deviceSlug = ''){
                // for content
                var css = ''; 
            
                // mask
                css += $.pixeSetCss(id + ' > .pixe-column-content', {
                    'mask': value[deviceSlug + 'mask'],
                    'shadow': value[deviceSlug + 'shadow'],
                    'border-radius': value[deviceSlug + 'border']? value[deviceSlug + 'border'].radius: ''
                });
                css += $.pixeSetCss(id + ':hover > .pixe-column-content', {
                    'mask': value[deviceSlug + 'mask-hover'],
                    'shadow': value[deviceSlug + 'shadow-hover'],
                    'border-radius': value[deviceSlug + 'border-hover']? value[deviceSlug + 'border-hover'].radius: ''
                });
                
                // for bg-style
                var css2 = ''; 

                // background color
                css2 += $.pixeSetCss(id + ' > .pixe-column-content > .pixe-bg-style', {
                    'background-color': value[deviceSlug + 'color'],
                    'border': value[deviceSlug + 'border'],
                    'custom': $.pixeBgColorFilterCss(value, deviceSlug)
                });
                css2 += $.pixeSetCss(id + ':hover > .pixe-column-content > .pixe-bg-style', {
                    'background-color': value[deviceSlug + 'color-hover'],
                    'border': value[deviceSlug + 'border-hover']
                });

                // for render function
                if( css2 ){
                    settings['bg-style-display'] = 1;
                }
                return css + css2;
            }

            // apply css
            $.pixeAddCss(column, 'bg-style', getCss());
            $.pixeAddCss(column, 'bg-style', getCss('tablet-'), 'tablet');
            $.pixeAddCss(column, 'bg-style', getCss('mobile-'), 'mobile');
        },

        getToolbar: function(column){
            var settings = column.data('settings');
            var html = '';

            if( settings._subtype == 'carousel' ){
                // do nothing
            }else if( column.hasClass('pixe-query-grid') ){
                html  = '<div class="pixe-column-toolbar pixe-type-2" >';
                html += '<div class="pixe-action pixe-maximize pixe-svg-preset pixe-svg-column-space" ></div>';
                html += '<div class="pixe-action pixe-media pixe-svg-preset pixe-svg-column-image" ></div>';
                html += '<div class="pixe-action pixe-palette pixe-svg-preset pixe-svg-column-color" ></div>';
                html += '<div class="pixe-action pixe-settings pixe-svg-preset pixe-svg-column-settings" ></div>';
                html += '</div>';
            }else{
                html  = '<div class="pixe-column-toolbar" >';
                html += '<div class="pixe-column-head pixe-svg-preset pixe-svg-column-head" ></div>';
                html += '<div class="pixe-action pixe-drag pixe-svg-preset pixe-svg-column-drag" ></div>';
                html += '<div class="pixe-size-wrap">';
                html += '<input class="pixe-size-text" type="text" value="1/1" />';
                html += '<div class="pixe-resize" >';
                html += '<div class="pixe-action pixe-up pixe-svg-preset pixe-svg-column-up" ></div>';
                html += '<div class="pixe-action pixe-down pixe-svg-preset pixe-svg-column-down" ></div>';
                html += '</div>';
                html += '</div>'; // pixe-size-action-wrap
                html += '<div class="pixe-action pixe-size-type" ><span class="pixe-text" >col</span><div class="pixe-svg-preset pixe-svg-column-down" ></div></div>';
                html += '<div class="pixe-action pixe-maximize pixe-svg-preset pixe-svg-column-space" ></div>';
                html += '<div class="pixe-action pixe-media pixe-svg-preset pixe-svg-column-image" ></div>';
                html += '<div class="pixe-action pixe-palette pixe-svg-preset pixe-svg-column-color" ></div>';
                html += '<div class="pixe-action pixe-copy pixe-svg-preset pixe-svg-column-copy" ></div>';
                html += '<div class="pixe-action pixe-settings pixe-svg-preset pixe-svg-column-settings" ></div>';
                html += '<div class="pixe-action pixe-close pixe-svg-preset pixe-svg-column-trash" ></div>';
                html += '</div>';
            }

            return html;
        },

        remove: function(column, updateNavigator = true){

            function remove(){
                var parent = column.parent();

                // save for history
                var action = $.pixeHistory.createAction(column, 'remove');
                
                // remove from dom
                column.detach();

                // add history action
                $.pixeHistory.addAction(action, updateNavigator);

                // check parents status
                if( parent.hasClass('pixe-editor') ){
                    $.pixeEditor.setStatus();
                }else{
                    parent.closest('.pixe-tab-container').each(function(){ $.pixeItem.setTabContainerStatus($(this)); });
                    parent.closest('.pixe-column').each(function(){ $.pixeColumn.setStatus($(this)); });
                    parent.closest('.pixe-wrapper').each(function(){ $.pixeWrapper.setStatus($(this)); });
                    parent.closest('.pixe-collection').each(function(){ $.pixeCollection.setStatus($(this)); });
                }
            }

            // ask before remove on mobile/tablet devices
            if( $.pixeEditor.viewport == 'desktop' ){
                remove();
            }else{
                $.pixeConfirmationBox({
                    extraClass: 'pixe-red',
                    title: 'Remove Element',
                    confirmText: 'Remove',
                    message: 'Please note that removing an element while editing in Tablet or Mobile view will also remove it from the Desktop view and across all devices.',
                    onSuccess: function(){
                        remove();
                    }
                });
            }
        },

        bindToolbar: function(editor){
            var t = this;

            editor.on('click', '.pixe-column-toolbar .pixe-action', function(){
                var column = $(this).closest('.pixe-column');

                // edit settings
                if( $(this).hasClass('pixe-settings') ){
                    pixeData.hideBuilderPanel = false;
                    $.pixeEditor.setEditTarget(column);
                
                // remove item
                }else if( $(this).hasClass('pixe-close') ){

                    t.remove(column);
                    
                // duplicate item
                }else if( $(this).hasClass('pixe-copy') ){

                    // copy & assign unique id
                    var settings = $.pixeClone($.pixeGetEditorVal(column));
                    $.pixeEditor.setUniqueIdData(settings);

                    // add item
                    var newItem = t.create(settings);
                    newItem.insertAfter(column);
    
                    // save for history
                    var action = $.pixeHistory.createAction(newItem, 'duplicate');
                    $.pixeHistory.addAction(action);

                    // set column status & class
                    var container = newItem.parent().closest('.pixe-column, .pixe-wrapper, .pixe-editor');
                    $.pixeEditor.setStatus(container);
                
                // pixe size up down
                }else if( $(this).hasClass('pixe-up') || $(this).hasClass('pixe-down') ){
                    
                    var size = t.getWidth(column);
                    var widthType = $.pixeGetUnit(size);
                    var container = column.parent();

                    // get size
                    if( widthType == 'col' || widthType == 'auto' ){
                        if( $(this).hasClass('pixe-up') ){
                            size = t.getColSizes(column.width() * 100 / container.width(), 1);
                        }else if( $(this).hasClass('pixe-down') ){
                            size = t.getColSizes(column.width() * 100 / container.width(), -1);
                        }
                    }else if( widthType == 'px' || widthType == '%' ){
                        if( $(this).hasClass('pixe-up') ){
                            size = (parseInt(size) + 1) + widthType;
                        }else if( $(this).hasClass('pixe-down') ){
                            size = (parseInt(size) - 1) + widthType;
                        }
                    }
                    t.setWidth(column, size);

                // pixe size type
                }else if( $(this).hasClass('pixe-size-type') ){
                    if( $(this).hasClass('pixe-target-close') ){
                        $(this).removeClass('pixe-target-close');
                        return;
                    }
        
                    var button = $(this);
                    var size = column.data('settings').width;
                    var widthType = $.pixeGetUnit(size);
                    var content = $('<div>col</div>');
                    content = content.add('<div>%</div>')
                    content = content.add('<div>px</div>')
                    content = content.add('<div>auto</div>')
                    
                    column.addClass('pixe-focus');
        
                    var popup = new $.pixePopup({
                        content: content,
                        target: button,
                        style: 'pixe-width-type-popup pixe-options',
                        onClose: function(){
                            column.removeClass('pixe-focus');
                        }
                    });
        
                    // select type event
                    content.on('click', function(){
                        var type = $(this).text();
                        if( type != widthType ){

                            var container = column.parent();
                            if( type == 'col' ){
                                size = t.getColSizes(column.width() * 100 / container.width());
                            }else if( type == '%' ){
                                size = column.width() * 100 / container.width();
                                size = (Math.floor(size * 100) / 100) + '%';
                            }else if( type == 'px' ){
                                size = column.width();
                                size = Math.floor(size * 100) / 100 + 'px';
                            }else if( type == 'auto' ){
                                size = 'auto';
                            }
                            t.setWidth(column, size, type);
                        }
                        
                        popup.close();
                    });

                // pixe margin & padding
                }else if( $(this).hasClass('pixe-maximize') ){
                    
                    $.pixeSpacingPopup(column, {
                        button: $(this),
                        onChange: function(type){
                            t.renderStyle(column, type);
                            t.setStatus(column);
                        }
                    });
                
                // column background media
                }else if( $(this).hasClass('pixe-media') ){

                    $.pixeBgMediaPopup(column, {
                        button: $(this),
                        onChange: function(value, subtype){
                            t.renderStyle(column, 'bg-media', subtype);
                            t.setStatus(column);
                        }
                    });

                // column background style
                }else if( $(this).hasClass('pixe-palette') ){

                    $.pixeBgStylePopup(column, {
                        button: $(this),
                        type: 'bg-style-filter',
                        onChange: function(){
                            t.renderStyle(column, 'bg-style');
                            t.setStatus(column);
                        }
                    });
                }

            });

        },

        // calculate 
        setStatus: function(column){
            if( column.hasClass('pixe-preview-element') ) return;
            
            var settings = column.data('settings');
            if( !settings ) return;
            
            var content = column.children('.pixe-column-content');
            
            // if has column or item as children
            var isEmpty = true;
            if( content.children('.pixe-column, .pixe-item').length ){ 
                delete settings['no-content'];
                column.removeClass('pixe-column-no-content');
                column.removeClass('pixe-has-bg');
                isEmpty = false;

            // only media and style div
            }else{
                var hasMedia = content.children('.pixe-bg-style').children().length;
                var hasStyle = settings['bg-style-display'];

                settings['no-content'] = 1;
                settings['has-bg'] = (hasMedia || hasStyle);
                column.addClass('pixe-column-no-content');
                
                if( settings['has-bg'] ){
                    isEmpty = false;
                    column.addClass('pixe-has-bg');
                }else{
                    isEmpty = true;
                    column.removeClass('pixe-has-bg');
                }
            }

            if( isEmpty ){
                column.addClass('pixe-empty');

                // empty content for post template grid style
                if( column.hasClass('pixe-query-grid') && !content.children('.pixe-editor-empty').length ){
                    var emptyContent = $($.pixeEditorArea.emptyHtml());
                    emptyContent.appendTo(content);
                    emptyContent.on('click', '.pixe-action', function(){
                        if( $(this).hasClass('pixe-new-element') ){
                            $.pixeEditor.setParentStatus({
                                event: 'newElement',
                            });
                        }else if( $(this).hasClass('pixe-new-container') ){
                            $.pixeEditor.setParentStatus({
                                event: 'newTemplate',
                                type: pixeData.part
                            });
                        }
                    });
                }
                
            }else{
                column.removeClass('pixe-empty');

                // empty content for post template grid style
                if( column.hasClass('pixe-query-grid') ){
                    content.children('.pixe-editor-empty').remove();
                }
            }

            // check nested column status
            var parents = column.parentsUntil('.pixe-active-editor').filter('.pixe-column');
            if( parents.length ){
                column.addClass('pixe-nested-column');
            }else{
                column.removeClass('pixe-nested-column');
            }
            if( parents.length % 2 == 0 ){
                column.addClass('pixe-even').removeClass('pixe-odd');
            }else{
                column.addClass('pixe-odd').removeClass('pixe-even');
            }

            // check for 0 space
            if( content.css('padding-top') == '0px' && content.css('padding-left') == '0px' ){
                column.addClass('pixe-0gap');
            }else{
                column.removeClass('pixe-0gap');
            }
        },

        // assign row & col atts
        setColumnAtts: function(container){

            container.each(function(){
                var containerWidth = $(this).width();
                var rowCount = 0;
                var colCount = 0;
                var sumSize = 0;

                $(this).children().each(function(){
                    if( $(this).hasClass('pixe-bg-style') ) return;

                    // ignore & reset if not column
                    if( !$(this).hasClass('pixe-column') ){
                        rowCount++;
                        colCount = 0;
                        sumSize = 0;
                        return;
                    }
    
                    // next row
                    sumSize += $(this).outerWidth();
                    if( sumSize > containerWidth ){
                        rowCount++;
                        colCount = 0;
                        sumSize = $(this).outerWidth();
                    }
    
                    // apply row attribute
                    $(this).attr('data-row', rowCount); 
                    $(this).attr('data-col', colCount); 
    
                    colCount++;
                });
            });

        },

        // drag & input resize action
        bindColumnPaddingResize: function(editor){
            var t = this;

            // dragging resize
            editor.pixeDragResize({
                selector: '.pixe-column-padding-resize',
                itemSelector: '.pixe-column',
                onResize: function(column, handler, diff){
                    $.pixeSetPaddingDiff(column, handler, diff, false);
                    t.renderStyle(column, 'padding');
                }
            });

            // input change action
            editor.on('focusin focusout change keydown', '.pixe-column-padding-resize input', function(e){
                var column = $(this).closest('.pixe-column');
                var handler = $(this).closest('.pixe-column-padding-resize');

                if( e.type == 'focusin' ){
                    column.addClass('pixe-focus');
                    handler.addClass('pixe-focus');
                }else if( e.type == 'focusout' ){
                    column.removeClass('pixe-focus');
                    handler.removeClass('pixe-focus');
                }else if( e.type == 'change' ){
                    var padding = $(this).val()? parseInt($(this).val()) + 'px': undefined;
    
                    if( handler.hasClass('pixe-top') ){
                        $.pixeSetPadding(column, 'top', padding);
                    }else if( handler.hasClass('pixe-bottom') ){
                        $.pixeSetPadding(column, 'bottom', padding);
                    }
    
                    // render style
                    t.renderStyle(column, 'padding');
                }else if( e.type == 'keydown' ){
                    if( e.keyCode != 38 && e.keyCode != 40 ) return;
    
                    var diff = 0;
                    if( e.keyCode == 38 ){
                        diff = 1;
                    }else if( e.keyCode == 40 ){
                        diff = -1;
                    }
                    if( e.shiftKey ){
                        diff *= 10;
                    }
    
                    $.pixeSetPaddingDiff(column, handler, diff);
                    t.renderStyle(column, 'padding');
                }
            });
        },
        bindColumnWidthResize: function(editor){
            var t = this;

            // width resize
            editor.on('focusin focusout change keydown', '.pixe-column-toolbar .pixe-size-text, .pixe-column-resize .pixe-size-text', function(e){
                var column = $(this).closest('.pixe-column');
                
                if( e.type == 'focusin' ){
                    column.addClass('pixe-resize-text-focus');
                }else if( e.type == 'focusout' ){
                    column.removeClass('pixe-resize-text-focus');
                }else if( e.type == 'change' ){
                    var containerWidth = column.parent().width();
                    var size = $(this).val();
                    var widthType = $.pixeGetUnit(size);

                    // get default width type if only number is filled
                    if( !widthType ){ 
                        widthType = $.pixeGetUnit(t.getWidth(column)); 
                        
                        if( !widthType ){
                            widthType = '%';
                        }
                    }

                    // check if width is valid
                    if( widthType == 'col' ){
                        if( $.pixeColumnSize.columnAlt[size] ){
                            size = $.pixeColumnSize.columnAlt[size];
                        }
                        var p = t.getPercentSizes(size);
                        
                        if( p ){
                            t.setWidth(column, size);
                        }else{
                            t.setWidthText(column);
                        }

                    }else if( widthType == '%' ){
                        size = parseFloat(size);
                        if( isNaN(size) ){
                            t.setWidthText(column);
                        }else{ 
                            if( size < $.pixeColumnSize.minSize ){
                                size = $.pixeColumnSize.minSize;
                            }else if( size > 100 ){
                                size = '100';
                            }

                            size = size + '%';
                            t.setWidth(column, size);
                        }
                    }else if( widthType == 'px' ){
                        size = parseFloat(size);
                        if( isNaN(size) ){
                            t.setWidthText(column);
                        }else{
                            if( size > containerWidth ){
                                size = containerWidth;
                            }else if( size < ($.pixeColumnSize.minSize * containerWidth / 100) ){
                                size = ($.pixeColumnSize.minSize * containerWidth / 100);
                            }

                            size = size + 'px';
                            t.setWidth(column, size);
                        } 
                    }
                }else if( e.type == 'keydown' ){
                    if( e.keyCode != 38 && e.keyCode != 40 ) return;
    
                    var diff = 0;
                    if( e.keyCode == 38 ){
                        diff = 1;
                    }else if( e.keyCode == 40 ){
                        diff = -1;
                    }
                    if( e.shiftKey ){
                        diff *= 10;
                    }
                    
                    var data = $(this).val();
                    var value = data? parseFloat(data): 0;
                    var suffix = '';
                    if( $(this).parent().hasClass('pixe-size-wrap') ){
                        suffix = $(this).closest('.pixe-column-toolbar').find('.pixe-size-type .pixe-text').html();
                        if( suffix == 'auto' || suffix == 'col' ) return;
                    }else{
                        var match = data.match(/[^\.\-0-9]+/);
                        suffix = match && match[0]? match[0]: '';
                    }
                    if( isNaN(value) ) return;
                    
                    var size = (value + diff) + suffix;
                    $(this).val(size);
                    t.setWidth(column, size);
                }
            });

            editor.on('click', '.pixe-column-resize .pixe-new', function(){
                var column = $(this).closest('.pixe-column');
                var newColumn = t.create();
                newColumn.insertAfter(column);
                
                $.pixeEditor.setUniqueId(newColumn);
                t.setWidth(newColumn, '1/6', false);
                t.setStatus(newColumn);

                // save for history
                var action = $.pixeHistory.createAction(newColumn, 'add');
                $.pixeHistory.addAction(action);
            });
            
            editor.on('mousedown', '.pixe-column-resize .pixe-handler', function(e){
                if( e.buttons != 1 || $(e.target).is('.pixe-action, input') ) return;
                e.preventDefault();

                var column = $(this).closest('.pixe-column');
                t.setColumnAtts(column.parent());

                var container = column.parent();
                var columns = container.children('[data-row="' + column.attr('data-row') + '"]'); // columns in the same row
                var nextColumn = column.next(':not(.pixe-preview-element)').is(columns)? column.next(): false;

                var columnStart = column.offset().left;
                var columnEnd = columnStart + column.outerWidth();
                var nextColumnEnd = (nextColumn)? nextColumn.offset().left + nextColumn.outerWidth(): 0;

                var containerWidth = container.width();
                var containerEnd = container.offset().left + parseFloat(container.css('border-left-width')) + parseFloat(container.css('padding-left')) + container.width();
                var minColumnPx = (containerWidth * $.pixeColumnSize.minSize) / 100;

                // for history
                var slug = ($.pixeEditor.viewport == 'desktop')? 'width': $.pixeEditor.viewport + '-width';
                var columnSize = t.getWidth(column);
                var nextColumnSize = (nextColumn)? t.getWidth(nextColumn): false;
                var widthType = $.pixeGetUnit(columnSize);

                $(columns).each(function(){ $(this).addClass('pixe-resize-siblings'); });
                column.addClass('pixe-resize-focus').removeClass('pixe-resize-siblings');

                // set and assign new width to specified item
                function resizeWidth(item, size){
                    if( widthType == 'col' || widthType == '%' || widthType == 'auto' ){
                        size = (size * 100) / containerWidth;
                        size = Math.floor(size * 100) / 100; 
                        t.setWidth(item, size + '%', false);
                    }else if( widthType == 'px' ){
                        size = Math.floor(size * 100) / 100; 
                        t.setWidth(item, size + 'px', false);
                    }
                }
                
                // dragging action
                function resizeColumn(e){

                    if( e.type == 'mousemove' ){

                        var columnWidth = e.pageX - columnStart;
                        
                        // decrease column size & increase next column size
                        if( e.pageX < columnEnd ){
                            if( columnWidth < minColumnPx ){ columnWidth = minColumnPx; }

                            // set current column size
                            resizeWidth(column, columnWidth);
                            columnEnd = columnStart + columnWidth;

                            // set next column size
                            if( nextColumn !== false ){
                                var nextColumnWidth = nextColumnEnd - columnEnd;
                                resizeWidth(nextColumn, nextColumnWidth);
                            }

                        // increase column size
                        }else if( e.pageX > columnEnd ){

                            // if not last item
                            if( nextColumn !== false ){
                                var maxWidth = nextColumnEnd - columnStart - minColumnPx;
                                if( columnWidth > maxWidth ){ columnWidth = maxWidth; }

                                // set current column
                                resizeWidth(column, columnWidth);
                                columnEnd = columnStart + columnWidth;

                                // set next column
                                var nextColumnWidth = nextColumnEnd - columnEnd;
                                resizeWidth(nextColumn, nextColumnWidth);
                            
                            // if last item
                            }else{
                                var maxWidth = containerEnd - columnStart;
                                if( columnWidth > maxWidth ){ columnWidth = maxWidth; }
                                resizeWidth(column, columnWidth);
                                columnEnd = columnStart + columnWidth;
                            }

                        }
                    }

                    // unbind event after finish
                    if( e.buttons != 1 ){
                        pixeData.isItemEditing = true; // prevent side bar from changing
                        columns.each(function(){ $(this).removeClass('pixe-resize-siblings'); });
                        column.removeClass('pixe-resize-focus');
                        $(document.body).off('mousemove mouseup', resizeColumn);

                        // add action to history
                        if( columnSize != column.data('settings')[slug] ){
                            var action = $.pixeHistory.createAction(column, 'edit', slug);
                            $.pixeHistory.setActionStep(action, column, slug, columnSize, true);
                            $.pixeHistory.setActionStep(action, column, slug, column.data('settings')[slug]);
                            $.pixeEditor.updateSettingsPanel(column, slug, column.data('settings')[slug]);
                            if( nextColumn ){
                                $.pixeHistory.setActionStep(action, nextColumn, slug, nextColumnSize, true);
                                $.pixeHistory.setActionStep(action, nextColumn, slug, nextColumn.data('settings')[slug]);
                                $.pixeEditor.updateSettingsPanel(nextColumn, slug, nextColumn.data('settings')[slug]);
                            }
                            $.pixeHistory.addAction(action);
                        }
                    }
                }

                // bind move event
                $(document.body).on('mousemove mouseup', resizeColumn);

                // show/hide resize area
                column.addClass('pixe-resize-enable');
                function disableResize(e){
                    if( e.type == 'click' && $(e.target).closest('.pixe-column-resize').length ){
                        return;
                    }
                    
                    column.removeClass('pixe-resize-enable');
                    column.off('click mouseleave', disableResize);
                }
                column.on('click mouseleave', disableResize);
            });
        },

        // column width
        getWidth: function(column){
            var settings = column.data('settings');
            if( !settings ) return; 

            var size;

            switch($.pixeEditor.viewport){
                case 'desktop':
                    size = settings['width'];
                    break;
                case 'tablet':
                    size = (settings['tablet-width'])? settings['tablet-width']: settings['width'];
                    break;
                case 'mobile':
                    size = (settings['mobile-width'])? settings['mobile-width']: '100%';
                    break;
            }

            return size;
        },
        setWidth: function(column, size, toHistory = true){
            var t = this;

            // set width data
            var settings = column.data('settings');
            var slug = ($.pixeEditor.viewport == 'desktop')? 'width': $.pixeEditor.viewport + '-width';
            
            // create action for history
            if( toHistory ){             
                var action = $.pixeHistory.createAction(column, 'edit', slug);
                $.pixeHistory.setActionStep(action, column, slug, settings[slug], true);
                $.pixeHistory.setActionStep(action, column, slug, size);
                $.pixeHistory.addAction(action);
                $.pixeEditor.updateSettingsPanel(column, slug, size);
            }

            settings[slug] = size;

            // visualize
            t.setWidthText(column);
            t.setWidthStyle(column);
            t.renderCss(column);
        },
        setWidthStyle: function(column){
            if( column.hasClass('pixe-block-container') ) $.pixeColumn.setBlockColumnWidthStyle(column);
            if( !column.hasClass('pixe-column') ) return;

            var settings = column.data('settings');
            var id = '[data-id="' + settings._id + '"]';

            // apply css desktop
            var ttype = $.pixeGetUnit(settings['width']);
            if( ttype == 'col' ){
                column.attr('data-width', settings['width'].replace('/', '-'));
                $.pixeAddCss(column, 'width', '');
            }else{
                $.pixeAddCss(column, 'width', $.pixeSetCss(id, {width: settings['width']}));
                column.removeAttr('data-width');
            }
            
            // mobile
            $.pixeAddCss(column, 'width', $.pixeSetCss(id, {width: settings['tablet-width']}), 'tablet');
            $.pixeAddCss(column, 'width', $.pixeSetCss(id + '.pixe-column', {width: settings['mobile-width']}), 'mobile');
        },
        
        // only for block container
        setBlockColumnWidthStyle: function(column){
            var settings = column.data('settings');
            var ttype = $.pixeGetUnit(settings['width']);
            if( ttype == 'col' ){
                column.attr('data-width', settings['width'].replace('/', '-'));
                $.pixeAddCss(column, 'width', '');
            }
        },
        setWidthText: function(column){
            if( !column.hasClass('pixe-column') ) return;

            // get current column size based on device
            var t = this;
            var size = t.getWidth(column);
            var type = $.pixeGetUnit(size);

            // assign width to the column
            column.children('.pixe-column-toolbar').each(function(){
                if( type == 'px' || type == '%' ){
                    var sizeText = Math.floor(parseFloat(size) * 10) / 10
                    $(this).find('.pixe-size-text').val(sizeText);
                    $(this).find('.pixe-size-type .pixe-text').html(type);
                }else if( type == 'auto' ){
                    $(this).find('.pixe-size-text').val('-');
                    $(this).find('.pixe-size-type .pixe-text').html(size);
                }else{
                    $(this).find('.pixe-size-text').val(size);
                    $(this).find('.pixe-size-type .pixe-text').html(type);
                }
            });
            column.children('.pixe-column-resize').each(function(){
                $(this).find('.pixe-size-text').val(size);
            });
        }

    }

})(jQuery);	