(function($){
    "use strict";

    const { __, _x, sprintf } = wp.i18n;

    $.pixeBlockSettings = {

        blockCatLabels: {
            cta: 'CTA'
        },

        init: function(settings){
            settings = $.extend({
                activeTab: 'blocks',
                container: undefined
            }, settings);

            var t = this;
            var container = $('<div class="pixe-template-settings pixe-box-sizing" ></div>');

            // popup content
            var tab = $('<div class="pixe-settings-tab" ></div>');
            tab.appendTo(container);

            // init header area
            t.tabHead = $('<div class="pixe-settings-tab-head" ></div>');
            t.tabHead.append('<span data-tab="blocks" >' + $.pixeGetAdminIcon('block') + pixei18n.template.blocks + '</span>');
            t.tabHead.append('<span data-tab="sites" >' + $.pixeGetAdminIcon('page') + pixei18n.template.sites + '</span>');
            t.tabHead.append('<span data-tab="custom-blocks" >' + $.pixeGetAdminIcon('customBlock') + pixei18n.template.customBlocks + '</span>');
            t.tabHead.append('<span data-tab="custom-pages" >' + $.pixeGetAdminIcon('customPage') + pixei18n.template.customPages + '</span>');
            tab.append(t.tabHead);
    
            // init content area
            t.tabContent = $('<div class="pixe-settings-tab-content" ></div>');
            t.tabContent.appendTo(tab);

            var tabHeadRight = $('<div class="pixe-settings-tab-head-right" ></div>');
            tabHeadRight.append($.pixeGetAdminIcon('favourite', { data: 'data-tab="favourites"' }));
            tabHeadRight.append('<span data-tab="import" >' + $.pixeGetAdminIcon('upload') + 'Import</span>');
            tabHeadRight.append('<div class="pixe-divider-v" ></div>');
            tabHeadRight.append($.pixeGetAdminIcon('cancel', { class: 'pixe-close' }));
            tabHeadRight.appendTo(t.tabHead);
            
            // create popup
            t.lb = new $.pixeLightboxPopup({
                class: 'pixe-lb-template-settings',
                content: container
            });

            // close button
            t.tabHead.on('click', '.pixe-close', function(){
                t.lb.close();
                $.pixeBuilder.displaySettingsByType();
            });

            // get content
            t.changeTab(settings.activeTab);
            t.tabHead.on('click', '[data-tab]', function(){
                t.changeTab($(this).attr('data-tab'));
            });

        },

        // change font settings tab
        changeTab: function(activeTab){
            var t = this;
            var tab = t.tabHead.find('[data-tab="' + activeTab + '"]');
            if( tab.hasClass('pixe-active') ) return;

            t.tabHead.find('.pixe-active').removeClass('pixe-active');
            tab.addClass('pixe-active');
            
            // tab content
            switch(activeTab){
                case 'blocks':
                case 'pages':
                case 'sites':
                    t.getPrebuiltTemplateSection(t.tabContent, activeTab);
                    break;
                case 'custom-blocks':
                case 'custom-pages':
                    if( !t.getCustomTemplateItems || typeof(pixePP) === 'undefined' || !pixePP.active ){
                        t.tabContent.empty();
            
                        var content = $('<div class="pixe-template-section pixe-fixed-height pixe-type-notice" ></div>');
                        content.append($.pixeProNotice('feature', 'block'));
                        content.appendTo(t.tabContent);
                    }else{
                        t.getCustomTemplateItems(activeTab);
                    }
                    break;
                case 'favourites':
                    t.getFavouriteSection(t.tabContent);
                    break;
                case 'import':
                    if( !t.getImportArea || typeof(pixePP) === 'undefined' || !pixePP.active ){
                        t.tabContent.empty();
            
                        var content = $('<div class="pixe-template-section pixe-fixed-height pixe-type-notice" ></div>');
                        content.append($.pixeProNotice('feature', 'block'));
                        content.appendTo(t.tabContent);
                    }else{
                        t.getImportArea();
                    }
                    break;
            }
        },

        // get favourite section
        getFavouriteSection: function(tabContent){
            var t = this;
            var hasContent = false;
            tabContent.empty();
            
            var container = $('<div class="pixe-template-section pixe-fixed-height pixe-scrollbar" ></div>');
            container.appendTo(tabContent);

            if( pixeData.favouriteBlock.blocks && pixeData.favouriteBlock.blocks.length && typeof(pixePbBlocks) != 'undefined' ){
                hasContent = true;
                container.append('<div class="pixe-template-custom-title" >' + pixei18n.template.blocks + '</div>');
                t.getFavouriteSubSection(container, 'blocks');
            }
            if( pixeData.favouriteBlock.sites && pixeData.favouriteBlock.sites.length && typeof(pixePbSites) != 'undefined' ){
                hasContent = true;
                container.append('<div class="pixe-template-custom-title" >' + pixei18n.template.sites + '</div>');
                t.getFavouriteSubSection(container, 'sites');
            }

            if( !hasContent ){
                container.addClass('pixe-type-notice pixe-l');
                container.append($.pixeEmptyNotice('favourite-block'));
            }
        },
        getFavouriteSubSection: function(tabContent, type){
            
            var t = this;
            var container = $('<div class="pixe-template-sub-section" ></div>');
            container.append('<div class="pixe-line" ></div>');
            container.append('<div class="pixe-line" ></div>');
            container.append('<div class="pixe-line" ></div>');
            container.appendTo(tabContent);

            var lines = container.children('.pixe-line');
            var blockIds, blocks;
            switch(type){
                case 'blocks':
                    blockIds = pixeData.favouriteBlock.blocks;
                    blocks = pixePbBlocks;
                    break;
                case 'sites':
                    blockIds = pixeData.favouriteBlock.sites;
                    blocks = pixePbSites;
                    break;
            }

            function addBlock(id, settings){
                var item = t.getPrebuiltTemplateItem(id, type, settings);
                var minHeight = 999999;
                var targetLine;
                lines.each(function(){
                    var lineHeight = $(this).outerHeight();
                    
                    if( lineHeight < minHeight ){
                        minHeight = lineHeight;
                        targetLine = $(this);
                    }
                });

                targetLine.append(item);
            }

            if( blockIds && blockIds.length ){
                for( var i in blockIds ){
                    var blockId = blockIds[i];
                    addBlock(blockId, blocks[blockId]);
                }
            } 

            // bind overlay
            t.bindPrebuiltActions(container, type, {
                onRemoveFavourite: function(){
                    t.getFavouriteSection(t.tabContent);
                }
            });
        },

        // get template items
        getPrebuiltTemplateItems: function(settings, type){
            settings.loadMore = false;

            var blocks, blockKeys;
            switch(type){
                case 'blocks': 
                    blocks = pixePbBlocks;
                    blockKeys = Object.keys(blocks);
                    break;
                case 'pages': 
                    blocks = pixePbPages; 
                    blockKeys = Object.keys(blocks);
                    break;
                case 'sites': 
                    blocks = pixePbSites; 
                    blockKeys = Object.keys(blocks).sort((a, b) => b - a);
                    break;
            }

            // loop through all items
            var offsetCount = 0;
            var count = 0;
            
            function isComplete(){
                if( count >= settings.display ){
                    settings.loadMore = true;
                    settings.offset += settings.display;
                    return true;
                }

                return false;
            }
            function display(id){

                // check tag
                if( settings.tag && blocks[id].g && blocks[id].g.indexOf(settings.tag.toString()) < 0 ) return false;

                // check category
                if( settings.category && blocks[id].c && blocks[id].c.indexOf(settings.category.toString()) < 0 ) return false;

                // check search
                if( settings.search && !blocks[id].t.toLowerCase().includes(settings.search.toLowerCase()) ) return false;

                // check offset
                if( offsetCount < settings.offset ){
                    offsetCount++;
                    return false;
                }

                // display item
                settings.onAdd(id, blocks[id]);
                count++;

                return true;
            }

            if( settings.ids ){
                for( var i in settings.ids ){
                    var id = settings.ids[i];
                    settings.onAdd(id, blocks[id]);
                }
            }else{

                var isPro = (typeof(pixePP) !== 'undefined' && pixePP.active);
                
                // loop free blocks first
                if( !isPro ){
                    for( var i in blockKeys ){ 
                        var id = blockKeys[i];

                        if( !blocks[id].f ) continue; // only do free post
                        if( isComplete() ) return;
                        display(id);
                    }
                }
                
                // normal loop
                for( var i in blockKeys ){ 
                    var id = blockKeys[i];

                    if( !isPro && blocks[id].f ) continue; // ignore free posts                    
                    if( isComplete() ) return;
                    display(id) 
                }
            }
        },

        getPrebuiltTemplateCats(type){
            var t = this;

            function getCat(blocks){
                var catCount = { all: 0 };
                for( var i in blocks ){
                    catCount.all++;
                    
                    if( !blocks[i].c ) continue;
                    blocks[i].c.map(function(item){
                        catCount[item] = catCount[item]? catCount[item] + 1: 1;
                    });
                }

                return catCount;
            }

            switch(type){
                case 'blocks': 
                    if( !t.blockCats ){
                        t.blockCats = getCat(pixePbBlocks);
                    }
                    return t.blockCats;

                case 'pages': 
                    if( !t.pageCats ){
                        t.pageCats = getCat(pixePbPages);
                    }
                    return t.pageCats;

                case 'sites':
                    return {};
            }
        },

        // get template sidebar
        getPrebuiltTempalteSidebar: function(container, type){
            var t = this;
            container.empty();

            var searchBar = $('<div class="pixe-input pixe-search-input" ><input type="text" placeholder="Search" /></div>');
            searchBar.appendTo(container);
            
            var tags = $('<div class="pixe-template-tags" ></div>');
            tags.append('<span data-tag="light" >Light Style</span>');
            tags.append('<span data-tag="dark" >Dark Style</span>');
            tags.children().first().addClass('pixe-active');
            tags.appendTo(container);

            var categories = $('<div class="pixe-template-categories" ></div>');
            categories.append('<h3>Categories</h3>');
            categories.appendTo(container);

            function getCategoryItem(slug, label, count){
                var catItem = $('<div class="pixe-template-category" ></div>');
                catItem.attr('data-category', slug);
                catItem.append('<span>' + label + '</span>');
                catItem.append('<span>' + parseInt(count? parseInt(count) / 2: 0) + '</span>');
                catItem.appendTo(categories);
            }

            // loop through all items
            var catCount = t.getPrebuiltTemplateCats(type);
            var categoryList = Object.keys(catCount).sort();
            getCategoryItem('', 'All', catCount['all']);
            for(var i in categoryList){
                var slug = categoryList[i];
                if( slug == 'all' ) continue;

                var label = '';
                if( t.blockCatLabels[slug] ){
                    label = t.blockCatLabels[slug];
                }else{
                    label = slug.replace('-', ' ');
                    label = label.replace(/\b\w/g, c => c.toUpperCase());
                }
                getCategoryItem(slug, label, catCount[slug]);
            }
            categories.children('.pixe-template-category').first().addClass('pixe-active');
        },

        getUrl: function(url){
            if( !url ){
                return;
            }else if( url.startsWith("https://") ){
                return url;
            }else{
                return pixeData.prebuiltTemplateDir + url;
            }
        },

        // blocks template
        getPrebuiltTemplateOverlay: function(type, id, settings){
            var t = this;
            var overlay  = '<div class="pixe-template-thumbnail-overlay pixe-overlay pixe-type-' + $.pixeEscAttr(type) + '" >';

            // action button
            if( type == 'pages' ){
                overlay += '<a class="pixe-preview-button pixe-action pixe-link" href="' + $.pixeEscAttr(settings.u) + '" target="_blank">';
                overlay += '<div class="pixe-svg-preset pixe-svg-preview" ></div>';
                overlay += pixei18n.button.preview;
                overlay += '</a>';  
            }else if( type == 'sites' ){
                overlay += '<div class="pixe-preview-button pixe-insert pixe-action ' + (settings.f? 'pixe-free': '') + '" >';
                overlay += $.pixeGetAdminIcon('pages');
                overlay += pixei18n.template.viewPages;
                overlay += '</div>';  
            }else if( type == 'blocks' ){
                overlay += $.pixeGetAdminIcon('expand', { class: 'pixe-full-screen pixe-action', data: 'data-preview="' + $.pixeEscAttr(settings.p) + '"' });
            }

            if( type == 'sites' || type == 'blocks' ){
                var favouriteClass = 'pixe-favourite pixe-action ';
                favouriteClass += pixeData.favouriteBlock[type] && pixeData.favouriteBlock[type].indexOf(parseInt(id)) >= 0? 'pixe-active': '';
                overlay += $.pixeGetAdminIcon('favourite', { class: favouriteClass, data: 'data-id="' + $.pixeEscAttr(id) + '"' });
            }

            // upgrade button
            if( type == 'pages' || type == 'blocks' ){
                if( !settings.f && (typeof(pixePP) === 'undefined' || !pixePP.active) ){
                    var source = pixeData.pageType? pixeData.pageType: 'page_builder';
                    var medium = (type == 'pages')? 'thumbnail_button': 'blocks';
                    overlay += $.pixeProUpgradeButton('upgrade', '?utm_source=' + source + '&utm_medium=' + medium + '&utm_campaign=upgrade', 'upgrade');
                }else if( !t.hideInsertButton ){
                    overlay += '<div class="pixe-add-block-button pixe-insert pixe-action" >';
                    overlay += '<div class="pixe-svg-preset pixe-svg-insert" ></div>';
                    overlay += pixei18n.button.insert;
                    overlay += '</div>';
                }
            }else if( type == 'sites' ){
                if( settings.f || (typeof(pixePP) !== 'undefined' && pixePP.active) ){
                    overlay += '<div class="pixe-add-block-button pixe-import-website pixe-action" >';
                    overlay += $.pixeGetAdminIcon('download');
                    overlay += pixei18n.template.importSite;
                    overlay += '</div>';
                }
            }
            overlay += '</div>'; // pixe-overlay

            if( !settings.f && (typeof(pixePP) === 'undefined' || !pixePP.active) ){
                overlay += $.pixeProBadge(true);  
            }

            return overlay;
        },
        getPrebuiltTemplateItem: function(id, type, settings){
            var t = this;
            var item = $('<div class="pixe-template-thumbnail-item" ></div>');
            item.addClass(settings.g && settings.g.indexOf('dark') >= 0? 'pixe-dark': 'pixe-light');
            item.attr('data-id', id);
            item.data('value', [{ _type: 'block-dragging', type: 'wrapper', ID: id, _source: 'pixe' }]);

            if( settings.i ){
                var imageSize = settings.s? settings.s.split(':'): [];
                var image  = '<img src="' + $.pixeEscAttr(t.getUrl(settings.i)) + '" ';
                    image += (imageSize[0])? 'width="' + $.pixeEscAttr(imageSize[0]) + '" ': '';
                    image += (imageSize[1])? 'height="' + $.pixeEscAttr(imageSize[1]) + '" ': '';
                    image += ' />';

                var thumbnail = $('<div class="pixe-thumbnail" ></div>');
                thumbnail.append(image);
                thumbnail.append(t.getPrebuiltTemplateOverlay(type, id, settings));
                thumbnail.appendTo(item);
            }
            if( settings.t ){
                item.append('<div class="pixe-title" >' + settings.t + '</div>');
            }
            return item;
        },
        getPrebuiltTemplateSection: function(tabContent, type, pbSettings){
            pbSettings = $.extend({
                loadMore: false, 
                offset: 0, 
                display: 20,
            }, pbSettings);

            var t = this;
            tabContent.empty();

            // main area
            var container = $('<div class="pixe-template-section pixe-fixed-height pixe-scrollbar" ></div>');
            container.append('<div class="pixe-line" ></div>');
            container.append('<div class="pixe-line" ></div>');
            container.append('<div class="pixe-line" ></div>');
            container.appendTo(tabContent);
            var lines = container.children('.pixe-line');
            var sidebar, sidebarContainer;

            // query settings
            if( type == 'blocks' ){
                pbSettings.tag = 'light';

                // create sidebar
                sidebar = $('<div class="pixe-template-sidebar" ></div>');
                sidebar.appendTo(tabContent);

                sidebarContainer = $('<div class="pixe-sidebar-container pixe-scrollbar" ></div>');
                sidebarContainer.appendTo(sidebar);
                
                t.getPrebuiltTempalteSidebar(sidebarContainer, type);
            }
            
            // add item function
            pbSettings.onAdd = function(id, settings){
                var item = t.getPrebuiltTemplateItem(id, type, settings);
                var minHeight = 999999;
                var targetLine;
                lines.each(function(){
                    var lineHeight = $(this).outerHeight();
                    
                    if( lineHeight < minHeight ){
                        minHeight = lineHeight;
                        targetLine = $(this);
                    }
                });

                targetLine.append(item);
            }
            
            // display
            lines.empty();
            t.getPrebuiltTemplateItems(pbSettings, type);

            // load more on scroll
            container.on('scroll', function(){
                if( pbSettings.loadMore ){
                    if( $(this).scrollTop() + $(this).innerHeight() + 30 > this.scrollHeight ){
                        t.getPrebuiltTemplateItems(pbSettings, type);
                    }
                }
            });

            // bind overlay
            t.bindPrebuiltActions(container, type);

            if( sidebar ){

                // change category
                sidebar.on('click', '[data-category], [data-tag]', function(){
                    if( $(this).hasClass('pixe-active') ) return;
                    $(this).addClass('pixe-active').siblings().removeClass('pixe-active');

                    if( $(this).is('[data-category]') ){
                        pbSettings.offset = 0;
                        pbSettings.category = $(this).attr('data-category');
                    }else{
                        pbSettings.offset = 0;
                        pbSettings.tag = $(this).attr('data-tag');
                    }
                    
                    lines.empty();
                    t.getPrebuiltTemplateItems(pbSettings, type);
                });

                // update search
                sidebar.on('input', '.pixe-search-input input', $.pixeDebounce(function(){
                    pbSettings.offset = 0;
                    pbSettings.search = $(this).val();

                    lines.empty();
                    t.getPrebuiltTemplateItems(pbSettings, type);
                }));
            }
        },

        // overlay action
        bindPrebuiltActions: function(container, type, settings){
            settings = $.extend({
                onRemoveFavourite: function(){}
            }, settings);

            var t = this;

            // actions
            container.on('click', '.pixe-action, .pixe-insert', function(){
                var item = $(this).closest('.pixe-template-thumbnail-item');

                if( $(this).hasClass('pixe-full-screen') ){
                    var url = t.getUrl($(this).attr('data-preview'));
                    $.pixeImageLightboxPopup(url);

                }else if( $(this).hasClass('pixe-insert') ){

                    if( type == 'blocks' || type == 'pages' ){
                        var status = { 
                            event: 'addNew',
                            value: item.data('value')
                        };

                        // add item to iframe drop target
                        $.pixeBuilder.setIframeStatus(status);

                        // close lightbox
                        if( t.lb ){ t.lb.close(); }
                        if( t.siteLb ){ t.siteLb.close(); }

                    }else if( type == 'sites' ){

                        // create popup
                        t.getPrebuiltSitePopup(item.attr('data-id'), $(this).hasClass('pixe-free'))
                    }

                }else if( $(this).hasClass('pixe-favourite') ){

                    var id = item.attr('data-id');
                    var added = !$(this).hasClass('pixe-active');
                    if( added ){
                        $(this).addClass('pixe-active');
                    }else{
                        $(this).removeClass('pixe-active')
                    }
                    t.addFavourite(type, id, added);
                    if( !added ){
                        settings.onRemoveFavourite({
                            type: type,
                            id: id,
                            item: item
                        });
                    }

                }else if( $(this).hasClass('pixe-import-website') ){

                    var siteId = item.attr('data-id');
                    t.importPopup(siteId);

                }
            });

        },

        // site popup
        importPopup(siteId){
            var t = this;

            $.pixeConfirmationBox({
                title: pixei18n.alert.importSiteTitle,
                message: pixei18n.alert.importSiteContent,
                extraClass: 'pixe-confirmation-site-import',
                onSuccess: function(popup){
                    var options = [];

                    popup.find('input:checked').each(function(){
                        options.push($(this).val());
                    });

                    if( options.indexOf('typo') >= 0 || options.indexOf('controls') >= 0 ){
                        $.pixeConfirmationBox({
                            title: pixei18n.alert.warning,
                            message: pixei18n.alert.overridePreset,
                            onSuccess: function(){
                                t.importSite(siteId, options);
                            }
                        });
                    }else{
                        t.importSite(siteId, options);
                    }
                }
            });

        },
        getPrebuiltSitePopup: function(siteId, isFree = false){
            if( !pixePbSites[siteId] ) return '';

            var t = this;
            var pages = pixePbSites[siteId].a;
            var pageAmount = pixei18n.template.pageAmount.replace('%d', pages.length);

            var container = $('<div class="pixe-template-settings pixe-box-sizing" ></div>');

            t.siteLb = new $.pixeLightboxPopup({
                class: 'pixe-lb-site-settings',
                content: container
            });

            // popup content
            var tab = $('<div class="pixe-settings-tab" ></div>');
            tab.appendTo(container);

            var tabHead = $('<div class="pixe-settings-tab-head" ></div>');
            tabHead.append('<span class="pixe-title" >' + pixePbSites[siteId].t + ' : ' + pageAmount + '</span>');
            tabHead.append('<span class="pixe-caption" >Choose a page to preview or insert it instantly.</span>');
            tabHead.append($.pixeGetAdminIcon('cancel', { class: 'pixe-close' }));
            tabHead.appendTo(tab);
            
            var tabContent = $('<div class="pixe-settings-tab-content" ></div>');
            tabContent.appendTo(tab);

            var tabFoot = $('<div class="pixe-settings-tab-foot" ></div>');
            if( isFree || (typeof(pixePP) !== 'undefined' && pixePP.active) ){
                tabFoot.append('<div class="pixe-import-button pixe-import-website" >' + $.pixeGetAdminIcon('download') + pixei18n.template.importFullSite + '</div>');
            }else{
                var source = pixeData.pageType? pixeData.pageType: 'page_builder';
                tabFoot.append('<a class="pixe-import-button" href="https://pixebuilder.com/pricing?utm_source=' + source + '&utm_medium=bottom_button&utm_campaign=upgrade" target="_blank" >' + $.pixeGetAdminIcon('upgrade') + pixei18n.upgrade.upgradeImport + '</a>');
            }
            tabFoot.appendTo(tab);

            t.getPrebuiltTemplateSection(tabContent, 'pages', {
                ids: pages
            });

            // close button
            tabHead.on('click', '.pixe-close', function(){
                t.siteLb.close();
            });

            tabFoot.on('click', '.pixe-import-website', function(){
                t.importPopup(siteId);
            });

            return tab;
        },
        importSite: function(id, options){
            var loadingText  = '<div class="pixe-icon pixe-icon-svg" ><svg fill="hsl(228, 97%, 0%)" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,20a9,9,0,1,1,9-9A9,9,0,0,1,12,21Z" transform="translate(12, 12) scale(0)"><animateTransform attributeName="transform" calcMode="spline" type="translate" dur="1.2s" values="12 12;0 0" keySplines=".52,.6,.25,.99" repeatCount="indefinite"/><animateTransform attributeName="transform" calcMode="spline" additive="sum" type="scale" dur="1.2s" values="0;1" keySplines=".52,.6,.25,.99" repeatCount="indefinite"/><animate attributeName="opacity" calcMode="spline" dur="1.2s" values="1;0" keySplines=".52,.6,.25,.99" repeatCount="indefinite"/></path></svg></div>';
                loadingText += '<div class="pixe-title" >' + pixei18n.alert.importing + '</div>';
                loadingText += '<div class="pixe-content" >' + pixei18n.alert.importingContent + '</div>';

            var loading = new $.pixeLightboxPopup({
                class: 'pixe-lb-loading',
                closeEvent: false,
                content: loadingText
            });
            
            var ajaxData = $.pixeGetAjaxData({
                action: 'pixe_import_site',
                id: id,
                options: options
            });
            
            $.pixeAjax({
                ajaxData: ajaxData,
                onSuccess: function(data){
                    loading.close();

                    var completeText  = '<div class="pixe-icon pixe-icon-svg" ><svg width="39" height="39" viewBox="0 0 39 39"><path d="M16.4833 27.9833L29.9958 14.4708L27.3125 11.7875L16.4833 22.6167L11.0208 17.1542L8.3375 19.8375L16.4833 27.9833ZM19.1667 38.3333C16.5153 38.3333 14.0236 37.8302 11.6917 36.824C9.35972 35.8177 7.33125 34.4521 5.60625 32.7271C3.88125 31.0021 2.51562 28.9736 1.50937 26.6417C0.503125 24.3097 0 21.8181 0 19.1667C0 16.5153 0.503125 14.0236 1.50937 11.6917C2.51562 9.35972 3.88125 7.33125 5.60625 5.60625C7.33125 3.88125 9.35972 2.51562 11.6917 1.50937C14.0236 0.503125 16.5153 0 19.1667 0C21.8181 0 24.3097 0.503125 26.6417 1.50937C28.9736 2.51562 31.0021 3.88125 32.7271 5.60625C34.4521 7.33125 35.8177 9.35972 36.824 11.6917C37.8302 14.0236 38.3333 16.5153 38.3333 19.1667C38.3333 21.8181 37.8302 24.3097 36.824 26.6417C35.8177 28.9736 34.4521 31.0021 32.7271 32.7271C31.0021 34.4521 28.9736 35.8177 26.6417 36.824C24.3097 37.8302 21.8181 38.3333 19.1667 38.3333ZM19.1667 34.5C23.4472 34.5 27.0729 33.0146 30.0437 30.0437C33.0146 27.0729 34.5 23.4472 34.5 19.1667C34.5 14.8861 33.0146 11.2604 30.0437 8.28958C27.0729 5.31875 23.4472 3.83333 19.1667 3.83333C14.8861 3.83333 11.2604 5.31875 8.28958 8.28958C5.31875 11.2604 3.83333 14.8861 3.83333 19.1667C3.83333 23.4472 5.31875 27.0729 8.28958 30.0437C11.2604 33.0146 14.8861 34.5 19.1667 34.5Z" fill="#0487FF"/></svg></div>';
                        completeText += '<div class="pixe-title" >' + pixei18n.alert.importingComplete + '</div>';
                        completeText += '<div class="pixe-content" >' + pixei18n.alert.importingCompleteContent + '</div>';
                        completeText += '<div class="pixe-button-wrap" >';
                        completeText += '<a class="pixe-button" href="' + $.pixeEscAttr(pixeData.pageUrl) + '" >' + pixei18n.button.goToPages + '</a>';
                        completeText += '<span class="pixe-close" >' + pixei18n.button.close + '</span>';
                        completeText += '</div>';

                    var complete = new $.pixeLightboxPopup({
                        class: 'pixe-lb-loading',
                        closeEvent: false,
                        content: completeText
                    });

                    complete.lb.on('click', '.pixe-close', function(){
                        complete.close();
                    });
                }
            });
        },

        addFavourite: function(type, id, added){
            var id = parseInt(id);

            if( added ){
                if( !pixeData.favouriteBlock[type] ){
                    pixeData.favouriteBlock[type] = [];
                }
                if( pixeData.favouriteBlock[type].indexOf(id) < 0 ){
                    pixeData.favouriteBlock[type].push(id);
                }
            }else{
                pixeData.favouriteBlock[type] = pixeData.favouriteBlock[type].filter(item => item !== id);
                if( !pixeData.favouriteBlock[type].length ){
                    delete pixeData.favouriteBlock[type];
                }
            }

            // format data
            var ajaxData = $.pixeGetAjaxData({
                action: 'pixe_save_favourite_block',
                ids: pixeData.favouriteBlock
            });

            $.pixeAjax({
                ajaxData: ajaxData
            });

        }
    }

    $(document).ready(function(){
        if( !pixeData.favouriteBlock || Array.isArray(pixeData.favouriteBlock) ){
            pixeData.favouriteBlock = {};
        };
    });

})(jQuery);	
