(function($) {
    $.ui = $.ui || {};
    $.fn.ikeEditor = function(opts) {
        var ikeEditorInstance = false;
        if (this[0])
            ikeEditorInstance = new $.ui.ikeEditor(opts, this);
        return ikeEditorInstance;
    };
    $.ui.ikeEditor = function(opt, elem) {
        var options = $.extend({
            controls: ['bold', 'italic', 'underline', 'font', 'size', 'color', 'leftalign', 'centeralign', 'rightalign', 'blockjustify'],
            separator: 'tedivider',
            headercss: 'teheader',
            toolcss: 'div-form-editor-toolbar',
            btncss: 'tecontrol',
            containcss: 'div-form-editor',
            width: 500,
            height: 200,
            fontName: [
                '宋体',
                '新宋体',
                '华文彩云',
                '楷体_GB2312',
                '黑体',
                '微软雅黑',
                'Arial',
                'Arial Black',
                'Courier New',
                'Tahoma',
                'Verdana'
            ],
            footer: false,
            resize: { css: 'resize' },
            toggle: { text: 'source', activetext: 'ikeEditor', css: 'toggle' },
            fontSize: [
		    	{ t: "1", n: "极小" },
				{ t: "2", n: "特小" },
				{ t: "3", n: "小" },
				{ t: "4", n: "中" },
				{ t: "5", n: "大" },
				{ t: "6", n: "特大" },
				{ t: "7", n: "极大" }
			],
            fontColor: [
		    	{ t: "#000000", n: "黑色" },
				{ t: "#CCCCCC", n: "灰色" },
				{ t: "#FF0000", n: "红色" },
				{ t: "#FFFF00", n: "黄色" },
                { t: "#0000CC", n: "蓝色" },
                { t: "#006600", n: "绿色" },
                { t: "#660066", n: "紫色" }

			]
        }, opt);
        var c = [], offset = -20;
        c['bold'] = [7, '加粗', 'a', 'bold'];
        c['italic'] = [8, '斜体', 'a', 'italic'];
        c['underline'] = [9, '下横线', 'a', 'underline'];
        c['leftalign'] = [27, '左对齐', 'a', 'justifyleft'];
        c['centeralign'] = [28, '居中', 'a', 'justifycenter'];
        c['rightalign'] = [29, '右对齐', 'a', 'justifyright'];
        c['blockjustify'] = [30, '自适应', 'a', 'justifyfull'];
        var frameID = "IkeHtmlEditor_" + elem.attr("id");
        var iframe = $('<iframe/>').attr({ "id": frameID, "name": frameID, "frameBorder": 0 });
        $(iframe).css({ width: options.width, height: options.height }).appendTo(document.body);
        var frDocument = window.frames[frameID].document;
        frDocument.open();
        var m = '<html><head><style type="text/css">' + "html,body{margin:0 0 0 5px;padding:0 0 0 0px;background-color:#fff;},p{margin:0px;padding:0px;}" + '</style></head><body></body></html>';
        frDocument.write(m);
        frDocument.close();
        frDocument.designMode = "on";
        if (!$.browser.msie)
            frDocument.execCommand("useCSS", false, true);
        //document.getElementById(frameID).focus();
        var darrenEidtor = {
            getHeader: function() {
                var toolContainer = $("<div/>").addClass(options.containcss);
                var toolRowHeader = $("<div/>").addClass(options.headercss).appendTo(toolContainer);
                var toolbar = $("<div/>").addClass(options.toolcss).appendTo(toolRowHeader);
                $(options.controls).each(function(index, ele) {
                    var key = ele;
                    switch (key) {

                        //                      case "n": { toolRowHeader = $("<div/>").addClass(options.headercss).appendTo(toolContainer); break; }                                                
                        case '|': { var d = $("<div/>").addClass(options.separator).appendTo(toolbar); break; }
                        case "font":
                            {
                                var fontname = $("<select/>").attr("title", "选择字体");
                                $(options.fontName).each(function(index, ele) { var opt = $("<option/>").val(ele).text(ele); fontname.append(opt); });
                                fontname.appendTo(toolbar);
                                $(fontname).change(function() { darrenEidtor.fontAction($(this).val(), "fontname"); });
                                break;
                            }
                        case "size":
                            {
                                var fontsize = $("<select/>").attr("title", "选择字体大小");
                                $(options.fontSize).each(function(index, ele) { var opt = $("<option/>").val(ele.t).text(ele.n); fontsize.append(opt); });
                                fontsize.appendTo(toolbar);
                                $(fontsize).change(function() { darrenEidtor.fontAction($(this).val(), "fontsize"); });
                                break;
                            }
                        case "color":
                            {
                                var fontcolor = $("<select/>").attr("title", "选择字体颜色");
                                $(options.fontColor).each(function(index, ele) { var opt = $("<option/>").val(ele.t).text(ele.n); fontcolor.append(opt); });
                                fontcolor.appendTo(toolbar);
                                $(fontcolor).change(function() { darrenEidtor.fontAction($(this).val(), "foreColor"); });
                                break;
                            }
                        default:
                            {

                                var x = c[ele], func = x[2], ex, pos = x[0] * offset;
                                var div = $("<div/>").addClass(options.btncss).css("backgroundPosition", pos + 'px' + ' 0px').attr({ "title": x[1], "flag": false }).appendTo(toolbar);
                                $(div).hover(function() { $(this).css({ "backgroundPosition": pos + 'px' + ' 20px' }) }, function() {
                                    $(this).css({ "backgroundPosition": pos + 'px' + ' 0px' })
                                    if (!$(this).attr("flag")) {
                                        $(this).css({ "backgroundPosition": pos + 'px' + ' 20px' })
                                    }
                                });
                                $(div).click(function() {
                                    $(this).attr("flag") ? $(this).attr("flag", false) : $(this).attr("flag", true);
                                    darrenEidtor.executeCmd(x[3], x[4]);
                                });
                                if ($.browser.msie) { $(div).attr("unselectable", "on") }
                                break;
                            }
                    }
                });
                return toolContainer;
            },
            fontAction: function(value, cmd) {

                this.executeCmd(cmd, value)
            },
            executeCmd: function(cmd, param) {

                var f = window.frames[frameID];
                f.focus();
                if (!param)
                    if ($.browser.msie)
                    f.document.execCommand(cmd)
                else
                    f.document.execCommand(cmd, false, false)
                else
                    f.document.execCommand(cmd, false, param)
                f.focus();
            },
            IkeFocus: function() {

                iframe.focus();
            }

        }
        $(elem).each(function() {
            var me = $(this);
            var wrapper = $(me).wrap("<div/>").hide().parent();
            wrapper.append(iframe);
            var editorContainer = darrenEidtor.getHeader().css({ width: options.width }).appendTo(wrapper.parent());
            editorContainer.append(wrapper);

            $(window).unload(function() {
                var obj = document.getElementById(frameID);
                obj.src = "javascript:false";
                obj.removeNode(true);
                obj = null;
                CollectGarbage();
            });
            return iframe;

        });
        this.setReadonly = function(isReadonly) {
            var timer = setInterval(checkloaded, 100)
            function checkloaded() {
                if (iframe.readyState != "complete") {
                    clearInterval(timer);
                    if ($.browser.msie) {
                        frDocument.body.contentEditable = isReadonly ? 'false' : 'true';
                    }
                    else { iframe.contentWindow.document.designMode = isReadonly ? 'off' : 'on'; }
                }
            }
        },
        this.value = function(str) {
            if (typeof str != "undefined") {
                window.frames[frameID].document.body.innerHTML = str;
            }
            else {
                return window.frames[frameID].document.body.innerHTML;

            }

        },
        $.fn.setReadonly = function(isReadonly) {
            var frameStanceID = "IkeHtmlEditor_" + $(this).attr("id");
            var timer = setInterval(checkloaded, 100);
            function checkloaded() {
                var currentfr = window.frames[frameStanceID];
                if (currentfr.readyState != "complete") {
                    clearInterval(timer);
                    if ($.browser.msie) {
                        currentfr.document.body.contentEditable = isReadonly ? 'false' : 'true';
                    }
                    else { currentfr.contentWindow.document.designMode = isReadonly ? 'off' : 'on'; }
                }
            }

        },
        $.fn.value = function(str) {

            var frameStanceID = "IkeHtmlEditor_" + $(this).attr("id");
            if (typeof window.frames[frameStanceID] == "undefined") {
                alert("不存在此编辑器");
                return false;
            }

            if (typeof str != "undefined") {

                window.frames[frameStanceID].document.body.innerHTML = str;
            }
            else {
                // alert(window.frames[frameStanceID].document.body)
                return window.frames[frameStanceID].document.body.innerHTML;

            }
            var frameStanceID = "IkeHtmlEditor_" + $(this).attr("id");
            var timer = setInterval(checkloaded, 100);
            function checkloaded() {
                var currentfr = window.frames[frameStanceID];
                if (currentfr.readyState != "complete") {
                    clearInterval(timer);
                    if (typeof str != "undefined") {

                        window.frames[frameStanceID].document.body.innerHTML = str;
                    }
                    else {
                        // alert(window.frames[frameStanceID].document.body)
                        return window.frames[frameStanceID].document.body.innerHTML;

                    }
                }
            }


        },
        $.fn.ikeFocus = function() {
            var frameStanceID = "IkeHtmlEditor_" + $(this).attr("id");
            if (typeof window.frames[frameStanceID] == "undefined") {
                alert("不存在此编辑器");
                return false;
            }
            darrenEidtor.IkeFocus();
        }

    }
})(jQuery);