source: branches/1.2/workflow/js/htmlarea/htmlarea.js @ 1349

Revision 1349, 69.3 KB checked in by niltonneto, 15 years ago (diff)

Ticket #561 - Inclusão do módulo Workflow faltante nessa versão.

  • Property svn:executable set to *
Line 
1// htmlArea v3.0 - Copyright (c) 2002-2004 interactivetools.com, inc.
2// This copyright notice MUST stay intact for use (see license.txt).
3//
4// Portions (c) dynarch.com, 2003-2004
5//
6// A free WYSIWYG editor replacement for <textarea> fields.
7// For full source code and docs, visit http://www.interactivetools.com/
8//
9// Version 3.0 developed by Mihai Bazon.
10//   http://dynarch.com/mishoo
11//
12
13if (typeof _editor_url == "string") {
14        // Leave exactly one backslash at the end of _editor_url
15        _editor_url = _editor_url.replace(/\x2f*$/, '/');
16} else {
17        alert("WARNING: _editor_url is not set!  You should set this variable to the editor files path; it should preferably be an absolute path, like in '/htmlarea/', but it can be relative if you prefer.  Further we will try to load the editor files correctly but we'll probably fail.");
18        _editor_url = '';
19}
20
21// make sure we have a language
22if (typeof _editor_lang == "string") {
23        _editor_lang = _editor_lang.toLowerCase();
24} else {
25        _editor_lang = "en";
26}
27
28// Creates a new HTMLArea object.  Tries to replace the textarea with the given
29// ID with it.
30function HTMLArea(textarea, config) {
31        if (HTMLArea.checkSupportedBrowser()) {
32                if (typeof config == "undefined") {
33                        this.config = new HTMLArea.Config();
34                } else {
35                        this.config = config;
36                }
37                this._htmlArea = null;
38                this._textArea = textarea;
39                this._editMode = "wysiwyg";
40                this.plugins = {};
41                this._timerToolbar = null;
42                this._timerUndo = null;
43                this._undoQueue = new Array(this.config.undoSteps);
44                this._undoPos = -1;
45                this._customUndo = false;
46                this._mdoc = document; // cache the document, we need it in plugins
47                this.doctype = '';
48        }
49};
50
51// load some scripts
52(function() {
53        var scripts = HTMLArea._scripts = [ _editor_url + "htmlarea.js",
54                                            _editor_url + "dialog.js",
55                                            _editor_url + "popupwin.js",
56                                            _editor_url + "lang/" + _editor_lang + ".js" ];
57        var head = document.getElementsByTagName("head")[0];
58        // start from 1, htmlarea.js is already loaded
59        for (var i = 1; i < scripts.length; ++i) {
60                var script = document.createElement("script");
61                script.src = scripts[i];
62                head.appendChild(script);
63        }
64})();
65
66// cache some regexps
67HTMLArea.RE_tagName = /(<\/|<)\s*([^ \t\n>]+)/ig;
68HTMLArea.RE_doctype = /(<!doctype((.|\n)*?)>)\n?/i;
69HTMLArea.RE_head    = /<head>((.|\n)*?)<\/head>/i;
70HTMLArea.RE_body    = /<body>((.|\n)*?)<\/body>/i;
71
72HTMLArea.Config = function () {
73        this.version = "3.0";
74
75        this.width = "auto";
76        this.height = "auto";
77
78        // enable creation of a status bar?
79        this.statusBar = true;
80
81        // maximum size of the undo queue
82        this.undoSteps = 20;
83
84        // the time interval at which undo samples are taken
85        this.undoTimeout = 500; // 1/2 sec.
86
87        // the next parameter specifies whether the toolbar should be included
88        // in the size or not.
89        this.sizeIncludesToolbar = true;
90
91        // if true then HTMLArea will retrieve the full HTML, starting with the
92        // <HTML> tag.
93        this.fullPage = false;
94
95        // style included in the iframe document
96        this.pageStyle = "";
97
98        // set to true if you want Word code to be cleaned upon Paste
99        this.killWordOnPaste = false;
100
101        // BaseURL included in the iframe document
102        this.baseURL = document.baseURI || document.URL;
103        if (this.baseURL && this.baseURL.match(/(.*)\/([^\/]+)/))
104                this.baseURL = RegExp.$1 + "/";
105
106        // URL-s
107        this.imgURL = "images/";
108        this.popupURL = "popups/";
109
110        /** CUSTOMIZING THE TOOLBAR
111         * -------------------------
112         *
113         * It is recommended that you customize the toolbar contents in an
114         * external file (i.e. the one calling HTMLArea) and leave this one
115         * unchanged.  That's because when we (InteractiveTools.com) release a
116         * new official version, it's less likely that you will have problems
117         * upgrading HTMLArea.
118         */
119        this.toolbar = [
120                [ "fontname", "space",
121                  "fontsize", "space",
122                  "formatblock", "space",
123                  "bold", "italic", "underline", "strikethrough", "separator",
124                  "subscript", "superscript", "separator",
125                  "copy", "cut", "paste", "space", "undo", "redo" ],
126
127                [ "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
128                  "lefttoright", "righttoleft", "separator",
129                  "orderedlist", "unorderedlist", "outdent", "indent", "separator",
130                  "forecolor", "hilitecolor", "separator",
131                  "inserthorizontalrule", "createlink", "insertimage", "inserttable", "htmlmode", "separator",
132                  "popupeditor", "separator", "showhelp", "about" ]
133        ];
134
135        this.fontname = {
136                "Arial":           'arial,helvetica,sans-serif',
137                "Courier New":     'courier new,courier,monospace',
138                "Georgia":         'georgia,times new roman,times,serif',
139                "Tahoma":          'tahoma,arial,helvetica,sans-serif',
140                "Times New Roman": 'times new roman,times,serif',
141                "Verdana":         'verdana,arial,helvetica,sans-serif',
142                "impact":          'impact',
143                "WingDings":       'wingdings'
144        };
145
146        this.fontsize = {
147                "1 (8 pt)":  "1",
148                "2 (10 pt)": "2",
149                "3 (12 pt)": "3",
150                "4 (14 pt)": "4",
151                "5 (18 pt)": "5",
152                "6 (24 pt)": "6",
153                "7 (36 pt)": "7"
154        };
155
156        this.formatblock = {
157                "Heading 1": "h1",
158                "Heading 2": "h2",
159                "Heading 3": "h3",
160                "Heading 4": "h4",
161                "Heading 5": "h5",
162                "Heading 6": "h6",
163                "Normal": "p",
164                "Address": "address",
165                "Formatted": "pre"
166        };
167
168        this.customSelects = {};
169
170        function cut_copy_paste(e, cmd, obj) {
171                e.execCommand(cmd);
172        };
173
174        // ADDING CUSTOM BUTTONS: please read below!
175        // format of the btnList elements is "ID: [ ToolTip, Icon, Enabled in text mode?, ACTION ]"
176        //    - ID: unique ID for the button.  If the button calls document.execCommand
177        //          it's wise to give it the same name as the called command.
178        //    - ACTION: function that gets called when the button is clicked.
179        //              it has the following prototype:
180        //                 function(editor, buttonName)
181        //              - editor is the HTMLArea object that triggered the call
182        //              - buttonName is the ID of the clicked button
183        //              These 2 parameters makes it possible for you to use the same
184        //              handler for more HTMLArea objects or for more different buttons.
185        //    - ToolTip: default tooltip, for cases when it is not defined in the -lang- file (HTMLArea.I18N)
186        //    - Icon: path to an icon image file for the button (TODO: use one image for all buttons!)
187        //    - Enabled in text mode: if false the button gets disabled for text-only mode; otherwise enabled all the time.
188        this.btnList = {
189                bold: [ "Bold", "ed_format_bold.gif", false, function(e) {e.execCommand("bold");} ],
190                italic: [ "Italic", "ed_format_italic.gif", false, function(e) {e.execCommand("italic");} ],
191                underline: [ "Underline", "ed_format_underline.gif", false, function(e) {e.execCommand("underline");} ],
192                strikethrough: [ "Strikethrough", "ed_format_strike.gif", false, function(e) {e.execCommand("strikethrough");} ],
193                subscript: [ "Subscript", "ed_format_sub.gif", false, function(e) {e.execCommand("subscript");} ],
194                superscript: [ "Superscript", "ed_format_sup.gif", false, function(e) {e.execCommand("superscript");} ],
195                justifyleft: [ "Justify Left", "ed_align_left.gif", false, function(e) {e.execCommand("justifyleft");} ],
196                justifycenter: [ "Justify Center", "ed_align_center.gif", false, function(e) {e.execCommand("justifycenter");} ],
197                justifyright: [ "Justify Right", "ed_align_right.gif", false, function(e) {e.execCommand("justifyright");} ],
198                justifyfull: [ "Justify Full", "ed_align_justify.gif", false, function(e) {e.execCommand("justifyfull");} ],
199                orderedlist: [ "Ordered List", "ed_list_num.gif", false, function(e) {e.execCommand("insertorderedlist");} ],
200                unorderedlist: [ "Bulleted List", "ed_list_bullet.gif", false, function(e) {e.execCommand("insertunorderedlist");} ],
201                outdent: [ "Decrease Indent", "ed_indent_less.gif", false, function(e) {e.execCommand("outdent");} ],
202                indent: [ "Increase Indent", "ed_indent_more.gif", false, function(e) {e.execCommand("indent");} ],
203                forecolor: [ "Font Color", "ed_color_fg.gif", false, function(e) {e.execCommand("forecolor");} ],
204                hilitecolor: [ "Background Color", "ed_color_bg.gif", false, function(e) {e.execCommand("hilitecolor");} ],
205                inserthorizontalrule: [ "Horizontal Rule", "ed_hr.gif", false, function(e) {e.execCommand("inserthorizontalrule");} ],
206                createlink: [ "Insert Web Link", "ed_link.gif", false, function(e) {e.execCommand("createlink", true);} ],
207                insertimage: [ "Insert/Modify Image", "ed_image.gif", false, function(e) {e.execCommand("insertimage");} ],
208                inserttable: [ "Insert Table", "insert_table.gif", false, function(e) {e.execCommand("inserttable");} ],
209                htmlmode: [ "Toggle HTML Source", "ed_html.gif", true, function(e) {e.execCommand("htmlmode");} ],
210                popupeditor: [ "Enlarge Editor", "fullscreen_maximize.gif", true, function(e) {e.execCommand("popupeditor");} ],
211                about: [ "About this editor", "ed_about.gif", true, function(e) {e.execCommand("about");} ],
212                showhelp: [ "Help using editor", "ed_help.gif", true, function(e) {e.execCommand("showhelp");} ],
213                undo: [ "Undoes your last action", "ed_undo.gif", false, function(e) {e.execCommand("undo");} ],
214                redo: [ "Redoes your last action", "ed_redo.gif", false, function(e) {e.execCommand("redo");} ],
215                cut: [ "Cut selection", "ed_cut.gif", false, cut_copy_paste ],
216                copy: [ "Copy selection", "ed_copy.gif", false, cut_copy_paste ],
217                paste: [ "Paste from clipboard", "ed_paste.gif", false, cut_copy_paste ],
218                lefttoright: [ "Direction left to right", "ed_left_to_right.gif", false, function(e) {e.execCommand("lefttoright");} ],
219                righttoleft: [ "Direction right to left", "ed_right_to_left.gif", false, function(e) {e.execCommand("righttoleft");} ]
220        };
221        /* ADDING CUSTOM BUTTONS
222         * ---------------------
223         *
224         * It is recommended that you add the custom buttons in an external
225         * file and leave this one unchanged.  That's because when we
226         * (InteractiveTools.com) release a new official version, it's less
227         * likely that you will have problems upgrading HTMLArea.
228         *
229         * Example on how to add a custom button when you construct the HTMLArea:
230         *
231         *   var editor = new HTMLArea("your_text_area_id");
232         *   var cfg = editor.config; // this is the default configuration
233         *   cfg.btnList["my-hilite"] =
234         *      [ function(editor) { editor.surroundHTML('<span style="background:yellow">', '</span>'); }, // action
235         *        "Highlight selection", // tooltip
236         *        "my_hilite.gif", // image
237         *        false // disabled in text mode
238         *      ];
239         *   cfg.toolbar.push(["linebreak", "my-hilite"]); // add the new button to the toolbar
240         *
241         * An alternate (also more convenient and recommended) way to
242         * accomplish this is to use the registerButton function below.
243         */
244        // initialize tooltips from the I18N module and generate correct image path
245        for (var i in this.btnList) {
246                var btn = this.btnList[i];
247                btn[1] = _editor_url + this.imgURL + btn[1];
248                if (typeof HTMLArea.I18N.tooltips[i] != "undefined") {
249                        btn[0] = HTMLArea.I18N.tooltips[i];
250                }
251        }
252};
253
254/** Helper function: register a new button with the configuration.  It can be
255 * called with all 5 arguments, or with only one (first one).  When called with
256 * only one argument it must be an object with the following properties: id,
257 * tooltip, image, textMode, action.  Examples:
258 *
259 * 1. config.registerButton("my-hilite", "Hilite text", "my-hilite.gif", false, function(editor) {...});
260 * 2. config.registerButton({
261 *      id       : "my-hilite",      // the ID of your button
262 *      tooltip  : "Hilite text",    // the tooltip
263 *      image    : "my-hilite.gif",  // image to be displayed in the toolbar
264 *      textMode : false,            // disabled in text mode
265 *      action   : function(editor) { // called when the button is clicked
266 *                   editor.surroundHTML('<span class="hilite">', '</span>');
267 *                 },
268 *      context  : "p"               // will be disabled if outside a <p> element
269 *    });
270 */
271HTMLArea.Config.prototype.registerButton = function(id, tooltip, image, textMode, action, context) {
272        var the_id;
273        if (typeof id == "string") {
274                the_id = id;
275        } else if (typeof id == "object") {
276                the_id = id.id;
277        } else {
278                alert("ERROR [HTMLArea.Config::registerButton]:\ninvalid arguments");
279                return false;
280        }
281        // check for existing id
282        if (typeof this.customSelects[the_id] != "undefined") {
283                // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA dropdown with the same ID already exists.");
284        }
285        if (typeof this.btnList[the_id] != "undefined") {
286                // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA button with the same ID already exists.");
287        }
288        switch (typeof id) {
289            case "string": this.btnList[id] = [ tooltip, image, textMode, action, context ]; break;
290            case "object": this.btnList[id.id] = [ id.tooltip, id.image, id.textMode, id.action, id.context ]; break;
291        }
292};
293
294/** The following helper function registers a dropdown box with the editor
295 * configuration.  You still have to add it to the toolbar, same as with the
296 * buttons.  Call it like this:
297 *
298 * FIXME: add example
299 */
300HTMLArea.Config.prototype.registerDropdown = function(object) {
301        // check for existing id
302        if (typeof this.customSelects[object.id] != "undefined") {
303                // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA dropdown with the same ID already exists.");
304        }
305        if (typeof this.btnList[object.id] != "undefined") {
306                // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA button with the same ID already exists.");
307        }
308        this.customSelects[object.id] = object;
309};
310
311/** Call this function to remove some buttons/drop-down boxes from the toolbar.
312 * Pass as the only parameter a string containing button/drop-down names
313 * delimited by spaces.  Note that the string should also begin with a space
314 * and end with a space.  Example:
315 *
316 *   config.hideSomeButtons(" fontname fontsize textindicator ");
317 *
318 * It's useful because it's easier to remove stuff from the defaul toolbar than
319 * create a brand new toolbar ;-)
320 */
321HTMLArea.Config.prototype.hideSomeButtons = function(remove) {
322        var toolbar = this.toolbar;
323        for (var i in toolbar) {
324                var line = toolbar[i];
325                for (var j = line.length; --j >= 0; ) {
326                        if (remove.indexOf(" " + line[j] + " ") >= 0) {
327                                var len = 1;
328                                if (/separator|space/.test(line[j + 1])) {
329                                        len = 2;
330                                }
331                                line.splice(j, len);
332                        }
333                }
334        }
335};
336
337/** Helper function: replace all TEXTAREA-s in the document with HTMLArea-s. */
338HTMLArea.replaceAll = function(config) {
339        var tas = document.getElementsByTagName("textarea");
340        for (var i = tas.length; i > 0; (new HTMLArea(tas[--i], config)).generate()){};
341};
342
343/** Helper function: replaces the TEXTAREA with the given ID with HTMLArea. */
344HTMLArea.replace = function(id, config) {
345        var ta = HTMLArea.getElementById("textarea", id);
346        return ta ? (new HTMLArea(ta, config)).generate() : null;
347};
348
349// Creates the toolbar and appends it to the _htmlarea
350HTMLArea.prototype._createToolbar = function () {
351        var editor = this;      // to access this in nested functions
352
353        var toolbar = document.createElement("div");
354        this._toolbar = toolbar;
355        toolbar.className = "toolbar";
356        toolbar.unselectable = "1";
357        toolbar.style.width = this.config.width - 4;
358        var tb_row = null;
359        var tb_objects = new Object();
360        this._toolbarObjects = tb_objects;
361
362        // creates a new line in the toolbar
363        function newLine() {
364                var table = document.createElement("table");
365                table.border = "0px";
366                table.cellSpacing = "0px";
367                table.cellPadding = "0px";
368                toolbar.appendChild(table);
369                // TBODY is required for IE, otherwise you don't see anything
370                // in the TABLE.
371                var tb_body = document.createElement("tbody");
372                table.appendChild(tb_body);
373                tb_row = document.createElement("tr");
374                tb_body.appendChild(tb_row);
375        }; // END of function: newLine
376        // init first line
377        newLine();
378
379        // updates the state of a toolbar element.  This function is member of
380        // a toolbar element object (unnamed objects created by createButton or
381        // createSelect functions below).
382        function setButtonStatus(id, newval) {
383                var oldval = this[id];
384                var el = this.element;
385                if (oldval != newval) {
386                        switch (id) {
387                            case "enabled":
388                                if (newval) {
389                                        HTMLArea._removeClass(el, "buttonDisabled");
390                                        el.disabled = false;
391                                } else {
392                                        HTMLArea._addClass(el, "buttonDisabled");
393                                        el.disabled = true;
394                                }
395                                break;
396                            case "active":
397                                if (newval) {
398                                        HTMLArea._addClass(el, "buttonPressed");
399                                } else {
400                                        HTMLArea._removeClass(el, "buttonPressed");
401                                }
402                                break;
403                        }
404                        this[id] = newval;
405                }
406        }; // END of function: setButtonStatus
407
408        // this function will handle creation of combo boxes.  Receives as
409        // parameter the name of a button as defined in the toolBar config.
410        // This function is called from createButton, above, if the given "txt"
411        // doesn't match a button.
412        function createSelect(txt) {
413                var options = null;
414                var el = null;
415                var cmd = null;
416                var customSelects = editor.config.customSelects;
417                var context = null;
418                var tooltip = "";
419                switch (txt) {
420                    case "fontsize":
421                    case "fontname":
422                    case "formatblock":
423                        // the following line retrieves the correct
424                        // configuration option because the variable name
425                        // inside the Config object is named the same as the
426                        // button/select in the toolbar.  For instance, if txt
427                        // == "formatblock" we retrieve config.formatblock (or
428                        // a different way to write it in JS is
429                        // config["formatblock"].
430                        options = editor.config[txt];
431                        cmd = txt;
432                        break;
433                    default:
434                        // try to fetch it from the list of registered selects
435                        cmd = txt;
436                        var dropdown = customSelects[cmd];
437                        if (typeof dropdown != "undefined") {
438                                options = dropdown.options;
439                                context = dropdown.context;
440                                if (typeof dropdown.tooltip != "undefined") {
441                                        tooltip = dropdown.tooltip;
442                                }
443                        } else {
444                                alert("ERROR [createSelect]:\nCan't find the requested dropdown definition");
445                        }
446                        break;
447                }
448                if (options) {
449                        el = document.createElement("select");
450                        el.title = tooltip;
451                        var obj = {
452                                name    : txt, // field name
453                                element : el,   // the UI element (SELECT)
454                                enabled : true, // is it enabled?
455                                text    : false, // enabled in text mode?
456                                cmd     : cmd, // command ID
457                                state   : setButtonStatus, // for changing state
458                                context : context
459                        };
460                        tb_objects[txt] = obj;
461                        for (var i in options) {
462                                var op = document.createElement("option");
463                                op.appendChild(document.createTextNode(i));
464                                op.value = options[i];
465                                el.appendChild(op);
466                        }
467                        HTMLArea._addEvent(el, "change", function () {
468                                editor._comboSelected(el, txt);
469                        });
470                }
471                return el;
472        }; // END of function: createSelect
473
474        // appends a new button to toolbar
475        function createButton(txt) {
476                // the element that will be created
477                var el = null;
478                var btn = null;
479                switch (txt) {
480                    case "separator":
481                        el = document.createElement("div");
482                        el.className = "separator";
483                        break;
484                    case "space":
485                        el = document.createElement("div");
486                        el.className = "space";
487                        break;
488                    case "linebreak":
489                        newLine();
490                        return false;
491                    case "textindicator":
492                        el = document.createElement("div");
493                        el.appendChild(document.createTextNode("A"));
494                        el.className = "indicator";
495                        el.title = HTMLArea.I18N.tooltips.textindicator;
496                        var obj = {
497                                name    : txt, // the button name (i.e. 'bold')
498                                element : el, // the UI element (DIV)
499                                enabled : true, // is it enabled?
500                                active  : false, // is it pressed?
501                                text    : false, // enabled in text mode?
502                                cmd     : "textindicator", // the command ID
503                                state   : setButtonStatus // for changing state
504                        };
505                        tb_objects[txt] = obj;
506                        break;
507                    default:
508                        btn = editor.config.btnList[txt];
509                }
510                if (!el && btn) {
511                        el = document.createElement("div");
512                        el.title = btn[0];
513                        el.className = "button";
514                        // let's just pretend we have a button object, and
515                        // assign all the needed information to it.
516                        var obj = {
517                                name    : txt, // the button name (i.e. 'bold')
518                                element : el, // the UI element (DIV)
519                                enabled : true, // is it enabled?
520                                active  : false, // is it pressed?
521                                text    : btn[2], // enabled in text mode?
522                                cmd     : btn[3], // the command ID
523                                state   : setButtonStatus, // for changing state
524                                context : btn[4] || null // enabled in a certain context?
525                        };
526                        tb_objects[txt] = obj;
527                        // handlers to emulate nice flat toolbar buttons
528                        HTMLArea._addEvent(el, "mouseover", function () {
529                                if (obj.enabled) {
530                                        HTMLArea._addClass(el, "buttonHover");
531                                }
532                        });
533                        HTMLArea._addEvent(el, "mouseout", function () {
534                                if (obj.enabled) with (HTMLArea) {
535                                        _removeClass(el, "buttonHover");
536                                        _removeClass(el, "buttonActive");
537                                        (obj.active) && _addClass(el, "buttonPressed");
538                                }
539                        });
540                        HTMLArea._addEvent(el, "mousedown", function (ev) {
541                                if (obj.enabled) with (HTMLArea) {
542                                        _addClass(el, "buttonActive");
543                                        _removeClass(el, "buttonPressed");
544                                        _stopEvent(is_ie ? window.event : ev);
545                                }
546                        });
547                        // when clicked, do the following:
548                        HTMLArea._addEvent(el, "click", function (ev) {
549                                if (obj.enabled) with (HTMLArea) {
550                                        _removeClass(el, "buttonActive");
551                                        _removeClass(el, "buttonHover");
552                                        obj.cmd(editor, obj.name, obj);
553                                        _stopEvent(is_ie ? window.event : ev);
554                                }
555                        });
556                        var img = document.createElement("img");
557                        img.src = btn[1];
558                        img.style.width = "18px";
559                        img.style.height = "18px";
560                        el.appendChild(img);
561                } else if (!el) {
562                        el = createSelect(txt);
563                }
564                if (el) {
565                        var tb_cell = document.createElement("td");
566                        tb_row.appendChild(tb_cell);
567                        tb_cell.appendChild(el);
568                } else {
569                        alert("FIXME: Unknown toolbar item: " + txt);
570                }
571                return el;
572        };
573
574        var first = true;
575        for (var i in this.config.toolbar) {
576                if (!first) {
577                        createButton("linebreak");
578                } else {
579                        first = false;
580                }
581                var group = this.config.toolbar[i];
582                for (var j in group) {
583                        var code = group[j];
584                        if (/^([IT])\[(.*?)\]/.test(code)) {
585                                // special case, create text label
586                                var l7ed = RegExp.$1 == "I"; // localized?
587                                var label = RegExp.$2;
588                                if (l7ed) {
589                                        label = HTMLArea.I18N.custom[label];
590                                }
591                                var tb_cell = document.createElement("td");
592                                tb_row.appendChild(tb_cell);
593                                tb_cell.className = "label";
594                                tb_cell.innerHTML = label;
595                        } else {
596                                createButton(code);
597                        }
598                }
599        }
600
601        this._htmlArea.appendChild(toolbar);
602};
603
604HTMLArea.prototype._createStatusBar = function() {
605        var statusbar = document.createElement("div");
606        statusbar.className = "statusBar";
607        this._htmlArea.appendChild(statusbar);
608        this._statusBar = statusbar;
609        // statusbar.appendChild(document.createTextNode(HTMLArea.I18N.msg["Path"] + ": "));
610        // creates a holder for the path view
611        div = document.createElement("span");
612        div.className = "statusBarTree";
613        div.innerHTML = HTMLArea.I18N.msg["Path"] + ": ";
614        this._statusBarTree = div;
615        this._statusBar.appendChild(div);
616        if (!this.config.statusBar) {
617                // disable it...
618                statusbar.style.display = "none";
619        }
620};
621
622// Creates the HTMLArea object and replaces the textarea with it.
623HTMLArea.prototype.generate = function () {
624        var editor = this;      // we'll need "this" in some nested functions
625        // get the textarea
626        var textarea = this._textArea;
627        if (typeof textarea == "string") {
628                // it's not element but ID
629                this._textArea = textarea = HTMLArea.getElementById("textarea", textarea);
630        }
631        this._ta_size = {
632                w: textarea.offsetWidth,
633                h: textarea.offsetHeight
634        };
635        textarea.style.display = "none";
636
637        // create the editor framework
638        var htmlarea = document.createElement("div");
639        htmlarea.className = "htmlarea";
640        htmlarea.style.width = this.config.width;
641        this._htmlArea = htmlarea;
642
643        // insert the editor before the textarea.
644        textarea.parentNode.insertBefore(htmlarea, textarea);
645
646        if (textarea.form) {
647                // we have a form, on submit get the HTMLArea content and
648                // update original textarea.
649                var f = textarea.form;
650                if (typeof f.onsubmit == "function") {
651                        var funcref = f.onsubmit;
652                        if (typeof f.__msh_prevOnSubmit == "undefined") {
653                                f.__msh_prevOnSubmit = [];
654                        }
655                        f.__msh_prevOnSubmit.push(funcref);
656                }
657                f.onsubmit = function() {
658                        editor._textArea.value = editor.getHTML();
659                        var a = this.__msh_prevOnSubmit;
660                        // call previous submit methods if they were there.
661                        if (typeof a != "undefined") {
662                                for (var i in a) {
663                                        a[i]();
664                                }
665                        }
666                };
667        }
668
669        // add a handler for the "back/forward" case -- on body.unload we save
670        // the HTML content into the original textarea.
671        try {
672                window.onunload = function() {
673                        editor._textArea.value = editor.getHTML();
674                };
675        } catch(e) {};
676
677        // creates & appends the toolbar
678        this._createToolbar();
679
680        // create the IFRAME
681        var iframe = document.createElement("iframe");
682
683        // workaround for the HTTPS problem
684        // iframe.setAttribute("src", "javascript:void(0);");
685        iframe.src = _editor_url + "popups/blank.html";
686
687        htmlarea.appendChild(iframe);
688
689        this._iframe = iframe;
690
691        // creates & appends the status bar, if the case
692        this._createStatusBar();
693
694        // remove the default border as it keeps us from computing correctly
695        // the sizes.  (somebody tell me why doesn't this work in IE)
696
697        if (!HTMLArea.is_ie) {
698                iframe.style.borderWidth = "1px";
699        // iframe.frameBorder = "1";
700        // iframe.marginHeight = "0";
701        // iframe.marginWidth = "0";
702        }
703
704        // size the IFRAME according to user's prefs or initial textarea
705        var height = (this.config.height == "auto" ? (this._ta_size.h + "px") : this.config.height);
706        height = parseInt(height);
707        var width = (this.config.width == "auto" ? (this._ta_size.w + "px") : this.config.width);
708        width = parseInt(width);
709
710        if (!HTMLArea.is_ie) {
711                height -= 2;
712                width -= 2;
713        }
714
715        iframe.style.width = width + "px";
716        if (this.config.sizeIncludesToolbar) {
717                // substract toolbar height
718                height -= this._toolbar.offsetHeight;
719                height -= this._statusBar.offsetHeight;
720        }
721        if (height < 0) {
722                height = 0;
723        }
724        iframe.style.height = height + "px";
725
726        // the editor including the toolbar now have the same size as the
727        // original textarea.. which means that we need to reduce that a bit.
728        textarea.style.width = iframe.style.width;
729        textarea.style.height = iframe.style.height;
730
731        // IMPORTANT: we have to allow Mozilla a short time to recognize the
732        // new frame.  Otherwise we get a stupid exception.
733        function initIframe() {
734                var doc = editor._iframe.contentWindow.document;
735                if (!doc) {
736                        // Try again..
737                        // FIXME: don't know what else to do here.  Normally
738                        // we'll never reach this point.
739                        if (HTMLArea.is_gecko) {
740                                setTimeout(initIframe, 100);
741                                return false;
742                        } else {
743                                alert("ERROR: IFRAME can't be initialized.");
744                        }
745                }
746                if (HTMLArea.is_gecko) {
747                        // enable editable mode for Mozilla
748                        doc.designMode = "on";
749                }
750                editor._doc = doc;
751                if (!editor.config.fullPage) {
752                        doc.open();
753                        var html = "<html>\n";
754                        html += "<head>\n";
755                        if (editor.config.baseURL)
756                                html += '<base href="' + editor.config.baseURL + '" />';
757                        html += "<style>" + editor.config.pageStyle +
758                                " html,body { border: 0px; }</style>\n";
759                        html += "</head>\n";
760                        html += "<body>\n";
761                        html += editor._textArea.value;
762                        html += "</body>\n";
763                        html += "</html>";
764                        doc.write(html);
765                        doc.close();
766                } else {
767                        var html = editor._textArea.value;
768                        if (html.match(HTMLArea.RE_doctype)) {
769                                editor.setDoctype(RegExp.$1);
770                                html = html.replace(HTMLArea.RE_doctype, "");
771                        }
772                        doc.open();
773                        doc.write(html);
774                        doc.close();
775                }
776
777                if (HTMLArea.is_ie) {
778                        // enable editable mode for IE.  For some reason this
779                        // doesn't work if done in the same place as for Gecko
780                        // (above).
781                        doc.body.contentEditable = true;
782                }
783
784                editor.focusEditor();
785                // intercept some events; for updating the toolbar & keyboard handlers
786                HTMLArea._addEvents
787                        (doc, ["keydown", "keypress", "mousedown", "mouseup", "drag"],
788                         function (event) {
789                                 return editor._editorEvent(HTMLArea.is_ie ? editor._iframe.contentWindow.event : event);
790                         });
791
792                // check if any plugins have registered refresh handlers
793                for (var i in editor.plugins) {
794                        var plugin = editor.plugins[i].instance;
795                        if (typeof plugin.onGenerate == "function")
796                                plugin.onGenerate();
797                        if (typeof plugin.onGenerateOnce == "function") {
798                                plugin.onGenerateOnce();
799                                plugin.onGenerateOnce = null;
800                        }
801                }
802
803                setTimeout(function() {
804                        editor.updateToolbar();
805                }, 250);
806
807                if (typeof editor.onGenerate == "function")
808                        editor.onGenerate();
809        };
810        setTimeout(initIframe, 100);
811};
812
813// Switches editor mode; parameter can be "textmode" or "wysiwyg".  If no
814// parameter was passed this function toggles between modes.
815HTMLArea.prototype.setMode = function(mode) {
816        if (typeof mode == "undefined") {
817                mode = ((this._editMode == "textmode") ? "wysiwyg" : "textmode");
818        }
819        switch (mode) {
820            case "textmode":
821                this._textArea.value = this.getHTML();
822                this._iframe.style.display = "none";
823                this._textArea.style.display = "block";
824                if (this.config.statusBar) {
825                        this._statusBar.innerHTML = HTMLArea.I18N.msg["TEXT_MODE"];
826                }
827                break;
828            case "wysiwyg":
829                if (HTMLArea.is_gecko) {
830                        // disable design mode before changing innerHTML
831                        try {
832                                this._doc.designMode = "off";
833                        } catch(e) {};
834                }
835                if (!this.config.fullPage)
836                        this._doc.body.innerHTML = this.getHTML();
837                else
838                        this.setFullHTML(this.getHTML());
839                this._iframe.style.display = "block";
840                this._textArea.style.display = "none";
841                if (HTMLArea.is_gecko) {
842                        // we need to refresh that info for Moz-1.3a
843                        try {
844                                this._doc.designMode = "on";
845                        } catch(e) {};
846                }
847                if (this.config.statusBar) {
848                        this._statusBar.innerHTML = '';
849                        this._statusBar.appendChild(document.createTextNode(HTMLArea.I18N.msg["Path"] + ": "));
850                        this._statusBar.appendChild(this._statusBarTree);
851                }
852                break;
853            default:
854                alert("Mode <" + mode + "> not defined!");
855                return false;
856        }
857        this._editMode = mode;
858        this.focusEditor();
859
860        for (var i in this.plugins) {
861                var plugin = this.plugins[i].instance;
862                if (typeof plugin.onMode == "function") plugin.onMode(mode);
863        }
864};
865
866HTMLArea.prototype.setFullHTML = function(html) {
867        var save_multiline = RegExp.multiline;
868        RegExp.multiline = true;
869        if (html.match(HTMLArea.RE_doctype)) {
870                this.setDoctype(RegExp.$1);
871                html = html.replace(HTMLArea.RE_doctype, "");
872        }
873        RegExp.multiline = save_multiline;
874        if (!HTMLArea.is_ie) {
875                if (html.match(HTMLArea.RE_head))
876                        this._doc.getElementsByTagName("head")[0].innerHTML = RegExp.$1;
877                if (html.match(HTMLArea.RE_body))
878                        this._doc.getElementsByTagName("body")[0].innerHTML = RegExp.$1;
879        } else {
880                var html_re = /<html>((.|\n)*?)<\/html>/i;
881                html = html.replace(html_re, "$1");
882                this._doc.open();
883                this._doc.write(html);
884                this._doc.close();
885                this._doc.body.contentEditable = true;
886                return true;
887        }
888};
889
890/***************************************************
891 *  Category: PLUGINS
892 ***************************************************/
893
894// this is the variant of the function above where the plugin arguments are
895// already packed in an array.  Externally, it should be only used in the
896// full-screen editor code, in order to initialize plugins with the same
897// parameters as in the opener window.
898HTMLArea.prototype.registerPlugin2 = function(plugin, args) {
899        if (typeof plugin == "string")
900                plugin = eval(plugin);
901        if (typeof plugin == "undefined") {
902                /* FIXME: This should never happen. But why does it do? */
903                return false;
904        }
905        var obj = new plugin(this, args);
906        if (obj) {
907                var clone = {};
908                var info = plugin._pluginInfo;
909                for (var i in info)
910                        clone[i] = info[i];
911                clone.instance = obj;
912                clone.args = args;
913                this.plugins[plugin._pluginInfo.name] = clone;
914        } else
915                alert("Can't register plugin " + plugin.toString() + ".");
916};
917
918// Create the specified plugin and register it with this HTMLArea
919HTMLArea.prototype.registerPlugin = function() {
920        var plugin = arguments[0];
921        var args = [];
922        for (var i = 1; i < arguments.length; ++i)
923                args.push(arguments[i]);
924        this.registerPlugin2(plugin, args);
925};
926
927// static function that loads the required plugin and lang file, based on the
928// language loaded already for HTMLArea.  You better make sure that the plugin
929// _has_ that language, otherwise shit might happen ;-)
930HTMLArea.loadPlugin = function(pluginName) {
931        var dir = _editor_url + "plugins/" + pluginName;
932        var plugin = pluginName.replace(/([a-z])([A-Z])([a-z])/g,
933                                        function (str, l1, l2, l3) {
934                                                return l1 + "-" + l2.toLowerCase() + l3;
935                                        }).toLowerCase() + ".js";
936        var plugin_file = dir + "/" + plugin;
937        var plugin_lang = dir + "/lang/" + HTMLArea.I18N.lang + ".js";
938        HTMLArea._scripts.push(plugin_file, plugin_lang);
939        document.write("<script type='text/javascript' src='" + plugin_file + "'></script>");
940        document.write("<script type='text/javascript' src='" + plugin_lang + "'></script>");
941};
942
943HTMLArea.loadStyle = function(style, plugin) {
944        var url = _editor_url || '';
945        if (typeof plugin != "undefined") {
946                url += "plugins/" + plugin + "/";
947        }
948        url += style;
949        document.write("<style type='text/css'>@import url(" + url + ");</style>");
950};
951HTMLArea.loadStyle("htmlarea.css");
952
953/***************************************************
954 *  Category: EDITOR UTILITIES
955 ***************************************************/
956
957// The following function is a slight variation of the word cleaner code posted
958// by Weeezl (user @ InteractiveTools forums).
959HTMLArea.prototype._wordClean = function() {
960        var D = this.getInnerHTML();
961        if (D.indexOf('class=Mso') >= 0) {
962
963                // make one line
964                D = D.replace(/\r\n/g, ' ').
965                        replace(/\n/g, ' ').
966                        replace(/\r/g, ' ').
967                        replace(/\&nbsp\;/g,' ');
968
969                // keep tags, strip attributes
970                D = D.replace(/ class=[^\s|>]*/gi,'').
971                        //replace(/<p [^>]*TEXT-ALIGN: justify[^>]*>/gi,'<p align="justify">').
972                        replace(/ style=\"[^>]*\"/gi,'').
973                        replace(/ align=[^\s|>]*/gi,'');
974
975                //clean up tags
976                D = D.replace(/<b [^>]*>/gi,'<b>').
977                        replace(/<i [^>]*>/gi,'<i>').
978                        replace(/<li [^>]*>/gi,'<li>').
979                        replace(/<ul [^>]*>/gi,'<ul>');
980
981                // replace outdated tags
982                D = D.replace(/<b>/gi,'<strong>').
983                        replace(/<\/b>/gi,'</strong>');
984
985                // mozilla doesn't like <em> tags
986                D = D.replace(/<em>/gi,'<i>').
987                        replace(/<\/em>/gi,'</i>');
988
989                // kill unwanted tags
990                D = D.replace(/<\?xml:[^>]*>/g, '').       // Word xml
991                        replace(/<\/?st1:[^>]*>/g,'').     // Word SmartTags
992                        replace(/<\/?[a-z]\:[^>]*>/g,'').  // All other funny Word non-HTML stuff
993                        replace(/<\/?font[^>]*>/gi,'').    // Disable if you want to keep font formatting
994                        replace(/<\/?span[^>]*>/gi,' ').
995                        replace(/<\/?div[^>]*>/gi,' ').
996                        replace(/<\/?pre[^>]*>/gi,' ').
997                        replace(/<\/?h[1-6][^>]*>/gi,' ');
998
999                //remove empty tags
1000                //D = D.replace(/<strong><\/strong>/gi,'').
1001                //replace(/<i><\/i>/gi,'').
1002                //replace(/<P[^>]*><\/P>/gi,'');
1003
1004                // nuke double tags
1005                oldlen = D.length + 1;
1006                while(oldlen > D.length) {
1007                        oldlen = D.length;
1008                        // join us now and free the tags, we'll be free hackers, we'll be free... ;-)
1009                        D = D.replace(/<([a-z][a-z]*)> *<\/\1>/gi,' ').
1010                                replace(/<([a-z][a-z]*)> *<([a-z][^>]*)> *<\/\1>/gi,'<$2>');
1011                }
1012                D = D.replace(/<([a-z][a-z]*)><\1>/gi,'<$1>').
1013                        replace(/<\/([a-z][a-z]*)><\/\1>/gi,'<\/$1>');
1014
1015                // nuke double spaces
1016                D = D.replace(/  */gi,' ');
1017
1018                this.setHTML(D);
1019                this.updateToolbar();
1020        }
1021};
1022
1023HTMLArea.prototype.forceRedraw = function() {
1024        this._doc.body.style.visibility = "hidden";
1025        this._doc.body.style.visibility = "visible";
1026        // this._doc.body.innerHTML = this.getInnerHTML();
1027};
1028
1029// focuses the iframe window.  returns a reference to the editor document.
1030HTMLArea.prototype.focusEditor = function() {
1031        return this._doc;
1032        /*
1033        switch (this._editMode) {
1034            // notice the try { ... } catch block to avoid some rare exceptions in FireFox
1035            // (perhaps also in other Gecko browsers). Manual focus by user is required in
1036        // case of an error. Somebody has an idea?
1037            case "wysiwyg" : try { this._iframe.contentWindow.focus() } catch (e) {} break;
1038            case "textmode": try { this._textArea.focus() } catch (e) {} break;
1039            default        : alert("ERROR: mode " + this._editMode + " is not defined");
1040        }
1041        return this._doc;
1042        */
1043};
1044
1045// takes a snapshot of the current text (for undo)
1046HTMLArea.prototype._undoTakeSnapshot = function() {
1047        ++this._undoPos;
1048        if (this._undoPos >= this.config.undoSteps) {
1049                // remove the first element
1050                this._undoQueue.shift();
1051                --this._undoPos;
1052        }
1053        // use the fasted method (getInnerHTML);
1054        var take = true;
1055        var txt = this.getInnerHTML();
1056        if (this._undoPos > 0)
1057                take = (this._undoQueue[this._undoPos - 1] != txt);
1058        if (take) {
1059                this._undoQueue[this._undoPos] = txt;
1060        } else {
1061                this._undoPos--;
1062        }
1063};
1064
1065HTMLArea.prototype.undo = function() {
1066        if (this._undoPos > 0) {
1067                var txt = this._undoQueue[--this._undoPos];
1068                if (txt) this.setHTML(txt);
1069                else ++this._undoPos;
1070        }
1071};
1072
1073HTMLArea.prototype.redo = function() {
1074        if (this._undoPos < this._undoQueue.length - 1) {
1075                var txt = this._undoQueue[++this._undoPos];
1076                if (txt) this.setHTML(txt);
1077                else --this._undoPos;
1078        }
1079};
1080
1081// updates enabled/disable/active state of the toolbar elements
1082HTMLArea.prototype.updateToolbar = function(noStatus) {
1083        var doc = this._doc;
1084        var text = (this._editMode == "textmode");
1085        var ancestors = null;
1086        if (!text) {
1087                ancestors = this.getAllAncestors();
1088                if (this.config.statusBar && !noStatus) {
1089                        this._statusBarTree.innerHTML = HTMLArea.I18N.msg["Path"] + ": "; // clear
1090                        for (var i = ancestors.length; --i >= 0;) {
1091                                var el = ancestors[i];
1092                                if (!el) {
1093                                        // hell knows why we get here; this
1094                                        // could be a classic example of why
1095                                        // it's good to check for conditions
1096                                        // that are impossible to happen ;-)
1097                                        continue;
1098                                }
1099                                var a = document.createElement("a");
1100                                a.href = "#";
1101                                a.el = el;
1102                                a.editor = this;
1103                                a.onclick = function() {
1104                                        this.blur();
1105                                        this.editor.selectNodeContents(this.el);
1106                                        this.editor.updateToolbar(true);
1107                                        return false;
1108                                };
1109                                a.oncontextmenu = function() {
1110                                        // TODO: add context menu here
1111                                        this.blur();
1112                                        var info = "Inline style:\n\n";
1113                                        info += this.el.style.cssText.split(/;\s*/).join(";\n");
1114                                        alert(info);
1115                                        return false;
1116                                };
1117                                var txt = el.tagName.toLowerCase();
1118                                a.title = el.style.cssText;
1119                                if (el.id) {
1120                                        txt += "#" + el.id;
1121                                }
1122                                if (el.className) {
1123                                        txt += "." + el.className;
1124                                }
1125                                a.appendChild(document.createTextNode(txt));
1126                                this._statusBarTree.appendChild(a);
1127                                if (i != 0) {
1128                                        this._statusBarTree.appendChild(document.createTextNode(String.fromCharCode(0xbb)));
1129                                }
1130                        }
1131                }
1132        }
1133
1134        for (var i in this._toolbarObjects) {
1135                var btn = this._toolbarObjects[i];
1136                var cmd = i;
1137                var inContext = true;
1138                if (btn.context && !text) {
1139                        inContext = false;
1140                        var context = btn.context;
1141                        var attrs = [];
1142                        if (/(.*)\[(.*?)\]/.test(context)) {
1143                                context = RegExp.$1;
1144                                attrs = RegExp.$2.split(",");
1145                        }
1146                        context = context.toLowerCase();
1147                        var match = (context == "*");
1148                        for (var k in ancestors) {
1149                                if (!ancestors[k]) {
1150                                        // the impossible really happens.
1151                                        continue;
1152                                }
1153                                if (match || (ancestors[k].tagName.toLowerCase() == context)) {
1154                                        inContext = true;
1155                                        for (var ka in attrs) {
1156                                                if (!eval("ancestors[k]." + attrs[ka])) {
1157                                                        inContext = false;
1158                                                        break;
1159                                                }
1160                                        }
1161                                        if (inContext) {
1162                                                break;
1163                                        }
1164                                }
1165                        }
1166                }
1167                btn.state("enabled", (!text || btn.text) && inContext);
1168                if (typeof cmd == "function") {
1169                        continue;
1170                }
1171                // look-it-up in the custom dropdown boxes
1172                var dropdown = this.config.customSelects[cmd];
1173                if ((!text || btn.text) && (typeof dropdown != "undefined")) {
1174                        dropdown.refresh(this);
1175                        continue;
1176                }
1177                switch (cmd) {
1178                    case "fontname":
1179                    case "fontsize":
1180                    case "formatblock":
1181                        if (!text) try {
1182                                var value = ("" + doc.queryCommandValue(cmd)).toLowerCase();
1183                                if (!value) {
1184                                        // FIXME: what do we do here?
1185                                        break;
1186                                }
1187                                // HACK -- retrieve the config option for this
1188                                // combo box.  We rely on the fact that the
1189                                // variable in config has the same name as
1190                                // button name in the toolbar.
1191                                var options = this.config[cmd];
1192                                var k = 0;
1193                                // btn.element.selectedIndex = 0;
1194                                for (var j in options) {
1195                                        // FIXME: the following line is scary.
1196                                        if ((j.toLowerCase() == value) ||
1197                                            (options[j].substr(0, value.length).toLowerCase() == value)) {
1198                                                btn.element.selectedIndex = k;
1199                                                break;
1200                                        }
1201                                        ++k;
1202                                }
1203                        } catch(e) {};
1204                        break;
1205                    case "textindicator":
1206                        if (!text) {
1207                                try {with (btn.element.style) {
1208                                        backgroundColor = HTMLArea._makeColor(
1209                                                doc.queryCommandValue(HTMLArea.is_ie ? "backcolor" : "hilitecolor"));
1210                                        if (/transparent/i.test(backgroundColor)) {
1211                                                // Mozilla
1212                                                backgroundColor = HTMLArea._makeColor(doc.queryCommandValue("backcolor"));
1213                                        }
1214                                        color = HTMLArea._makeColor(doc.queryCommandValue("forecolor"));
1215                                        fontFamily = doc.queryCommandValue("fontname");
1216                                        fontWeight = doc.queryCommandState("bold") ? "bold" : "normal";
1217                                        fontStyle = doc.queryCommandState("italic") ? "italic" : "normal";
1218                                }} catch (e) {
1219                                        // alert(e + "\n\n" + cmd);
1220                                }
1221                        }
1222                        break;
1223                    case "htmlmode": btn.state("active", text); break;
1224                    case "lefttoright":
1225                    case "righttoleft":
1226                        var el = this.getParentElement();
1227                        while (el && !HTMLArea.isBlockElement(el))
1228                                el = el.parentNode;
1229                        if (el)
1230                                btn.state("active", (el.style.direction == ((cmd == "righttoleft") ? "rtl" : "ltr")));
1231                        break;
1232                    default:
1233                        cmd = cmd.replace(/(un)?orderedlist/i, "insert$1orderedlist");
1234                        try {
1235                                btn.state("active", (!text && doc.queryCommandState(cmd)));
1236                        } catch (e) {}
1237                }
1238        }
1239        // take undo snapshots
1240        if (this._customUndo && !this._timerUndo) {
1241                this._undoTakeSnapshot();
1242                var editor = this;
1243                this._timerUndo = setTimeout(function() {
1244                        editor._timerUndo = null;
1245                }, this.config.undoTimeout);
1246        }
1247
1248        // check if any plugins have registered refresh handlers
1249        for (var i in this.plugins) {
1250                var plugin = this.plugins[i].instance;
1251                if (typeof plugin.onUpdateToolbar == "function")
1252                        plugin.onUpdateToolbar();
1253        }
1254};
1255
1256/** Returns a node after which we can insert other nodes, in the current
1257 * selection.  The selection is removed.  It splits a text node, if needed.
1258 */
1259HTMLArea.prototype.insertNodeAtSelection = function(toBeInserted) {
1260        if (!HTMLArea.is_ie) {
1261                var sel = this._getSelection();
1262                var range = this._createRange(sel);
1263                // remove the current selection
1264                sel.removeAllRanges();
1265                range.deleteContents();
1266                var node = range.startContainer;
1267                var pos = range.startOffset;
1268                switch (node.nodeType) {
1269                    case 3: // Node.TEXT_NODE
1270                        // we have to split it at the caret position.
1271                        if (toBeInserted.nodeType == 3) {
1272                                // do optimized insertion
1273                                node.insertData(pos, toBeInserted.data);
1274                                range = this._createRange();
1275                                range.setEnd(node, pos + toBeInserted.length);
1276                                range.setStart(node, pos + toBeInserted.length);
1277                                sel.addRange(range);
1278                        } else {
1279                                node = node.splitText(pos);
1280                                var selnode = toBeInserted;
1281                                if (toBeInserted.nodeType == 11 /* Node.DOCUMENT_FRAGMENT_NODE */) {
1282                                        selnode = selnode.firstChild;
1283                                }
1284                                node.parentNode.insertBefore(toBeInserted, node);
1285                                this.selectNodeContents(selnode);
1286                                this.updateToolbar();
1287                        }
1288                        break;
1289                    case 1: // Node.ELEMENT_NODE
1290                        var selnode = toBeInserted;
1291                        if (toBeInserted.nodeType == 11 /* Node.DOCUMENT_FRAGMENT_NODE */) {
1292                                selnode = selnode.firstChild;
1293                        }
1294                        node.insertBefore(toBeInserted, node.childNodes[pos]);
1295                        this.selectNodeContents(selnode);
1296                        this.updateToolbar();
1297                        break;
1298                }
1299        } else {
1300                return null;    // this function not yet used for IE <FIXME>
1301        }
1302};
1303
1304// Returns the deepest node that contains both endpoints of the selection.
1305HTMLArea.prototype.getParentElement = function() {
1306        var sel = this._getSelection();
1307        var range = this._createRange(sel);
1308        if (HTMLArea.is_ie) {
1309                switch (sel.type) {
1310                    case "Text":
1311                    case "None":
1312                        // It seems that even for selection of type "None",
1313                        // there _is_ a parent element and it's value is not
1314                        // only correct, but very important to us.  MSIE is
1315                        // certainly the buggiest browser in the world and I
1316                        // wonder, God, how can Earth stand it?
1317                        return range.parentElement();
1318                    case "Control":
1319                        return range.item(0);
1320                    default:
1321                        return this._doc.body;
1322                }
1323        } else try {
1324                var p = range.commonAncestorContainer;
1325                if (!range.collapsed && range.startContainer == range.endContainer &&
1326                    range.startOffset - range.endOffset <= 1 && range.startContainer.hasChildNodes())
1327                        p = range.startContainer.childNodes[range.startOffset];
1328                /*
1329                alert(range.startContainer + ":" + range.startOffset + "\n" +
1330                      range.endContainer + ":" + range.endOffset);
1331                */
1332                while (p.nodeType == 3) {
1333                        p = p.parentNode;
1334                }
1335                return p;
1336        } catch (e) {
1337                return null;
1338        }
1339};
1340
1341// Returns an array with all the ancestor nodes of the selection.
1342HTMLArea.prototype.getAllAncestors = function() {
1343        var p = this.getParentElement();
1344        var a = [];
1345        while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
1346                a.push(p);
1347                p = p.parentNode;
1348        }
1349        a.push(this._doc.body);
1350        return a;
1351};
1352
1353// Selects the contents inside the given node
1354HTMLArea.prototype.selectNodeContents = function(node, pos) {
1355        this.focusEditor();
1356        this.forceRedraw();
1357        var range;
1358        var collapsed = (typeof pos != "undefined");
1359        if (HTMLArea.is_ie) {
1360                range = this._doc.body.createTextRange();
1361                range.moveToElementText(node);
1362                (collapsed) && range.collapse(pos);
1363                range.select();
1364        } else {
1365                var sel = this._getSelection();
1366                range = this._doc.createRange();
1367                range.selectNodeContents(node);
1368                (collapsed) && range.collapse(pos);
1369                sel.removeAllRanges();
1370                sel.addRange(range);
1371        }
1372};
1373
1374/** Call this function to insert HTML code at the current position.  It deletes
1375 * the selection, if any.
1376 */
1377HTMLArea.prototype.insertHTML = function(html) {
1378        var sel = this._getSelection();
1379        var range = this._createRange(sel);
1380        if (HTMLArea.is_ie) {
1381                range.pasteHTML(html);
1382        } else {
1383                // construct a new document fragment with the given HTML
1384                var fragment = this._doc.createDocumentFragment();
1385                var div = this._doc.createElement("div");
1386                div.innerHTML = html;
1387                while (div.firstChild) {
1388                        // the following call also removes the node from div
1389                        fragment.appendChild(div.firstChild);
1390                }
1391                // this also removes the selection
1392                var node = this.insertNodeAtSelection(fragment);
1393        }
1394};
1395
1396/**
1397 *  Call this function to surround the existing HTML code in the selection with
1398 *  your tags.  FIXME: buggy!  This function will be deprecated "soon".
1399 */
1400HTMLArea.prototype.surroundHTML = function(startTag, endTag) {
1401        var html = this.getSelectedHTML();
1402        // the following also deletes the selection
1403        this.insertHTML(startTag + html + endTag);
1404};
1405
1406/// Retrieve the selected block
1407HTMLArea.prototype.getSelectedHTML = function() {
1408        var sel = this._getSelection();
1409        var range = this._createRange(sel);
1410        var existing = null;
1411        if (HTMLArea.is_ie) {
1412                existing = range.htmlText;
1413        } else {
1414                existing = HTMLArea.getHTML(range.cloneContents(), false, this);
1415        }
1416        return existing;
1417};
1418
1419/// Return true if we have some selection
1420HTMLArea.prototype.hasSelectedText = function() {
1421        // FIXME: come _on_ mishoo, you can do better than this ;-)
1422        return this.getSelectedHTML() != '';
1423};
1424
1425HTMLArea.prototype._createLink = function(link) {
1426        var editor = this;
1427        var outparam = null;
1428        if (typeof link == "undefined") {
1429                link = this.getParentElement();
1430                if (link && !/^a$/i.test(link.tagName))
1431                        link = null;
1432        }
1433        if (link) outparam = {
1434                f_href   : HTMLArea.is_ie ? editor.stripBaseURL(link.href) : link.getAttribute("href"),
1435                f_title  : link.title,
1436                f_target : link.target
1437        };
1438        this._popupDialog("link.html", function(param) {
1439                if (!param)
1440                        return false;
1441                var a = link;
1442                if (!a) try {
1443                        editor._doc.execCommand("createlink", false, param.f_href);
1444                        a = editor.getParentElement();
1445                        var sel = editor._getSelection();
1446                        var range = editor._createRange(sel);
1447                        if (!HTMLArea.is_ie) {
1448                                a = range.startContainer;
1449                                if (!/^a$/i.test(a.tagName)) {
1450                                        a = a.nextSibling;
1451                                        if (a == null)
1452                                                a = range.startContainer.parentNode;
1453                                }
1454                        }
1455                } catch(e) {}
1456                else {
1457                        var href = param.f_href.trim();
1458                        editor.selectNodeContents(a);
1459                        if (href == "") {
1460                                editor._doc.execCommand("unlink", false, null);
1461                                editor.updateToolbar();
1462                                return false;
1463                        }
1464                        else {
1465                                a.href = href;
1466                        }
1467                }
1468                if (!(a && /^a$/i.test(a.tagName)))
1469                        return false;
1470                a.target = param.f_target.trim();
1471                a.title = param.f_title.trim();
1472                editor.selectNodeContents(a);
1473                editor.updateToolbar();
1474        }, outparam);
1475};
1476
1477// Called when the user clicks on "InsertImage" button.  If an image is already
1478// there, it will just modify it's properties.
1479HTMLArea.prototype._insertImage = function(image) {
1480        var editor = this;      // for nested functions
1481        var outparam = null;
1482        if (typeof image == "undefined") {
1483                image = this.getParentElement();
1484                if (image && !/^img$/i.test(image.tagName))
1485                        image = null;
1486        }
1487        if (image) outparam = {
1488                f_url    : HTMLArea.is_ie ? editor.stripBaseURL(image.src) : image.getAttribute("src"),
1489                f_alt    : image.alt,
1490                f_border : image.border,
1491                f_align  : image.align,
1492                f_vert   : image.vspace,
1493                f_horiz  : image.hspace
1494        };
1495        this._popupDialog("insert_image.html", function(param) {
1496                if (!param) {   // user must have pressed Cancel
1497                        return false;
1498                }
1499                var img = image;
1500                if (!img) {
1501                        var sel = editor._getSelection();
1502                        var range = editor._createRange(sel);
1503                        editor._doc.execCommand("insertimage", false, param.f_url);
1504                        if (HTMLArea.is_ie) {
1505                                img = range.parentElement();
1506                                // wonder if this works...
1507                                if (img.tagName.toLowerCase() != "img") {
1508                                        img = img.previousSibling;
1509                                }
1510                        } else {
1511                                img = range.startContainer.previousSibling;
1512                        }
1513                } else {
1514                        img.src = param.f_url;
1515                }
1516
1517                for (field in param) {
1518                        var value = param[field];
1519                        switch (field) {
1520                            case "f_alt"    : img.alt    = value; break;
1521                            case "f_border" : img.border = parseInt(value || "0"); break;
1522                            case "f_align"  : img.align  = value; break;
1523                            case "f_vert"   : img.vspace = parseInt(value || "0"); break;
1524                            case "f_horiz"  : img.hspace = parseInt(value || "0"); break;
1525                        }
1526                }
1527        }, outparam);
1528};
1529
1530// Called when the user clicks the Insert Table button
1531HTMLArea.prototype._insertTable = function() {
1532        var sel = this._getSelection();
1533        var range = this._createRange(sel);
1534        var editor = this;      // for nested functions
1535        this._popupDialog("insert_table.html", function(param) {
1536                if (!param) {   // user must have pressed Cancel
1537                        return false;
1538                }
1539                var doc = editor._doc;
1540                // create the table element
1541                var table = doc.createElement("table");
1542                // assign the given arguments
1543
1544                for (var field in param) {
1545                        var value = param[field];
1546                        if (!value) {
1547                                continue;
1548                        }
1549                        switch (field) {
1550                            case "f_width"   : table.style.width = value + param["f_unit"]; break;
1551                            case "f_align"   : table.align       = value; break;
1552                            case "f_border"  : table.border      = parseInt(value); break;
1553                            case "f_spacing" : table.cellSpacing = parseInt(value); break;
1554                            case "f_padding" : table.cellPadding = parseInt(value); break;
1555                        }
1556                }
1557                var tbody = doc.createElement("tbody");
1558                table.appendChild(tbody);
1559                for (var i = 0; i < param["f_rows"]; ++i) {
1560                        var tr = doc.createElement("tr");
1561                        tbody.appendChild(tr);
1562                        for (var j = 0; j < param["f_cols"]; ++j) {
1563                                var td = doc.createElement("td");
1564                                tr.appendChild(td);
1565                                // Mozilla likes to see something inside the cell.
1566                                (HTMLArea.is_gecko) && td.appendChild(doc.createElement("br"));
1567                        }
1568                }
1569                if (HTMLArea.is_ie) {
1570                        range.pasteHTML(table.outerHTML);
1571                } else {
1572                        // insert the table
1573                        editor.insertNodeAtSelection(table);
1574                }
1575                return true;
1576        }, null);
1577};
1578
1579/***************************************************
1580 *  Category: EVENT HANDLERS
1581 ***************************************************/
1582
1583// el is reference to the SELECT object
1584// txt is the name of the select field, as in config.toolbar
1585HTMLArea.prototype._comboSelected = function(el, txt) {
1586        this.focusEditor();
1587        var value = el.options[el.selectedIndex].value;
1588        switch (txt) {
1589            case "fontname":
1590            case "fontsize": this.execCommand(txt, false, value); break;
1591            case "formatblock":
1592                (HTMLArea.is_ie) && (value = "<" + value + ">");
1593                this.execCommand(txt, false, value);
1594                break;
1595            default:
1596                // try to look it up in the registered dropdowns
1597                var dropdown = this.config.customSelects[txt];
1598                if (typeof dropdown != "undefined") {
1599                        dropdown.action(this);
1600                } else {
1601                        alert("FIXME: combo box " + txt + " not implemented");
1602                }
1603        }
1604};
1605
1606// the execCommand function (intercepts some commands and replaces them with
1607// our own implementation)
1608HTMLArea.prototype.execCommand = function(cmdID, UI, param) {
1609        var editor = this;      // for nested functions
1610        this.focusEditor();
1611        cmdID = cmdID.toLowerCase();
1612        switch (cmdID) {
1613            case "htmlmode" : this.setMode(); break;
1614            case "hilitecolor":
1615                (HTMLArea.is_ie) && (cmdID = "backcolor");
1616            case "forecolor":
1617                this._popupDialog("select_color.html", function(color) {
1618                        if (color) { // selection not canceled
1619                                editor._doc.execCommand(cmdID, false, "#" + color);
1620                        }
1621                }, HTMLArea._colorToRgb(this._doc.queryCommandValue(cmdID)));
1622                break;
1623            case "createlink":
1624                this._createLink();
1625                break;
1626            case "popupeditor":
1627                // this object will be passed to the newly opened window
1628                HTMLArea._object = this;
1629                if (HTMLArea.is_ie) {
1630                        //if (confirm(HTMLArea.I18N.msg["IE-sucks-full-screen"]))
1631                        {
1632                                window.open(this.popupURL("fullscreen.html"), "ha_fullscreen",
1633                                            "toolbar=no,location=no,directories=no,status=no,menubar=no," +
1634                                            "scrollbars=no,resizable=yes,width=640,height=480");
1635                        }
1636                } else {
1637                        window.open(this.popupURL("fullscreen.html"), "ha_fullscreen",
1638                                    "toolbar=no,menubar=no,personalbar=no,width=640,height=480," +
1639                                    "scrollbars=no,resizable=yes");
1640                }
1641                break;
1642            case "undo":
1643            case "redo":
1644                if (this._customUndo)
1645                        this[cmdID]();
1646                else
1647                        this._doc.execCommand(cmdID, UI, param);
1648                break;
1649            case "inserttable": this._insertTable(); break;
1650            case "insertimage": this._insertImage(); break;
1651            case "about"    : this._popupDialog("about.html", null, this); break;
1652            case "showhelp" : window.open(_editor_url + "reference.html", "ha_help"); break;
1653
1654            case "killword": this._wordClean(); break;
1655
1656            case "cut":
1657            case "copy":
1658            case "paste":
1659                try {
1660                        if (this.config.killWordOnPaste)
1661                                this._wordClean();
1662                        this._doc.execCommand(cmdID, UI, param);
1663                } catch (e) {
1664                        if (HTMLArea.is_gecko) {
1665                                if (typeof HTMLArea.I18N.msg["Moz-Clipboard"] == "undefined") {
1666                                        HTMLArea.I18N.msg["Moz-Clipboard"] =
1667                                                "Unprivileged scripts cannot access Cut/Copy/Paste programatically " +
1668                                                "for security reasons.  Click OK to see a technical note at mozilla.org " +
1669                                                "which shows you how to allow a script to access the clipboard.\n\n" +
1670                                                "[FIXME: please translate this message in your language definition file.]";
1671                                }
1672                                if (confirm(HTMLArea.I18N.msg["Moz-Clipboard"]))
1673                                        window.open("http://mozilla.org/editor/midasdemo/securityprefs.html");
1674                        }
1675                }
1676                break;
1677            case "lefttoright":
1678            case "righttoleft":
1679                var dir = (cmdID == "righttoleft") ? "rtl" : "ltr";
1680                var el = this.getParentElement();
1681                while (el && !HTMLArea.isBlockElement(el))
1682                        el = el.parentNode;
1683                if (el) {
1684                        if (el.style.direction == dir)
1685                                el.style.direction = "";
1686                        else
1687                                el.style.direction = dir;
1688                }
1689                break;
1690            default: this._doc.execCommand(cmdID, UI, param);
1691        }
1692        this.updateToolbar();
1693        return false;
1694};
1695
1696/** A generic event handler for things that happen in the IFRAME's document.
1697 * This function also handles key bindings. */
1698HTMLArea.prototype._editorEvent = function(ev) {
1699        var editor = this;
1700        var keyEvent = (HTMLArea.is_ie && ev.type == "keydown") || (ev.type == "keypress");
1701
1702        if (keyEvent) {
1703                for (var i in editor.plugins) {
1704                        var plugin = editor.plugins[i].instance;
1705                        if (typeof plugin.onKeyPress == "function") plugin.onKeyPress(ev);
1706                }
1707        }
1708        if (keyEvent && ev.ctrlKey && !ev.altKey) {
1709                var sel = null;
1710                var range = null;
1711                var key = String.fromCharCode(HTMLArea.is_ie ? ev.keyCode : ev.charCode).toLowerCase();
1712                var cmd = null;
1713                var value = null;
1714                switch (key) {
1715                    case 'a':
1716                        if (!HTMLArea.is_ie) {
1717                                // KEY select all
1718                                sel = this._getSelection();
1719                                sel.removeAllRanges();
1720                                range = this._createRange();
1721                                range.selectNodeContents(this._doc.body);
1722                                sel.addRange(range);
1723                                HTMLArea._stopEvent(ev);
1724                        }
1725                        break;
1726
1727                        // simple key commands follow
1728
1729                    case 'b': cmd = "bold"; break;
1730                    case 'i': cmd = "italic"; break;
1731                    case 'u': cmd = "underline"; break;
1732                    case 's': cmd = "strikethrough"; break;
1733                    case 'l': cmd = "justifyleft"; break;
1734                    case 'e': cmd = "justifycenter"; break;
1735                    case 'r': cmd = "justifyright"; break;
1736                    case 'j': cmd = "justifyfull"; break;
1737                    case 'z': cmd = "undo"; break;
1738                    case 'y': cmd = "redo"; break;
1739                    //case 'v': cmd = "paste"; break;
1740
1741                    case '0': cmd = "killword"; break;
1742
1743                        // headings
1744                    case '1':
1745                    case '2':
1746                    case '3':
1747                    case '4':
1748                    case '5':
1749                    case '6':
1750                        cmd = "formatblock";
1751                        value = "h" + key;
1752                        if (HTMLArea.is_ie) {
1753                                value = "<" + value + ">";
1754                        }
1755                        break;
1756                }
1757                if (cmd) {
1758                        // execute simple command
1759                        this.execCommand(cmd, false, value);
1760                        HTMLArea._stopEvent(ev);
1761                }
1762        }
1763       
1764        else if (keyEvent) {
1765                // other keys here
1766                switch (ev.keyCode) {
1767                    case 13: // KEY enter
1768                        if (HTMLArea.is_ie) {   
1769                                HTMLArea._stopEvent(ev);
1770                                this.insertHTML("<br>&nbsp;");
1771                        }
1772                        break;
1773                }
1774        }
1775       
1776        // update the toolbar state after some time
1777        if (editor._timerToolbar) {
1778                clearTimeout(editor._timerToolbar);
1779        }
1780        editor._timerToolbar = setTimeout(function() {
1781                editor.updateToolbar();
1782                editor._timerToolbar = null;
1783        }, 50);
1784};
1785
1786// retrieve the HTML
1787HTMLArea.prototype.getHTML = function() {
1788        switch (this._editMode) {
1789            case "wysiwyg"  :
1790                if (!this.config.fullPage) {
1791                        return HTMLArea.getHTML(this._doc.body, false, this);
1792                } else
1793                        return this.doctype + "\n" + HTMLArea.getHTML(this._doc.documentElement, true, this);
1794            case "textmode" : return this._textArea.value;
1795            default         : alert("Mode <" + mode + "> not defined!");
1796        }
1797        return false;
1798};
1799
1800// retrieve the HTML (fastest version, but uses innerHTML)
1801HTMLArea.prototype.getInnerHTML = function() {
1802        switch (this._editMode) {
1803            case "wysiwyg"  :
1804                if (!this.config.fullPage)
1805                        return this._doc.body.innerHTML;
1806                else
1807                        return this.doctype + "\n" + this._doc.documentElement.innerHTML;
1808            case "textmode" : return this._textArea.value;
1809            default         : alert("Mode <" + mode + "> not defined!");
1810        }
1811        return false;
1812};
1813
1814// completely change the HTML inside
1815HTMLArea.prototype.setHTML = function(html) {
1816        switch (this._editMode) {
1817            case "wysiwyg"  :
1818                if (!this.config.fullPage)
1819                        this._doc.body.innerHTML = html;
1820                else
1821                        // this._doc.documentElement.innerHTML = html;
1822                        this._doc.body.innerHTML = html;
1823                break;
1824            case "textmode" : this._textArea.value = html; break;
1825            default         : alert("Mode <" + mode + "> not defined!");
1826        }
1827        return false;
1828};
1829
1830// sets the given doctype (useful when config.fullPage is true)
1831HTMLArea.prototype.setDoctype = function(doctype) {
1832        this.doctype = doctype;
1833};
1834
1835/***************************************************
1836 *  Category: UTILITY FUNCTIONS
1837 ***************************************************/
1838
1839// browser identification
1840
1841HTMLArea.agt = navigator.userAgent.toLowerCase();
1842HTMLArea.is_ie     = ((HTMLArea.agt.indexOf("msie") != -1) && (HTMLArea.agt.indexOf("opera") == -1));
1843HTMLArea.is_opera  = (HTMLArea.agt.indexOf("opera") != -1);
1844HTMLArea.is_mac    = (HTMLArea.agt.indexOf("mac") != -1);
1845HTMLArea.is_mac_ie = (HTMLArea.is_ie && HTMLArea.is_mac);
1846HTMLArea.is_win_ie = (HTMLArea.is_ie && !HTMLArea.is_mac);
1847HTMLArea.is_gecko  = (navigator.product == "Gecko");
1848
1849// variable used to pass the object to the popup editor window.
1850HTMLArea._object = null;
1851
1852// function that returns a clone of the given object
1853HTMLArea.cloneObject = function(obj) {
1854        var newObj = new Object;
1855
1856        // check for array objects
1857        if (obj.constructor.toString().indexOf("function Array(") == 1) {
1858                newObj = obj.constructor();
1859        }
1860
1861        // check for function objects (as usual, IE is fucked up)
1862        if (obj.constructor.toString().indexOf("function Function(") == 1) {
1863                newObj = obj; // just copy reference to it
1864        } else for (var n in obj) {
1865                var node = obj[n];
1866                if (typeof node == 'object') { newObj[n] = HTMLArea.cloneObject(node); }
1867                else                         { newObj[n] = node; }
1868        }
1869
1870        return newObj;
1871};
1872
1873// FIXME!!! this should return false for IE < 5.5
1874HTMLArea.checkSupportedBrowser = function() {
1875        if (HTMLArea.is_gecko) {
1876                if (navigator.productSub < 20021201) {
1877                        alert("You need at least Mozilla-1.3 Alpha.\n" +
1878                              "Sorry, your Gecko is not supported.");
1879                        return false;
1880                }
1881                if (navigator.productSub < 20030210) {
1882                        alert("Mozilla < 1.3 Beta is not supported!\n" +
1883                              "I'll try, though, but it might not work.");
1884                }
1885        }
1886        return HTMLArea.is_gecko || HTMLArea.is_ie;
1887};
1888
1889// selection & ranges
1890
1891// returns the current selection object
1892HTMLArea.prototype._getSelection = function() {
1893        if (HTMLArea.is_ie) {
1894                return this._doc.selection;
1895        } else {
1896                return this._iframe.contentWindow.getSelection();
1897        }
1898};
1899
1900// returns a range for the current selection
1901HTMLArea.prototype._createRange = function(sel) {
1902        if (HTMLArea.is_ie) {
1903                return sel.createRange();
1904        } else {
1905                this.focusEditor();
1906                if (typeof sel != "undefined") {
1907                        try {
1908                                return sel.getRangeAt(0);
1909                        } catch(e) {
1910                                return this._doc.createRange();
1911                        }
1912                } else {
1913                        return this._doc.createRange();
1914                }
1915        }
1916};
1917
1918// event handling
1919
1920HTMLArea._addEvent = function(el, evname, func) {
1921        if (HTMLArea.is_ie) {
1922                el.attachEvent("on" + evname, func);
1923        } else {
1924                el.addEventListener(evname, func, true);
1925        }
1926};
1927
1928HTMLArea._addEvents = function(el, evs, func) {
1929        for (var i in evs) {
1930                HTMLArea._addEvent(el, evs[i], func);
1931        }
1932};
1933
1934HTMLArea._removeEvent = function(el, evname, func) {
1935        if (HTMLArea.is_ie) {
1936                el.detachEvent("on" + evname, func);
1937        } else {
1938                el.removeEventListener(evname, func, true);
1939        }
1940};
1941
1942HTMLArea._removeEvents = function(el, evs, func) {
1943        for (var i in evs) {
1944                HTMLArea._removeEvent(el, evs[i], func);
1945        }
1946};
1947
1948HTMLArea._stopEvent = function(ev) {
1949        if (HTMLArea.is_ie) {
1950                ev.cancelBubble = true;
1951                ev.returnValue = false;
1952        } else {
1953                ev.preventDefault();
1954                ev.stopPropagation();
1955        }
1956};
1957
1958HTMLArea._removeClass = function(el, className) {
1959        if (!(el && el.className)) {
1960                return;
1961        }
1962        var cls = el.className.split(" ");
1963        var ar = new Array();
1964        for (var i = cls.length; i > 0;) {
1965                if (cls[--i] != className) {
1966                        ar[ar.length] = cls[i];
1967                }
1968        }
1969        el.className = ar.join(" ");
1970};
1971
1972HTMLArea._addClass = function(el, className) {
1973        // remove the class first, if already there
1974        HTMLArea._removeClass(el, className);
1975        el.className += " " + className;
1976};
1977
1978HTMLArea._hasClass = function(el, className) {
1979        if (!(el && el.className)) {
1980                return false;
1981        }
1982        var cls = el.className.split(" ");
1983        for (var i = cls.length; i > 0;) {
1984                if (cls[--i] == className) {
1985                        return true;
1986                }
1987        }
1988        return false;
1989};
1990
1991HTMLArea.isBlockElement = function(el) {
1992        var blockTags = " body form textarea fieldset ul ol dl li div " +
1993                "p h1 h2 h3 h4 h5 h6 quote pre table thead " +
1994                "tbody tfoot tr td iframe address ";
1995        return (blockTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
1996};
1997
1998HTMLArea.needsClosingTag = function(el) {
1999        var closingTags = " head script style div span tr td tbody table em strong font a title ";
2000        return (closingTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
2001};
2002
2003// performs HTML encoding of some given string
2004HTMLArea.htmlEncode = function(str) {
2005        // we don't need regexp for that, but.. so be it for now.
2006        str = str.replace(/&/ig, "&amp;");
2007        str = str.replace(/</ig, "&lt;");
2008        str = str.replace(/>/ig, "&gt;");
2009        str = str.replace(/\x22/ig, "&quot;");
2010        // \x22 means '"' -- we use hex reprezentation so that we don't disturb
2011        // JS compressors (well, at least mine fails.. ;)
2012        return str;
2013};
2014
2015// Retrieves the HTML code from the given node.  This is a replacement for
2016// getting innerHTML, using standard DOM calls.
2017HTMLArea.getHTML = function(root, outputRoot, editor) {
2018        var html = "";
2019        switch (root.nodeType) {
2020            case 1: // Node.ELEMENT_NODE
2021            case 11: // Node.DOCUMENT_FRAGMENT_NODE
2022                var closed;
2023                var i;
2024                var root_tag = (root.nodeType == 1) ? root.tagName.toLowerCase() : '';
2025                if (HTMLArea.is_ie && root_tag == "head") {
2026                        if (outputRoot)
2027                                html += "<head>";
2028                        // lowercasize
2029                        var save_multiline = RegExp.multiline;
2030                        RegExp.multiline = true;
2031                        var txt = root.innerHTML.replace(HTMLArea.RE_tagName, function(str, p1, p2) {
2032                                return p1 + p2.toLowerCase();
2033                        });
2034                        RegExp.multiline = save_multiline;
2035                        html += txt;
2036                        if (outputRoot)
2037                                html += "</head>";
2038                        break;
2039                } else if (outputRoot) {
2040                        closed = (!(root.hasChildNodes() || HTMLArea.needsClosingTag(root)));
2041                        html = "<" + root.tagName.toLowerCase();
2042                        var attrs = root.attributes;
2043                        for (i = 0; i < attrs.length; ++i) {
2044                                var a = attrs.item(i);
2045                                if (!a.specified) {
2046                                        continue;
2047                                }
2048                                var name = a.nodeName.toLowerCase();
2049                                if (/_moz_editor_bogus_node/.test(name)) {
2050                                        html = "";
2051                                        break;
2052                                }
2053                                if (/_moz|contenteditable|_msh/.test(name)) {
2054                                        // avoid certain attributes
2055                                        continue;
2056                                }
2057                                var value;
2058                                if (name != "style") {
2059                                        // IE5.5 reports 25 when cellSpacing is
2060                                        // 1; other values might be doomed too.
2061                                        // For this reason we extract the
2062                                        // values directly from the root node.
2063                                        // I'm starting to HATE JavaScript
2064                                        // development.  Browser differences
2065                                        // suck.
2066                                        //
2067                                        // Using Gecko the values of href and src are converted to absolute links
2068                                        // unless we get them using nodeValue()
2069                                        if (typeof root[a.nodeName] != "undefined" && name != "href" && name != "src") {
2070                                                value = root[a.nodeName];
2071                                        } else {
2072                                                value = a.nodeValue;
2073                                                // IE seems not willing to return the original values - it converts to absolute
2074                                                // links using a.nodeValue, a.value, a.stringValue, root.getAttribute("href")
2075                                                // So we have to strip the baseurl manually -/
2076                                                if (HTMLArea.is_ie && (name == "href" || name == "src")) {
2077                                                        value = editor.stripBaseURL(value);
2078                                                }
2079                                        }
2080                                } else { // IE fails to put style in attributes list
2081                                        // FIXME: cssText reported by IE is UPPERCASE
2082                                        value = root.style.cssText;
2083                                }
2084                                if (/(_moz|^$)/.test(value)) {
2085                                        // Mozilla reports some special tags
2086                                        // here; we don't need them.
2087                                        continue;
2088                                }
2089                                html += " " + name + '="' + value + '"';
2090                        }
2091                        if (html != "") {
2092                                html += closed ? " />" : ">";
2093                        }
2094                }
2095                for (i = root.firstChild; i; i = i.nextSibling) {
2096                        html += HTMLArea.getHTML(i, true, editor);
2097                }
2098                if (outputRoot && !closed) {
2099                        html += "</" + root.tagName.toLowerCase() + ">";
2100                }
2101                break;
2102            case 3: // Node.TEXT_NODE
2103                // If a text node is alone in an element and all spaces, replace it with an non breaking one
2104                // This partially undoes the damage done by moz, which translates '&nbsp;'s into spaces in the data element
2105                if ( !root.previousSibling && !root.nextSibling && root.data.match(/^\s*$/i) ) html = '&nbsp;';
2106                else html = /^script|style$/i.test(root.parentNode.tagName) ? root.data : HTMLArea.htmlEncode(root.data);
2107                break;
2108            case 4: // Node.CDATA_SECTION_NODE
2109                // FIXME: it seems we never get here, but I believe we should..
2110                //        maybe a browser problem?--CDATA sections are converted to plain text nodes and normalized
2111                // CDATA sections should go "as is" without further encoding
2112                html = "<![CDATA[" + root.data + "]]>";
2113                break;
2114            case 8: // Node.COMMENT_NODE
2115                html = "<!--" + root.data + "-->";
2116                break;          // skip comments, for now.
2117        }
2118        return html;
2119};
2120
2121HTMLArea.prototype.stripBaseURL = function(string) {
2122        var baseurl = this.config.baseURL;
2123
2124        // strip to last directory in case baseurl points to a file
2125        baseurl = baseurl.replace(/[^\/]+$/, '');
2126        var basere = new RegExp(baseurl);
2127        string = string.replace(basere, "");
2128
2129        // strip host-part of URL which is added by MSIE to links relative to server root
2130        baseurl = baseurl.replace(/^(https?:\/\/[^\/]+)(.*)$/, '$1');
2131        basere = new RegExp(baseurl);
2132        return string.replace(basere, "");
2133};
2134
2135String.prototype.trim = function() {
2136        a = this.replace(/^\s+/, '');
2137        return a.replace(/\s+$/, '');
2138};
2139
2140// creates a rgb-style color from a number
2141HTMLArea._makeColor = function(v) {
2142        if (typeof v != "number") {
2143                // already in rgb (hopefully); IE doesn't get here.
2144                return v;
2145        }
2146        // IE sends number; convert to rgb.
2147        var r = v & 0xFF;
2148        var g = (v >> 8) & 0xFF;
2149        var b = (v >> 16) & 0xFF;
2150        return "rgb(" + r + "," + g + "," + b + ")";
2151};
2152
2153// returns hexadecimal color representation from a number or a rgb-style color.
2154HTMLArea._colorToRgb = function(v) {
2155        if (!v)
2156                return '';
2157
2158        // returns the hex representation of one byte (2 digits)
2159        function hex(d) {
2160                return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
2161        };
2162
2163        if (typeof v == "number") {
2164                // we're talking to IE here
2165                var r = v & 0xFF;
2166                var g = (v >> 8) & 0xFF;
2167                var b = (v >> 16) & 0xFF;
2168                return "#" + hex(r) + hex(g) + hex(b);
2169        }
2170
2171        if (v.substr(0, 3) == "rgb") {
2172                // in rgb(...) form -- Mozilla
2173                var re = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/;
2174                if (v.match(re)) {
2175                        var r = parseInt(RegExp.$1);
2176                        var g = parseInt(RegExp.$2);
2177                        var b = parseInt(RegExp.$3);
2178                        return "#" + hex(r) + hex(g) + hex(b);
2179                }
2180                // doesn't match RE?!  maybe uses percentages or float numbers
2181                // -- FIXME: not yet implemented.
2182                return null;
2183        }
2184
2185        if (v.substr(0, 1) == "#") {
2186                // already hex rgb (hopefully :D )
2187                return v;
2188        }
2189
2190        // if everything else fails ;)
2191        return null;
2192};
2193
2194// modal dialogs for Mozilla (for IE we're using the showModalDialog() call).
2195
2196// receives an URL to the popup dialog and a function that receives one value;
2197// this function will get called after the dialog is closed, with the return
2198// value of the dialog.
2199HTMLArea.prototype._popupDialog = function(url, action, init) {
2200        Dialog(this.popupURL(url), action, init);
2201};
2202
2203// paths
2204
2205HTMLArea.prototype.imgURL = function(file, plugin) {
2206        if (typeof plugin == "undefined")
2207                return _editor_url + file;
2208        else
2209                return _editor_url + "plugins/" + plugin + "/img/" + file;
2210};
2211
2212HTMLArea.prototype.popupURL = function(file) {
2213        var url = "";
2214        if (file.match(/^plugin:\/\/(.*?)\/(.*)/)) {
2215                var plugin = RegExp.$1;
2216                var popup = RegExp.$2;
2217                if (!/\.html$/.test(popup))
2218                        popup += ".html";
2219                url = _editor_url + "plugins/" + plugin + "/popups/" + popup;
2220        } else
2221                url = _editor_url + this.config.popupURL + file;
2222        return url;
2223};
2224
2225/**
2226 * FIX: Internet Explorer returns an item having the _name_ equal to the given
2227 * id, even if it's not having any id.  This way it can return a different form
2228 * field even if it's not a textarea.  This workarounds the problem by
2229 * specifically looking to search only elements having a certain tag name.
2230 */
2231HTMLArea.getElementById = function(tag, id) {
2232        var el, i, objs = document.getElementsByTagName(tag);
2233        for (i = objs.length; --i >= 0 && (el = objs[i]);)
2234                if (el.id == id)
2235                        return el;
2236        return null;
2237};
2238
2239
2240
2241// EOF
2242// Local variables: //
2243// c-basic-offset:8 //
2244// indent-tabs-mode:t //
2245// End: //
Note: See TracBrowser for help on using the repository browser.