﻿/*
* jHtmlArea 0.6.0 - WYSIWYG Html Editor jQuery Plugin
* Copyright (c) 2009 Chris Pietschmann
* http://jhtmlarea.codeplex.com
* Licensed under the Microsoft Reciprocal License (Ms-RL)
* http://jhtmlarea.codeplex.com/license
*/
(function($) {
    $.fn.htmlarea = function(opts) {
        if (opts && typeof (opts) === "string") {
            var args = [];
            for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); }
            var htmlarea = jHtmlArea(this[0]);
            var f = htmlarea[opts];
            if (f) { return f.apply(htmlarea, args); }
        }
        return this.each(function() { jHtmlArea(this, opts); });
    };
    var jHtmlArea = window.jHtmlArea = function(elem, options) {
        if (elem.jquery) {
            return jHtmlArea(elem[0]);
        }
        if (elem.jhtmlareaObject) {
            return elem.jhtmlareaObject;
        } else {
            return new jHtmlArea.fn.init(elem, options);
        }
    };
    jHtmlArea.fn = jHtmlArea.prototype = {

        // 版本号
        jhtmlarea: "0.6.0",

        //初始化
        init: function(elem, options) {

            if (elem.nodeName.toLowerCase() === "textarea") {
                var opts = $.extend({}, jHtmlArea.defaultOptions, options);
                elem.jhtmlareaObject = this;

                var textarea = this.textarea = $(elem);
                var container = this.container = $("<div/>").addClass("jHtmlArea").width(textarea.width()).insertAfter(textarea);

                var toolbar = this.toolbar = $("<div/>").addClass("ToolBar").appendTo(container);
                priv.initToolBar.call(this, opts);

                var iframe = this.iframe = $("<iframe frameborder='0' style='border:1px solid #CCCCCC;' />").height(textarea.height());
                iframe.width(textarea.width() - ($.browser.msie ? 0 : 4));
                var htmlarea = this.htmlarea = $("<div/>").append(iframe);
              
                container.append(htmlarea).append(textarea.hide());

                priv.initEditor.call(this, opts);
                priv.attachEditorEvents.call(this);

                // Fix total height to match TextArea
                iframe.height(iframe.height() - toolbar.height());
               
                toolbar.width(textarea.width() - 2);
                
                if (opts.loaded) { opts.loaded.call(this); }
            }
        },


        dispose: function() {
            this.textarea.show().insertAfter(this.container);
            this.container.remove();
            this.textarea[0].jhtmlareaObject = null;
        },
        execCommand: function(a, b, c) {
            this.iframe[0].contentWindow.focus();
            this.editor.execCommand(a, b || false, c || null);
            this.updateTextArea();
        },
        ec: function(a, b, c) {
            this.execCommand(a, b, c);
        },
        queryCommandValue: function(a) {
            this.iframe[0].contentWindow.focus();
            return this.editor.queryCommandValue(a);
        },
        qc: function(a) {
            return this.queryCommandValue(a);
        },
        getSelectedHTML: function() {
            if ($.browser.msie) {
                return this.getRange().htmlText;
            } else {
                var elem = this.getRange().cloneContents();
                return $("<p/>").append($(elem)).html();
            }
        },
        getSelection: function() {
            if ($.browser.msie) {
                //return (this.editor.parentWindow.getSelection) ? this.editor.parentWindow.getSelection() : this.editor.selection;
                return this.editor.selection;
            } else {
                return this.iframe[0].contentDocument.defaultView.getSelection();
            }
        },
        getRange: function() {
            var s = this.getSelection();
            if (!s) { return null; }
            //return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange();
            return (s.getRangeAt) ? s.getRangeAt(0) : s.createRange();
        },
        pasteHTML: function(html) {
            alert(html);
            this.iframe[0].contentWindow.focus();
            var r = this.getRange();
            if ($.browser.msie) {
                r.pasteHTML(html);
            } else if ($.browser.mozilla) {
                r.deleteContents();
                r.insertNode($((html.indexOf("<") != 0) ? $("<span/>").append(html) : html)[0]);
            } else { // Safari
                r.deleteContents();
                r.insertNode($(this.iframe[0].contentWindow.document.createElement("span")).append($((html.indexOf("<") != 0) ? "<span>" + html + "</span>" : html))[0]);
            }
            r.collapse(false);
            r.select();
        },
        cut: function() {
            alert("");
            this.ec("cut");
        },
        copy: function() {
            this.ec("copy");
        },
        paste: function() {
            this.ec("paste");
        },
        bold: function() { this.ec("bold"); },
        italic: function() { this.ec("italic"); },
        underline: function() { this.ec("underline"); },
        strikeThrough: function() { this.ec("strikethrough"); },



        color: function() {
                        $("#panelWindow").remove(); //$(this).parent().remove();
                        var content = "<div class=\"window \" id=\"panelWindow\"><div class=\"title\"><span class=\"fttitle\">图片添加</span><span class=\"buttons\"><span class=\"close\" id=\"spanclose\" ></span></span></div>";
                        content += "<div class=\"wdxtEdit_content\">";
                        content += "<ul ><li style='font-family: 黑体;' onclick='oFamily(\"黑体\")'>黑体</li><li style='font-family: 隶书;' onclick='oFamily(\"隶书\")'>隶书</li><li></li><li></li><li></li><li></li></ul>";

                        content += "</div>";
                        $('body').append(content);
                        $("#panelWindow").jWindowOpen({
                        modal: true,
                        close: "#panelWindow .close",
                        closeHoverClass: "hover"

                    });
      
        },

      
        face: function() { 
          
                        var imgurl=url+'/JavaScript/SimpleEdit/';
                        $("#panelWindow").remove(); //$(this).parent().remove();
                        var content = "<div class=\"window \" id=\"panelWindow\"><div class=\"title\"><span class=\"fttitle\">添加表情</span><span class=\"buttons\"><span class=\"close\" id=\"spanclose\" ></span></span></div>";
                        content += "<div class=\"wdxtEdit_content\">";
                        content += "<ul ><li onclick='onEditFace(\""+imgurl+"face/2.gif\")'><img src='"+imgurl+"face/2.gif'style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/3.gif\")'><img src='"+imgurl+"face/3.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/4.gif\")'><img src='"+imgurl+"face/4.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/5.gif\")'><img src='"+imgurl+"face/5.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/6.gif\")'><img src='"+imgurl+"face/6.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/7.gif\")'><img src='"+imgurl+"face/7.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/8.gif\")'><img src='"+imgurl+"face/8.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/11.gif\")'><img src='"+imgurl+"face/11.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/13.gif\")'><img src='"+imgurl+"face/13.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/14.gif\")'><img src='"+imgurl+"face/14.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/17.gif\")'><img src='"+imgurl+"face/17.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/18.gif\")'><img src='"+imgurl+"face/18.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/19.gif\")'><img src='"+imgurl+"face/19.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/23.gif\")'><img src='"+imgurl+"face/23.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/24.gif\")'><img src='"+imgurl+"face/24.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/25.gif\")'><img src='"+imgurl+"face/25.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/26.gif\")'><img src='"+imgurl+"face/26.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/28.gif\")'><img src='"+imgurl+"face/28.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/29.gif\")'><img src='"+imgurl+"face/29.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/30.gif\")'><img src='"+imgurl+"face/30.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/15.gif\")'><img src='"+imgurl+"face/15.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/27.gif\")'><img src='"+imgurl+"face/27.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/22.gif\")'><img src='"+imgurl+"face/22.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/16.gif\")'><img src='"+imgurl+"face/16.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/12.gif\")'><img src='"+imgurl+"face/12.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/10.gif\")'><img src='"+imgurl+"face/10.gif'style=\"cursor:pointer\" /></li><li onclick='onEditFace(\""+imgurl+"face/9.gif\")'><img src='"+imgurl+"face/9.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/20.gif\")'><img src='"+imgurl+"face/20.gif' style=\"cursor:pointer\"/></li><li onclick='onEditFace(\""+imgurl+"face/21.gif\")'><img src='"+imgurl+"face/21.gif'style=\"cursor:pointer\" /></li></ul>";

                        content += "</div>";
                        $('body').append(content);
                        $("#panelWindow").jWindowOpen({
                        modal: true,
                        center: true,
                        close: "#panelWindow .close",
                        closeHoverClass: "hover"

                    });
        
        
        },
        background: function() { },
        image: function(url) {
            $("#panelWindow").remove();
            var content = "<div class=\"window \" id=\"panelWindow\"><div class=\"title\"><span class=\"fttitle\">图片添加</span><span class=\"buttons\"><span class=\"close\" id=\"spanclose\" ></span></span></div>";
            content += "<div class=\"wdxtEdit_content\"><div style=\"width:300px;\">从网上地址添加：<font color=#B4B4B4>(请直接把图片地址复制到输入框中)</font></div><div style=\"width:380px;\"><input id=\"txtadress\" type=\"text\"  size=\"28\" class=\"inputs\"/><input id=\"btnadress\" type=\"button\" value=\"确 定\" class=\"buttons\" onclick=\"onupload()\"  /></div>";
            content += "<div style=\"width:300px;float:left\">通过本地上传：<font color=#B4B4B4>(请在你电脑中选择图片)</font></div><div id=\"uploadbox\" class=\"box\"></div><div class=\"status\"><span class=\"resize\"></span></div></div></div>";

            $('body').append(content);
            $("#panelWindow").jWindowOpen({
                modal: true,
                center: true,
                close: "#panelWindow .close",
                closeHoverClass: "hover"

            });
            uploadcreate($("#uploadbox"), 0);
        },
        insertImage: function(i) {

            this.ec("insertImage", false, i);
        },
        removeFormat: function() {
            this.ec("removeFormat", false, []);
            this.unlink();
        },
        link: function() {
            if ($.browser.msie) {
                this.ec("createLink", true);
            } else {
                this.ec("createLink", false, prompt("请输入超级链接地址：", "http://"));
            }
        },
        unlink: function() { this.ec("unlink", false, []); },
        orderedList: function() { this.ec("insertorderedlist"); },
        unorderedList: function() { this.ec("insertunorderedlist"); },
        superscript: function() { this.ec("superscript"); },
        subscript: function() { this.ec("subscript"); },

        h1: function() {
            this.heading(1);
        },
        h2: function() {
            this.heading(2);
        },
        h3: function() {
            this.heading(3);
        },
        h4: function() {
            this.heading(4);
        },
        h5: function() {
            this.heading(5);
        },
        h6: function() {
            this.heading(6);
        },
        heading: function(h) {
            this.formatBlock($.browser.msie ? "Heading " + h : "h" + h);
        },

        indent: function() {
            this.ec("indent");
        },
        outdent: function() {
            this.ec("outdent");
        },

        insertHorizontalRule: function() {
            this.ec("insertHorizontalRule", false, "ht");
        },

        justifyLeft: function() {
            this.ec("justifyLeft");
        },
        justifyCenter: function() {
            this.ec("justifyCenter");
        },
        justifyRight: function() {
            this.ec("justifyRight");
        },

        increaseFontSize: function() {
            if ($.browser.msie) {
                this.ec("fontSize", false, this.qc("fontSize") + 1);
            } else if ($.browser.safari) {
                this.getRange().surroundContents($(this.iframe[0].contentWindow.document.createElement("span")).css("font-size", "larger")[0]);
            } else {
                this.ec("increaseFontSize", false, "big");
            }
        },
        decreaseFontSize: function() {
            if ($.browser.msie) {
                this.ec("fontSize", false, this.qc("fontSize") - 1);
            } else if ($.browser.safari) {
                this.getRange().surroundContents($(this.iframe[0].contentWindow.document.createElement("span")).css("font-size", "smaller")[0]);
            } else {
                this.ec("decreaseFontSize", false, "small");
            }
        },

        forecolor: function(c) {

            this.ec("foreColor", false, c || prompt("Enter HTML Color:", "#"));
        },


        formatBlock: function(v) {
            this.ec("formatblock", false, v || null);
        },

        showHTMLView: function() {
            this.updateTextArea();
            this.textarea.show();
            this.htmlarea.hide();
            $("ul li:not(li:has(a.html))", this.toolbar).hide();
            $("ul:not(:has(:visible))", this.toolbar).hide();
            $("ul li a.html", this.toolbar).addClass("highlighted");
        },
        hideHTMLView: function() {
            this.updateHtmlArea();
            this.textarea.hide();
            this.htmlarea.show();
            $("ul", this.toolbar).show();
            $("ul li", this.toolbar).show().find("a.html").removeClass("highlighted");
        },
        toggleHTMLView: function() {
            (this.textarea.is(":hidden")) ? this.showHTMLView() : this.hideHTMLView();
        },

        toHtmlString: function() {  return this.editor.body.innerHTML; },
         DownFontsize: function(){ this.editor.body.style.fontSize="12px";this.editor.body.style.color="#5a5a5a"},  
        
        toString: function() { return this.editor.body.innerText; },

        updateTextArea: function() { this.textarea.val(this.toHtmlString()); },
        updateHtmlAreaValue: function(g) { this.editor.body.innerHTML = g; },
        updateHtmlArea: function() { this.editor.body.innerHTML = this.textarea.val(); }
    };
    jHtmlArea.fn.init.prototype = jHtmlArea.fn;

    jHtmlArea.defaultOptions = {
        toolbar: [
        //  ["bold", "italic", "underline", "strikethrough", "|", "subscript", "superscript"],
       // ["increasefontsize", "decreasefontsize"],
       // ["orderedlist", "unorderedlist"],
       // ["indent", "outdent"],
       // ["justifyleft", "justifycenter", "justifyright", "|"],
      //  ["link", "image", "horizontalrule", "|"],
        // ["h1","h2","h3","h4","h5","h6"],
        [ 'face']
        //["cut", "copy", "paste"]
    ], //["html"],"unlink",'family', 'color', 'background',
        css: null,
        toolbarText: {
            bold: "加粗", italic: "倾斜", underline: "下划线", strikethrough: "去除线",
            cut: "剪切", copy: "拷贝", paste: "复制",
            h1: "H 1", h2: "H 2", h3: "H 3", h4: "H 4", h5: "H 5", h6: "H 6",
            indent: "增加缩进量", outdent: "减少缩进量", horizontalrule: "水平线",
            justifyleft: "左对齐", justifycenter: "两端对齐", justifyright: "右对齐",
            increasefontsize: "字体加大", decreasefontsize: "字体减小", forecolor: "字体颜色",
            link: "超级链接", unlink: "移除链接", image: "添加图片",
            orderedlist: "编号", unorderedlist: "项目符号",
            subscript: "Subscript", superscript: "Superscript", family: "字体", color: '字体颜色', background: '字体背景颜色', face: '表情',
            html: "Show/Hide HTML Source View"
        }
    };
    var priv = {
        toolbarButtons: {
            strikethrough: "strikeThrough", orderedlist: "orderedList", unorderedlist: "unorderedList",
            horizontalrule: "insertHorizontalRule",
            justifyleft: "justifyLeft", justifycenter: "justifyCenter", justifyright: "justifyRight",
            increasefontsize: "increaseFontSize", decreasefontsize: "decreaseFontSize",
            html: function(btn) {
                this.toggleHTMLView();
            }
        },
        initEditor: function(options) {
            var edit = this.editor = this.iframe[0].contentWindow.document;
            edit.designMode = 'on';
            edit.open();
            edit.write(this.textarea.val());
            edit.close();
            if (options.css) {
                var e = edit.createElement('link'); e.rel = 'stylesheet'; e.type = 'text/css'; e.href = options.css; edit.getElementsByTagName('head')[0].appendChild(e);
                
            }
        },
        initToolBar: function(options) {
            var that = this;

            var menuItem = function(className, altText, action) {
                return $("<li/>").append($("<a href='javascript:void(0);'/>").addClass(className).attr("title", altText).click(function() { action.call(that, $(this)); }));
            };

            function addButtons(arr) {
                var ul = $("<ul/>").appendTo(that.toolbar);
                for (var i = 0; i < arr.length; i++) {
                    var e = arr[i];
                    if ((typeof (e)).toLowerCase() === "string") {
                        if (e === "|") {
                            ul.append($('<li class="separator"/>'));
                        } else {
                            var f = (function(e) {
                                // If button name exists in priv.toolbarButtons then call the "method" defined there, otherwise call the method with the same name
                                var m = priv.toolbarButtons[e] || e;
                                if ((typeof (m)).toLowerCase() === "function") {
                                    return function(btn) { m.call(this, btn); };
                                } else {
                                    return function() { this[m](); this.editor.body.focus(); };
                                }
                            })(e.toLowerCase());
                            var t = options.toolbarText[e.toLowerCase()];
                            ul.append(menuItem(e.toLowerCase(), t || e, f));
                        }
                    } else {
                        ul.append(menuItem(e.css, e.text, e.action));
                    }
                }
            };
            if (options.toolbar.length !== 0 && priv.isArray(options.toolbar[0])) {
                for (var i = 0; i < options.toolbar.length; i++) {
                    addButtons(options.toolbar[i]);
                }
            } else {
                addButtons(options.toolbar);
            }
        },
        attachEditorEvents: function() {
            var t = this;
            $(this.editor.body).click(function() { t.updateTextArea(); }).keyup(function() { t.updateTextArea(); });
            this.textarea.change(function() { t.updateHtmlArea(); });
        },
        isArray: function(v) {
            return v && typeof v === 'object' && typeof v.length === 'number' && typeof v.splice === 'function' && !(v.propertyIsEnumerable('length'));
        }
    };
})(jQuery);
