/*global jQuery*/
(function($) {
    $.fn.richEditor = function(params) {
        params = $.extend({
            base_path: "/noovo/static/js/"
        }, params);

        return this.each(function() {
            if (this.nodeName.toLowerCase() == "textarea") {
                var textarea = $(this);
                var instance = null;
                var onchange_lock = false;

                var editor = new FCKeditor(textarea.attr("id"), textarea.outerWidth(), textarea.outerHeight(), "Noovo");
                editor.Config["AutoDetectLanguage"] = false;
                editor.Config["DefaultLanguage"] = (LANG) ? LANG : "en";

                var par = textarea;
                while (par.length > 0 && !par.hasClass("mini_editor")) {
                    par = par.parent();
                }
                if (par.hasClass("mini_editor")) {
                    editor.Config["CustomConfigurationsPath"] = "fckconfig_noovo_mini.js";
                }

                var cover = $('<div id="loader_' + textarea.attr("id") + '" class="editorLoader">&nbsp;</div>').insertBefore(textarea).css({
                    width: textarea.outerWidth() + "px",
                    height: textarea.outerHeight() + "px"
                });

                editor.BasePath = params.base_path + "fckeditor/";

                setTimeout(function() {
                    editor.ReplaceTextarea();
                }, 2);

                textarea.data("editor", editor);

                // -------------------------------------------------------------
                //         Events
                // -------------------------------------------------------------
                // unlock event on html change
                textarea.bind("htmlChange", function () {
                    this.onchange_lock = false;
                });

                // hooked on editor's OnSelectionChange event
                this.onHTMLChange = function () {
                    if (!this.onchange_lock) {
                        this.onchange_lock = true;
                        setTimeout(function () {
                                textarea.trigger("htmlChange");
                            }, 2000);
                    }
                };

                // hooked on editor's OnPaste event
                this.onPaste = function () {
                    // XXX: Proper way of handling this would be to access
                    //      clipboard content and clean html before it is pasted.
                    //      FCK GetClipboardHTML method returns empty string on
                    //      all browsers except IE.
                    if (!$.browser.msie) {
                        var _this = this;
                        setTimeout(function () {
                            _this.cleanPaste();
                        }, 100);
                    }
                    return true;
                };

                // -------------------------------------------------------------
                //  Public API
                // -------------------------------------------------------------
                this.cleanHTML = function () {
                    var jimages = $(this.instance.EditorDocument).find("img");
                    var jimage = null;
                    var w = 0;
                    var h = 0;

                    for (var i = 0; i < jimages.length; i++) {
                        jimage = $(jimages.get(i));

                        w = jimage.width();

                        if (w > 500) {
                            h = jimage.height();

                            if (h == 0) {
                                continue;
                            }

                            var scale = w/h;
                            w = 500;
                            h = w/scale;

                            jimage.width(w);
                            jimage.height(Math.floor(h));
                        }
                    }
                }

                this.cleanPaste = function () {
                    var html = this.instance.GetHTML();
                    this.instance.SetHTML(NoovoCleanHTML(html));
                }

                this.insertResource = function (resource) {
                    var sizes = resource.thumbnails.medium.match(/\?maxsize=([0-9]+)/);
                    var size = (sizes && sizes.length > 1 && sizes[1] > 500) ? 500 : 'base'; // for old photos with no max size info
                    var resource_src = resource.thumbnails.medium.replace('@45', '@' + size);

                    if (resource.type == 'file') {
                        var subtype = resource.subtype ? resource.subtype : "";
                        this.instance.InsertHtml('<a href="' + resource.uri
                                        + '"><img name="file_info" type="'+subtype+'" title="'+resource.name+'" src="' + resource_src + '" alt="' + resource.uri.replace(/\/([^\/]+)$/, "$1")
                                        + '"/></a>');
                    } else if (resource.type == 'video') {
                        if (resource.video_uri != undefined) {
                            var temp_uri = resource.video_uri
                        } else {
                            var temp_uri = resource.uri
                        }
                        this.instance.InsertHtml('<img src="' + resource_src + '" id="' + resource.id + '" url="' + temp_uri + '" frame="' + resource.thumbnails.medium
                                        + '" type="' + resource.subtype + '" name="video_info" />');
                    } else {
                        this.instance.InsertHtml('<img src="' + resource_src
                                        + '" alt="' + resource.uri.replace(/\/([^\/]+)$/, "$1")
                                        + '"/>');
                    }
                };

                this.getHTML = function () {
                    return this.instance.GetHTML();
                };

                this.getEditor = function() {
                    return textarea.data("editor");
                };

                this.setInstance = function (insta) {
                    this.instance = insta;
                };
            }
        });
    };

})(jQuery);

$(document).ready(function () {
    $("textarea.widgEditor").richEditor({
        base_path: $.fck_media_url
    });
    $("form").bind("submit", function () {
        var jeditors = $(".widgEditor");
        for (var i = 0; i < jeditors.length; i++) {
            jeditors[i].cleanHTML();
        }
        return true;
    });
});

function FCKeditor_OnComplete(editorInstance) {
    setTimeout(function() {
        $('#loader_' + editorInstance.Name).remove();

        var richEditor = $('#' + editorInstance.Name)[0];
        richEditor.setInstance(editorInstance);

        editorInstance.Events.AttachEvent('OnSelectionChange', function () {
            richEditor.onHTMLChange();
        });

        editorInstance.Events.AttachEvent("OnPaste", function () {
            return richEditor.onPaste();
        });
    }, 2);
};



