<script src="/admin/assets/editor/tinymce/tinymce.min.js"></script>
<script>
	{literal}
    $(function(){

        function mnv_image_upload_handler (blobInfo, success, failure, progress) {
            var xhr, formData, editor, node;

            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '{/literal}{$GLOBAL_URL}{literal}/admin/handlers/uploading-file-to-content.php');
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.upload.onprogress = function (e) {
                progress(e.loaded / e.total * 100);
            };

            xhr.onload = function() {
                var json;

                if (xhr.status === 500) {
                    failure('HTTP Error: ' + xhr.status, { remove: true });
                    return;
                }

                if (xhr.status < 200 || xhr.status >= 300) {
                    failure('HTTP Error: ' + xhr.status);
                    return;
                }

                json = JSON.parse(xhr.responseText);
                // json = xhr.responseText;
                console.log(json);

                if (!json || typeof json.link != 'string') {

                    if (typeof json.error == 'string') {
                        failure(json.message);
                    } else {
                        failure('Invalid JSON: ' + xhr.responseText);
                    }

                    editor = tinymce.activeEditor;
                    node = editor.selection.getEnd();
                    editor.selection.select(node);
                    editor.selection.setContent('');

                    return;
                }

                if( json.flink ) {
                    console.log("json.flink => " + json.flink)
                    editor = tinymce.activeEditor;
                    node = editor.selection.getEnd();
                    editor.selection.select(node);
                    editor.selection.setContent('<a href="' + json.flink + '" class="highslide"><img src="' + json.link + '" style="display: block; margin-left: auto; margin-right: auto;"></a>&nbsp;');
                    editor.notificationManager.close();

                } else {
                    console.log("json.link => " + json.link)
                    success(json.link);
                }
            };

            xhr.onerror = function () {
                failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
            };

            formData = new FormData();
            formData.append('file', blobInfo.blob(), blobInfo.filename());
            formData.append("action", "upload");
            xhr.send(formData);
        }

        tinyMCE.baseURL = '/admin/assets/editor/tinymce';
        tinyMCE.suffix = '.min';

        tinymce.init({
            selector: 'textarea.description',
            language : "{/literal}{$config.admin_language}{literal}",
            element_format : 'html',
            theme: 'silver',
            skin:  'oxide',
            width : "100%",
            height : 400,
            deprecation_warnings: false,
            // plugins: ["fullscreen advlist autolink lists link image charmap anchor searchreplace visualblocks visualchars nonbreaking noneditable table paste codemirror spellchecker mnvbutton codesample hr quickbars autosave wordcount pagebreak"],
            plugins: ["fullscreen advlist autolink lists link image charmap anchor searchreplace visualblocks visualchars nonbreaking noneditable table paste codemirror spellchecker mnvbutton codesample hr quickbars autosave wordcount pagebreak"],

            setup: function(editor) {
                // editor.on('change', function () {
                //     tinymce.triggerSave();
                // });
                editor.on('PreInit', function() {
                    var shortEndedElements = editor.schema.getShortEndedElements();
                    shortEndedElements['path'] = {};
                    shortEndedElements['source'] = {};
                    shortEndedElements['use'] = {};
                });
            },

            relative_urls : false,
            convert_urls : false,
            remove_script_host : false,
            verify_html: false,
            nonbreaking_force_tab: true,
            branding: false,
            default_link_target: '_blank',
            browser_spellcheck: true,
            pagebreak_separator: '{PAGEBREAK}',
            pagebreak_split_block: true,
            noneditable_editable_class: 'contenteditable',
            noneditable_noneditable_class: 'noncontenteditable',
            contextmenu: 'image imagetools table spellchecker lists',

            image_advtab: true,
            image_caption: true,
            paste_data_images: true,
            automatic_uploads: true,
            images_upload_handler: mnv_image_upload_handler,
            images_reuse_filename: true,

            image_uploadtab: false,
            images_file_types: 'gif,jpg,png,jpeg,bmp,webp',

            file_picker_types: 'image',
            file_picker_callback: function (cb, value, meta) {
                var input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'image/*');

                input.onchange = function () {
                    var file = this.files[0];

                    var filename = file.name;
                    filename = filename.split('.').slice(0, -1).join('.');

                    var reader = new FileReader();

                    reader.onload = function () {

                        var id = filename;
                        var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                        var base64 = reader.result.split(',')[1];
                        var blobInfo = blobCache.create(id, file, base64);
                        blobCache.add(blobInfo);

                        cb(blobInfo.blobUri());
                    };

                    reader.readAsDataURL(file);
                };

                input.click();
            },

            draggable_modal: true,
            menubar: 'edit insert format table view tools',
            // toolbar: 'bold italic underline strikethrough | align | bullist numlist | indent outdent | link mnvleech unlink | image mnvupload  mnvmp mnvaudio mnvtube mnvemo | mnv | fontformatting textformatting code',
            toolbar: 'bold italic underline strikethrough | align | bullist numlist | indent outdent | link unlink | image mnvupload mnvvideo mnvaudio mnvtube | mnv | fontformatting textformatting code removeformat',
            toolbar_mode: 'floating',
            toolbar_groups: {

                fontformatting: {
                    icon: 'change-case',
                    tooltip: 'Formatting',
                    items: 'formatselect fontselect fontsizeselect | forecolor backcolor'
                },

                textformatting: {
                    icon: 'edit-block',
                    tooltip: 'Tools',
                    items: 'searchreplace spellchecker | mnvtypo removeformat'
                },

                align: {
                    icon: 'align-center',
                    tooltip: 'Formatting',
                    items: 'alignleft aligncenter alignright alignjustify'
                },

                mnv: {
                    icon: 'preview',
                    tooltip: 'MNV Tags',
                    items: 'mnvquote codesample | pagebreak'
                }
            },

            menu: {
                view: { title: 'View', items: 'restoredraft | visualaid visualchars visualblocks' }
            },
            removed_menuitems: 'codeformat, bold, italic, underline, strikethrough',

            quickbars_insert_toolbar: '',
            quickbars_selection_toolbar: 'bold italic underline | quicklink mnvquote mnvspoiler mnvhide | forecolor backcolor formatselect',

            autosave_ask_before_unload: true,
            autosave_interval: '10s',
            autosave_prefix: 'mnv-editor',
            autosave_restore_when_empty: false,
            autosave_retention: '10m',
			forced_root_block : false,
            formats: {
                bold: { inline: 'b' },
                italic: { inline: 'i' },
                underline: { inline: 'u', exact : true },
                strikethrough: { inline: 's', exact : true }
            },

            spellchecker_language : "{/literal}{$config.admin_language}{literal}",
            spellchecker_languages : "Russian=ru,English=en",
            spellchecker_rpc_url : "https://speller.yandex.net/services/tinyspell",

            mnv_root : "",
            mnv_upload_area : "description",
            mnv_upload_user : "admin",
            mnv_upload_news : "0",

            content_css : "/admin/assets/editor/tinymce/css/content.css"

        });

    });

    {/literal}
</script>
