window.jQuery(function($) {
	window.metaslider.app.EventManager.$on("metaslider/app-loaded", function (e) {
    
	var APP = window.metaslider.app.MetaSlider;
	
    if (typeof APP === 'undefined') {
        console.error('APP is not defined!');
        return;
    }

    var $ = window.jQuery;

	// Enable the correct options for this slider type
    var checkSlideCompatibility = function(slider) {
        // slides - set red background on incompatible slides
        jQuery("#compatibilityWarning").remove();

        if (jQuery('.metaslider .slide:not(.' + slider + ')').length) {
            var sup_types = APP && __('Image and Post Feed', 'ml-slider-pro');
            if(slider === 'responsive') {
                sup_types = APP && __('Image, Post Feed, Vimeo, YouTube, External URL and Layer Slide', 'ml-slider-pro');
            }
            var message = ucFirst(slider) + APP.sprintf(
                APP && __(' Slider is only compatible with %s slides.', 'ml-slider-pro'),
                sup_types
            );
            var warningDiv = jQuery("<div id='compatibilityWarning' class='updated ms-slideshow-warning'><p><b>Warning:</b> " + message + "</p></div>");
            jQuery(".metaslider .left").prepend(warningDiv);
        };
    };

    var ucFirst = function(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    // handle slide libary switching
    $(".metaslider").on('click', '.select-slider', function() {
        checkSlideCompatibility(jQuery(this).attr('rel'));
    });

    checkSlideCompatibility(jQuery('.metaslider .select-slider:checked').attr('rel'));

    var loadWysiwygPostFeed = function () {

        if (typeof tinymce === 'undefined') {
            console.error('TinyMCE is not defined!');
            return;
        }

        // Add Post Feed data to metaslider.tinymce
        if (typeof metaslider.tinymce.find(obj => obj.type === 'post_feed') === 'undefined') {
            metaslider.tinymce.push({
                type: 'post_feed',
                configuration: {
                    toolbar: [
                        'ms_insert_tag',
                        'undo redo bold italic forecolor link unlink alignleft aligncenter alignright styles code'
                    ],
                    menubar: false,
                    plugins: 'code link',
                    branding: false,
                    promotion: false,
                    height: 280,
                    forced_root_block: 'div',
                    convert_urls: false,
                    setup: function (editor) {
                        var select = document.getElementsByName('template_tags');
                        var options = select.length > 0 ? Array.from(select[0].options) : false;
                        var shortcodes_with_limit = [
                            '{tags}',
                            '{cats}',
                            '{content}',
                            '{excerpt}',
                            '{content_with_formatting}'
                        ];
        
                        if (!options) {
                            return;
                        }
        
                        var items = options.map(function (option, i) {
                            if (i > 0) {
                                return {
                                    type: 'menuitem',
                                    text: option.text,
                                    onAction: function () {
                                        if (shortcodes_with_limit.indexOf(option.value) !== -1) {
                                            // This shortcode allow limit arg. Let's extract the shortcode word
                                            // and open a modal. e.g. '{cats}' -> 'cats'
                                            var match = option.value.match(/{(.*?)}/);
                                            if (match) {
                                                openPopup(match[1], editor);
                                            } else {
                                                alert('There was an error!');
                                            }
                                        } else {
                                            // Just insert content in editor
                                            editor.insertContent(option.value);
                                        }
                                    } 
                                }
                            }
                        }).filter(Boolean); // Remove undefined entries
        
                        editor.ui.registry.addMenuButton('ms_insert_tag', {
                            text: options[0].innerText,
                            classes: 'ms-wysiwyg-insert-tag',
                            fetch: function (callback) {
                                callback(items);
                            }
                        });
        
                        editor.on('input', function () {
                            updateContent(editor);
                        });
        
                        editor.on('ExecCommand', function () {
                            updateContent(editor);
                        });
        
                        var updateContent = function (editor) {
                            var el = document.getElementById(editor.id);
                            if (el) {
                                el.value = editor.getContent();
                            }
                        }
        
                        var openPopup = function (value, editor) {
                            var labels = {
                                cats: {
                                    option: APP && __('Category List', 'ml-slider-pro'),
                                    default: APP && __('Display all the categories', 'ml-slider-pro'),
                                    limit: APP && __('Custom number of categories', 'ml-slider-pro'),
                                    instructions: APP && __('Type the maximum number of categories to display', 'ml-slider-pro')
                                },
                                tags: {
                                    option: APP && __('Tag List', 'ml-slider-pro'),
                                    default: APP && __('Display all the tags', 'ml-slider-pro'),
                                    limit: APP && __('Custom number of tags', 'ml-slider-pro'),
                                    instructions: APP && __('Type the maximum number of tags to display', 'ml-slider-pro')
                                },
                                content: {
                                    option: APP && __('Content', 'ml-slider-pro'),
                                    default: APP && __('Display default words length', 'ml-slider-pro'),
                                    limit: APP && __('Custom words length', 'ml-slider-pro'),
                                    instructions: APP && __('Type the maximum words length to display', 'ml-slider-pro')
                                },
                                excerpt: {
                                    option: APP && __('Excerpt', 'ml-slider-pro'),
                                    default: APP && __('Display default words length', 'ml-slider-pro'),
                                    limit: APP && __('Custom words length', 'ml-slider-pro'),
                                    instructions: APP && __('Type the maximum words length to display', 'ml-slider-pro')
                                },
                                content_with_formatting: {
                                    option: APP && __('Content with formatting', 'ml-slider-pro'),
                                    default: APP && __('Display default length', 'ml-slider-pro'),
                                    limit: APP && __('Custom blocks length (paragraph, div, etc.)', 'ml-slider-pro'),
                                    instructions: APP && __('Type the maximum blocks length to display (paragraph, div, etc.)', 'ml-slider-pro')
                                },
                            };
        
                            if (typeof labels[value]['default'] === 'undefined' 
                                || typeof labels[value]['option'] === 'undefined'
                                || typeof labels[value]['limit'] === 'undefined'
                                || typeof labels[value]['instructions'] === 'undefined'
                            ) {
                                console.error("At least one of the labels data is undefined!");
                                return;
                            }
        
                            var default_lbl = labels[value]['default'];
                            var option_lbl = labels[value]['option'];
                            var limit_lbl = labels[value]['limit'];
                            var instructions_lbl = labels[value]['instructions'];
                            
                            var titleConfig = APP.sprintf(
                                __('Configuration for %s', 'ml-slider-pro'),
                                option_lbl
                            );

                            var buttonsConfig = [
                                {
                                    type: 'cancel',
                                    name: 'cancel',
                                    text: __('Cancel', 'ml-slider-pro')
                                },
                                {
                                    type: 'submit',
                                    name: 'submit',
                                    text: __('Insert', 'ml-slider-pro'),
                                    primary: true
                                }
                            ];

                            // Configuration page for all tags
                            var allTagsConfig = {
                                title: titleConfig,
                                body: {
                                    type: 'panel',
                                    items: [
                                        {
                                            type: 'bar',
                                            items: [
                                                {
                                                    type: 'selectbox',
                                                    name: 'elements',
                                                    size: 1, // Visible options
                                                    items: [
                                                        {
                                                            text: default_lbl,
                                                            value: 'all'
                                                        },
                                                        {
                                                            text: limit_lbl,
                                                            value: 'limited',
                                                            enabled: false
                                                        }
                                                    ]
                                                },
                                                
                                            ]
                                        }
                                    ]
                                },
                                buttons: buttonsConfig,
                                initialData: {
                                    elements: 'all'
                                },
                                onChange: function (api) {
                                    var data = api.getData();

                                    // Show the configuration with "Type the maximum number of categories to display" field
                                    if (data.elements === 'limited') {
                                        api.redial(limitedTagsConfig);
                                    }
                                },
                                onSubmit: function (api) {
                                    editor.insertContent(`{${value}}`);
                                    api.close();
                                }
                            };

                            // Configuration page for limited tags
                            var limitedTagsConfig = {
                                title: titleConfig,
                                body: {
                                    type: 'panel',
                                    items: [
                                        {
                                            type: 'bar',
                                            items: [
                                                {
                                                    type: 'selectbox',
                                                    name: 'elements',
                                                    size: 1, // Visible options
                                                    items: [
                                                        {
                                                            text: default_lbl,
                                                            value: 'all'
                                                        },
                                                        {
                                                            text: limit_lbl,
                                                            value: 'limited'
                                                        }
                                                    ]
                                                },
                                                
                                            ]
                                        },
                                        {
                                            type: 'bar',
                                            items: [
                                                {
                                                    type: 'input',
                                                    name: 'limit',
                                                    label: instructions_lbl,
                                                    maximized: false
                                                }
                                            ]
                                        }
                                    ]
                                },
                                buttons: buttonsConfig,
                                initialData: {
                                    elements: 'limited',
                                    limit: '1'
                                },
                                onChange: function (api) {
                                    var data = api.getData();

                                    // Enable insert button
                                    api.setEnabled('submit', 
                                        (data.elements == 'limited' && data.limit > 0)
                                        || data.elements == 'all'
                                    );

                                    // Show the configuration without "Type the maximum number of categories to display" field
                                    if (data.elements === 'all') {
                                        api.redial(allTagsConfig);
                                    }
                                },
                                onSubmit: function (api) {
                                    var elements = api.getData().elements;
                                    var limit = parseInt(api.getData().limit);
                                        
                                    if (elements == 'limited' && limit > 0) {
                                        editor.insertContent(`{${value} limit=${limit}}`);
                                        api.close();
                                    } else {
                                        alert(APP && __('Please enter a number', 'ml-slider-pro'));
                                    }
                                }
                            };

                            editor.windowManager.open(allTagsConfig);
                        }
                    }
                }
            });
        }
        
        var textarea = '.metaslider-ui textarea.wysiwyg-post-feed';

        $(textarea).each(function() {
            tinymce.init({ 
                ...{ selector: textarea },
                ...metaslider.tinymce.find(obj => obj.type === 'post_feed').configuration
            });
        });
    }
    
    var loadWysiwygExternalImage = function () {

        if (typeof tinymce === 'undefined') {
            console.error('TinyMCE is not defined!');
            return;
        }

        // Add External Image data to metaslider.tinymce
        if (typeof metaslider.tinymce.find(obj => obj.type === 'external') === 'undefined') {
            metaslider.tinymce.push({
                type: 'external',
                configuration: {
                    toolbar: [
                        'undo redo bold italic forecolor link unlink alignleft aligncenter alignright styles code'
                    ],
                    menubar: false,
                    plugins: 'code link',
                    branding: false,
                    promotion: false,
                    height: 240,
                    forced_root_block: 'div',
                    convert_urls: false,
                    setup: function (editor) {
                        editor.on('input', function () {
                            updateContent(editor);
                        });
        
                        editor.on('ExecCommand', function () {
                            updateContent(editor);
                        });
        
                        var updateContent = function (editor) {
                            var el = document.getElementById(editor.id);
                            if (el) {
                                el.value = editor.getContent();
                            }
                        }
                    }
                }
            });
        }
        
        var textarea = '.metaslider-ui textarea.wysiwyg-external';

        $(textarea).each(function() {
            tinymce.init({ 
                ...{ selector: textarea },
                ...metaslider.tinymce.find(obj => obj.type === 'external').configuration
            });
        });
    }
	
    var loadWysiwyg = function () {
        loadWysiwygPostFeed();
        loadWysiwygExternalImage();
    }

    loadWysiwyg();
	window.metaslider.app.EventManager.$on("metaslider/slides-created", function() { 
        loadWysiwyg();
    }); 

    $(".metaslider").on('change', '.external input.extimgurl', function() {
        var val = $(this).val();
        $(this).parents('.slide').find('.thumb').css('background-image', 'url(' + val + ')');
    });

    /**
     * Hide slide
     */
    // Stop propagation
    $(".metaslider").on('click', 'button.hide-slide input[type=checkbox]', function(e){
        e.stopPropagation();
    });
    // Button click handler
    $(".metaslider").on('click', 'button.hide-slide', function(e) {
        e.stopPropagation();
        $(this).find('input[type=checkbox]').trigger('click');
        $(this).closest('tr.slide').toggleClass('slide-is-hidden', $(this).find('input[type=checkbox]').is(':checked'));
        checkDelayCompatibility();
    });

	var updateDatepicker = function() {
		$('.metaslider .datepicker').datepicker({
			dateFormat:'yy-mm-dd',
		}).on('focus', function(e){
			if ($(this).datepicker('widget').offset().top > $(this).offset().top) {
				$(this).datepicker('widget').addClass('bottom');
				$(this).datepicker('widget').removeClass('top');
			} else {
				$(this).datepicker('widget').addClass('top');
				$(this).datepicker('widget').removeClass('bottom');
			}
		});
	}
	updateDatepicker();
	window.metaslider.app.EventManager.$on('metaslider/slides-created', function() { updateDatepicker(); });

    /**
     * Set Hiden slide class on page load
     */
    $(".metaslider button.hide-slide input[type=checkbox]").each(function(i) {
        $(this).closest('tr.slide').toggleClass('slide-is-hidden', $(this).is(':checked'));
    });

    /**
     * Check if custom delay is enabled in "Advanced" tab
     * 
     * @param {obj} el The input checkbox
     * 
     * @return void
     */
    var checkDelayCompatibility = function () {
        jQuery("#compatibilityWarningDelay").remove();
        
        if (jQuery('.ms-switch-button input[name*="[delay]"]:checked').length > 0
            && jQuery('tr.slide.post_feed').length > 0
        ) {
            var message = "Post Feed slide isn't compatible with custom delay. Disable custom delay through 'Advanced' tab of each slide.";
            var warningDiv = jQuery("<div id='compatibilityWarningDelay' class='updated ms-slideshow-warning'><p><b>Warning:</b> " + message + "</p></div>");
            jQuery(".metaslider .left").prepend(warningDiv);
        };
    }

    // When custom delay checkboxes changes
    $(document).on('change', '.ms-switch-button input[name*="[delay]"]', function() {
        checkDelayCompatibility();
    });

    // Check all the custom delay checkboxes on load
    $('.ms-switch-button input[name*="[delay]"]').each( function() {
        checkDelayCompatibility();
    });
});
});
