<script src="{{ asset('/bundles/comitium5designer/ckeditor/ckeditor.js') }}"></script>
{% for name, plugin in config.plugins if plugin.autoload %}
    <script src="{{ asset( plugin.path|trim('/') ~ '/' ~ plugin.filename ) }}"></script>
{% endfor %}
{% spaceless %}
<script type="text/javascript">

    var CKEDITOR_BASEPATH = "{{ '/bundles/comitium5designer/ckeditor/' }}";

    CKEDITOR.plugins.basePath = "{{ '/bundles/comitium5designer/ckeditor/plugins/' }}";
    CKEDITOR.config.language = "{{ app.request.locale }}";
    CKEDITOR.config.defaultLanguage = "{{ app.request.locale }}";
    CKEDITOR.config.filebrowserBrowseUrl  = "{{ url('designer_asset_browse') }}";
    CKEDITOR.config.filebrowserImageUploadUrl = "{{ url('designer_assets_alternate_upload') }}";
    CKEDITOR.config.autoGrow_minHeight = 10;
    CKEDITOR.config.autoGrow_onStartup = true;

    CKEDITOR.config.allowedTagsOnPaste = {
        p : {},
        a: {
            attributes: [ '!href', 'title' ]
        },
        img: {
            attributes: [ '!src', 'alt', 'width', 'height' ]
        },
        br: {},
        b: {},
        strong: {},
        ul: {},
        li: {},
        ol: {},
        dl: {},
        dd: {},
        dt: {},
        u: {},
        i: {},
        em: {}
    };

    {% for name, value in attribute(config.configs, config.default_config) %}
        CKEDITOR.config.{{ name }} = {{ value|json_encode|raw }};
    {% endfor %}

    {% for name, plugin in config.plugins if not plugin.autoload %}
        CKEDITOR.plugins.addExternal("{{ name }}", "{{ plugin.path }}", "{{ plugin.filename }}");
    {% endfor %}

    {% for name, toolbar in config.toolbars %}
        CKEDITOR.config.toolbar_{{ name }} = {{ toolbar|json_encode|raw }};
    {% endfor %}

    CKEDITOR.on('instanceReady', function(e) {
        e.editor.on('simpleuploads.startUpload', function (ev) {
            ev.data.extraFields = {
                "type" : "image"
            };
        });

        e.editor.on( 'change', function( evt ) {
            document.getElementById(evt.editor.name).value = evt.editor.getData();
        });

        e.editor.on('paste', function(event) {
            if(event.data.type === 'html') {
                var filter = new CKEDITOR.filter( CKEDITOR.config.allowedTagsOnPaste ),
                        fragment = CKEDITOR.htmlParser.fragment.fromHtml( event.data.dataValue ),
                        writer = new CKEDITOR.htmlParser.basicWriter();

                filter.applyTo(fragment);
                fragment.writeHtml( writer );
                event.data.dataValue = writer.getHtml();
            }
        });
    });
</script>
{% endspaceless %}
