var AceEditorSyncHelper = function (editor) {
    this.editor = editor;
    this.inlineCKEditorConfig = {
        "toolbar":"visualEditor",
        "style":"style_1",
        "template":"template_1",
        "extraPlugins": "basicstyles,simpleuploads,preview,newpage,autogrow,justify,find,iframe,iframedialog,cslinks,csimage,csvideo,csaudio,cscustomhtml,jqueryspellchecker,sourcedialog",
        "skin":"kama",
        "autoGrow_minHeight":250,
        "simpleuploads_acceptedExtensions":"jpg|png",
        "simpleuploads_imageExtensions":"jpe?g|gif|png",
        "csAsset": {
            "absoluteUrl": true
        },
        autoParagraph: false
    };
};

AceEditorSyncHelper.prototype.bindWithPreview = function () {
    var _this = this;

    if (typeof this.editor.iframe === 'undefined') {
        var editor = this.editor;
        var iframe = $('<iframe />').addClass('mailing-preview-iframe');

        $('[data-role="preview-placeholder"]', $(this.editor.container).closest('[data-wrapper="live-code"]')).append(iframe);

        this.editor.iframe = iframe;

        this.editor.on('change', function () {
            if (typeof silent === 'undefined' || !silent) {
                _this.writeContentIntoPreview(editor);
            }
        });
    }

    _this.writeContentIntoPreview(this.editor);
};

AceEditorSyncHelper.prototype.writeContentIntoPreview = function (editor) {
    var _this        = this,
        iframe       = editor.iframe,
        iframeWindow = iframe.get(0).contentWindow || ( iframe.get(0).contentDocument.document || iframe.get(0).contentDocument);

    var injectedStyles = '<style>/* MAILINGS - Mailing preview - Inner styles */ \
                .cke_editable {outline-color:#F5CB74; outline-width:2px; outline-offset:0;} \
                .cke_editable.cke_focus {box-shadow:none !important; outline:2px dashed #F5CB74 !important; outline-offset:4px; transition:all 0.1s ease-in-out !important;} \
                </style>';

    $('html', iframeWindow.document).get(0).innerHTML = editor.getValue();
    $('head', iframe.contents()).append(injectedStyles);

    var editableElements = $('[cs-editable]', iframe.contents());

    if (editableElements.length === 0) {
        var body = $('body', iframe.contents());
        if (body.length > 0) {
            _this.initCKEditor($('body', iframe.contents()), iframe, editor);
        }
    } else {
        // Avoid links clicks, preventing go to external sites inside the iframe
        $('a', iframe.contents()).on("click", function(e) {
            e.preventDefault();
        });

        $('[cs-editable]', iframe.contents()).each(function () {
            _this.initCKEditor($(this, iframe.contents()), iframe, editor);
        });
    }

    editor.renderer.updateFull();
};

AceEditorSyncHelper.prototype.initCKEditor = function (editableElement, iframe, editor) {
    var el = editableElement
        .wrapInner('<div />')
        .children()
        .prop('contenteditable', true)
        .attr('lang', $('#crm_newsletter_standard_type_localeId').find('option:selected').data("slug"))
        .get(0);

    $.extend(this.inlineCKEditorConfig, {
        'on' : {
            'change' : function() {
                var submit = $("button.button-submit");

                submit.addClass("disabled");
                var data    = $('body', iframe.contents()).html(),
                    element = $('<div>'+ data + '</div>');

                $('.cke_editable', element).each(function(){
                    $(this).replaceWith($(this).html());
                });

                silent = true;
                var content = editor.getValue();
                editor.session.setValue(html_beautify(content.replace(/<body([^>]*)>((.|[\n\r])*)<\/body>/g, '<body $1>' + element.html() + '</body>')));
                editor.codeElement.val(editor.getValue());
                silent = false;
                submit.removeClass("disabled");
            },
            'focus' : function (event) {
                var dimensions = iframe.get(0).getBoundingClientRect();
                var selector = 'data-editor="' + event.editor.name + '"';
                var styles = '<style ' + selector + '>';
                styles += '.' + event.editor.id + '.cke_editor_' + event.editor.name + '{';
                styles += 'position: absolute !important;';
                styles += 'top:' + iframe.offset().top + 'px !important;';
                styles += 'left:'+ dimensions.left + 'px !important;';
                styles += 'width:'+ dimensions.width + 'px !important;';
                styles += '}';
                styles += '</style>';
                var styleElement = $('[' + selector + ']');
                if (styleElement.length > 0) {
                    styleElement.replaceWith(styles);
                } else {
                    $('body').append(styles);
                }

            }
        }
    });

    CKEDITOR.inline(el, this.inlineCKEditorConfig);
};
