var WYSIWYG = {
    Settings: function() {
        this.ImagesDir = "/Images/OpenWysiwyg/";
        this.PopupsDir = "/Content/Common/OpenWysiwyg/";
        this.openwysiwyg_path = "";
        this.CSSFile = "/Content/Common/openwysiwyg.css";
        this.Width = "500px";
        this.Height = "400px";
        this.DefaultStyle = "font-family:Arial;font-size:12px;background-color:#FFFFFF";
        this.DisabledStyle = "font-family:Arial;font-size:12px;background-color:#EEEEEE";
        this.PreviewWidth = 500;
        this.PreviewHeight = 400;
        this.CutCopyFirefoxMsg = "Copy/Cut/Paste is not available in Mozilla and Firefox\nMore info?";
        this.RemoveFormatConfMessage = "Clean HTML inserted by MS Word ?";
        this.NoValidBrowserMessage = "openWYSIWYG does not support your browser.";
        this.AnchorPathToStrip = "auto";
        this.ImagePathToStrip = "auto";
        this.ContextMenu = true;
        this.StatusBarEnabled = true;
        this.InvertIELineBreaks = false;
        this.ReplaceLineBreaks = false;
        this.Opener = "admin.asp";
        this.ImagePopupFileUrl = "insert_image.html";
        this.HyperlinkPopupFileUrl = "insert_hyperlink.html";
        this.AboutPopupFileUrl = "about.html";
        this.TablePopupFileUrl = "create_table.html";
        this.PreviewPopupFileUrl = "preview.html###";
        this.ColorPopupFileUrl = "select_color.html###";
        this.ImagePopupFile = "";
        this.ImagePopupWidth = 0;
        this.ImagePopupHeight = 0;
        this.RightClickPanelLabels = new Array(
            'Copy',
            'Cut',
            'Paste',
            'Modify Image Properties...',
            'Create or Modify Link...',
            'Remove'
            );
        this.Toolbar = new Array();
        this.Toolbar[0] = new Array(
            "fonts",
            "fontsizes",
            "headings",
            "bold",
            "italic",
            "underline",
            "strikethrough",
            "seperator",
//            "subscript",
//            "superscript",
//            "seperator",
            "justifyfull",
            "justifyleft",
            "justifycenter",
            "justifyright",
            "seperator",
            "indent",
            "outdent",
            "unorderedlist",
            "orderedlist"
            );
        this.Toolbar[1] = new Array(
            "cut",
            "copy",
            "paste",
            "removeformat",
            "seperator",
            "undo",
            "redo",
            "seperator",
            "forecolor",
            "backcolor",
            "seperator",
            "inserttable",
            "insertimage",
            "createlink",
            "seperator",
            "preview",
            "print",
            "seperator",
            "viewsource",
            "maximize",
            "seperator",
            "help"
            );
        this.DropDowns = new Array();
        this.DropDowns['fonts'] = {
            id: "fonts",
            command: "FontName",
            label: "<font style=\"font-family:{value};font-size:12px;\">{value}</font>",
            width: "50px",
            elements: new Array(
                                "Arial",
                                "Sans Serif",
                                "Tahoma",
                                "Verdana",
                                "Courier New",
                                "Georgia",
                                "Times New Roman",
                                "Impact",
                                "Comic Sans MS"
                                )
        };
        this.DropDowns['fontsizes'] = {
            id: "fontsizes",
            command: "FontSize",
            label: "<font size=\"{value}\">Size{value}</font>",
            width: "50px",
            elements: new Array(
                                "1",
                                "2",
                                "3",
                                "4",
                                "5",
                                "6",
                                "7"
                                )
        };
        this.DropDowns['headings'] = {
            id: "headings",
            command: "FormatBlock",
            label: "<{value} style=\"margin:0px;text-decoration:none;font-family:Arial\">{value}</{value}>",
            width: "50px",
            elements: new Array(
                                "H1",
                                "H2",
                                "H3",
                                "H4",
                                "H5",
                                "H6"
                                )
        };
        this.ToolbarList = {
            "bold": ['Bold', 'Bold', 'bold.gif', 'bold.gif'],
            "italic": ['Italic', 'Italic', 'italic.gif', 'italic.gif'],
            "underline": ['Underline', 'Underline', 'underline.gif', 'underline.gif'],
            "strikethrough": ['Strikethrough', 'Strikethrough', 'strikethrough.gif', 'strikethrough.gif'],
            "seperator": ['', '', 'seperator.gif', 'seperator.gif'],
            "subscript": ['Subscript', 'Subscript', 'subscript.gif', 'subscript.gif'],
            "superscript": ['Superscript', 'Superscript', 'superscript.gif', 'superscript.gif'],
            "justifyleft": ['Justifyleft', 'Justifyleft', 'justifyleft.gif', 'justifyleft.gif'],
            "justifycenter": ['Justifycenter', 'Justifycenter', 'justifycenter.gif', 'justifycenter.gif'],
            "justifyright": ['Justifyright', 'Justifyright', 'justifyright.gif', 'justifyright.gif'],
            "justifyfull": ['Justifyfull', 'Justifyfull', 'justifyfull.gif', 'justifyfull.gif'],
            "unorderedlist": ['InsertUnorderedList', 'Insert Unordered List', 'unorderedlist.gif', 'unorderedlist.gif'],
            "orderedlist": ['InsertOrderedList', 'Insert Ordered List', 'orderedlist.gif', 'orderedlist.gif'],
            "outdent": ['Outdent', 'Outdent', 'outdent.gif', 'outdent.gif'],
            "indent": ['Indent', 'Indent', 'indent.gif', 'indent.gif'],
            "cut": ['Cut', 'Cut', 'cut.gif', 'cut.gif'],
            "copy": ['Copy', 'Copy', 'copy.gif', 'copy.gif'],
            "paste": ['Paste', 'Paste', 'paste.gif', 'paste.gif'],
            "forecolor": ['ForeColor', 'Fore Color', 'forecolor.gif', 'forecolor.gif'],
            "backcolor": ['BackColor', 'Back Color', 'backcolor.gif', 'backcolor.gif'],
            "undo": ['Undo', 'Undo', 'undo.gif', 'undo.gif'],
            "redo": ['Redo', 'Redo', 'redo.gif', 'redo.gif'],
            "inserttable": ['InsertTable', 'Insert Table', 'inserttable.gif', 'inserttable.gif'],
            "insertimage": ['InsertImage', 'Insert Image', 'insertimage.gif', 'insertimage.gif'],
            "createlink": ['CreateLink', 'Create Link', 'createlink.gif', 'createlink.gif'],
            "viewsource": ['ViewSource', 'View Source', 'viewsource.gif', 'viewsource.gif'],
            "viewText": ['ViewText', 'View Text', 'viewtext.gif', 'viewtext.gif'],
            "help": ['Help', 'Help', 'help.gif', 'help.gif'],
            "fonts": ['Fonts', 'Select Font', 'fonts.gif', 'fonts_on.gif'],
            "fontsizes": ['Fontsizes', 'Select Size', 'fontsizes.gif', 'fontsizes_on.gif'],
            "headings": ['Headings', 'Select Size', 'headings.gif', 'headings_on.gif'],
            "preview": ['Preview', 'Preview', 'preview.gif', 'preview.gif'],
            "print": ['Print', 'Print', 'print.gif', 'print.gif'],
            "removeformat": ['RemoveFormat', 'Strip Word HTML', 'removeformat.gif', 'removeformat.gif'],
            "delete": ['Delete', 'Delete', 'delete.gif', 'delete.gif'],
            "save": ['Save', 'Save document', 'save.gif', 'save.gif'],
            "return": ['Return', 'Return without saving', 'return.gif', 'return.gif'],
            "maximize": ['Maximize', 'Maximize the editor', 'maximize.gif', 'maximize.gif']
        };
        this.addToolbarElement = function(element, toolbar, position) {
            if (element != "seperator") {
                this.removeToolbarElement(element);
            }
            if (this.Toolbar[toolbar - 1] == null) {
                this.Toolbar[toolbar - 1] = new Array();
            }
            this.Toolbar[toolbar - 1].splice(position + 1, 1, element);
        };
        this.removeToolbarElement = function(element) {
            if (element == "seperator") {
                return;
            }
            for (var i = 0; i < this.Toolbar.length; i++) {
                if (this.Toolbar[i]) {
                    var toolbar = this.Toolbar[i];
                    for (var j = 0; j < toolbar.length; j++) {
                        if (toolbar[j] != null && toolbar[j] == element) {
                            this.Toolbar[i].splice(j, 1);
                        }
                    }
                }
            }
        };
        this.clearToolbar = function(toolbar) {
            if (typeof toolbar == "undefined") {
                this.Toolbar = new Array();
            }
            else {
                this.Toolbar[toolbar + 1] = new Array();
            }
        };
    },
    config: new Array(),
    viewTextMode: new Array(),
    maximized: new Array(),
    getRange: function(sel) {
        return sel.createRange ? sel.createRange() : sel.getRangeAt(0);
    },
    getEditorDiv: function(n) {
        return $_ow("wysiwyg_div_" + n);
    },
    getEditorTable: function(n) {
        return $_ow("wysiwyg_table_" + n);
    },
    getEditor: function(n) {
        return $_ow("wysiwyg" + n);
    },
    getEditorWindow: function(n) {
        return this.getEditor(n).contentWindow;
    },
    attach: function(id, settings) {
        if (id != "all") {
            this.setSettings(id, settings);
            WYSIWYG_Core.includeCSS(this.config[id].CSSFile);
            //WYSIWYG_Core.addEvent(window, "load", function generateEditor() { WYSIWYG._generate(id, settings); });
            WYSIWYG._generate(id, settings);
        }
        else {
            WYSIWYG_Core.addEvent(window, "load", function generateEditor() { WYSIWYG.attachAll(settings); });
        }
    },
    attachAll: function(settings) {
        var areas = document.getElementsByTagName("textarea");
        for (var i = 0; i < areas.length; i++) {
            var id = areas[i].getAttribute("id");
            if (id == null || id == "") continue;
            this.setSettings(id, settings);
            WYSIWYG_Core.includeCSS(this.config[id].CSSFile);
            WYSIWYG._generate(id, settings);
        }
    },
    display: function(id, settings) {
        if (id != "all") {
            this.setSettings(id, settings);
            WYSIWYG_Core.includeCSS(this.config[id].CSSFile);
            WYSIWYG_Core.addEvent(window, "load", function displayIframe() { WYSIWYG._display(id, settings); });
        }
        else {
            WYSIWYG_Core.addEvent(window, "load", function displayIframe() { WYSIWYG.displayAll(settings); });
        }
    },
    displayAll: function(settings) {
        var areas = document.getElementsByTagName("textarea");
        for (var i = 0; i < areas.length; i++) {
            var id = areas[i].getAttribute("id");
            if (id == null || id == "") continue;
            this.setSettings(id, settings);
            WYSIWYG_Core.includeCSS(this.config[id].CSSFile);
            WYSIWYG._display(id, settings);
        }
    },
    setSettings: function(n, settings) {
        if (typeof (settings) != "object") {
            this.config[n] = new this.Settings();
        }
        else {
            this.config[n] = settings;
        }
    },
    insertImage: function(src, width, height, align, border, alt, hspace, vspace, n) {
        var doc = this.getEditorWindow(n).document;
        var sel = this.getSelection(n);
        var range = this.getRange(sel);
        var img = this.findParent("img", range);
        var update = (img == null) ? false : true;
        if (!update) {
            img = doc.createElement("img");
        }
        WYSIWYG_Core.setAttribute(img, "src", src);
        WYSIWYG_Core.setAttribute(img, "width", width);
        WYSIWYG_Core.setAttribute(img, "height", height);
        if (align != "") {
            WYSIWYG_Core.setAttribute(img, "align", align);
        }
        else {
            img.removeAttribute("align");
        }
        WYSIWYG_Core.setAttribute(img, "border", border);
        WYSIWYG_Core.setAttribute(img, "alt", alt);
        WYSIWYG_Core.setAttribute(img, "hspace", hspace);
        WYSIWYG_Core.setAttribute(img, "vspace", vspace);
        img.removeAttribute("style");
        if (update) {
            return;
        }
        if (WYSIWYG_Core.isMSIE) {
            range.pasteHTML(img.outerHTML);
        }
        else {
            this.insertNodeAtSelection(img, n);
        }
    },
    insertLink: function(href, target, style, styleClass, name, n) {
        var doc = this.getEditorWindow(n).document;
        var sel = this.getSelection(n);
        var range = this.getRange(sel);
        var lin = null;
        if (WYSIWYG_Core.isMSIE) {
            if (sel.type == "Control" && range.length == 1) {
                range = this.getTextRange(range(0));
                range.select();
            }
        }
        lin = this.findParent("a", range);
        var update = (lin == null) ? false : true;
        if (!update) {
            lin = doc.createElement("a");
        }
        WYSIWYG_Core.setAttribute(lin, "href", href);
        WYSIWYG_Core.setAttribute(lin, "class", styleClass);
        WYSIWYG_Core.setAttribute(lin, "className", styleClass);
        WYSIWYG_Core.setAttribute(lin, "target", target);
        WYSIWYG_Core.setAttribute(lin, "name", name);
        WYSIWYG_Core.setAttribute(lin, "style", style);
        if (update) {
            return;
        }
        if (WYSIWYG_Core.isMSIE) {
            range.select();
            lin.innerHTML = range.htmlText;
            range.pasteHTML(lin.outerHTML);
        }
        else {
            var node = range.startContainer;
            var pos = range.startOffset;
            if (node.nodeType != 3) {
                node = node.childNodes[pos];
            }
            if (node.tagName) {
                lin.appendChild(node);
            }
            else {
                lin.innerHTML = sel;
            }
            this.insertNodeAtSelection(lin, n);
        }
    },
    removeFormat: function(n) {
        if (!confirm(this.config[n].RemoveFormatConfMessage)) {
            return;
        }
        var doc = this.getEditorWindow(n).document;
        var str = doc.body.innerHTML;
        str = str.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi, '');
        str = str.replace(/<span[^>]*>/gi, '');
        str = str.replace(/<\/span[^>]*>/gi, '');
        str = str.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi, '');
        str = str.replace(/<p[^>]*>/gi, '');
        str = str.replace(/<\/p[^>]*>/gi, '');
        str = str.replace(/<h([^>])[0-9]>(&nbsp;)*\s*<\/h>/gi, '');
        str = str.replace(/<h[^>][0-9]>/gi, '');
        str = str.replace(/<\/h[^>][0-9]>/gi, '');
        str = str.replace(/<B [^>]*>/ig, '<b>');
        str = str.replace(/<DIV[^>]*>/ig, '');
        str = str.replace(/<\/DIV>/gi, '');
        str = str.replace(/<[\/\w?]+:[^>]*>/ig, '');
        str = str.replace(/(&nbsp;){2,}/ig, '&nbsp;');
        str = str.replace(/<STRONG>/ig, '');
        str = str.replace(/<\/STRONG>/ig, '');
        str = str.replace(/<TT>/ig, '');
        str = str.replace(/<\/TT>/ig, '');
        str = str.replace(/<FONT [^>]*>/ig, '');
        str = str.replace(/<\/FONT>/ig, '');
        str = str.replace(/STYLE=\"[^\"]*\"/ig, '');
        str = str.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, '<$1$3');
        str = str.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, '<$1$3');
        str = str.replace(/width=([^ |>]*)([^>]*)/gi, '');
        str = str.replace(/classname=([^ |>]*)([^>]*)/gi, '');
        str = str.replace(/align=([^ |>]*)([^>]*)/gi, '');
        str = str.replace(/valign=([^ |>]*)([^>]*)/gi, '');
        str = str.replace(/<\\?\??xml[^>]>/gi, '');
        str = str.replace(/<\/?\w+:[^>]*>/gi, '');
        str = str.replace(/<st1:.*?>/gi, '');
        str = str.replace(/o:/gi, '');
        str = str.replace(/<!--([^>])*>(&nbsp;)*\s*<\/-->/gi, '');
        str = str.replace(/<!--[^>]*>/gi, '');
        str = str.replace(/<\/--[^>]*>/gi, '');
        doc.body.innerHTML = str;
    },
    _display: function(n, settings) {
        var textarea = $_ow(n);
        if (textarea == null) {
            alert("No textarea found with the given identifier (ID:" + n + ").");
            return;
        }
        if (!WYSIWYG_Core.isBrowserCompatible()) {
            if (this.config[n].NoValidBrowserMessage != "") {
                alert(this.config[n].NoValidBrowserMessage);
            }
            return;
        }
        if (typeof (settings) != "object") {
            this.config[n] = new this.Settings();
        }
        else {
            this.config[n] = settings;
        }
        textarea.style.display = "none";
        if (textarea.style.width) {
            this.config[n].Width = textarea.style.width;
        }
        if (textarea.style.height) {
            this.config[n].Height = textarea.style.height
        }
        var currentWidth = this.config[n].Width;
        var currentHeight = this.config[n].Height;
        var ifrmWidth = "100%";
        varifrmHeight = "100%";
        if (currentWidth.search(/%/) == -1) {
            ifrmWidth = currentWidth;
            ifrmHeight = currentHeight;
        }
        var iframe = '<table cellpadding="0" cellspacing="0" border="0" style="width:' + currentWidth + ';height:' + currentHeight + ';" class="tableTextareaEditor"><tr><td valign="top">\n'
            + '<iframe frameborder="0" id="wysiwyg' + n + '" class="iframeText" style="width:' + ifrmWidth + ';height:' + ifrmHeight + ';"></iframe>\n'
            + '</td></tr></table>\n';
        //textarea.insertAdjacentHTML("afterEnd",iframe);
        if (textarea.insertAdjacentHTML) {
            textarea.insertAdjacentHTML("afterEnd", iframe);
        }
        else {
            textarea.insertAdjacentHTML2("afterEnd", iframe);
        }

        var content = textarea.value;
        var doc = this.getEditorWindow(n).document;
        if (this.config[n].ReplaceLineBreaks) {
            content = content.replace(/(\r\n)|(\n)/ig, "<br>");
        }
        doc.open();
        doc.write(content);
        doc.close();
        WYSIWYG_Core.setAttribute(doc.body, "style", this.config[n].DefaultStyle);
    },
    _generate: function(n, settings) {
        var textarea = $_ow(n);
        if (textarea == null) {
            alert("No textarea found with the given identifier (ID:" + n + ").");
            return;
        }
        if (!WYSIWYG_Core.isBrowserCompatible()) {
            if (this.config[n].NoValidBrowserMessage != "") {
                alert(this.config[n].NoValidBrowserMessage);
            }
            return;
        }
        textarea.style.display = 'none';
        if (textarea.style.width) {
            this.config[n].Width = textarea.style.width;
        }
        if (textarea.style.height) {
            this.config[n].Height = textarea.style.height
        }
        var currentWidth = this.config[n].Width;
        var currentHeight = this.config[n].Height;
        var toolbarWidth = currentWidth;
        var ifrmWidth = "100%";
        varifrmHeight = "100%";
        if (currentWidth.search(/%/) == -1) {
            toolbarWidth = currentWidth.replace(/px/gi, "");
            toolbarWidth = (parseFloat(toolbarWidth) + 2) + "px";
            ifrmWidth = currentWidth;
            ifrmHeight = currentHeight;
        }
        var editor = "";
        editor += '<div id="wysiwyg_div_' + n + '" style="width:' + currentWidth + ';">';
        editor += '<table border="0" cellpadding="0" cellspacing="0" class="tableTextareaEditor" id="wysiwyg_table_' + n + '" style="width:' + currentWidth + ';height:' + currentHeight + ';">';
        editor += '<tr><td style="height:22px;vertical-align:top;">';
        for (var j = 0; j < this.config[n].Toolbar.length; j++) {
            if (this.config[n].Toolbar[j] && this.config[n].Toolbar[j].length > 0) {
                var toolbar = this.config[n].Toolbar[j];
                editor += '<table border="0" cellpadding="0" cellspacing="0" class="toolbar1" style="width:100%;" id="toolbar' + j + '_' + n + '">';
                editor += '<tr><td style="width:6px;"><img src="' + this.config[n].ImagesDir + 'seperator2.gif" alt="" hspace="3"></td>';
                for (var i = 0; i < toolbar.length; i++) {
                    var id = toolbar[i];
                    if (toolbar[i]) {
                        if (typeof (this.config[n].DropDowns[id]) != "undefined") {
                            var dropdown = this.config[n].DropDowns[id];
                            editor += '<td style="width:' + dropdown.width + ';">';
                            editor += this.writeDropDown(n, id);
                            editor += '</td>';
                        }
                        else {
                            var buttonObj = this.config[n].ToolbarList[toolbar[i]];
                            if (buttonObj) {
                                var buttonID = buttonObj[0];
                                var buttonTitle = buttonObj[1];
                                var buttonImage = this.config[n].ImagesDir + buttonObj[2];
                                var buttonImageRollover = this.config[n].ImagesDir + buttonObj[3];
                                if (toolbar[i] == "seperator") {
                                    editor += '<td style="width:12px;" align="center">';
                                    editor += '<img src="' + buttonImage + '" border=0 unselectable="on" width="2" height="18" hspace="2" unselectable="on">';
                                    editor += '</td>';
                                }
                                else if (toolbar[i] == "viewsource") {
                                    editor += '<td style="width:22px;">';
                                    editor += '<span id="HTMLMode' + n + '"><img src="' + buttonImage + '" border="0" unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class="buttonEditor" onmouseover="this.className=\'buttonEditorOver\';this.src=\'' + buttonImageRollover + '\';" onmouseout="this.className=\'buttonEditor\';this.src=\'' + buttonImage + '\';" onclick="WYSIWYG.execCommand(\'' + n + '\',\'' + buttonID + '\');" unselectable="on" width="20" height="20"></span>';
                                    editor += '<span id="textMode' + n + '"><img src="' + this.config[n].ImagesDir + this.config[n].ToolbarList["viewText"][2] + '" border="0" unselectable="on" title="viewText" id="ViewText" class="buttonEditor" ' + ' onmouseover="this.className=\'buttonEditorOver\';this.src=\'' + this.config[n].ImagesDir + this.config[n].ToolbarList["viewText"][2] + '\';" onmouseout="this.className=\'buttonEditor\';this.src=\'' + this.config[n].ImagesDir + this.config[n].ToolbarList["viewText"][2] + '\';" onclick="WYSIWYG.execCommand(\'' + n + '\',\'ViewText\');" unselectable="on" ' + ' width="20" height="20"></span>';
                                    editor += '</td>';
                                }
                                else {
                                    editor += '<td style="width:22px;">';
                                    editor += '<img src="' + buttonImage + '" border=0 unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class="buttonEditor" onmouseover="this.className=\'buttonEditorOver\';this.src=\'' + buttonImageRollover + '\';" onmouseout="this.className=\'buttonEditor\';this.src=\'' + buttonImage + '\';" onclick="WYSIWYG.execCommand(\'' + n + '\',\'' + buttonID + '\');" unselectable="on" width="20" height="20">';
                                    editor += '</td>';
                                }
                            }
                        }
                    }
                }
                editor += '<td>&nbsp;</td></tr></table>';
            }
        }
        editor += '</td></tr><tr><td valign="top">\n';
        editor += '<iframe frameborder="0" id="wysiwyg' + n + '" class="iframeText" style="width:100%;height:' + currentHeight + ';"></iframe>\n'
+ '</td></tr>';
        if (this.config[n].StatusBarEnabled) {
            editor += '<tr><td class="wysiwyg-statusbar" style="height:10px;" id="wysiwyg_statusbar_' + n + '">&nbsp;</td></tr>';
        }
        editor += '</table>';
        editor += '</div>';
        //textarea.insertAdjacentHTML("afterEnd", editor);
        if (textarea.insertAdjacentHTML) {
            textarea.insertAdjacentHTML("afterEnd", editor);
        }
        else {
            textarea.insertAdjacentHTML2("afterEnd", editor);
        }

        if ($_ow("textMode" + n)) {
            $_ow("textMode" + n).style.display = 'none';
        }
        var content = textarea.value;
        var doc = this.getEditorWindow(n).document;
        if (this.config[n].ReplaceLineBreaks) {
            content = content.replace(/\n\r|\n/ig, "<br>");
        }
        doc.open();
        doc.write(content);
        doc.close();
        if (doc.body.contentEditable) {
            doc.body.contentEditable = true;
        }
        else {
            doc.designMode = "on";
        }
        WYSIWYG_Core.setAttribute(doc.body, "style", this.config[n].DefaultStyle);
        WYSIWYG_Table.refreshHighlighting(n);
        for (var idx = 0; idx < document.forms.length; idx++) {
            WYSIWYG_Core.addEvent(document.forms[idx], "submit", function xxx_aa() { WYSIWYG.updateTextArea(n); });
        }
        WYSIWYG_Core.addEvent(doc, "mouseover", function xxx_bb() { WYSIWYG.closeDropDowns(n); });
        if (this.config[n].InvertIELineBreaks) {
            WYSIWYG_Core.addEvent(doc, "keypress", function xxx_cc() { WYSIWYG.invertIELineBreakCapability(n); });
        }
        if (this.config[n].StatusBarEnabled) {
            WYSIWYG_Core.addEvent(doc, "mouseup", function xxx_dd() { WYSIWYG.updateStatusBar(n); });
        }
        if (this.config[n].ContextMenu) {
            WYSIWYG_ContextMenu.init(n);
        }
        this.viewTextMode[n] = false;
        this.styleWithCSS(n, false);
    },
    disable: function(n) {
        var editor = this.getEditorWindow(n);
        if (editor == null) {
            alert("No editor found with the given identifier (ID:" + n + ").");
            return;
        }
        if (editor) {
            if (editor.document.body.contentEditable) {
                editor.document.body.contentEditable = false;
            }
            else {
                editor.document.designMode = "Off";
            }
            WYSIWYG_Core.setAttribute(editor.document.body, "style", this.config[n].DisabledStyle);
            this.hideStatusBar(n);
            this.hideToolbars(n);
        }
    },
    enable: function(n) {
        var editor = this.getEditorWindow(n);
        if (editor == null) {
            alert("No editor found with the given identifier (ID:" + n + ").");
            return;
        }
        if (editor) {
            if (editor.document.body.contentEditable) {
                editor.document.body.contentEditable = true;
            }
            else {
                editor.document.designMode = "On";
            }
            WYSIWYG_Core.setAttribute(editor.document.body, "style", this.config[n].DefaultStyle);
            this.showStatusBar(n);
            this.showToolbars(n);
        }
    },
    getNodeTree: function(n) {
        var sel = this.getSelection(n);
        var range = this.getRange(sel);
        var tag = this.getTag(range);
        if (tag == null) {
            return;
        }
        var node = this.getParent(tag);
        var nodeTree = new Array(tag);
        var ii = 1;
        while (node != null && node.nodeName != "#document") {
            nodeTree[ii] = node;
            node = this.getParent(node);
            ii++;
        }
        return nodeTree;
    },
    removeNode: function(n) {
        var sel = this.getSelection(n);
        var range = this.getRange(sel);
        var tag = this.getTag(range);
        var parent = tag.parentNode;
        if (tag == null || parent == null) {
            return;
        }
        if (tag.nodeName == "HTML" || tag.nodeName == "BODY") {
            return;
        }
        var childNodes = new Array();
        for (var i = 0; i < tag.childNodes.length; i++)
            childNodes[i] = tag.childNodes[i];
        for (var i = 0; i < childNodes.length; i++)
            parent.insertBefore(childNodes[i], tag);
        parent.removeChild(tag);
        if (parent.nodeName == "A" && !parent.hasChildNodes()) {
            if (parent.parentNode) {
                parent.parentNode.removeChild(parent);
            }
        }
        this.updateStatusBar(n);
    },
    getSelection: function(n) {
        var ifrm = this.getEditorWindow(n);
        var doc = ifrm.document;
        var sel = null;
        if (ifrm.getSelection) {
            sel = ifrm.getSelection();
        }
        else if (doc.getSelection) {
            sel = doc.getSelection();
        }
        else if (doc.selection) {
            sel = doc.selection;
        }
        return sel;
    },
    updateStatusBar: function(n) {
        var nodeTree = this.getNodeTree(n);
        if (nodeTree == null) {
            return;
        }
        var outputTree = "";
        var max = nodeTree.length - 1;
        for (var i = max; i >= 0; i--) {
            if (nodeTree[i].nodeName != "HTML" && nodeTree[i].nodeName != "BODY") {
                outputTree += '<a class="wysiwyg-statusbar" href="javascript:WYSIWYG.selectNode(\'' + n + '\',' + i + ');">' + nodeTree[i].nodeName + '</a>';
            }
            else {
                outputTree += nodeTree[i].nodeName;
            }
            if (i > 0) {
                outputTree += " > ";
            }
        }
        var statusbar = $_ow("wysiwyg_statusbar_" + n);
        if (statusbar) {
            statusbar.innerHTML = outputTree;
        }
    },
    execCommand: function(n, cmd, value) {
        this.getEditorWindow(n).focus();
        var textModeCommands = new Array("ViewText", "Print");
        var cmdValid = false;
        for (var i = 0; i < textModeCommands.length; i++) {
            if (textModeCommands[i] == cmd) {
                cmdValid = true;
            }
        }
        if (this.viewTextMode[n] && !cmdValid) {
            alert("You are in TEXT Mode. This feature has been disabled.");
            return;
        }
        var toHexColor = WYSIWYG_Core.isMSIE ? WYSIWYG_Core._dec_to_rgb : WYSIWYG_Core.toHexColor;
        var popupPosition = { left: parseInt(window.screen.availWidth / 3), top: parseInt(window.screen.availHeight / 3) };
        var imagePopupFile = this.config[n].PopupsDir + this.config[n].ImagePopupFileUrl;
        var imagePopupWidth = 400;
        var imagePopupHeight = 220;
        if (typeof this.config[n].ImagePopupFile != "undefined" && this.config[n].ImagePopupFile != "") {
            imagePopupFile = this.config[n].ImagePopupFile;
        }
        if (typeof this.config[n].ImagePopupWidth && this.config[n].ImagePopupWidth > 0) {
            imagePopupWidth = this.config[n].ImagePopupWidth;
        }
        if (typeof this.config[n].ImagePopupHeight && this.config[n].ImagePopupHeight > 0) {
            imagePopupHeight = this.config[n].ImagePopupHeight;
        }
        switch (cmd) {
            case "Maximize":
                this.maximize(n);
                break;
            case "FormatBlock":
                WYSIWYG_Core.execCommand(n, cmd, "<" + value + ">");
                break;
            //case "bold":WYSIWYG_Core.execCommand(n,cmd,"<b>"+value+"</b>");break;                                                                       
            case "ForeColor":
                var rgb = this.getEditorWindow(n).document.queryCommandValue(cmd);
                var currentColor = rgb != '' ? toHexColor(this.getEditorWindow(n).document.queryCommandValue(cmd)) : "000000";
                window.open(this.config[n].PopupsDir + this.config[n].ColorPopupFileUrl + '?color=' + currentColor + '&command=' + cmd + '&wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,width=210,height=165,top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "BackColor":
                var currentColor = toHexColor(this.getEditorWindow(n).document.queryCommandValue(cmd));
                window.open(this.config[n].PopupsDir + this.config[n].ColorPopupFileUrl + '?color=' + currentColor + '&command=' + cmd + '&wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,width=210,height=165,top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "InsertImage":
                window.open(imagePopupFile + '?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=' + imagePopupWidth + ',height=' + imagePopupHeight + ',top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "RemoveImage":
                this.removeImage(n);
                break;
            case "RemoveLink":
                this.removeLink(n);
                break;
            case "RemoveNode":
                this.removeNode(n);
                break;
            case "CreateLink":
                window.open(this.config[n].PopupsDir + this.config[n].HyperlinkPopupFileUrl + '?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=350,height=160,top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "InsertTable":
                window.open(this.config[n].PopupsDir + this.config[n].TablePopupFileUrl + '?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=500,height=260,top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "ViewSource":
                this.viewsource(n);
                break;
            case "ViewText":
                this.viewText(n);
                break;
            case "Help":
                window.open(this.config[n].PopupsDir + this.config[n].AboutPopupFileUrl + '?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=400,height=350,top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "RemoveFormat":
                this.removeFormat(n);
                break;
            case "Preview":
                window.open(this.config[n].PopupsDir + this.config[n].PreviewPopupFileUrl + '?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=1,resizable=1,width=' + this.config[n].PreviewWidth + ',height=' + this.config[n].PreviewHeight + ',top=' + popupPosition.top + ',left=' + popupPosition.left).focus();
                break;
            case "Print":
                this.print(n);
                break;
            case "Save":
                WYSIWYG.updateTextArea(n);
                var form = WYSIWYG_Core.findParentNode("FORM", this.getEditor(n));
                if (form == null) {
                    alert("Can not submit the content,because no form element found.");
                    return;
                }
                form.submit();
                break;
            case "Return":
                location.replace(this.config[n].Opener);
                break;
            default:
                WYSIWYG_Core.execCommand(n, cmd, value);
        }
        this.closeDropDowns(n);
    },
    maximize: function(n) {
        var divElm = this.getEditorDiv(n);
        var tableElm = this.getEditorTable(n);
        var editor = this.getEditor(n);
        var setting = this.config[n];
        var size = WYSIWYG_Core.windowSize();
        size.width -= 5;
        if (this.maximized[n]) {
            WYSIWYG_Core.setAttribute(divElm, "style", "position:static;z-index:9998;top:0px;left:0px;width:" + setting.Width + ";height:100%;");
            WYSIWYG_Core.setAttribute(tableElm, "style", "width:" + setting.Width + ";height:" + setting.Height + ";");
            WYSIWYG_Core.setAttribute(editor, "style", "width:100%;height:" + setting.Height + ";");
            this.maximized[n] = false;
        }
        else {
            WYSIWYG_Core.setAttribute(divElm, "style", "position:absolute;z-index:9998;top:0px;left:0px;width:" + size.width + "px;height:" + size.height + "px;");
            WYSIWYG_Core.setAttribute(tableElm, "style", "width:100%;height:100%;");
            WYSIWYG_Core.setAttribute(editor, "style", "width:100%;height:100%;");
            this.maximized[n] = true;
        }
    },
    insertHTML: function(html, n) {
        if (WYSIWYG_Core.isMSIE) {
            this.getEditorWindow(n).document.selection.createRange().pasteHTML(html);
        }
        else {
            var span = this.getEditorWindow(n).document.createElement("span");
            span.innerHTML = html;
            this.insertNodeAtSelection(span, n);
        }
    },
    insertNodeAtSelection: function(insertNode, n) {
        var doc = this.getEditorWindow(n).document;
        var sel = this.getSelection(n);
        var range = sel.getRangeAt(0);
        sel.removeAllRanges();
        range.deleteContents();
        var container = range.startContainer;
        var pos = range.startOffset;
        range = doc.createRange();
        if (container.nodeType == 3 && insertNode.nodeType == 3) {
            container.insertData(pos, insertNode.data);
            range.setEnd(container, pos + insertNode.length);
            range.setStart(container, pos + insertNode.length);
        }
        else {
            var afterNode;
            var beforeNode;
            if (container.nodeType == 3) {
                var textNode = container;
                container = textNode.parentNode;
                var text = textNode.nodeValue;
                var textBefore = text.substr(0, pos);
                var textAfter = text.substr(pos);
                beforeNode = document.createTextNode(textBefore);
                afterNode = document.createTextNode(textAfter);
                container.insertBefore(afterNode, textNode);
                container.insertBefore(insertNode, afterNode);
                container.insertBefore(beforeNode, insertNode);
                container.removeChild(textNode);
            }
            else {
                afterNode = container.childNodes[pos];
                container.insertBefore(insertNode, afterNode);
            }
            try {
                range.setEnd(afterNode, 0);
                range.setStart(afterNode, 0);
            }
            catch (e) {
                alert(e);
            }
        }
        sel.addRange(range);
    },
    print: function(n) {
        if (document.all && navigator.appVersion.substring(22, 23) == 4) {
            var doc = this.getEditorWindow(n).document;
            doc.focus();
            var OLECMDID_PRINT = 6;
            var OLECMDEXECOPT_DONTPROMPTUSER = 2;
            var OLECMDEXECOPT_PROMPTUSER = 1;
            var WebBrowser = '<object id="WebBrowser1" width="0" height="0" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
            //doc.body.insertAdjacentHTML('beforeEnd', WebBrowser);
            if (doc.body.insertAdjacentHTML) {
                doc.body.insertAdjacentHTML('beforeEnd', WebBrowser);
            }
            else {
                doc.body.insertAdjacentHTML2('beforeEnd', WebBrowser);
            }

            WebBrowser.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER);
            WebBrowser.outerHTML = '';
        }
        else {
            this.getEditorWindow(n).print();
        }
    },
    writeDropDown: function(n, id) {
        var dropdown = this.config[n].DropDowns[id];
        var toolbarObj = this.config[n].ToolbarList[dropdown.id];
        var image = this.config[n].ImagesDir + toolbarObj[2];
        var imageOn = this.config[n].ImagesDir + toolbarObj[3];
        dropdown.elements.sort();
        var output = "";
        output += '<table border="0" cellpadding="0" cellspacing="0"><tr>';
        output += '<td onMouseOver="$_ow(\'img_' + dropdown.id + '_' + n + '\').src=\'' + imageOn + '\';" onMouseOut="$_ow(\'img_' + dropdown.id + '_' + n + '\').src=\'' + image + '\';">';
        output += '<img src="' + image + '" id="img_' + dropdown.id + '_' + n + '" height="20" onClick="WYSIWYG.openDropDown(\'' + n + '\',\'' + dropdown.id + '\');" unselectable="on" border="0"><br>';
        output += '<span id="elm_' + dropdown.id + '_' + n + '" class="dropdown" style="width:145px;display:none;">';
        for (var i = 0; i < dropdown.elements.length; i++) {
            if (dropdown.elements[i]) {
                var value = dropdown.elements[i];
                var label = dropdown.label.replace(/{value}/gi, value);
                output += '<button type="button" onClick="WYSIWYG.execCommand(\'' + n + '\',\'' + dropdown.command + '\',\'' + value + '\')\;" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width:120px;">';
                output += '<table cellpadding="0" cellspacing="0" border="0"><tr>';
                output += '<td align="left">' + label + '</td>';
                output += '</tr></table></button><br>';
            }
        }
        output += '</span></td></tr></table>';
        return output;
    },
    closeDropDowns: function(n, exid) {
        if (typeof (exid) == "undefined") exid = "";
        var dropdowns = this.config[n].DropDowns;
        for (var id in dropdowns) {
            var dropdown = dropdowns[id];
            if (dropdown.id != exid) {
                var divId = "elm_" + dropdown.id + "_" + n;
                if ($_ow(divId)) $_ow(divId).style.display = 'none';
            }
        }
    },
    openDropDown: function(n, id) {
        var divId = "elm_" + id + "_" + n;
        if ($_ow(divId).style.display == "none") {
            $_ow(divId).style.display = "block";
        }
        else {
            $_ow(divId).style.display = "none";
        }
        $_ow(divId).style.position = "absolute";
        this.closeDropDowns(n, id);
    },
    viewsource: function(n) {
        var doc = this.getEditorWindow(n).document;
        WYSIWYG_Table.disableHighlighting(n);
        if (WYSIWYG_Core.isMSIE) {
            var iHTML = doc.body.innerHTML;
            iHTML = this.stripURLPath(n, iHTML);
            iHTML = WYSIWYG_Core.replaceRGBWithHexColor(iHTML);
            doc.body.innerText = iHTML;
        }
        else {
            var html = WYSIWYG_Core.replaceRGBWithHexColor(doc.body.innerHTML);
            html = document.createTextNode(html);
            doc.body.innerHTML = "";
            doc.body.appendChild(html);
        }
        if ($_ow('HTMLMode' + n)) {
            $_ow('HTMLMode' + n).style.display = 'none';
        }
        if ($_ow('textMode' + n)) {
            $_ow('textMode' + n).style.display = 'block';
        }
        doc.body.style.fontSizes = "12px";
        doc.body.style.fontFamily = "Courier New";
        this.viewTextMode[n] = true;
    },
    viewText: function(n) {
        var doc = this.getEditorWindow(n).document;
        if (WYSIWYG_Core.isMSIE) {
            var iText = doc.body.innerText;
            iText = this.stripURLPath(n, iText);
            iText = WYSIWYG_Core.replaceRGBWithHexColor(iText);
            doc.body.innerHTML = iText;
        }
        else {
            var html = doc.body.ownerDocument.createRange();
            html.selectNodeContents(doc.body);
            html = WYSIWYG_Core.replaceRGBWithHexColor(html.toString());
            doc.body.innerHTML = html;
        }
        WYSIWYG_Table.refreshHighlighting(n);
        if ($_ow('textMode' + n)) {
            $_ow('textMode' + n).style.display = 'none';
        }
        if ($_ow('HTMLMode' + n)) {
            $_ow('HTMLMode' + n).style.display = 'block';
        }
        WYSIWYG_Core.setAttribute(doc.body, "style", this.config[n].DefaultStyle);
        this.viewTextMode[n] = false;
    },
    stripURLPath: function(n, content, exact) {
        if (typeof exact == "undefined") {
            exact = true;
        }
        var stripImgageUrl = null;
        var stripAnchorUrl = null;
        if (this.config[n].AnchorPathToStrip == "auto") {
            stripAnchorUrl = WYSIWYG_Core.getDocumentUrl(document);
        }
        else if (this.config[n].AnchorPathToStrip != "") {
            stripAnchorUrl = this.config[n].AnchorPathToStrip;
        }
        if (this.config[n].ImagePathToStrip == "auto") {
            stripImgageUrl = WYSIWYG_Core.getDocumentUrl(document);
        }
        else if (this.config[n].ImagePathToStrip != "") {
            stripImgageUrl = this.config[n].ImagePathToStrip;
        }
        var url;
        var regex;
        var result;
        if (stripImgageUrl) {
            url = WYSIWYG_Core.stringToRegex(WYSIWYG_Core.getDocumentPathOfUrl(stripImgageUrl));
            if (exact) {
                regex = eval("/(src=\")(" + url + ")([^\"]*)/gi");
                content = content.replace(regex, "$1$3");
            }
            else {
                regex = eval("/(" + url + ")(.+)/gi");
                content = content.replace(regex, "$2");
            }
            result = WYSIWYG_Core.getDocumentPathOfUrl(stripImgageUrl).match(/.+[\/]{2,3}[^\/]*/, "");
            if (result) {
                url = WYSIWYG_Core.stringToRegex(result[0]);
                if (exact) {
                    regex = eval("/(src=\")(" + url + ")([^\"]*)/gi");
                    content = content.replace(regex, "$1$3");
                }
                else {
                    regex = eval("/(" + url + ")(.+)/gi");
                    content = content.replace(regex, "$2");
                }
            }
        }
        if (stripAnchorUrl) {
            url = WYSIWYG_Core.stringToRegex(WYSIWYG_Core.getDocumentPathOfUrl(stripAnchorUrl));
            if (exact) {
                regex = eval("/(href=\")(" + url + ")([^\"]*)/gi");
                content = content.replace(regex, "$1$3");
            }
            else {
                regex = eval("/(" + url + ")(.+)/gi");
                content = content.replace(regex, "$2");
            }
            result = WYSIWYG_Core.getDocumentPathOfUrl(stripAnchorUrl).match(/.+[\/]{2,3}[^\/]*/, "");
            if (result) {
                url = WYSIWYG_Core.stringToRegex(result[0]);
                if (exact) {
                    regex = eval("/(href=\")(" + url + ")([^\"]*)/gi");
                    content = content.replace(regex, "$1$3");
                }
                else {
                    regex = eval("/(" + url + ")(.+)/gi");
                    content = content.replace(regex, "$2");
                }
            }
            url = WYSIWYG_Core.stringToRegex(stripAnchorUrl);
            if (exact) {
                regex = eval("/(href=\")(" + url + ")(#[^\"]*)/gi");
                content = content.replace(regex, "$1$3");
            }
            else {
                regex = eval("/(" + url + ")(.+)/gi");
                content = content.replace(regex, "$2");
            }
            url = WYSIWYG_Core.getDocumentUrl(document);
            var pos = url.lastIndexOf("/");
            if (pos != -1) {
                url = url.substring(pos + 1, url.length);
                url = WYSIWYG_Core.stringToRegex(url);
                if (exact) {
                    regex = eval("/(href=\")(" + url + ")(#[^\"]*)/gi");
                    content = content.replace(regex, "$1$3");
                }
                else {
                    regex = eval("/(" + url + ")(.+)/gi");
                    content = content.replace(regex, "$2");
                }
            }
        }
        return content;
    },
    updateTextArea: function(n) {
        if (this.viewTextMode[n]) {
            this.viewText(n);
        }
        var content = this.getEditorWindow(n).document.body.innerHTML;
        content = this.stripURLPath(n, content);
        content = WYSIWYG_Core.replaceRGBWithHexColor(content);
        if (this.config[n].ReplaceLineBreaks) {
            content = content.replace(/(\r\n)|(\n)/ig, "");
        }
        $_ow(n).value = content;
    },
    hideToolbars: function(n) {
        for (var i = 0; i < this.config[n].Toolbar.length; i++) {
            var toolbar = $_ow("toolbar" + i + "_" + n);
            if (toolbar) {
                toolbar.style.display = "none";
            }
        }
    },
    showToolbars: function(n) {
        for (var i = 0; i < this.config[n].Toolbar.length; i++) {
            var toolbar = $_ow("toolbar" + i + "_" + n);
            if (toolbar) {
                toolbar.style.display = "";
            }
        }
    },
    hideStatusBar: function(n) {
        var statusbar = $_ow('wysiwyg_statusbar_' + n);
        if (statusbar) {
            statusbar.style.display = "none";
        }
    },
    showStatusBar: function(n) {
        var statusbar = $_ow('wysiwyg_statusbar_' + n);
        if (statusbar) {
            statusbar.style.display = "";
        }
    },
    findParent: function(parentTagName, range) {
        parentTagName = parentTagName.toUpperCase();
        var rangeWorking;
        var elmWorking = null;
        try {
            if (!WYSIWYG_Core.isMSIE) {
                var node = range.startContainer;
                var pos = range.startOffset;
                if (node.nodeType != 3) {
                    node = node.childNodes[pos];
                }
                return WYSIWYG_Core.findParentNode(parentTagName, node);
            }
            else {
                elmWorking = (range.length > 0) ? range.item(0) : range.parentElement();
                elmWorking = WYSIWYG_Core.findParentNode(parentTagName, elmWorking);
                if (elmWorking != null) return elmWorking;
                rangeWorking = range.duplicate();
                rangeWorking.collapse(true);
                rangeWorking.moveEnd("character", 1);
                if (rangeWorking.text.length > 0) {
                    while (rangeWorking.compareEndPoints("EndToEnd", range) < 0) {
                        rangeWorking.move("Character");
                        if (null != this.findParentTag(parentTagName, rangeWorking)) {
                            return this.findParentTag(parentTagName, rangeWorking);
                        }
                    }
                }
                return null;
            }
        }
        catch (e) {
            return null;
        }
    },
    getTag: function(range) {
        try {
            if (!WYSIWYG_Core.isMSIE) {
                var node = range.startContainer;
                var pos = range.startOffset;
                if (node.nodeType != 3) {
                    node = node.childNodes[pos];
                }
                if (node.nodeName && node.nodeName.search(/#/) != -1) {
                    return node.parentNode;
                }
                return node;
            }
            else {
                if (range.length > 0) {
                    return range.item(0);
                }
                else if (range.parentElement()) {
                    return range.parentElement();
                }
            }
            return null;
        }
        catch (e) {
            return null;
        }
    },
    getParent: function(element) {
        if (element.parentNode) {
            return element.parentNode;
        }
        return null;
    },
    getTextRange: function(element) {
        var range = element.parentTextEdit.createTextRange();
        range.moveToElementText(element);
        return range;
    },
    invertIELineBreakCapability: function(n) {
        var editor = this.getEditorWindow(n);
        var sel;
        if (editor.event.keyCode == 13) {
            if (!editor.event.shiftKey) {
                sel = this.getRange(this.getSelection(n));
                sel.pasteHTML("<br>");
                editor.event.cancelBubble = true;
                editor.event.returnValue = false;
                sel.select();
                sel.moveEnd("character", 1);
                sel.moveStart("character", 1);
                sel.collapse(false);
                return false;
            }
            else {
                sel = this.getRange(this.getSelection(n));
                sel.pasteHTML("<p>");
                editor.event.cancelBubble = true;
                editor.event.returnValue = false;
                sel.select();
                sel.moveEnd("character", 1);
                sel.moveStart("character", 1);
                sel.collapse(false);
                return false;
            }
        }
    },
    selectNode: function(n, level) {
        var sel = this.getSelection(n);
        var range = this.getRange(sel);
        var parentnode = this.getTag(range);
        var i = 0;
        for (var node = parentnode; (node && (node.nodeType == 1)); node = node.parentNode) {
            if (i == level) {
                this.nodeSelection(n, node);
            }
            i++;
        }
        this.updateStatusBar(n);
    },
    nodeSelection: function(n, node) {
        var doc = this.getEditorWindow(n).document;
        var sel = this.getSelection(n);
        var range = this.getRange(sel);
        if (!WYSIWYG_Core.isMSIE) {
            if (node.nodeName == "BODY") {
                range.selectNodeContents(node);
            }
            else {
                range.selectNode(node);
            }
            if (sel) {
                sel.removeAllRanges();
            }
            if (sel) {
                sel.addRange(range);
            }
        }
        else {
            if ((node.nodeName == "TABLE") || (node.nodeName == "IMG") || (node.nodeName == "INPUT") || (node.nodeName == "SELECT") || (node.nodeName == "TEXTAREA")) {
                try {
                    range = doc.body.createControlRange();
                    range.addElement(node);
                    range.select();
                }
                catch (e) {
                }
            }
            else {
                range = doc.body.createTextRange();
                if (range) {
                    range.collapse();
                    if (range.moveToElementText) {
                        try {
                            range.moveToElementText(node);
                            range.select();
                        }
                        catch (e) {
                            try {
                                range = doc.body.createTextRange();
                                range.moveToElementText(node);
                                range.select();
                            }
                            catch (e) {
                            }
                        }
                    }
                    else {
                        try {
                            range = doc.body.createTextRange();
                            range.moveToElementText(node);
                            range.select();
                        }
                        catch (e) {
                        }
                    }
                }
            }
        }
    },
    styleWithCSS: function(n, value) {
        if (WYSIWYG_Core.isFF) {
            WYSIWYG_Core.execCommand(n, 'styleWithCSS', value);
            return true;
        }
        return false;
    }
}
var WYSIWYG_Core = {
    isMSIE: navigator.appName == "Microsoft Internet Explorer" ? true : false,
    isFF: !document.all && document.getElementById && !this.isOpera,
    isOpera: navigator.appName == "Opera" ? true : false,
    trim: function(str)
    {
        return str.replace(/^\s*|\s*$/g, "");
    },
    defined: function(p)
    {
        return typeof p == "undefined" ? false : true;
    },
    isBrowserCompatible: function()
    {
        if (!document.getElementById || !document.designMode)
        {
            return false;
        }
        return true;
    },
    _setStyleAttribute: function(node, style)
    {
        if (style == null) return;
        var styles = style.split(";");
        var pos;
        for (var i = 0; i < styles.length; i++)
        {
            var attributes = styles[i].split(":");
            if (attributes.length == 2)
            {
                try
                {
                    var attr = WYSIWYG_Core.trim(attributes[0]);
                    while ((pos = attr.search(/-/)) != -1)
                    {
                        var strBefore = attr.substring(0, pos);
                        var strToUpperCase = attr.substring(pos + 1, pos + 2);
                        var strAfter = attr.substring(pos + 2, attr.length);
                        attr = strBefore + strToUpperCase.toUpperCase() + strAfter;
                    }
                    var value = WYSIWYG_Core.trim(attributes[1]).toLowerCase();
                    node.style[attr] = value;
                }
                catch (e)
                {
                    alert(e);
                }
            }
        }
    },
    _getStyleAttribute: function(node)
    {
        if (this.isMSIE)
        {
            return node.style['cssText'].toLowerCase();
        }
        else
        {
            return node.getAttribute("style");
        }
    },
    setAttribute: function(node, attr, value)
    {
        if (value == null || node == null || attr == null) return;
        if (value == "") return;
        if (attr.toLowerCase() == "style")
        {
            this._setStyleAttribute(node, value);
        }
        else
        {
            node.setAttribute(attr, value);
        }
    },
    removeAttribute: function(node, attr)
    {
        node.removeAttribute(attr, false);
    },
    getAttribute: function(node, attr)
    {
        if (node == null || attr == null) return;
        if (attr.toLowerCase() == "style")
        {
            return this._getStyleAttribute(node);
        }
        else
        {
            return node.getAttribute(attr);
        }
    },
    getDocumentPathOfUrl: function(url)
    {
        var path = null;
        url = url.replace(/file:\/\//gi, "file:///");
        url = url.replace(/\\/gi, "\/");
        var pos = url.lastIndexOf("/");
        if (pos != -1)
        {
            path = url.substring(0, pos + 1);
        }
        return path;
    },
    getDocumentUrl: function(doc)
    {
        var url = doc.URL;
        url = url.replace(/file:\/\//gi, "file:///");
        url = url.replace(/\\/gi, "\/");
        return url;
    },
    findParentNode: function(tagName, node)
    {
        while (node.tagName != "HTML")
        {
            if (node.tagName == tagName)
            {
                return node;
            }
            node = node.parentNode;
        }
        return null;
    },
    cancelEvent: function(e)
    {
        if (!e) return false;
        if (this.isMSIE)
        {
            e.returnValue = false;
            e.cancelBubble = true;
        }
        else
        {
            e.preventDefault();
            e.stopPropagation && e.stopPropagation();
        }
        return false;
    },
    toHexColor: function(color)
    {
        color = color.replace(/^rgb/g, '');
        color = color.replace(/\(/g, '');
        color = color.replace(/\)/g, '');
        color = color.replace(/ /g, '');
        color = color.split(',');
        var r = parseFloat(color[0]).toString(16).toUpperCase();
        var g = parseFloat(color[1]).toString(16).toUpperCase();
        var b = parseFloat(color[2]).toString(16).toUpperCase();
        if (r.length < 2)
        {
            r = '0' + r;
        }
        if (g.length < 2)
        {
            g = '0' + g;
        }
        if (b.length < 2)
        {
            b = '0' + b;
        }
        return r + g + b;
    },
    _dec_to_rgb: function(value)
    {
        var hex_string = "";
        for (var hexpair = 0; hexpair < 3; hexpair++)
        {
            var myByte = value & 0xFF;
            value >>= 8;
            var nybble2 = myByte & 0x0F;
            var nybble1 = (myByte >> 4) & 0x0F;
            hex_string += nybble1.toString(16);
            hex_string += nybble2.toString(16);
        }
        return hex_string.toUpperCase();
    },
    replaceRGBWithHexColor: function(str)
    {
        if (str == null) return "";
        var matcher = str.match(/rgb\([0-9 ]+,[0-9 ]+,[0-9 ]+\)/gi);
        if (matcher)
        {
            for (var j = 0; j < matcher.length; j++)
            {
                var regex = eval("/" + WYSIWYG_Core.stringToRegex(matcher[j]) + "/gi");
                str = str.replace(regex, "#" + this.toHexColor(matcher[j]));
            }
        }
        return str;
    },
    execCommand: function(n, cmd, value)
    {
        if (typeof (value) == "undefined") value = null;
        if (cmd == 'BackColor' && WYSIWYG_Core.isFF) cmd = 'HiliteColor';
        if (WYSIWYG_Core.isFF && (cmd == "Cut" || cmd == "Paste" || cmd == "Copy"))
        {
            try
            {
                WYSIWYG.getEditorWindow(n).document.execCommand(cmd, false, value);
            }
            catch (e)
            {
                if (confirm(WYSIWYG.config[n].CutCopyFirefoxMsg))
                {
                    window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html');
                }
            }
        }
        else
        {
            WYSIWYG.getEditorWindow(n).document.execCommand(cmd, false, value);
        }
    },
    stringToRegex: function(string)
    {
        string = string.replace(/\//gi, "\\/");
        string = string.replace(/\(/gi, "\\(");
        string = string.replace(/\)/gi, "\\)");
        string = string.replace(/\[/gi, "\\[");
        string = string.replace(/\]/gi, "\\]");
        string = string.replace(/\+/gi, "\\+");
        string = string.replace(/\$/gi, "\\$");
        string = string.replace(/\*/gi, "\\*");
        string = string.replace(/\?/gi, "\\?");
        string = string.replace(/\^/gi, "\\^");
        string = string.replace(/\\b/gi, "\\\\b");
        string = string.replace(/\\B/gi, "\\\\B");
        string = string.replace(/\\d/gi, "\\\\d");
        string = string.replace(/\\B/gi, "\\\\B");
        string = string.replace(/\\D/gi, "\\\\D");
        string = string.replace(/\\f/gi, "\\\\f");
        string = string.replace(/\\n/gi, "\\\\n");
        string = string.replace(/\\r/gi, "\\\\r");
        string = string.replace(/\\t/gi, "\\\\t");
        string = string.replace(/\\v/gi, "\\\\v");
        string = string.replace(/\\s/gi, "\\\\s");
        string = string.replace(/\\S/gi, "\\\\S");
        string = string.replace(/\\w/gi, "\\\\w");
        string = string.replace(/\\W/gi, "\\\\W");
        return string;
    },
    addEvent: function(obj, ev, fu)
    {
        if (obj.attachEvent)
        {
            obj.attachEvent("on" + ev, fu);
        }
        else
        {
            obj.addEventListener(ev, fu, false);
        }
    },
    removeEvent: function(obj, ev, fu)
    {
        if (obj.attachEvent)
        {
            obj.detachEvent("on" + ev, fu);
        }
        else
        {
            obj.removeEventListener(ev, fu, false);
        }
    },
    includeJS: function(file)
    {
        var script = document.createElement("script");
        this.setAttribute(script, "type", "text/javascript");
        this.setAttribute(script, "src", file);
        var heads = document.getElementsByTagName("head");
        for (var i = 0; i < heads.length; i++)
        {
            heads[i].appendChild(script);
        }
    },
    includeCSS: function(path)
    {
        var link = document.createElement("link");
        this.setAttribute(link, "rel", "stylesheet");
        this.setAttribute(link, "type", "text/css");
        this.setAttribute(link, "href", path);
        var heads = document.getElementsByTagName("head");
        for (var i = 0; i < heads.length; i++)
        {
            heads[i].appendChild(link);
        }
    },
    getElementPosition: function(elm1, elm2)
    {
        var top = 0, left = 0;
        while (elm1 && elm1 != elm2)
        {
            left += elm1.offsetLeft;
            top += elm1.offsetTop;
            elm1 = elm1.offsetParent;
        }
        return { left: left, top: top };
    },
    windowSize: function()
    {
        if (window.innerWidth)
        {
            return { width: window.innerWidth, height: window.innerHeight };
        }
        else if (document.body && document.body.offsetWidth)
        {
            return { width: document.body.offsetWidth, height: document.body.offsetHeight };
        }
        else
        {
            return { width: 0, height: 0 };
        }
    }
}

var WYSIWYG_ContextMenu = {
    html: "",
    contextMenuDiv: null,
    init: function(n) {
        var doc = WYSIWYG.getEditorWindow(n).document;
        this.contextMenuDiv = document.createElement("div");
        this.contextMenuDiv.className = "wysiwyg-context-menu-div";
        this.contextMenuDiv.setAttribute("class", "wysiwyg-context-menu-div");
        this.contextMenuDiv.style.display = "none";
        this.contextMenuDiv.style.position = "absolute";
        this.contextMenuDiv.style.zIndex = 9999;
        this.contextMenuDiv.style.left = "0";
        this.contextMenuDiv.style.top = "0";
        this.contextMenuDiv.unselectable = "on";
        document.body.insertBefore(this.contextMenuDiv, document.body.firstChild);
        WYSIWYG_Core.addEvent(doc, "contextmenu", function context(e) { WYSIWYG_ContextMenu.show(e, n); });
        WYSIWYG_Core.addEvent(doc, "click", function context(e) { WYSIWYG_ContextMenu.close(); });
        WYSIWYG_Core.addEvent(doc, "keydown", function context(e) { WYSIWYG_ContextMenu.close(); });
        WYSIWYG_Core.addEvent(document, "click", function context(e) { WYSIWYG_ContextMenu.close(); });
    },
    show: function(e, n) {
        if (this.contextMenuDiv == null) return false;
        var ifrm = WYSIWYG.getEditor(n);
        var doc = WYSIWYG.getEditorWindow(n).document;
        var pos = WYSIWYG_Core.getElementPosition(ifrm);
        var x = WYSIWYG_Core.isMSIE ? pos.left + e.clientX : pos.left + (e.pageX - doc.body.scrollLeft);
        var y = WYSIWYG_Core.isMSIE ? pos.top + e.clientY : pos.top + (e.pageY - doc.body.scrollTop);
        this.contextMenuDiv.style.left = x + "px";
        this.contextMenuDiv.style.top = y + "px";
        this.contextMenuDiv.style.visibility = "visible";
        this.contextMenuDiv.style.display = "block";
        window.setTimeout("WYSIWYG_ContextMenu.output('" + n + "')", 10);
        WYSIWYG_Core.cancelEvent(e);
        return false;
    },
    output: function(n) {
        var sel = WYSIWYG.getSelection(n);
        var range = WYSIWYG.getRange(sel);
        var tag = WYSIWYG.getTag(range);
        if (tag == null) {
            return;
        }
        this.clear();
        var isImg = (tag.nodeName == "IMG") ? true : false;
        var isLink = (tag.nodeName == "A") ? true : false;
        var len = 0;
        if (WYSIWYG_Core.isMSIE) {
            len = (document.selection && range.text) ? range.text.length : 0;
        }
        else {
            len = range.toString().length;
        }
        var sel = len != 0 || isImg;
        var iconLink = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["createlink"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["createlink"][2] };
        var iconImage = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["insertimage"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["insertimage"][2] };
        var iconDelete = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["delete"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["delete"][2] };
        var iconCopy = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["copy"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["copy"][2] };
        var iconCut = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["cut"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["cut"][2] };
        var iconPaste = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["paste"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.config[n].ToolbarList["paste"][2] };
        var labels = WYSIWYG.config[n].RightClickPanelLabels;
        this.html += '<table class="wysiwyg-context-menu" border="0" cellpadding="0" cellspacing="0">';
        this.addItem(n, 'Copy', iconCopy, labels[0], sel);
        this.addItem(n, 'Cut', iconCut, labels[1], sel);
        this.addItem(n, 'Paste', iconPaste, labels[2], true);
        this.addSeperator();
        this.addItem(n, 'InsertImage', iconImage, labels[3], isImg);
        this.addItem(n, 'CreateLink', iconLink, labels[4], sel || isLink);
        this.addItem(n, 'RemoveNode', iconDelete, labels[5], true);
        this.html += '</table>';
        this.contextMenuDiv.innerHTML = this.html;
    },
    close: function() {
        this.contextMenuDiv.style.visibility = "hidden";
        this.contextMenuDiv.style.display = "none";
    },
    clear: function() {
        this.contextMenuDiv.innerHTML = "";
        this.html = "";
    },
    addItem: function(n, cmd, icon, title, disabled) {
        var item = '';
        if (disabled) {
            item += '<tr>';
            item += '<td class="icon"><a href="javascript:WYSIWYG.execCommand(\'' + n + '\',\'' + cmd + '\',null);"><img src="' + icon.enabled + '" border="0"></a></td>';
            item += '<td onmouseover="this.className=\'mouseover\'" onmouseout="this.className=\'\'" onclick="WYSIWYG.execCommand(\'' + n + '\',\'' + cmd + '\',null);WYSIWYG_ContextMenu.close();"><a href="javascript:void(0);">' + title + '</a></td>';
            item += '</tr>';
        }
        else {
            item += '<tr>';
            item += '<td class="icon"><img src="' + icon.disabled + '" border="0"></td>';
            item += '<td onmouseover="this.className=\'mouseover\'" onmouseout="this.className=\'\'"><span class="disabled">' + title + '</span></td>';
            item += '</tr>';
        }
        this.html += item;
    },
    addSeperator: function() {
        var output = '';
        output += '<tr>';
        output += '<td colspan="2" style="text-align:center;"><hr size="1" color="#C9C9C9" width="95%"></td>';
        output += '</tr>';
        this.html += output;
    }
}

var WYSIWYG_Table = {
    create: function(n, tbl)
    {
        var doc = WYSIWYG.getEditorWindow(n).document;
        var sel = WYSIWYG.getSelection(n);
        var range = WYSIWYG.getRange(sel);
        var table = null;
        if (WYSIWYG_Core.isMSIE)
        {
            if (sel.type == "Control" && range.length == 1)
            {
                range = WYSIWYG.getTextRange(range(0));
                range.select();
            }
        }
        table = tbl;
        var rows = WYSIWYG_Core.getAttribute(tbl, "tmprows");
        var cols = WYSIWYG_Core.getAttribute(tbl, "tmpcols");
        WYSIWYG_Core.removeAttribute(tbl, "tmprows");
        WYSIWYG_Core.removeAttribute(tbl, "tmpcols");
        for (var i = 0; i < rows; i++)
        {
            var tr = doc.createElement("tr");
            for (var j = 0; j < cols; j++)
            {
                var td = createTD();
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
        if (WYSIWYG_Core.isMSIE)
        {
            range.pasteHTML(table.outerHTML);
        }
        else
        {
            WYSIWYG.insertNodeAtSelection(table, n);
        }
        this.refreshHighlighting(n);
        function createTD()
        {
            var td = doc.createElement("td");
            td.innerHTML = "&nbsp;";
            return td;
        }
    },
    refreshHighlighting: function(n)
    {
        var doc = WYSIWYG.getEditorWindow(n).document;
        var tables = doc.getElementsByTagName("table");
        for (var i = 0; i < tables.length; i++)
        {
            this._enableHighlighting(tables[i]);
        }
        var tds = doc.getElementsByTagName("td");
        for (var i = 0; i < tds.length; i++)
        {
            this._enableHighlighting(tds[i]);
        }
    },
    disableHighlighting: function(n)
    {
        var doc = WYSIWYG.getEditorWindow(n).document;
        var tables = doc.getElementsByTagName("table");
        for (var i = 0; i < tables.length; i++)
        {
            this._disableHighlighting(tables[i]);
        }
        var tds = doc.getElementsByTagName("td");
        for (var i = 0; i < tds.length; i++)
        {
            this._disableHighlighting(tds[i]);
        }
    },
    _enableHighlighting: function(node)
    {
        var style = WYSIWYG_Core.getAttribute(node, "style");
        if (style == null) style = " ";
        WYSIWYG_Core.removeAttribute(node, "prevstyle");
        WYSIWYG_Core.setAttribute(node, "prevstyle", style);
        WYSIWYG_Core.setAttribute(node, "style", "border:1px dashed #AAAAAA;");
    },
    _disableHighlighting: function(node)
    {
        var style = WYSIWYG_Core.getAttribute(node, "prevstyle");
        if (style == null || style == "")
        {
            this._enableHighlighting(node);
            return;
        }
        WYSIWYG_Core.removeAttribute(node, "prevstyle");
        WYSIWYG_Core.removeAttribute(node, "style");
        WYSIWYG_Core.setAttribute(node, "style", style);
    }
}

function $_ow(id)
{
    return document.getElementById(id);
}

if (typeof HTMLElement != "undefined" && !HTMLElement.prototype.insertAdjacentElement2)
{
    HTMLElement.prototype.insertAdjacentElement2 = function(where, parsedNode)
    {
        switch (where)
        {
            case 'beforeBegin':
                this.parentNode.insertBefore(parsedNode, this);
                break;
            case 'afterBegin':
                this.insertBefore(parsedNode, this.firstChild);
                break;
            case 'beforeEnd':
                this.appendChild(parsedNode);
                break;
            case 'afterEnd':
                if (this.nextSibling)
                {
                    this.parentNode.insertBefore(parsedNode, this.nextSibling);
                }
                else
                {
                    this.parentNode.appendChild(parsedNode);
                }
                break;
        }
    };
    HTMLElement.prototype.insertAdjacentHTML2 = function(where, htmlStr)
    {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement2(where, parsedHTML);
    };
    HTMLElement.prototype.insertAdjacentText2 = function(where, txtStr)
    {
        var parsedText = document.createTextNode(txtStr);
        this.insertAdjacentElement2(where, parsedText);
    };
}

