CKEDITOR.plugins.add('cscustomhtml', {
    init: function (editor) {
        editor.csCustomHtml = CsCustomHtml.init(editor.element.$.lang);

        var command = new CKEDITOR.command(editor, {
            exec: function (editor) {

                _initEvents();

                var customHtml = _buildCustomHtml();

                editor.csCustomHtml.exec(customHtml, function (element) {
                    _createElement(element);
                });
            }
        });

        var _initEvents = function () {
            editor.focusManager.lock();

            editor.csCustomHtml.signals.onDestroyModal.add(function () {
                editor.focusManager.unlock();
            });
        };

        var _createElement = function (element) {
            var e = editor.document.createElement('div');
            e.setAttribute('id', element.customHtml.id);

            var wrapper = editor.document.createElement(createElementFromHTML(element.customHtml.value));

            editor.insertElement(wrapper);
        };

        var _buildCustomHtml = function () {
            return editor.csCustomHtml.createCustomHtml();
        };

        var createElementFromHTML = function (htmlString) {
            var div = document.createElement('div');

            div.innerHTML = htmlString.trim();

            return div.firstChild;
        };

        editor.addCommand('cscustomhtml', command);

        editor.ui.addButton('CsCustomHtml', {
            label: Translator.trans('cs_core.cs_custom_html.label'),
            command: 'cscustomhtml',
            icon: this.path + 'icons/cscustomhtml.png'
        });
    }
});
