/*
    IndaJava: change tahs generator;
    IndaJava: fix bug where insertElement inserts;
*/
(function () {
    'use strict';

    CKEDITOR.plugins.add('pastebase64', {
        init: init
    });

    function init(editor) {
        if (editor.addFeature) {
            editor.addFeature({
                allowedContent: 'img[alt,id,!src]{width,height};'
            });
        }

        editor.on("contentDom", function () {
            var editableElement = editor.editable ? editor.editable() : editor.document;
            editableElement.on("paste", onPaste, null, { editor: editor });
        });
    }

    function onPaste(event) {
        var editor = event.listenerData && event.listenerData.editor;
        var $event = event.data.$;
        var clipboardData = $event.clipboardData;
        var found = false;
        var imageType = /^image/;

        if (!clipboardData) {
            return;
        }

       
        return Array.prototype.forEach.call(clipboardData.types, function (type, i) {
            if (found) {
                return;
            }


            if (type.match(imageType) || ( clipboardData.items && clipboardData.items[i].type.match(imageType))) {
                readImageAsBase64(clipboardData.items[i], editor);
                return found = true;
            }
        });
    }

    function readImageAsBase64(item, editor) {
        if (!item || typeof item.getAsFile !== 'function') {
            return;
        }

        var file = item.getAsFile();
        var reader = new FileReader();

        reader.onload = function (evt) {
            var source = evt.target.result;
            var img = new Image();
            var width = 0;
            var height = 0;

            img.src = source;
            if (img.complete) { // was cached
                width = img.width;
                height = img.height;
            }
            else { // wait for decoding
                img.onload = function () {
                    width = img.width;
                    height = img.height;
                }
            }

            var css_style = "max-height:300px; max-width:400px;";
            var element = editor.document.createElement('img', {
                attributes: {
                    src: source,
                    style: css_style,
                    class: "forum-inline-message"
                }
            });

            // Use a timeout callback to prevent a bug where insertElement inserts at first caret position
            setTimeout(function () {
                editor.insertElement(element);
            }, 10);
        };

        reader.readAsDataURL(file);
    }
})();
