tinymce.init({
    body_class: 'content-text',
    convert_urls: false,
    content_css: document.getElementsByTagName('body')[0].getAttribute('data-styles-front'),
    entity_encoding : "raw",
    image_advtab: true,
    menubar: false,
    paste_auto_cleanup_on_paste: true,
    plugins: [
        "advlist autolink autosave autoresize link image lists charmap print preview hr anchor pagebreak spellchecker",
        "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
        "table contextmenu directionality emoticons template textcolor paste",
        "customkeyselect"
    ],
    advlist_bullet_styles: "disc",
    selector: "textarea.tinymce",
    setup: function(editor) {        
        // Get the lang attribute of the <html> tag
        var lang = document.getElementsByTagName('html')[0].getAttribute('lang');

        editor.settings.language = lang.replace('-', '_');        
    },
    skin: "lightgray",
    formats: {
        alignleft: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'text-left'},
        aligncenter: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'text-center'},
        alignright: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'text-right'},
        alignjustify: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'text-justify'},
    },
    block_formats : 'Paragraph=p;Heading 1=h1;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre;Bloc=div',
    style_formats: [        
        {title: '--- Theme - Couleur dynamique ---'},
        
        {title: 'Couleur du thème', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-theme', exact: true},
        {title: 'Lien Couleur du thème', selector: 'a', inline: 'span', classes: 'link link-theme', exact: true},
        {title: 'Bouton Couleur du thème', selector: 'a', inline: 'span', classes: 'btn btn-theme', exact: true},
        
        {title: '--- Couleurs ---'},

        {title: 'Couleur La Rioja', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-la-rioja', exact: true},
        {title: 'Couleur Pelorus', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-pelorous', exact: true},
        {title: 'Couleur Tangerine', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-tangerine', exact: true},
        {title: 'Couleur Tundora', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-tundora', exact: true},
        {title: 'Couleur Froly', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-froly', exact: true},
        {title: 'Couleur Blanc', selector: 'p,span,h1,h2,h3,h4,h5,h6,div,ul,ol,li,b,em,strong,u', inline: 'span', classes: 'color-white', exact: true},

        {title: '--- Liens ---', selector: 'a'},

        //{title: 'Lien', selector: 'a', inline: 'a', classes: 'link', exact: true},
        {title: 'Lien La Rioja', selector: 'a', inline: 'a', classes: 'link link-la-rioja', exact: true},
        {title: 'Lien Pelorus', selector: 'a', inline: 'a', classes: 'link link-pelorous', exact: true},
        {title: 'Lien Tangerine', selector: 'a', inline: 'a', classes: 'link link-tangerine', exact: true},
        {title: 'Lien Froly', selector: 'a', inline: 'a', classes: 'link link-froly', exact: true},
        {title: 'Lien Tundora', selector: 'a', inline: 'a', classes: 'link link-tundora', exact: true},
        {title: 'Lien Blanc', selector: 'a', inline: 'a', classes: 'link link-white', exact: true},

        {title: '--- Boutons ---', selector: 'a'},

        {title: 'Bouton', selector: 'a', inline: 'a', classes: 'btn', exact: true},
        {title: 'Bouton La Rioja', selector: 'a', inline: 'a', classes: 'btn btn-la-rioja', exact: true},
        {title: 'Bouton Pelorus', selector: 'a', inline: 'a', classes: 'btn btn-pelorous', exact: true},
        {title: 'Bouton Tangerine', selector: 'a', inline: 'a', classes: 'btn btn-tangerine', exact: true},
        {title: 'Bouton Froly', selector: 'a', inline: 'a', classes: 'btn btn-froly', exact: true},
        {title: 'Bouton Tundora', selector: 'a', inline: 'a', classes: 'btn btn-tundora', exact: true},
        {title: 'Bouton Blanc', selector: 'a', inline: 'a', classes: 'btn btn-white', exact: true},

        {title: '--- Titres ---', selector: 'h1,h2,h3,h4,h5,h6'},

        {title: 'Titre avec Bulles', selector: 'h1,h2,h3,h4,h5,h6', classes: 'has-color-bubbles'},


        {title: '--- Blocks ---', selector: 'div,p'},

        {title: 'Question FAQ', selector: 'div,p', classes: 'faq-answer'},
    ],
    style_formats_autohide: true,
    theme_advanced_resizing: true,
    toolbar1: "bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect",
    toolbar2: "cut copy paste | searchreplace | bullist | outdent indent blockquote | undo redo | link unlink anchor image media code",
    toolbar3: "table | hr removeformat | subscript superscript | charmap | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking restoredraft",
    toolbar4: "customkeyselect",
    toolbar_items_size: 'small',
    autoresize_min_height: 200,

    // enable or not paste image directly into editor
    paste_data_images: false,
    // enable title field in the Image dialog
    image_title: true,
    // enable automatic uploads of images represented by blob or data URIs
    automatic_uploads: true,
    images_upload_url: '/admin/tinymcePostAcceptor.php',
    //images_upload_base_path: '/uploads/images/',
    //images_upload_credentials: true,
}).then(function(editors) {
    $.each(editors, function(index, editor){
        var selectorColor = $('#simple_menu_class,#custom_html_color');

        var target_class = editor.targetElm.className;
        var body_class = editor.settings.body_class;
        var theme = selectorColor.find('input:checked').val();

        var editor_body = $('body', $(editor.editorContainer).find('iframe').contents());

        if (target_class.includes('tinymce-dynamic-color')) {
            // Init
            editor_body.attr('class', 'mce-content-body ' + body_class + ' ' + theme);

            selectorColor.on('change', function(e) { 
                theme = $(this).find('input:checked').val();
                editor_body.attr('class', 'mce-content-body ' + body_class + ' ' + theme);
            })
        }

        if (target_class.includes('tinymce-dynamic-background')) {
            // Init
            editor_body.attr('class', 'mce-content-body ' + body_class + ' bg-' + theme);

            selectorColor.on('change', function(e) { 
                theme = $(this).find('input:checked').val();
                editor_body.attr('class', 'mce-content-body ' + body_class + ' bg-' + theme);
            })
        }

        if (target_class.includes('tinymce-page-header')) {
            // Init
            editor_body.attr('class', 'mce-content-body ' + body_class + ' bg-tundora ' + theme);

            selectorColor.on('change', function(e) { 
                theme = $(this).find('input:checked').val();
                editor_body.attr('class', 'mce-content-body ' + body_class + ' bg-tundora ' + theme);
            })
        }

        if (target_class.includes('tinymce-grey-background')) {
            // Init
            editor_body.attr('class', 'mce-content-body ' + body_class + ' bg-alabaster');

            selectorColor.on('change', function(e) { 
                theme = $(this).find('input:checked').val();
                editor_body.attr('class', 'mce-content-body ' + body_class + ' bg-alabaster');
            })
        }
        
        $('body').on('click', '.mce-btn', function(e) { 
            var els = $('.mce-menu .mce-menu-item.mce-menu-item-preview');
            
            els.each(function(){
                var val = $(this).find('.mce-text').text();

                if (val.includes('---')) {
                    $(this).css({
                        'cursor': 'default',
                        'background': '#F6F6F6'
                    });

                    $(this).find('.mce-text').css({
                        'font-size': '12px'
                    });
                }
                else if (val.includes('Blanc') && !val.includes('Bouton')) {
                    $(this).find('.mce-text').css({
                        'background': '#4a4949'
                    });
                }
            })
        });
    })   
});

tinymce.PluginManager.add('customkeyselect', function(editor, url) {
    // Add a button that opens a window
    editor.addButton('customkeyselect', {
      type: 'listbox',
      text: 'Contenu dynamique',
      icon: false,
      values: [
        { text: 'Lien ajout d\'une opération IDTLC', value: '__LINK_ADD_OPE_ITDLC_DEPENDS_USER_TYPE__' },
        { text: 'Contenu spécifique aux professeurs', value: '__IF_TEACHER__' },
        { text: 'Contenu spécifique aux ingénieurs', value: '__IF_ENGINEER__' },
        { text: 'Contenu spécifique aux utilisateurs connectés', value: '__IF_USER_CONNECTED__' },
        { text: 'Contenu spécifique aux visiteurs non connectés', value: '__IF_USER_NOT_CONNECTED__' }
      ],
      onselect: function(e) {
        var key = this.value();

        if (key == '__LINK_ADD_OPE_ITDLC_DEPENDS_USER_TYPE__') {
            // Open window
            editor.windowManager.open({
                title: 'Lien ajout d\'une opération IDTLC',
                body: [
                    {type: 'textbox', name: 'btn_txt', label: 'Texte du lien'}
                ],
                onsubmit: function(e) {
                    // Insert content when the window form is submitted
                    editor.insertContent('<a href="__LINK_ADD_OPE_ITDLC_DEPENDS_USER_TYPE__">' + e.data.btn_txt + '</a>');
                }
            });
        }
        else if (key == '__IF_TEACHER__') {
            // Open window
            editor.windowManager.open({
                title: 'Contenu spécifique aux ingénieurs',
                body: [
                    {type: 'textbox', name: 'content', label: 'Contenu'}
                ],
                onsubmit: function(e) {
                    // Insert content when the window form is submitted
                    editor.insertContent('[IF TEACHER]' + e.data.content + '[ENDIF]');
                }
            });
        }
        else if (key == '__IF_ENGINEER__') {
            // Open window
            editor.windowManager.open({
                title: 'Contenu spécifique aux professeurs',
                body: [
                    {type: 'textbox', name: 'content', label: 'Contenu'}
                ],
                onsubmit: function(e) {
                    // Insert content when the window form is submitted
                    editor.insertContent('[IF ENGINEER]' + e.data.content + '[ENDIF]');
                }
            });
        }
        else if (key == '__IF_USER_CONNECTED__') {
            // Open window
            editor.windowManager.open({
                title: 'Contenu spécifique aux utilisateurs connectés',
                body: [
                    {type: 'textbox', name: 'content', label: 'Contenu'}
                ],
                onsubmit: function(e) {
                    // Insert content when the window form is submitted
                    editor.insertContent('[IF USER CONNECTED]' + e.data.content + '[ENDIF]');
                }
            });
        }
        else if (key == '__IF_USER_NOT_CONNECTED__') {
            // Open window
            editor.windowManager.open({
                title: 'Contenu spécifique aux visiteurs non connectés',
                body: [
                    {type: 'textbox', name: 'content', label: 'Contenu'}
                ],
                onsubmit: function(e) {
                    // Insert content when the window form is submitted
                    editor.insertContent('[IF USER NOT CONNECTED]' + e.data.content + '[ENDIF]');
                }
            });
        }
      }
    });
});

function deleteElement($el)
{
    var $container = $el.closest('.delete-element-container');

    if (1 === $container.length) {
        $container.fadeOut({
            complete: function() {
                $container.remove();
            }
        });
    }
}

function countdownTextarea(target) {
    var countable_limit = target.attr('data-limit') || 160;
    var countable_text = target.parent().find(".form-row-field-help .countable-text");
    var text_length = target.val().length;
    var text_remaining = countable_limit - text_length;
    var text_modulo = Math.ceil(text_length/countable_limit);
    var text_excess = text_length - countable_limit;

    var text_valid = target.attr('data-text-valid') || '%remaining% caractères restants.';
    var text_not_valid = target.attr('data-text-not-valid') || '%remaining% caractères restants.';
    
    if (text_remaining < 0) {
        countable_text.addClass("error");
        countable_text.html(text_not_valid.replace('%remaining%', text_remaining).replace('%excess%', text_excess).replace('%modulo%', text_modulo).replace('%count%', text_length));
    }
    else {
        countable_text.removeClass("error");
        countable_text.html(text_valid.replace('%remaining%', text_remaining).replace('%excess%', text_excess).replace('%modulo%', text_modulo).replace('%count%', text_length));
    }
}

$(function() {
    var $body = $('body');
    var fancyboxLoadUrls = $body.attr('data-fancybox-load');

    if (undefined !== fancyboxLoadUrls) {
        $.fancybox.open({
            autoSize: false,
            href: fancyboxLoadUrls.split(' ')[0],
            height: 500,
            padding: 0,
            type: 'iframe',
            width: 700,
        });
    }

    // Toggle the checkbox / radio input value according to a click on the custom version
    $body.on('click', '.checkbox, .radio', function() {
        var input = $(this).prev();

        if (!input.prop('disabled')) {
            input.prop('checked', !input.prop('checked')).trigger('change');
        }
    });

    // Custom input
    $body.on('click', '.fakefile--button', function(e) {
        e.preventDefault();

        $(this).parent().children('.fakefile--file').trigger('click');
    });
    $body.on('change', '.fakefile--file', function() {
        $(this).parent().children('.fakefile--value').val($(this).val());
    });

    // Delete an element
    $body.on('click', '.delete-element', function(e) {
        e.preventDefault();

        var $container,
            $el = $(e.target),
            href = $el.attr('href'),
            title = e.currentTarget.getAttribute('title');

        if (undefined === href) {
            deleteElement($el);
        } else if (true === confirm(title ? title + ' ?' : 'Voulez-vous réellement supprimer cet élément ?')) {
            $.ajax({
                type: 'GET',
                url: href,
                cache: false
            })
            .done(function() {
                deleteElement($el);
            });
        }
    });

    $('.date').datepicker({dateFormat: 'dd/mm/yy'});

    $('.input-active').on('change', function() {
        $.ajax({
            type: "POST",
            url: $(this).attr('data-url'),
            data: {
                id: $(this).val(),
                actif: $(this).is(':checked') ? 'true' : 'false',
                type: $(this).attr('data-type')
            },
            cache: false
        });
    });
    
    // Countable Textarea
    $('textarea.countable').each(function() {
        var countable_limit = $(this).attr('data-limit') || 160;
        var help_text = $(this).parent().find(".form-row-field-help");
        help_text.find('.icon').after('<span class="countable-text"></span>');
        help_text.find('.countable-text').html(countable_limit + ' caractères restants.');

        countdownTextarea($(this));
    });

    $('textarea.countable').on("keyup touchend change", function() {
        countdownTextarea($(this));
    });

    // Prevent Bootstrap dialog from blocking focusin
    $(document).on('focusin', function(e) {
        if ($(e.target).closest(".mce-window").length) {
            e.stopImmediatePropagation();
        }
    });
});

/**
 * Manage a tabulation component, like the bootstrap one (http://getbootstrap.com/components/#nav-tabs)
 */
(function() {
    var addLinkClickEvent,
        l,
        links,
        n,
        nav,
        navs = document.querySelectorAll('.nav-tabs'),
        navsQty = navs.length,
        tabContent,
        tabContents = document.querySelectorAll('.tab-content'),
        tabContentsQty = tabContents.length;    

    if (navsQty !== tabContentsQty) {
        console.error('Cannot instanciate nav tabs because number of navs and the number of tab contents do not match (' + navsQty + 'navs and ' + tabContentsQty + 'tab contents ).');
    } else {
        addLinkClickEvent = function(link, nav) {
            link.addEventListener('click', function(e) {
                // Un-select the previously selectionned tab and tabcontent
                nav.querySelector('a.active').classList.remove('active');
                tabContent.querySelector('.tabpane.active').classList.remove('active');

                // Select the new tab and tabcontent
                e.target.classList.add('active');
                document.getElementById(e.target.getAttribute('aria-controls')).classList.add('active');
            });
        };

        for (n = 0; n < navsQty; n++) {
            nav = navs[n];
            tabContent = tabContents[n];

            // Get all the link of the current tab navigation
            links = nav.querySelectorAll('a');

            // Bind a click event on each of these links
            for (l = 0; l < links.length; l++) {
                addLinkClickEvent(links[l], nav);
            }
        }
    }
})();
