const Helper = {
    makeId() {
        let text = "";
        let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        for (let i = 0; i < 2; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }

        let text2 = "";
        let possible2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (let i = 0; i < 5; i++) {
            text2 += possible2.charAt(Math.floor(Math.random() * possible2.length));
        }

        return text + text2;
    },
    addClass(element, classname) {
        if (! element) {
            return;
        }

        if (Helper.hasClass(element, classname)) {
            return;
        }

        if (element.classList.length === 0) {
            element.className = classname;
        } else {
            element.className = element.className + ' ' + classname;
        }

        element.className = element.className.replace(/  +/g, ' ');
    },
    hasClass(element, classname) {
        if (! element) {
            return false;
        }

        if (element.classList) {
            return element.classList.contains(classname);
        }

        return new RegExp('\\b' + classname + '\\b').test(element.className);
    },
    removeClass(element, classname) {
        if (! element) {
            return;
        }

        if (element.classList.length > 0) {
            element.className = element.className.replace(classname, '');
        }
    },
    isNumber(evt) {
        evt = (evt) ? evt : window.event;

        let charCode = (evt.which) ? evt.which : evt.keyCode;

        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        return true;
    },
    isBlank(string) {
        return ! string
            || /^\s*$/.test(string)
            || string.length === 0
            || string === 'null'
            || string === '/edit/null';
    }
};

const Module = {
    get() {
        return parent.document.querySelector("[data-module-active]");
    }
};

const Settings = {
    get() {
        return decodeURIComponent(
            Module.get().getAttribute('data-settings')
        );
    },
    save() {
        let updatedSettings = `{
            "type": "${ModalForm.fields.type.get().value}",
            "items": ${ModalForm.fields.items.get().value},
            "style": "${ModalForm.fields.style.get().value}",
            "transition": "${ModalForm.fields.transition.get().value}",
            "margin": ${ModalForm.fields.margin.get().value},
            "loop": ${ModalForm.fields.loop.isChecked()},
            "lazy_load": ${ModalForm.fields.lazy.isChecked()},
            "nav": ${ModalForm.fields.nav.isChecked()},
            "dots": ${ModalForm.fields.dots.isChecked()},
            "autoplay": ${ModalForm.fields.autoplay.isChecked()},
            "autoplay_pause": ${ModalForm.fields.pause.isChecked()}
        }`;
        updatedSettings = updatedSettings.replace(/ +(?= )/g, '').trim();

        parent.document.querySelector('#hidContentModuleSettings').value = updatedSettings;
    },
    restore() {
        let savedSettings = this.get();
        if (savedSettings !== 'undefined') {

            let jsonData = JSON.parse(savedSettings);

            ModalForm.fields.type.set(jsonData.type);
            ModalForm.fields.items.set(jsonData.items);
            ModalForm.fields.style.set(jsonData.style);
            ModalForm.fields.transition.set(jsonData.transition);
            ModalForm.fields.margin.set(jsonData.margin);

            ModalForm.fields.loop.set(jsonData.loop);
            ModalForm.fields.lazy.set(jsonData.lazy_load);
            ModalForm.fields.nav.set(jsonData.nav);
            ModalForm.fields.dots.set(jsonData.dots);
            ModalForm.fields.autoplay.set(jsonData.autoplay);
            ModalForm.fields.pause.set(jsonData.autoplay_pause);
        }
    }
}

const ModalForm = {
    register() {
        this.fields.type.restore();
        this.fields.style.restore();

        this.fields.action.events();
        this.fields.autoplay.events();
        this.fields.description.events();
        this.fields.dots.events();
        this.fields.items.events();
        this.fields.lazy.events();
        this.fields.loop.events();
        this.fields.margin.events();
        this.fields.nav.events();
        this.fields.pause.events();
        this.fields.style.events();
        this.fields.title.events();
        this.fields.transition.events();
        this.fields.type.events();
    },
    blocks : {
        caption : {
            get() {
                return document.querySelector('#caption-block');
            },
            show() {
                this.get().style.display = "block";
            },
            hide() {
                this.get().style.display = "none";
            }
        },
        carousel : {
            get() {
                return document.querySelector('#carousel-block');
            },
            show() {
                this.get().style.display = "block";
            },
            hide() {
                this.get().style.display = "none";
            }
        },
        slider : {
            get() {
                return document.querySelector('#slider-block');
            },
            show() {
                this.get().style.display = "block";
            },
            hide() {
                this.get().style.display = "none";
            }
        },
    },
    fields : {
        action : {
            get() {
                return document.querySelector('#action');
            },
            set(value) {
                this.get().value = value;
            },
            events() {
                this.get().addEventListener('input', function (e) {
                    ModalItems.updateActiveItem();
                    Snippet.update();
                });
            }
        },
        autoplay : {
            get() {
                return document.querySelector('#autoplay');
            },
            set(value) {
                this.get().checked = value;
            },
            isChecked() {
                return this.get().checked
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        description : {
            get() {
                return document.querySelector('#description');
            },
            set(value) {
                this.get().value = value;
            },
            events() {
                this.get().addEventListener('input', function (e) {
                    ModalItems.updateActiveItem();
                    Snippet.update();
                });
            }
        },
        dots : {
            get() {
                return document.querySelector('#dots');
            },
            set(value) {
                this.get().checked = value;
            },
            isChecked() {
                return this.get().checked
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        items : {
            get() {
                return document.querySelector('#items');
            },
            set(value) {
                this.get().value = value;
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    if (ModalForm.fields.items.get().value > 1) {
                        ModalForm.fields.type.set('carousel');
                        ModalForm.blocks.carousel.show();
                        ModalForm.blocks.slider.hide();
                    } else {
                        ModalForm.fields.type.set('slider');
                        ModalForm.blocks.carousel.hide();
                        ModalForm.blocks.slider.show();
                    }
                    Snippet.update();
                });
            }
        },
        lazy : {
            get() {
                return document.querySelector('#lazy');
            },
            set(value) {
                this.get().checked = value;
            },
            isChecked() {
                return this.get().checked
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        loop : {
            get() {
                return document.querySelector('#loop');
            },
            set(value) {
                this.get().checked = value;
            },
            isChecked() {
                return this.get().checked
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        margin : {
            get() {
                return document.querySelector('#margin');
            },
            set(value) {
                this.get().value = value;
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        nav : {
            get() {
                return document.querySelector('#nav');
            },
            set(value) {
                this.get().checked = value;
            },
            isChecked() {
                return this.get().checked
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        pause : {
            get() {
                return document.querySelector('#pause');
            },
            set(value) {
                this.get().checked = value;
            },
            isChecked() {
                return this.get().checked
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        style : {
            get() {
                return document.querySelector('#style');
            },
            set(value) {
                this.get().value = value;
            },
            restore() {
                SnippetItem.updateTemplate();
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    SnippetItem.updateTemplate();
                });
            }
        },
        transition : {
            get() {
                return document.querySelector('#transition');
            },
            set(value) {
                this.get().value = value;
            },
            isFade() {
                return this.get().value === "fade";
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    Snippet.update();
                });
            }
        },
        type : {
            get() {
                return document.querySelector('#type');
            },
            set(value) {
                this.get().value = value;
            },
            restore() {
                if (ModalForm.fields.type.isSlider()) {
                    ModalForm.fields.type.setAsSlider();
                } else {
                    ModalForm.fields.type.setAsCarousel();
                }
            },
            isCarousel() {
                return this.get().value === "carousel";
            },
            isSlider() {
                return this.get().value === "slider";
            },
            setAsSlider() {
                ModalForm.fields.items.set(1);
                ModalForm.fields.margin.set(0);
                ModalForm.fields.transition.set('slide');
                ModalForm.blocks.carousel.hide();
                ModalForm.blocks.slider.show();
            },
            setAsCarousel() {
                if (parseInt(ModalForm.fields.items.get().value) === 1) {
                    ModalForm.fields.items.set(4);
                }
                ModalForm.blocks.carousel.show();
                ModalForm.blocks.slider.hide();
            },
            events() {
                this.get().addEventListener('change', function (e) {
                    if (ModalForm.fields.type.isSlider()) {
                        ModalForm.fields.type.setAsSlider();
                    } else {
                        ModalForm.fields.type.setAsCarousel();
                    }
                    Snippet.update();
                });
            }
        },
        title : {
            get() {
                return document.querySelector('#title');
            },
            set(value) {
                this.get().value = value;
            },
            events() {
                this.get().addEventListener('input', function (e) {
                    ModalItems.updateActiveItem();
                    Snippet.update();
                });
            }
        },
    },
}

const ModalItems = {
    register() {
        this.restoreExisting();

        this.registerItemEvents();
        this.registerAddItemEvent();
    },
    get() {
        return document.querySelectorAll('#slides div[data-index]');
    },

    registerItemEvents() {
        let modalItems = ModalItems.get();

        Array.prototype.forEach.call(modalItems, function (modalItem) {
            let index = modalItem.getAttribute('data-index');
            let btnUp = modalItem.querySelector('.elm-up');
            let btnDown = modalItem.querySelector('.elm-down');
            let btnRemove = modalItem.querySelector('.elm-remove');

            modalItem.addEventListener('click', function (e) {
                ModalItem.select(modalItem);
            });

            btnUp.addEventListener('click', function (e) {
                if (modalItem.previousElementSibling) {
                    modalItem.parentElement.insertBefore(modalItem, modalItem.previousElementSibling);
                    Snippet.update();
                }
            });
            btnDown.addEventListener('click', function (e) {
                if (modalItem.nextElementSibling) {
                    modalItem.parentElement.insertBefore(modalItem.nextElementSibling, modalItem);
                    Snippet.update();
                }
            });
            btnRemove.addEventListener('click', function (e) {
                modalItem.parentNode.removeChild(modalItem);
                Snippet.update();
            });
        });
    },
    registerAddItemEvent() {
        document.querySelector('.input-add')
            .addEventListener('click', function (e) {

                let numOfItems = document.querySelector('#slides').childElementCount;
                let index = numOfItems + 1;

                let newItem = ModalItems.getNewItemHtml(index);
                document.querySelector('#slides').insertAdjacentHTML('beforeend', newItem);

                Snippet.update();
                ModalItems.registerItemEvents();
            });
    },
    restoreExisting() {
        let index = 1;
        let html = '';

        let snippetItems = Snippet.getItems();
        Array.prototype.forEach.call(snippetItems, function (snippetItem) {

            if (Helper.hasClass(snippetItem, 'cloned')) {
                return;
            }

            html += ModalItems.getItemHtml(snippetItem, index);

            index++;
        });

        document.querySelector('#slides').innerHTML = html;
    },
    getItemHtml(snippetItem, index) {

        let html = Module.get().getAttribute('data-html-' + index);
        let imgSrc = SnippetItem.getImageSrc(snippetItem);
        let dataSrc = SnippetItem.getDataSrc(snippetItem, imgSrc);

        let title = encodeURIComponent(SnippetItem.getTitle(snippetItem));
        let description = encodeURIComponent(SnippetItem.getDescription(snippetItem));
        let action = encodeURIComponent(SnippetItem.getAction(snippetItem));

        let alt = encodeURIComponent(SnippetItem.getAlt(snippetItem));
        let path = encodeURIComponent(SnippetItem.getPath(snippetItem));
        let name = encodeURIComponent(SnippetItem.getName(snippetItem));
        let preset = encodeURIComponent(SnippetItem.getPreset(snippetItem));
        let width = encodeURIComponent(SnippetItem.getWidth(snippetItem));
        let height = encodeURIComponent(SnippetItem.getHeight(snippetItem));
        let mode = encodeURIComponent(SnippetItem.getMode(snippetItem));

        return `
            <div
                class="existing-slide"
                style="position: relative;"
                data-index="${index}"
                data-caption-title="${title}"
                data-caption-description="${description}"
                data-caption-action="${action}"
                data-html-x="${html}"
            >
                <img 
                    style="width:125px" 
                    src="${imgSrc}" 
                    data-src="${dataSrc}" 
                    alt="${alt}" 
                    data-path="${path}"
                    data-name="${name}"
                    data-preset="${preset}"
                    data-width="${width}"
                    data-height="${height}"
                    data-mode="${mode}"
                />
                
                <div class="is-index">
                    <span class="index">${index}</span>
                </div>
                
                <div class="is-tool" style="display: flex;">
                    <button class="elm-up" data-title="Up" title="Up">
                        <svg class="is-icon-flex" style="width: 13px; height: 13px;">
                            <use xlink:href="#ion-ios-arrow-thin-up"></use>
                        </svg>
                    </button>
                    <button class="elm-down" data-title="Down" title="Down">
                        <svg class="is-icon-flex" style="width: 13px; height: 13px;">
                            <use xlink:href="#ion-ios-arrow-thin-down"></use>
                        </svg>
                    </button>
                    <button class="elm-remove" data-title="Delete" title="Delete">
                        <svg class="is-icon-flex" style="">
                            <use xlink:href="#ion-ios-close-empty"></use>
                        </svg>
                    </button>
                </div>
            </div>
        `;
    },
    getNewItemHtml(index) {

        let html = '';
        let imgSrc = '';
        let dataSrc = '';
        let title = '';
        let description = '';
        let action = '';

        let modalItems = ModalItems.get();
        Array.prototype.forEach.call(modalItems, function (modalItem) {
            html = modalItem.getAttribute('data-html-x');
            imgSrc = modalItem.querySelector('img').src;
            dataSrc = modalItem.getAttribute('data-src');
        });

        return `
            <div
                class="new-slide"
                style="position: relative;"
                data-index="${index}"
                data-caption-title="${title}"
                data-caption-description="${description}"
                data-caption-action="${action}"
                data-html-x="${html}"
            >
                <img style="width:125px" src="${imgSrc}" data-src="${dataSrc}" alt="" />
                
                <div class="is-index">
                    <span class="index">${index}</span>
                </div>
                
                <div class="is-tool" style="display: flex;">
                    <button class="elm-up" data-title="Up" title="Up">
                        <svg class="is-icon-flex" style="width: 13px; height: 13px;">
                            <use xlink:href="#ion-ios-arrow-thin-up"></use>
                        </svg>
                    </button>
                    <button class="elm-down" data-title="Down" title="Down">
                        <svg class="is-icon-flex" style="width: 13px; height: 13px;">
                            <use xlink:href="#ion-ios-arrow-thin-down"></use>
                        </svg>
                    </button>
                    <button class="elm-remove" data-title="Delete" title="Delete">
                        <svg class="is-icon-flex" style="">
                            <use xlink:href="#ion-ios-close-empty"></use>
                        </svg>
                    </button>
                </div>
            </div>
        `;
    },

    getActiveItem() {
        return document.querySelector('#slides div.active');
    },
    updateActiveItem() {
        let activeItem = ModalItems.getActiveItem();
        ModalItem.setTitle(activeItem);
        ModalItem.setDescription(activeItem);
        ModalItem.setAction(activeItem);
    },
    removeActiveClass() {
        let items = ModalItems.get();

        Array.prototype.forEach.call(items, function (item) {
            Helper.removeClass(item, 'active');
        });
    }
};

const ModalItem = {
    select(item) {
        ModalItem.updateTitleLabel(item.dataset.index);
        ModalItem.updateDescriptionLabel(item.dataset.index);
        ModalItem.updateActionLabel(item.dataset.index);

        ModalForm.fields.title.set('');
        ModalForm.fields.description.set('');
        ModalForm.fields.action.set('');

        let title = ModalItem.getTitle(item);
        let description = ModalItem.getDescription(item);
        let action = ModalItem.getAction(item);

        if (! Helper.isBlank(title)) {
            ModalForm.fields.title.set(title);
        }
        if (! Helper.isBlank(description)) {
            ModalForm.fields.description.set(description);
        }
        if (! Helper.isBlank(action)) {
            ModalForm.fields.action.set(action);
        }

        ModalItems.removeActiveClass();
        Helper.addClass(item, 'active');
        ModalForm.blocks.caption.show();
    },

    getTitle(item) {
        return decodeURIComponent(
            item.getAttribute('data-caption-title')
        );
    },
    setTitle(item) {
        let title = ModalForm.fields.title.get().value;
        item.setAttribute('data-caption-title', encodeURIComponent(title));
    },
    updateTitleLabel(index) {
        document.getElementById('title-label').innerHTML = `Item ${index} Title:`;
    },

    getDescription(item) {
        return decodeURIComponent(
            item.getAttribute('data-caption-description')
        );
    },
    setDescription(item) {
        let description = ModalForm.fields.description.get().value;
        item.setAttribute('data-caption-description', encodeURIComponent(description));
    },
    updateDescriptionLabel(index) {
        document.getElementById('action-label').innerHTML = `Item ${index} Action: (e.g /contact-us)`;
    },

    getAction(item) {
        return decodeURIComponent(
            item.getAttribute('data-caption-action')
        );
    },
    setAction(item) {
        let action = ModalForm.fields.action.get().value;
        item.setAttribute('data-caption-action', encodeURIComponent(action));
    },
    updateActionLabel(index) {
        document.getElementById('description-label').innerHTML = `Item ${index} Description: (HTML allowed)`;
    },

    getAlt(item) {
        return item.querySelector('img').getAttribute('alt');
    },
    getPath(item) {
        return item.querySelector('img').getAttribute('data-path');
    },
    getName(item) {
        return item.querySelector('img').getAttribute('data-name');
    },
    getPreset(item) {
        return item.querySelector('img').getAttribute('data-preset');
    },
    getWidth(item) {
        return item.querySelector('img').getAttribute('data-width');
    },
    getHeight(item) {
        return item.querySelector('img').getAttribute('data-height');
    },
    getMode(item) {
        return item.querySelector('img').getAttribute('data-mode');
    },

    getImageSrc(item) {

        let imgSrc = item.querySelector('img').src;

        if (imgSrc.includes('/photos/')) {
            const regex = new RegExp(/(\/photos\/)([0-9a-zA-z-_.]+)(\?[^#]+)?/g);
            let matches = regex.exec(imgSrc);

            imgSrc = matches[0];
            if (matches[1]) {
                imgSrc = matches[1];
            }
            if (matches[2]) {
                imgSrc += matches[2];
            }
            if (matches[3]) {
                imgSrc += matches[3];
            }
        }

        if (ModalForm.fields.lazy.isChecked() && imgSrc.includes('/photos/')) {
            if (! imgSrc.includes('?')) {
                imgSrc += `?`
            }
            if (! imgSrc.includes('&q=5')) {
                imgSrc += `&q=5`
            }
        } else {
            imgSrc = imgSrc.replace('&q=5', '');
        }

        return imgSrc;
    },
    getDataSrc(item, imgSrc) {

        let dataSrc = item.querySelector('img').getAttribute('data-src');

        if (! dataSrc || dataSrc === 'null') {
            dataSrc = imgSrc;
        }

        if (dataSrc.includes('/photos/')) {
            const regex = new RegExp(/(\/photos\/)([0-9a-zA-z-_.]+)(\?[^#]+)?/g);
            let matches = regex.exec(dataSrc);

            dataSrc = matches[0];
            if (matches[1]) {
                dataSrc = matches[1];
            }
            if (matches[2]) {
                dataSrc += matches[2];
            }
            if (matches[3]) {
                dataSrc += matches[3];
            }
            if (dataSrc.includes('&q=5')) {
                dataSrc = dataSrc.replace('&q=5', '');
            }
        }

        return dataSrc;
    },
};

const Snippet = {
    getDocumentReadyScript() {
        return `
            var docReady = function (fn) {
                var stateCheck = setInterval(function () {
                    if (document.readyState !== "complete") return;
                    clearInterval(stateCheck);
                    try { fn() } catch (e) { }
                }, 1);
            };
        `;
    },
    getItems() {
        return Module.get().querySelectorAll('[data-subblock]');
    },
    getHtml(id) {

        let style = ModalForm.fields.style.get().value;
        let type = ModalForm.fields.type.get().value;
        let imgClass = ModalForm.fields.lazy.isChecked() ? 'is-lazy' : '';

        let html = '';
        html += `<div id="${id}" class="bongo-carousel owl-theme bongo-slides ${type} ${style}">`;

        let index = 1;
        let modalItems = ModalItems.get();

        modalItems.forEach(function (modalItem) {
            let imgSrc = ModalItem.getImageSrc(modalItem);
            let dataSrc = ModalItem.getDataSrc(modalItem, imgSrc);

            let title = ModalItem.getTitle(modalItem);
            let description = ModalItem.getDescription(modalItem)
            let action = ModalItem.getAction(modalItem);

            let alt = ModalItem.getAlt(modalItem);
            let path = ModalItem.getPath(modalItem);
            let name = ModalItem.getName(modalItem);
            let preset = ModalItem.getPreset(modalItem);
            let width = ModalItem.getWidth(modalItem);
            let height = ModalItem.getHeight(modalItem);
            let mode = ModalItem.getMode(modalItem);

            let template = SnippetItem.getTemplate();

            template = template.replaceAll("[image_class]", imgClass);
            template = template.replaceAll("[image_src]", imgSrc);
            template = template.replaceAll("[data_src]", dataSrc);
            template = template.replaceAll("[alt]", alt);
            template = template.replaceAll("[data_path]", path);
            template = template.replaceAll("[data_name]", name);
            template = template.replaceAll("[data_preset]", preset);
            template = template.replaceAll("[data_width]", width);
            template = template.replaceAll("[data_height]", height);
            template = template.replaceAll("[data_mode]", mode);

            if (! Helper.isBlank(title) || ! Helper.isBlank(description) || ! Helper.isBlank(action)) {
                template = template.replace("d-none", '');
            }

            if (Helper.isBlank(action)) {
                template = SnippetItem.removeCaptionAction(template);
            } else {
                template = SnippetItem.addCaptionAction(template);
            }

            template = template.replaceAll("[title]", title);
            template = template.replaceAll("[description]", description);
            template = template.replaceAll("[action]", action);

            html += `
                <div 
                    data-subblock
                    data-index="${index}"
                    data-caption-title="${title}"
                    data-caption-description="${description}"
                    data-caption-action="${action}"
                >
            `;
            html += template;
            html += '</div>';

            template = template.replace(/ +(?= )/g, '').trim();
            Module.get().setAttribute('data-html-' + index, template);

            index++;
        });

        html += `</div>`;

        return html;
    },
    update() {
        let id = Helper.makeId();

        let itemsOnMobile = 1;
        let itemsOnTablet = ModalForm.fields.type.isSlider() ? 1 : 3;
        let itemsOnDesktop = ModalForm.fields.items.get().value;

        let speed = 1000;
        let animateIn = ModalForm.fields.type.isSlider() && ModalForm.fields.transition.isFade() ? '"fadeIn"' : false;
        let animateOut = ModalForm.fields.type.isSlider() && ModalForm.fields.transition.isFade() ? '"fadeOut"' : false;

        let html = '';
        html += Snippet.getHtml(id);

        html += '<scr' + 'ipt>';
        html += Snippet.getDocumentReadyScript();
        html += `
            docReady(function () {
            
                var clones = document.querySelectorAll(".cloned");
                Array.prototype.forEach.call(clones, function(clone) {
                    clone.removeAttribute("data-subblock");
                    clone.childNodes[0].removeAttribute("data-subblock");
                });
                
                if (! document.body.classList.contains('web-editor')) {
                    let items = document.querySelectorAll('.owl-image.is-lazy');
                    if (items.length) {
                        items.forEach(function (item) {
                            item.classList.remove('is-lazy');
                            item.classList.add('owl-lazy');                    
                        });
                    }
                }
    
                var slider_${id} = $("#${id}").owlCarousel({
                    items:    ${itemsOnDesktop},
                    margin:   ${ModalForm.fields.margin.get().value},
                    loop:     false,
                    lazyLoad: false,
                    nav:      ${ModalForm.fields.nav.isChecked()},
                    dots:     ${ModalForm.fields.dots.isChecked()},
                    smartSpeed: ${speed},
                    fluidSpeed: ${speed},
                    autoplay: false,
                    autoplayTimeout: 5000, 
                    autoplayHoverPause: ${ModalForm.fields.pause.isChecked()},
                    rewind: false,
                    animateIn: ${animateIn},
                    animateOut: ${animateOut},
                    responsiveClass: true,
                    responsive: {
                        0: {
                            items: ${itemsOnMobile}
                        },
                        768: {
                            items: ${itemsOnTablet}
                        },
                        960: {
                            items: ${itemsOnDesktop}
                        }
                    }
                });

                if (! document.body.classList.contains('web-editor')) {
                    slider_${id}.data('owl.carousel').options.lazyLoad = ${ModalForm.fields.lazy.isChecked()};
                    slider_${id}.data('owl.carousel').options.loop = ${ModalForm.fields.loop.isChecked()};
                    slider_${id}.data('owl.carousel').options.autoplay = ${ModalForm.fields.autoplay.isChecked()};
                    slider_${id}.trigger('refresh.owl.carousel');
                    
                    let autoplay = ${ModalForm.fields.autoplay.isChecked()};
                    if (autoplay) {
                        slider_${id}.on('changed.owl.carousel', function(e) {
                            slider_${id}.trigger('stop.owl.autoplay');
                            slider_${id}.data('owl.carousel')._plugins.autoplay._time = 0;
                            slider_${id}.trigger('play.owl.autoplay');
                        });
                    }
                }
                
                document.querySelector("#${id}").style.display = "block";
            });
        `;
        html += '</scr' + 'ipt>';

        Snippet.save(html);
        Settings.save();
    },
    save(html) {
        html = html.replace(/ +(?= )/g, '').trim();
        parent.document.querySelector('#hidContentModuleCode').value = html;
    }
}

const SnippetItem = {
    template : `
        <div class="default-template item position-relative">
            <img
                class="owl-image [image_class]"
                data-noresize data-noedit data-sync
                alt="[alt]"
                src="[image_src]"
                data-src="[data_src]"
                data-path="[data_path]"
                data-name="[data_name]"
                data-preset="[data_preset]"
                data-width="[data_width]"
                data-height="[data_height]"
                data-mode="[data_mode]"
            />
        </div>
    `,
    getTemplate() {
        return this.template;
    },
    setTemplate(template) {
        this.template = template;
    },
    updateTemplate() {
        let style = ModalForm.fields.style.get().value;
        let endpoint = ModalForm.fields.type.isCarousel()
            ? `/api/builder/carousels/${style}`
            : `/api/builder/sliders/${style}`;

        let request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
                SnippetItem.setTemplate(request.responseText);
                Snippet.update();
            }
        };
        request.open("GET", endpoint, true);
        request.send();
    },

    getTitle(item) {
        return item.getAttribute('data-caption-title');
    },
    getDescription(item) {
        return item.getAttribute('data-caption-description');
    },
    getAction(item) {
        return item.getAttribute('data-caption-action');
    },

    getAlt(item) {
        return item.querySelector('img').getAttribute('alt');
    },
    getPath(item) {
        return item.querySelector('img').getAttribute('data-path');
    },
    getName(item) {
        return item.querySelector('img').getAttribute('data-name');
    },
    getPreset(item) {
        return item.querySelector('img').getAttribute('data-preset');
    },
    getWidth(item) {
        return item.querySelector('img').getAttribute('data-width');
    },
    getHeight(item) {
        return item.querySelector('img').getAttribute('data-height');
    },
    getMode(item) {
        return item.querySelector('img').getAttribute('data-mode');
    },

    getImageSrc(item) {

        let imgSrc = item.querySelector('img').src;

        if (imgSrc.includes('/photos/')) {
            const regex = new RegExp(/(\/photos\/)([0-9a-zA-z-_.]+)(\?[^#]+)?/g);
            let matches = regex.exec(imgSrc);

            imgSrc = matches[0];
            if (matches[1]) {
                imgSrc = matches[1];
            }
            if (matches[2]) {
                imgSrc += matches[2];
            }
            if (matches[3]) {
                imgSrc += matches[3];
            }
        }

        return imgSrc;
    },
    getDataSrc(item, imgSrc) {
        let dataSrc = item.querySelector('img').getAttribute('data-src');

        if (! dataSrc || dataSrc === 'null') {
            dataSrc = imgSrc;
        }

        if (dataSrc.includes('/photos/')) {
            const regex = new RegExp(/(\/photos\/)([0-9a-zA-z-_.]+)(\?[^#]+)?/g);
            let matches = regex.exec(dataSrc);

            dataSrc = matches[0];
            if (matches[1]) {
                dataSrc = matches[1];
            }
            if (matches[2]) {
                dataSrc += matches[2];
            }
            if (matches[3]) {
                dataSrc += matches[3];
            }
            if (dataSrc.includes('&q=5')) {
                dataSrc = dataSrc.replace('&q=5', '');
            }
        }

        return dataSrc;
    },

    getCaptionActionHtml() {
        return `
            <div class="caption-action">
                <a class="btn btn-primary" href="[action]">
                    Read More...
                </a>
            </div>
        `;
    },
    addCaptionAction(template) {
        let html = new DOMParser().parseFromString(template, 'text/html');

        if (html.querySelector('.is-caption') && ! html.querySelector('.caption-action')) {

            html.querySelector('.is-caption')
                .insertAdjacentHTML('beforeend', this.getCaptionActionHtml());

            template = html.querySelector('.carousel')
                ? html.querySelector('.carousel').outerHTML
                : html.querySelector('.slider').outerHTML;

            html = null;
        }

        return String(template);
    },
    removeCaptionAction(template) {
        let html = new DOMParser().parseFromString(template, 'text/html');

        if (html.querySelector('.caption-action')) {

            html.querySelector('.caption-action').remove();

            template = html.querySelector('.carousel')
                ? html.querySelector('.carousel').outerHTML
                : html.querySelector('.slider').outerHTML;

            html = null;
        }

        return String(template);
    }
}

Settings.restore();

ModalForm.register();
ModalItems.register();

Snippet.update();