var HL = HL || {};

HL.edit = (function() {
    var container = document.createElement('div'),
        editor = document.createElement('textarea'),
        sample = document.getElementById('sample-html').innerHTML,
        button = OU.buttons.create({
            type: 'sample-html',
            html: 'Add sample HTML',
            classes: ['osep'],
            hidden: true,
            click: function() {
                editor.setContent(sample);
                status.updated = true;
            }
        }),
        status = {
            loaded: false,
            updated: false
        };

    var init = function() {
        container.appendChild(editor);
        container.appendChild(button);
    };

    var initEditor = function() {
        var cfg = {
            target: editor,
            width: 800,
            height: 400,
            encoding: 'xml',
            entity_encoding: 'raw',
            extended_valid_elements: 'span[tabindex|class|style|!data-hl]',
            valid_classes: {
                'span': 'yellow green pink blue orange red pre-highlight static space'
            },
            plugins: [
                'advlist lists image charmap print',
                'searchreplace visualchars visualblocks code fullscreen',
                'table contextmenu paste'
            ],
            /*[
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table contextmenu paste'
            ],*/
            toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | table | bullist numlist outdent indent | link image | code',
            setup: function(ed) {
                ed.on('change', function() {
                    status.updated = true;
                });
            }
        };

        tinymce.init(cfg).then(function(array) {
            editor = array[0];
            api.editor = editor;
            status.loaded = true;
            button.style.display = 'block';
            OU.utils.triggerCustomEvent(container, 'editor-loaded');
        });
    };

    var api = {
        container: container,
        sample: sample,
        status: status,
        init: init,
        initEditor: initEditor
    };

    return api;
})();