(function($){
    "use strict";
    
    pixeData.hideBuilderPanel = true;

    // postMessage : receive status from parent window 
    window.addEventListener('message', function(e){
        if( e.origin == window.location.origin && e.data.host == 'pixe' ){
            
            // events from parent window
            switch( e.data.event ){
                case 'pixeData':
                    if( e.data.action == 'set' ){
                        for( var slug in e.data.value ){
                            pixeData[slug] = e.data.value[slug];
                            switch(slug){
                                case 'iconPreset':
                                    $(window).trigger('closesubpopup');
                                    break;
                                case 'controlPreset':
                                    $.pixeControlStyle.updatePresetStyle();
                                    break;
                                case 'typoPreset':
                                    $(window).trigger('closesubpopup');
                                    $.pixeTypoStyle.updateStyle();
                            
                                    // update inline preset option
                                    $.pixeUpdateCombobox($.pixeInlineToolbar.elem, {
                                        selector: '.pixe-typo-preset-combobox',
                                        options: 'typoPreset'
                                    });
                                    $.pixeInlineToolbar.updateTypoToolbar();
                                    break;
                                case 'colorPreset':
                                    $.pixeColorStyle.updateStyle();
                                    break;
                                case 'variablePreset':
                                    $.pixeVariablePreset.updateStyle();
                                    break;
                                case 'buttonPreset':
                                    $.pixeButtonPreset.updateStyle();
                                    break;
                            }
                        }
                    }else if( e.data.action == 'get'){
                        $.pixeEditor.setParentData(e.data.value);
                    }
                    break;
                case 'clearEditTarget':
                    $.pixeEditor.clearEditTarget(false);
                    break;

                case 'navigator':
                    if( e.data.action == 'init' ){
                        $.pixeEditor.navigatorOpen = true;
                        $.pixeEditor.updateNavigatorPanel();
                    }else if( e.data.action == 'close' ){
                        $.pixeEditor.navigatorOpen = false;
                    }else if( e.data.action == 'focus' ){
                        if( !window.pixeNavigatorStyle ){
                            window.pixeNavigatorStyle = $('<style></style');
                            window.pixeNavigatorStyle.appendTo(document.body);
                        }
                        window.pixeNavigatorStyle.empty();
                        window.pixeNavigatorStyle.append(e.data.value);
                    }else if(e.data.action == 'edit'){
                        if( e.data.id ){
                            var item = $('[data-id="' + e.data.id + '"]');
                            $.pixeEditor.setEditTarget(item);
                            window.pixeNavigatorStyle.empty();
                        }
                    }else if( e.data.action == 'remove' ){
                        if( e.data.id ){
                            pixeData.hideBuilderPanel = false;
                            var item = $('[data-id="' + e.data.id + '"]');
                            if( item.hasClass('pixe-wrapper') ){
                                $.pixeWrapper.remove(item, false);
                            }else if( item.hasClass('pixe-column') ){
                                $.pixeColumn.remove(item, false);
                            }else if( item.hasClass('pixe-item') ){
                                $.pixeItem.remove(item, false);
                            }
                        }
                    }else if( e.data.action == 'move' ){
                        if( e.data.id ){
                            var item = $('[data-id="' + e.data.id + '"]');
                            var action = $.pixeHistory.createAction(item, 'move');

                            // move item
                            if( e.data.move == 'up' ){
                                if( item.prev().length ){
                                    item.insertBefore(item.prev());
                                }
                            }else if( e.data.move == 'down' ){
                                if( item.next().length ){
                                    item.insertAfter(item.next());
                                }
                            }else if( e.data.move == 'after' || e.data.move == 'before' ){
                                var target = $('[data-id="' + e.data.target + '"]');
                                if( target.length ){
                                    if( e.data.move == 'after' ){
                                        item.insertAfter(target);
                                    }else{
                                        item.insertBefore(target);
                                    }
                                }
                            }else if( e.data.move == 'children' ){
                                var target;
                                if( e.data.target == 'editor' ){
                                    target = window.pixeEditor;
                                }else{
                                    target = $('[data-id="' + e.data.target + '"]');
                                    // for tab item
                                    if( target.hasClass('pixe-item') ){
                                        target = target.children('.pixe-item-content').children('.pixe-item-tab-content');
                                    // for column
                                    }else if( target.hasClass('pixe-column') ){
                                        target = target.children('.pixe-column-content');
                                    // for wrapper
                                    }else if( target.hasClass('pixe-wrapper') ){
                                        target = target.children('.pixe-wrapper-content');
                                    }
                                }
                                if( target.length ){
                                    target.append(item);
                                }
                            }

                            // update new location & add action
                            $.pixeHistory.setActionLocation(action, 'target');
                            $.pixeHistory.addAction(action, false);

                            $.pixeEditor.setStatus();
                        }
                    }
                    break;
                case 'settings':
                    if( e.data.value && e.data.type ){
                        var actionHistory = new $.pixeEditHistory(pixeData.editorSettings, {type: 'object', debounceTime: 100});

                        // clear and update value
                        for( var key in pixeData.editorSettings ){ delete pixeData.editorSettings[key]; }
                        $.extend(pixeData.editorSettings, e.data.value);
                        
                        actionHistory.onChange(e.data.type, 'Page Settings Edited', {
                            onChange: function(){
                                $.pixeEditor.setParentData(['editorSettings']);
                            }
                        });
                    }
                    break;
                case 'changeViewport':
                    $.pixeEditor.changeViewport(e.data.action);
                    break;
                case 'preview':
                    if( e.data.value ){
                        $(document.body).addClass('pixe-preview');
                    }else{
                        $(document.body).removeClass('pixe-preview');
                    }
                    break;
                case 'addNew':
                    if( e.data.value ){

                        // change block type from 'block-dragging' to 'block'
                        for( var i in e.data.value ){
                            if( e.data.value[i]._type == 'block-dragging' ){
                                e.data.value[i]._type = 'block';
                            }
                        }
                        
                        // assign unique id
                        $.pixeEditor.setUniqueIdData(e.data.value);
                        
                        // append
                        var item = $.pixeEditor.render(e.data.value);
                        var droppable = $.pixeDragDrop.isDroppable(item, window.pixeDropTarget, false);
                        if( droppable ){
                            window.pixeDropTarget.append(item);
                        }else{
                            window.pixeDropTarget = window.pixeEditor;
                            window.pixeDropTarget.append(item);
                        }
                        
                        // save for history
                        var action = $.pixeHistory.createAction(item, 'add');
                        $.pixeHistory.addAction(action);

                        // set editor column / wrapper status
                        $.pixeEditor.setStatus();

                        // scroll to target
                        var itemPos = item.offset().top - (window.innerHeight * 0.25);
                        $('html, body').animate({scrollTop: itemPos});
                    }
                    break;
                case 'dragElement':
                    if( e.data.action == 'start' ){
                        $(window).trigger('closepopup');
                        $.pixeEditor.parentDrag(e.data);
                    }else if( e.data.action == 'stop'){
                        $(document.body).trigger('parentdragstop');
                    }
                    break;
                case 'history':
                    $(window).trigger('closepopup');
                    $(document.body).trigger('closeinline');
                    if( e.data.action == 'get' ){
                        $.pixeEditor.setParentStatus({
                            event: 'history',
                            action: 'show',
                            value: $.pixeHistory.getData()
                        });
                    }else if( e.data.action == 'doAt' ){
                        $.pixeHistory.doAt(e.data.index);
                    }else if( e.data.action == 'undo' ){
                        $.pixeHistory.undo();
                    }else if( e.data.action == 'redo' ){
                        $.pixeHistory.redo();
                    }else{
                        $(window).trigger('closepopup');
                        var offset = {top: 0, left: e.data.offsetLeft};
                        $.pixeHistory.show(offset);
                    }
                    break;
                case 'publish':
                    $.pixeEditor.save(e.data.action);
                    break;
                case 'autosave':
                    if( e.data.action == 'preview' ){
                        if( pixeData.updateStatus == 'enable' ){
                            $.pixeEditor.save('autosave', 'preview');
                        }else if( pixeData.updateStatus == 'disable' ){
                            window.open(pixeData.previewUrl, 'pixepreview');
                        }
                    }else if( e.data.action == 'refresh' ){
                        if( pixeData.updateStatus == 'enable' ){
                            $.pixeEditor.save('autosave', 'refresh');
                        }else if( pixeData.updateStatus == 'disable' ){
                            window.location.reload();
                        }
                    }else if( e.data.action == 'revision' ){
                        $.pixeEditor.save('autosave');
                        $.pixeEditor.initParentData();
                    }
                    break;
                case 'edit':
                    $(window).trigger('closepopup').trigger('closeinline');
                    
                    // update & render
                    if( e.data.value && e.data.type ){
                        var item;
                        if( window.pixeEditTarget && window.pixeEditTarget.attr('data-id') == e.data.value._id ){
                            item = window.pixeEditTarget;
                        }else{
                            item = $('[data-id="' + e.data.value._id + '"]');
                            if( item.length ){
                                window.pixeEditTarget = item;
                                window.pixeEditHistory = undefined;
                            }
                        }
                        if( item.length ){
                            if( !window.pixeEditHistory ){
                                window.pixeEditHistory = new $.pixeEditHistory(item, {
                                    updateSettingsPanel: false
                                });
                            }

                            if( item.length ){
                                item.data('settings', e.data.value);
                                
                                if( e.data.value._type == 'wrapper' || e.data.value._type == 'collection' ){
                                    $.pixeWrapper.renderStyle(item, e.data.type, e.data.subtype);
                                }else if( e.data.value._type == 'column' ){
                                    $.pixeColumn.renderStyle(item, e.data.type, e.data.subtype);
                                }else if( e.data.value._type == 'element' ){
                                    $.pixeItem.renderStyle(item, e.data.type, e.data.subtype);
                                }
                            }
                            window.pixeEditHistory.onChange(e.data.type);
                        }
                    }
                    break;
                case 'add-block':
                    if( e.data.type == 'block' && $.pixeSaveBlock ){
                        $.pixeSaveBlock(e.data);
                    }else if( e.data.type == 'download-block' && $.pixeDownloadBlock ){
                        $.pixeDownloadBlock(e.data);
                    }else if( e.data.type == 'page' && $.pixeSaveBlockPage ){
                        $.pixeSaveBlockPage(e.data);
                    }
                    break;
                case 'keyboardAction':
                    if( e.data.action ){
                        $.pixeEditorContextMenu.doAction(e.data.action, window.pixeEditTarget);
                    }
                    break;
                default:
                    if( $.pixeDebug ){ console.log('iframe post', e.data); }
                    break;
            }

        }
    });

    // editor
    $.pixeEditorEvents = {};
    $.pixeEditor = {

        viewport: 'desktop',

        // collect dependency list
        mergeDependency: function(dependency, type, subtype = true){
            var t = this;

            if( ['animation', 'typo-preset', 'button-preset', 'font-family', 'icon-dep', 'bullet', 'navigation', 'touch-navigation', 'pagination', 'template'].indexOf(type) >= 0 ){
                if( !dependency[type] ){
                    dependency[type] = [];
                }

                if( Array.isArray(subtype) ){
                    dependency[type] = $.pixeUnion(dependency[type], subtype);
                }else if( dependency[type].indexOf(subtype) == -1 ){
                    dependency[type].push(subtype);
                }
            }else if( !dependency[type] ){
                dependency[type] = 1;
            }
        },

        // find all dependencies
        getDependency(editor){
            var t = this;
            var dependency = {};
            
            // editor dependency
            var editorDependency = editor.data('dependency');
            if( editorDependency ){
                for( var slug in editorDependency ){
                    t.mergeDependency(dependency, slug, editorDependency[slug]);
                }
            }

            // item dependency
            editor.find('.pixe-wrapper, .pixe-column, .pixe-item').each(function(){
                var itemDependency = $(this).data('dependency');
                if( itemDependency ){
                    for( var slug in itemDependency ){
                        t.mergeDependency(dependency, slug, itemDependency[slug]);
                    }
                }
            });

            return dependency;
        },

        // do autosave action after stop editing for 8s
        autosave: $.pixeDebounce(function(){
            if( pixeData.updateStatus == 'enable' ){
                $.pixeEditor.save('autosave');
            }
        }, 8000),

        // update parent settings
        updateSettingsPanel: function(item, slug, value){

            // if currently editing 
            if( window.pixeEditTarget && window.pixeEditTarget.is(item) ){

                // send something to parent frame
                $.pixeEditor.setParentStatus({
                    event: 'edit',
                    action: 'update',
                    id: item.data('settings')._id,
                    slug: slug,
                    value: value
                });
            }
        },
        updateNavigatorPanel: function(){
            if( $.pixeEditor.navigatorOpen ){
                $.pixeEditor.setParentStatus({
                    event: 'navigator',
                    action: 'init',
                    value: $.pixeGetEditorVal(window.pixeEditor)
                });
            }
        },

        // set publish button status
        setPublishStatus: function(action, data){

            data = $.extend({
                event: 'publish'
            }, data);

            switch(action){
                case 'edited':
                    if( pixeData.updateStatus == 'disable' ){
                        data.action = 'edited';
                        $.pixeEditor.setParentStatus(data);
                        pixeData.updateStatus = 'enable';
                    }

                    // autosave
                    $.pixeEditor.autosave();
                    break;
                case 'failed':
                    data.action = 'failed';
                    $.pixeEditor.setParentStatus(data);
                    pixeData.updateStatus = 'enable';
                    break;
                case 'success':
                    data.action = 'success';
                    $.pixeEditor.setParentStatus(data);

                    if( data.status != 'autosave' ){
                        pixeData.updateStatus = 'disable';
                    }else{
                        pixeData.updateStatus = 'enable';
                    }
                    break;
                case 'loading':
                    data.action = 'loading';
                    $.pixeEditor.setParentStatus(data);
                    pixeData.updateStatus = 'loading';
                    break;
            }
        },

        // save data
        // type : preview, refresh
        save: function(status, type){
            if( pixeData.autosave == 'off' && status == 'autosave' ) return '';

            var t = this;
            var styleData = [];
            var ajaxData = $.pixeGetAjaxData({
                action: (pixeData.type == 'post')? 'pixe_save_post_editor': 'pixe_save_template_editor',
                id: pixeData.id,
                type: pixeData.type,
                part: pixeData.part,
                status: status,
                settings: pixeData.editorSettings,
                content: JSON.stringify($.pixeGetEditorVal(window.pixeEditor, styleData, true))
            });

            // screenshot template part
            if( pixeData.type == 'template_part' ){
                t.savePreview();
            }

            // format & group style
            var styles = {};
            if( styleData.length ){
                for( var i in styleData ){
                    if( styleData[i].desktop ){
                        if( !styles.desktop ) styles.desktop = '';
                        styles.desktop += $.pixeCleanCss(Object.values(styleData[i].desktop).join(" "));
                    }
                    if( styleData[i].tablet ){
                        if( !styles.tablet ) styles.tablet = '';
                        styles.tablet += $.pixeCleanCss(Object.values(styleData[i].tablet).join(" "));
                    }
                    if( styleData[i].mobile ){
                        if( !styles.mobile ) styles.mobile = '';
                        styles.mobile += $.pixeCleanCss(Object.values(styleData[i].mobile).join(" "));
                    }
                } 
            }
            if( Object.keys(styles).length ){
                ajaxData.styles = styles;
            }

            // get dependency
            ajaxData.dependency = t.getDependency(window.pixeEditor);

            // not autosave display loading animation
            if( status != 'autosave' ){
                $.pixeEditor.setPublishStatus('loading');
            }else if( type == 'preview' ){
                $.pixeEditor.setPublishStatus('loading');
            }

            // update data
            $.ajax({
                type: 'POST',
                url: pixeData.ajaxUrl,
                data: ajaxData,
                dataType: 'json',
                error: function(jqXHR, textStatus, errorThrown){
                    console.log(jqXHR, textStatus, errorThrown);

                    // publish button status
                    if( status != 'autosave' || type == 'preview' ){
                        $.pixeEditor.setPublishStatus('failed', {
                            message: 'An error occurs, Please try again.'
                        });
                    }
                },
                success: function(data){
                    if( $.pixeDebug ){ console.log('builder data saved:', status, data); }

                    // publish button status
                    $.pixeEditor.setPublishStatus('success', {
                        revision: data.revision,
                        deletedRevision: data['deleted-revision'],
                        status: status
                    });

                    // redirect if preview
                    if( type == 'preview' ){
                        window.open(pixeData.previewUrl, 'pixepreview');
                    }else if( type == 'refresh' ){
                        window.location.reload();
                    }
                }
            });
        },
        savePreview: function(){
            var targetImage = document.body.querySelector('.pixe-template-container');
            if( targetImage ){
                html2canvas(targetImage, {
                    scrollX: 0,
                    scrollY: 0,
                    windowWidth: document.documentElement.scrollWidth,
                    windowHeight: document.documentElement.scrollHeight
                }).then(canvas => {
                    canvas.toBlob(function(blob) {
                        var formData = new FormData();
                        formData.append('action', 'pixe_save_template_preview');
                        formData.append('security', pixeData.nonce);
                        formData.append('id', pixeData.id);
                        formData.append('type', pixeData.type);
                        formData.append('part', pixeData.part);
                        formData.append('preview', blob, pixeData.id + '.webp');

                        $.ajax({
                            type: 'POST',
                            url: pixeData.ajaxUrl,
                            data: formData,
                            dataType: 'json',
                            contentType: false,
                            processData: false
                        });
                        
                    }, 'image/webp', 0.7);
                    
                });
            }
        },

        // sync pixe data with builder
        setParentData: function(values, isChanged){
            var sentData = {}; 
            if( values ){
                for( var i in values ){
                    var slug = values[i];
                    sentData[slug] = pixeData[slug];
                }
            }

            $.pixeEditor.setParentStatus({ 
                event: 'pixeData',  
                action: 'set', 
                value: sentData,
                isChanged: isChanged
            });
        },
        getParentData: function(values){
            $.pixeEditor.setParentStatus({ 
                event: 'pixeData',  
                action: 'get', 
                value: values
            });
        },

        // send post message to parent 
        setParentStatus: function(settings){
            settings = $.extend({
                host: 'pixe'
            }, settings);

            window.parent.postMessage(settings, window.location.origin);
        },
        
        // render the page
        renderBlock: function(block){
            var settings = block.data('settings');
            if( settings.ID ){
                var ajaxData = $.pixeGetAjaxData({
                    id: settings.ID
                });

                if( settings._source == 'pixe' ){
                    ajaxData.action = 'pixe_get_prebuilt_content';
                }else if( settings._type == 'template' ){
                    ajaxData.action = 'pixe_get_template';
                }else if( settings._type == 'block' ){
                    ajaxData.action = 'pixe_get_block';
                }

                $.pixeAjax({
                    ajaxData: ajaxData,
                    defaultErrorAction: false,
                    onError: function(data){
                        block.trigger('removeblock');
                        block.remove();
                        console.log('Render Block Error');
                    },
                    onSuccess: function(data){
                        var content = data.content;
                        $.pixeEditor.setUniqueIdData(content);
                       
                        // render block content
                        var blockContent = $.pixeEditor.render(content);
                        if( settings.type == 'column' && settings.width ){
                            $.pixeColumn.setWidth(blockContent, settings.width, false);
                        }

                        // trigger to update history
                        block.data('block-content', blockContent);
                        block.trigger('convertblock');

                        // replace the block with content
                        block.replaceWith(blockContent);

                        // set class for editor
                        var parentContainer = blockContent.parent().closest('.pixe-column, .pixe-wrapper, .pixe-editor');
                        $.pixeEditor.setStatus(parentContainer);
                        
                        // update template object
                        $.pixeAppendTemplateData(data.templates);

                        // add control
                        $.pixeControlStyle.addControl(data.control);
                    }
                });
            }
        },
        render: function(data, renderStyle = true, preview = false, container){
            var elements = $();

            for( var i in data ){
                if( !data[i] ) continue; 

                switch( data[i]._type ){
                    case 'block-dragging':
                        data[i]._type = 'block';
                        var block = $('<div class="pixe-block-container" ></div>');
                        block.data('settings', data[i]);
                        elements = elements.add(block);
                        if( container ){ container.append(block); }
                        break;
                    case 'block':
                    case 'template':
                        var block = $('<div class="pixe-block-container" ></div>');
                        block.data('settings', data[i]);
                        elements = elements.add(block);
                        $.pixeEditor.renderBlock(block);
                        if( container ){ container.append(block); }
                        break;
                    case 'collection':
                        elements = elements.add($.pixeCollection.create(data[i], renderStyle, preview, container));
                        break;
                    case 'wrapper':
                        elements = elements.add($.pixeWrapper.create(data[i], renderStyle, preview, container));
                        break;
                    case 'column':
                        elements = elements.add($.pixeColumn.create(data[i], renderStyle, preview, container));
                        break;
                    case 'element':
                        elements = elements.add($.pixeItem.create(data[i], renderStyle, preview, container));
                        break;
                }
            }
    
            return elements;
        },
        rerender: function(item, type){
            var settings = item.data('settings');

            switch( settings._type ){
                case 'block':
                case 'template':
                    $.pixeEditor.renderBlock(item);
                    break;
                case 'collection':
                    $.pixeCollection.render(item, type);
                    break;
                case 'wrapper':
                    $.pixeWrapper.render(item, type);
                    break;
                case 'column':
                    $.pixeColumn.render(item, type);
                    break;
                case 'element':
                    $.pixeItem.render(item, type);
                    break;
            }
        },

        // dragging from parent window
        parentDrag: function(data){
            var t = this;
            var item = t.render(data.value, false);

            var subtype = $.pixeDragDrop.getItemType(item);
            var action = $.pixeHistory.createAction(item, 'add', subtype);
            var effectColumns = $();

            // dragging event
            $.pixeDragDrop.dragging(item, window.pixeEditor, {
                handler: false,
                scrollTarget: window.pixeDropTarget,
                events: 'mousemove mouseup parentdragstop',
                onMousemove: function(e){
                    $.pixeEditor.setParentStatus({
                        event: 'dragElement',
                        action: 'mousemove',
                        clientX: e.clientX,
                        clientY: e.clientY
                    });
                },
                onMouseup: function(e){
                    $.pixeEditor.setParentStatus({
                        event: 'dragElement',
                        action: 'mouseup'
                    });
                },
                beforeDropItem: function(dropTarget, item, editor){
                    if( subtype != 'column' ) return;

                    // target item & siblings
                    if( dropTarget.hasClass('pixe-h') ){
                        var targetColumn = dropTarget.closest('.pixe-column');
                        var targetRow = targetColumn.attr('data-row');
                        effectColumns = effectColumns.add(targetColumn);
                        effectColumns = effectColumns.add(targetColumn.siblings('[data-row="' + targetRow + '"]'));
                    }

                    // save previous value
                    effectColumns.each(function(){
                        $.pixeHistory.setActionStep(action, $(this), 'width', $(this).data('settings').width, true);
                    });
                },
                onDropItem: function(item, editor){
                    // assign unique id on drop item from editor
                    t.setUniqueId(item);
                    t.rerender(item);
                    item.find('.pixe-column, .pixe-item').each(function(){
                        t.rerender($(this));
                    });
                }, 
                afterDropItem:  function(item, editor){
                    // save new value
                    if( effectColumns ){
                        effectColumns.each(function(){
                            $.pixeHistory.setActionStep(action, $(this), 'width', $(this).data('settings').width);
                        });
                    }
                    
                    // update new location & add action
                    $.pixeHistory.setActionLocation(action, 'target');
                    $.pixeHistory.addAction(action);
                }
            });
        },

        // assign unique id to item, column, wrapper
        setUniqueId: function(item){
            var area = window.pixeEditor.attr('data-area');

            function setID(target){
                if( !target.data('settings') ) return;
                
                var uniqueId = $.pixeGetUniqueId();
                var id = 'pixe-' + area + '-' + uniqueId;
        
                target.attr('data-id', id);
                target.data('settings')._id = id;
            }

            if( item.hasClass('pixe-wrapper') || item.hasClass('pixe-column') || item.hasClass('pixe-item') ){
                setID(item);
            }
            item.find('.pixe-wrapper, .pixe-column, .pixe-item').each(function(){
                setID($(this));
            });
            
        },
        setUniqueIdData: function(settings, nested = true, replace = true){
            var t = this;

            if( Array.isArray(settings) ){
                for( var i in settings ){
                    if( settings[i].type == 'block' || settings[i].type == 'block-dragging' ) continue;
                    t.setUniqueIdData(settings[i], nested, replace);
                }
            }else{
                if( replace || !settings._id ){
                    var uniqueId = $.pixeGetUniqueId();
                    settings._id = 'pixe-' + window.pixeEditor.attr('data-area') + '-' + uniqueId;
                }
                
                if( nested ){
                    if( settings._elements ){
                        for( var i in settings._elements ){
                            t.setUniqueIdData(settings._elements[i], nested, replace);
                        }
                    }else if( settings._tab ){
                        for( var i in settings._tab ){
                            var currentTab = settings._tab[i];
                            for( var j in currentTab.content ){
                                t.setUniqueIdData(currentTab.content[j], nested, replace);
                            }
                        }
                    }
                }
            }
        },
        clearIdData: function(settings){
            var t = this;

            if( Array.isArray(settings) ){
                for( var i in settings ){
                    if( settings[i].type == 'block' || settings[i].type == 'block-dragging' ) continue;
                    t.clearIdData(settings[i]);
                }
            }else{
                delete settings._id;
                if( settings._elements ){
                    for( var i in settings._elements ){
                        t.clearIdData(settings._elements[i]);
                    }
                }else if( settings._tab ){
                    for( var i in settings._tab ){
                        var currentTab = settings._tab[i];
                        for( var j in currentTab.content ){
                            t.clearIdData(currentTab.content[j]);
                        }
                    }
                }
            }
        },

        // determine max editor id
        initUniqueID: function(data){
            var editor = window.pixeEditor;
            var maxId = editor.data('unique-id');
            var replaceStr = 'pixe-' + editor.attr('data-area') + '-';
            if( !maxId ){ maxId = 0; } 

            function getMaxId(elems){
                for( var i in elems ){
                    if( !elems[i] ) continue; 
                    
                    if( elems[i]._id ){
                        var id = parseInt(elems[i]._id.replace(replaceStr, ''));
                        if( !isNaN(id) && id > maxId ){
                            maxId = id;
                        } 
                    }

                    if( elems[i]._elements ){
                        getMaxId(elems[i]._elements);
                    }else if( elems[i]._tabo ){
                        for( var j in elems[i]._tabo ){
                            var currentTab = elems[i]._tabo[j];
                            getMaxId(currentTab);
                        }
                    }else if( elems[i]._tab ){
                        for( var j in elems[i]._tab ){
                            var currentTab = elems[i]._tab[j];
                            getMaxId(currentTab.content);
                        }
                    }
                }
            }
            getMaxId(data);

            editor.data('unique-id', maxId);
        },

        // use to assign necessary class | attributes when there're changes to item
        isEmpty: function(){
            var editor = window.pixeEditor;
            
            // not empty
            if( editor.children().not('style, .pixe-editor-empty, .pixe-close-popup').length ){

                if( editor.hasClass('pixe-empty') ){
                    editor.removeClass('pixe-empty');
                    editor.children('.pixe-editor-empty').remove();
                }
                return false;

            // empty
            }else{ 
                
                if( !editor.hasClass('pixe-empty') ){
                    var emptyArea = $($.pixeEditorArea.emptyHtml());
                    editor.append(emptyArea);
                    editor.addClass('pixe-empty');

                    emptyArea.on('click', '.pixe-action', function(){
                        if( $(this).hasClass('pixe-new-element') ){
                            $.pixeEditor.setParentStatus({
                                event: 'newContainer',
                            });
                            pixeData.hideBuilderPanel = false;
                        }else if( $(this).hasClass('pixe-new-container') ){
                            if( pixeData.type == 'template_part' ){
                                $.pixeEditor.setParentStatus({
                                    event: 'newTemplate',
                                    type: pixeData.part
                                });
                            }else{
                                $.pixeEditor.setParentStatus({
                                    event: 'newBlock',
                                });
                            }
                        }
                    });
                }
                return true;
            }

        },
        setStatus: function(container){
            var t = this;
            var area;

            if( !container ){ 
                // check for empty editor status
                if( t.isEmpty() ){ return; }

                area = window.pixeEditor.find('.pixe-wrapper, .pixe-column, .pixe-tab-container');
            }else{
                area = container.find('.pixe-wrapper, .pixe-column, .pixe-tab-container');
                if( container.is('.pixe-wrapper, .pixe-column, .pixe-tab-container') ){
                    area = container.add(area);
                }
            }

            // tab container
            area.filter('.pixe-tab-container').each(function(){
                $.pixeItem.setTabContainerStatus($(this));
            });

            // column
            area.filter('.pixe-column').each(function(){
                $.pixeColumn.setStatus($(this));
                $.pixeColumn.setColumnAtts($(this).children('.pixe-column-content'));
            });

            // wrapper
            area.filter('.pixe-wrapper').each(function(){
                $.pixeWrapper.setStatus($(this));
                $.pixeColumn.setColumnAtts($(this).children('.pixe-wrapper-content'));
            });

            // collection
            area.filter('.pixe-collection').each(function(){
                $.pixeCollection.setStatus($(this));
            });
        },

        // change viewport
        changeViewport: function(device){
            var t = this;
            t.viewport = device;

            // body css
            if( device == 'desktop' ){
                $(document.body).removeAttr('data-device');
            }else{
                $(document.body).attr('data-device', device);
            }

            // set item data
            $.pixeEditor.setStatus();
            
            // wrapper data
            window.pixeEditor.find('.pixe-wrapper').each(function(){
                $.pixeWrapper.renderStyle($(this), 'padding');
            });

            // column data
            window.pixeEditor.find('.pixe-column').each(function(){
                $.pixeColumn.renderStyle($(this), 'padding');
                $.pixeColumn.setWidthText($(this));
            });

            // spacer item
            window.pixeEditor.find('.pixe-item-spacer').each(function(){
                $.pixeItem.renderStyle($(this), 'spaces');
            });

            $(window).trigger('viewportchange');
        },

        // update settings on side panel
        clearEditTarget: function(resetPanel = true){
            window.pixeEditTarget = undefined;
            
            if( resetPanel ){
                $.pixeEditor.setParentStatus({
                    event: 'newElement'
                });
            }
        },
        setEditTarget: function(item, activeTab, isOpenPanel = true){
            if( !window.pixeEditTarget || !window.pixeEditTarget.is(item) ){
                window.pixeEditTarget = item;
                window.pixeEditHistory = undefined;
            }

            $.pixeEditor.setParentStatus({
                event: 'edit',
                value: item.data('settings'),
                activeTab: activeTab,
                isOpenPanel: isOpenPanel
            });
        },

        initParentData: function(){
            $.pixeEditor.setParentData(['postTitle', 'typoPreset', 'controlPreset', 'colorPreset', 'variablePreset', 'buttonPreset', 'adminIconPreset', 'editorSettings', 'site']);
        }

    };

    $.pixeEditorContextMenu = {

        isOpen: false,

        init: function(){
            if( $(document.body).hasClass('pixe-preview-thumbnail') ) return;
            
            var t = this;

            window.pixeEditor.on('contextmenu', function(e){
                if( pixeData.disableContextMenu ) return;

                var point = { x: e.clientX, y: e.clientY };
                var scrollPos = window.scrollY;
                var windowWidth = window.innerWidth;
                var windowHeight = window.innerHeight;
                var item = t.getTargetItem($(e.target));

                if( item.data('settings') ){
                    $(document.body).trigger('closepopup');

                    var popup = new $.pixePopup({
                        style: 'pixe-context-popup',
                        content: t.getContent(item),
                        customPosition: {},
                        onClose: function(){
                            delete t.contextTarget;
                        }
                    });

                    // set position
                    var popupArea = {
                        width: popup.popupBox.outerWidth(),
                        height: popup.popupBox.outerHeight(),
                    };
                    var position = {};

                    // check top position
                    if( point.y + popupArea.height <= windowHeight ){
                        position.top = scrollPos + point.y;
                    }else if( point.y > popupArea.height ){
                        position.top = scrollPos + point.y - popupArea.height;
                    }else{
                        position.top = scrollPos + point.y;

                        var documentHeight = $(document.body).outerHeight();
                        if( position.top + popupArea.height > documentHeight ){
                            position.top = documentHeight - popupArea.height - 20;
                        }
                    }

                    // left position
                    if( point.x + popupArea.width <= windowWidth ){
                        position.left = point.x;
                    }else{
                        position.left = point.x - popupArea.width;
                    }

                    popup.popupBox.css(position);

                    // events
                    popup.popupBox.on('click', '.pixe-action', function(){
                        var action = $(this).attr('data-action');
                        t.doAction(action, item);
                        popup.close();
                    });

                    e.preventDefault();
                }
            });

            t.bindKeyboardActions();
        },

        styleKey: ['_id', '_type', '_subtype', '_elements', '_element', 'id', 'title', 'text', 'content', 'link', 'image', 'video'],
        elementStyleKey: {
            'icon': { 'icon': ['icon'] }
        },

        pasteStyle: function(original, target){
            var t = this;
            if( !original || !original.length ) return;

            // check if same object type
            var origSettings = original.data('settings');
            var targetSettings = target.data('settings');

            if( origSettings._type != targetSettings._type ) return;

            if( origSettings._type == 'wrapper' || origSettings._type == 'column' ){
                // do nothing
            }else if( origSettings._type == 'collection' ){
                if( origSettings._subtype != targetSettings._subtype ) return;
            }else if( origSettings._type == 'element' ){
                if( origSettings._element != targetSettings._element ) return;
            }

            // create history
            var action = $.pixeHistory.createAction(target, 'paste-style', 'item', 'Paste Style');
            $.pixeHistory.setActionStep(action, target, 'item', targetSettings, true);

            // remove target style
            for( var slug in targetSettings ){

                // general key style
                if( t.styleKey.indexOf(slug) >= 0 ) continue;

                // target element key style
                if( targetSettings._type == 'element' && t.elementStyleKey[targetSettings._element] ){
                    var elemKey = t.elementStyleKey[targetSettings._element];

                    // inner object eg. ['icon']
                    if( typeof(elemKey[slug]) == 'object' ){
                        for( var innerSlug in targetSettings[slug] ){
                            if( elemKey[slug].indexOf(innerSlug) >= 0 ) continue;
                            delete targetSettings[slug][innerSlug];
                        }

                    // element object eg. icon
                    }else if( elemKey[slug] ){
                        continue;
                    }else{
                        delete targetSettings[slug];
                    }

                }else{
                    delete targetSettings[slug];
                }
            }
            
            // add original style
            for( var slug in origSettings ){

                // general key style
                if( t.styleKey.indexOf(slug) >= 0 ) continue;

                // target element key style
                if( targetSettings._type == 'element' && t.elementStyleKey[targetSettings._element] ){
                    var elemKey = t.elementStyleKey[targetSettings._element];

                    // inner object eg. ['icon']
                    if( typeof(elemKey[slug]) == 'object' ){
                        if( !targetSettings[slug] ) targetSettings[slug] = {};

                        for( var innerSlug in origSettings[slug] ){
                            if( elemKey[slug].indexOf(innerSlug) >= 0 ) continue;
                            targetSettings[slug][innerSlug] = $.pixeClone(origSettings[slug][innerSlug]);
                        }

                    // element object eg. 'icon'
                    }else if( elemKey[slug] ){
                        continue;
                    }else{
                        targetSettings[slug] = $.pixeClone(origSettings[slug]);
                    }

                }else{
                    targetSettings[slug] = $.pixeClone(origSettings[slug]);
                }

            }

            // add to history
            $.pixeHistory.setActionStep(action, target, 'item', targetSettings, false);
            $.pixeHistory.addAction(action);
            
            // rerender
            $.pixeEditor.rerender(target);
        },

        doAction: function(action, target){

            // ignore if editing input / textarea
            var el = document.activeElement;
            if( el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') ){
                return;
            }

            // do keyboard action
            var t = this;
            switch(action){
                case 'delete':
                    if( target.hasClass('pixe-item') ){
                        $.pixeItem.remove(target);
                    }else if( target.hasClass('pixe-column') ){
                        $.pixeColumn.remove(target);
                    }else if( target.hasClass('pixe-wrapper') ){
                        $.pixeWrapper.remove(target);
                    }
                    break;

                case 'undo':
                    $.pixeHistory.undo();
                    break;

                case 'redo':
                case 'redoMac':
                    $.pixeHistory.redo();
                    break;

                case 'duplicate':
                    if( target && target.length ){
                        target.children('.pixe-item-toolbar, .pixe-column-toolbar, .pixe-wrapper-toolbar').children('.pixe-copy').trigger('click');
                    }
                    break;

                case 'copy':
                    t.clipboardItem = target;
                    break;

                case 'paste':
                    if( t.clipboardItem && t.clipboardItem.length ){
                        
                        // copy & assign unique id
                        var settings = $.pixeClone($.pixeGetEditorVal(t.clipboardItem));
                        $.pixeEditor.setUniqueIdData(settings);

                        // create item
                        var newItem = $.pixeEditor.render([settings]);
                        
                        if( target.is('.pixe-column') ){
                            newItem.appendTo(target.children('.pixe-column-content'));

                        }else if( target.is('.pixe-wrapper') ){
                            newItem.appendTo(target.children('.pixe-wrapper-content'));
                            
                        }else{
                            newItem.insertAfter(target); 
                        }
                        $.pixeEditor.setStatus();

                        // save for history
                        var action = $.pixeHistory.createAction(newItem, 'add');
                        $.pixeHistory.addAction(action);
                    }
                    break;

                case 'pasteStyle':
                    t.pasteStyle(t.clipboardItem, target);
                    break;

                case 'nav':
                    var settings, targetId;
                    if( target ){  
                        settings = target.data('settings');
                        targetId = settings._id;
                    }

                    $.pixeEditor.setParentStatus({
                        event: 'navigator',
                        action: 'init',
                        value: $.pixeGetEditorVal(window.pixeEditor),
                        target: targetId
                    });

                    $(window).trigger('closepopup');
                    $(document.body).trigger('closeinline');
                    break;

                case 'preview':
                    $.pixeEditor.setParentStatus({ event: 'previewToggle' });
                    break;

                case 'customBlock':
                    var settings, targetId;
                    if( target ){  
                        settings = target.data('settings');
                        targetId = settings._id;
                    }
                    if( !targetId ) return;

                    // popup to fill name
                    var confirmBox = $.pixeConfirmationName({
                        title: 'Custom Block Name'
                    });
                    confirmBox.on('click', '.pixe-submit', function(){
                        var title = confirmBox.find('input[type="text"]').val();

                        var status = $.pixeSaveBlock({
                            type: 'block',
                            title: title,
                            id: targetId
                        });

                        if( status ){
                            confirmBox.fadeOut(150, function(){
                                $(this).remove();
                            });
                        }
                    });
                    break;

                case 'save':
                    if( pixeData.updateStatus == 'enable' ){
                        $.pixeEditor.save('publish');
                    }
                    break;
            }

        },

        bindKeyboardActions: function(){
            var t = this;
            $(document).on('keydown', function(e){
                var keyboardAction = $.pixeGetKeyboardAction(e);

                if( $(document.body).hasClass('pixe-inline-editing') ){
                    if( ['undo', 'redo', 'redoMac', 'paste', 'delete'].indexOf(keyboardAction) >= 0 ){
                        return;
                    }else if( keyboardAction == 'copy' && $.pixeRange.isHighlight() ){
                        return;
                    }
                }else if( $.pixeRange.isHighlight() ){
                    if( ['copy', 'paste'].indexOf(keyboardAction) >= 0 ){
                        return;
                    }
                }

                if( keyboardAction ){
                    t.doAction(keyboardAction, window.pixeEditTarget);
                    e.preventDefault();
                }
            });
        },

        getTargetItem: function(item){
            var t = this;
            var item = item.closest('.pixe-item, .pixe-column, .pixe-wrapper');

            if( item.length && !item.data('settings') ){
                item = t.getTargetItem(item.parent());
            }else{
                var settings = item.data('settings');
                if( settings &&
                    (settings._type == 'wrapper' && settings._subtype == 'slider') ||
                    (settings._type == 'column' && settings._subtype == 'carousel') ){
                    item = t.getTargetItem(item.parent());
                }
            }

            return item;
        },

        getRow: function(title, action, shortcut){
            var ret = $('<div class="pixe-action" ></div>');
            ret.append('<div class="pixe-head" >' + title + '</div>');
            ret.attr('data-action', action);

            if( shortcut ){
                ret.append('<div class="pixe-tail ">' + shortcut + '</div>');
            }

            return ret;
        },

        getContent: function(item){
            var t = this;
            var settings = item.data('settings');
            var content = $('<div class="pixe-context-content" ></div>');

            var ua = navigator.userAgent.toLowerCase();
            var isMac = ua.includes('mac');

            // head
            var title = $('<div class="pixe-context-head" ></div>');
            if( settings._type == 'wrapper' ){
                title.append('Container');
            }else if( settings._type == 'collection' ){
                if( settings._subtype == 'carousel' ){
                    title.append('Carousel');
                }else if( settings._subtype == 'slider' ){
                    title.append('Slider');
                }
            }else if( settings._type == 'column' ){
                title.append('Column');
            }else if( settings._type == 'element' ){
                if( pixeData.elements[settings._element] ){
                    title.append(pixeData.elements[settings._element].title);
                }else{
                    title.append(settings._element);
                }
            }
            title.append('<span>[data-id="' + settings._id + '"]</span>');
            title.appendTo(content);
            
            // history
            var history = $('<div class="pixe-context-section" ></div>'); 
            history.append(t.getRow('Undo', 'undo', isMac? '⌘+Z': 'Ctrl+Z'));
            history.append(t.getRow('Redo', 'redo', isMac? '⌘+Shift+Z': 'Ctrl+Y'));
            history.appendTo(content);

            // actions
            var actions = $('<div class="pixe-context-section" ></div>');
            actions.append(t.getRow('Copy', 'copy', isMac? '⌘+C': 'Ctrl+C'));
            actions.append(t.getRow('Paste', 'paste', isMac? '⌘+V': 'Ctrl+V'));
            actions.append(t.getRow('Paste Style', 'pasteStyle', isMac? '⌘+⇧+V': 'Ctrl+⇧+V'));
            actions.append(t.getRow('Duplicate', 'duplicate', isMac? '⌘+D': 'Ctrl+D'));
            actions.appendTo(content);

            // extra
            var extra = $('<div class="pixe-context-section" ></div>');
            extra.append(t.getRow('Show in Navigator', 'nav', isMac? '⌘+i': 'Ctrl+i'));
            extra.append(t.getRow('Save as Custom Block', 'customBlock'));
            extra.appendTo(content);

            // footer
            var footer = $('<div class="pixe-context-section" ></div>');
            footer.append(t.getRow('Delete', 'delete', '⇧+⌦'));
            footer.appendTo(content);

            return content;
        }

    }

    $(document).ready(function(){
        if( pixeData.type == 'script' ) return;

        if( window.top === window.self ){
            $(document.body).empty()
            $(document.body).append('<h1 style="text-align: center; padding: 50px 0 20px;">Forbidden</h1>');
            $(document.body).append('<div style="text-align: center;" >Access direclty is not allowed</div>');
            return;
        }

        // init variable to be in right format
        $.pixeVariableInit(['editorSettings', 'typoPreset', 'colorPreset', 'controlPreset', 'variablePreset', 'buttonPreset']);

        // find editor area
        window.pixeEditor = $('#pixe-editor');
        if( !window.pixeEditor.length ){
            $(document.body).append($.pixeEditorArea.noTheContent());
        }

        // init editor area
        $.pixeEditorArea.init();
        if( !$.pixeEditorArea.previewThumbnail ){ $.pixeDebug = true; }

        // bind tip text
        $(document.body).pixeTipText();

        // init components
        window.pixeEditor.pixeWrapper();
        window.pixeEditor.pixeColumn();
        window.pixeEditor.pixeItem();
        window.pixeEditor.pixeDragDrop();
        window.pixeEditor.pixeInlineEdit();
        window.pixeDropTarget = window.pixeEditor;

        // get typo data
        if( !pixeData.revision ){
            $.pixeEditor.initParentData();
        }
        $.pixeEditor.getParentData(['thumbnailSizes', 'postTypes', 'iconPreset', 'postTemplate', 'taxonomyTemplate', 'popupTemplate', 'headerTemplate', 'footerTemplate', 'defaultHeader', 'defaultFooter', 'navMenuUrl']);
        
        // init preset data
        $.pixeTypoStyle.updateStyle();
        $.pixeColorStyle.updateStyle();
        $.pixeControlStyle.updatePresetStyle();
        $.pixeVariablePreset.updateStyle();
        $.pixeButtonPreset.updateStyle();

        // wrapper width
        var editorContainer = window.pixeEditor.parent();
        function setWindowWidth(){
            window.pixeEditor.css({
                '--pixe--window--width': '',
                '--pixe--content--width': ''
            });

            var editorWidth = editorContainer.width();
            var rootContentWidth = parseFloat(editorContainer.css('--pixe--content--width'));
            var contentWidth = (editorWidth < rootContentWidth)? editorWidth + 'px': '';

            window.pixeEditor.css({ '--pixe--window--width': editorWidth + 'px' });
            if( editorWidth > 0 && contentWidth ){
                window.pixeEditor.css({ '--pixe--content--width': contentWidth });
            }
        }
        setWindowWidth();
        $(window).on('load resize resizewidth', function(){ setWindowWidth(); });

        // initiate main content
        if( pixeData.mainContent ){
            $.pixeEditor.initUniqueID(pixeData.mainContent);
            $.pixeEditor.setUniqueIdData(pixeData.mainContent, true, false);
            $.pixeEditor.render(pixeData.mainContent, undefined, undefined, window.pixeEditor);

            // style
            $.pixeVideo.resizePortrait(window.pixeEditor);
        }
        
        // settings for grid post_template & taxonomy_template
        if( pixeData.templateLayout == 'grid' ){

            // render empty content
            if( !pixeData.mainContent ){
                var emptyContent = [{"_type":"column","_subtype":"query","width":"30%"}];
                $.pixeEditor.setUniqueIdData(emptyContent); 
                $.pixeEditor.render(emptyContent, undefined, undefined, window.pixeEditor);
            }

            // avoid dropping item on editor
            window.pixeEditor.attr('data-droppable', 'no');

            // assign default drop target
            window.pixeDropTarget = window.pixeEditor.children().first();
        }
        $.pixeEditor.setStatus();
        $.pixeEditorContextMenu.init();

        // init event
        if( $.pixeEditorEvents.contentinit ){
            window.pixeEditor.trigger('contentinit');
        }

        // click on iframe content
        $(window).on('click', function(e){
            var target = $(e.target);
            
            // new element button
            if( target.is('.pixe-wrapper-content, .pixe-column-content, .pixe-tab-container') &&
                (target.closest('.pixe-wrapper.pixe-empty, .pixe-column.pixe-empty, .pixe-tab-container.pixe-empty').length) ){

                window.pixeDropTarget = target;
                $.pixeEditor.clearEditTarget();

            // click event
            }else{
                
                // update settings panel when click on item
                if( !pixeData.isItemEditing && !target.closest('.pixe-action').length && target.closest('.pixe-wrapper, .pixe-column, .pixe-item').length ){
                    
                    var item = target.closest('.pixe-wrapper, .pixe-column, .pixe-item');
                    if( !item.data('settings') && item.closest('.pixe-item-post-list').length ){
                        item = item.closest('.pixe-item-post-list');
                    }
                    if( !window.pixeEditTarget || !window.pixeEditTarget.is(item) ){
                        $.pixeEditor.setEditTarget(item, undefined, false);
                    }
                }

                // hide panel if not locked
                if( pixeData.hideBuilderPanel ){
                    window.pixeDropTarget = window.pixeEditor;
                    $.pixeEditor.setParentStatus({ event: 'hidePanel' });
                }
                pixeData.hideBuilderPanel = true;
                pixeData.isItemEditing = false;
            }

            // locked element
            if( target.closest('.pixe-collection, .pixe-item').hasClass('pixe-locked') ){
                var message = pixei18n.upgrade.renewContent2;
                    message += '<div class="pixe-button-wrap" >';
                    message += $.pixeProUpgradeButton('renewLicense', '?source=locked-editor-element', 'recycle');
                    message += '<input class="pixe-cancel" type="button" value="Cancel">';
                    message += '</div>';

                $.pixeConfirmationBox({
                    icon: 'info',
                    title: pixei18n.upgrade.renewTitle,
                    message: message,
                    extraClass: 'pixe-confirmation-upgrade',
                    confirmText: false,
                    cancelText: false,
                    customButton: true
                });
            }

        });

        // prevent link from being click
        $(document).on('click', 'a, input[type="submit"]', function(e){
            if( $(this).hasClass('pixe-link') ) return;
            e.preventDefault();
        });
        $(document).on('submit', 'form', function(e){
            e.preventDefault();
        });

        // log the item data
        if( $.pixeDebug ){
            window.pixeEditor.on('contextmenu', '.pixe-svg-wrapper-settings, .pixe-svg-column-settings, .pixe-svg-item-settings', function(){
                var item = $(this).closest('.pixe-wrapper, .pixe-column, .pixe-item');
                var object = $.pixeClone([$.pixeGetEditorVal(item)]);
                $.pixeEditor.clearIdData(object);
                console.log(object);
                console.log(JSON.stringify(object));
                // console.log($.pixeToPHPArray(object));
            });
        }

    });

})(jQuery);	
