source: trunk/htmlarea.js @ 1

Last change on this file since 1 was 1, checked in by xinha, 13 years ago

Bootstrap

File size: 127.9 KB
Line 
1// htmlArea v3.0 - Copyright (c) 2003-2004 dynarch.com
2//                               2002-2003 interactivetools.com, inc.
3// This copyright notice MUST stay intact for use (see license.txt).
4//
5// A free WYSIWYG editor replacement for <textarea> fields.
6// For full source code and docs, visit http://www.interactivetools.com/
7//
8// Version 3.0 developed by Mihai Bazon.
9//   http://dynarch.com/mishoo/
10//
11// $Id: htmlarea.js,v 1.95 2004/09/17 11:54:24 mishoo Exp $
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
28var __htmlareas = [ ];
29
30// browser identification
31HTMLArea.agt = navigator.userAgent.toLowerCase();
32HTMLArea.is_ie     = ((HTMLArea.agt.indexOf("msie") != -1) && (HTMLArea.agt.indexOf("opera") == -1));
33HTMLArea.is_opera  = (HTMLArea.agt.indexOf("opera") != -1);
34HTMLArea.is_mac    = (HTMLArea.agt.indexOf("mac") != -1);
35HTMLArea.is_mac_ie = (HTMLArea.is_ie && HTMLArea.is_mac);
36HTMLArea.is_win_ie = (HTMLArea.is_ie && !HTMLArea.is_mac);
37HTMLArea.is_gecko  = (navigator.product == "Gecko");
38
39// Creates a new HTMLArea object.  Tries to replace the textarea with the given
40// ID with it.
41function HTMLArea(textarea, config) {
42  if (HTMLArea.checkSupportedBrowser()) {
43    if (typeof config == "undefined") {
44      this.config = new HTMLArea.Config();
45    } else {
46      this.config = config;
47    }
48    this._htmlArea = null;
49    this._textArea = textarea;
50    this._editMode = "wysiwyg";
51    this.plugins = {};
52    this._timerToolbar = null;
53    this._timerUndo = null;
54    this._undoQueue = new Array(this.config.undoSteps);
55    this._undoPos = -1;
56    this._customUndo = true;
57    this._mdoc = document; // cache the document, we need it in plugins
58    this.doctype = '';
59    this.__htmlarea_id_num = __htmlareas.length;
60    __htmlareas[this.__htmlarea_id_num] = this;
61
62    this._notifyListeners = { };
63
64    // Panels
65    var panels = this._panels =
66    {
67      right:
68      {
69        on: true,
70        div:    document.createElement('div'),
71        panels: [ ]
72      },
73      left:
74      {
75        on: true,
76        div:    document.createElement('div'),
77        panels: [ ]
78      },
79      top:
80      {
81        on: true,
82        div:    document.createElement('div'),
83        panels: [ ]
84      },
85      bottom:
86      {
87        on: true,
88        div:    document.createElement('div'),
89        panels: [ ]
90      }
91    };
92
93    for(var i in panels)
94    {
95      panels[i].div.className = 'panels ' + i;
96    }
97  }
98};
99
100HTMLArea.onload = function(){};
101HTMLArea._scripts = [];
102
103HTMLArea.loadScript = function(url, plugin) {
104  if (plugin)
105    url = HTMLArea.getPluginDir(plugin) + '/' + url;
106  this._scripts.push(url);
107};
108
109
110HTMLArea.init = function() {
111
112  var head = document.getElementsByTagName("head")[0];
113  var current = 0;
114  var savetitle = document.title;
115  var evt = HTMLArea.is_ie ? "onreadystatechange" : "onload";
116  function loadNextScript() {
117    if (current > 0 && HTMLArea.is_ie &&
118        !/loaded|complete/.test(window.event.srcElement.readyState))
119      return;
120    if (current < HTMLArea._scripts.length) {
121      var url = HTMLArea._scripts[current++];
122      document.title = "[HTMLArea: loading script " + current + "/" + HTMLArea._scripts.length + "]";
123      var script = document.createElement("script");
124      script.type = "text/javascript";
125      script.src = url;
126      script[evt] = loadNextScript;
127      head.appendChild(script);
128    } else {
129      document.title = savetitle;
130      HTMLArea.onload();
131    }
132  };
133  loadNextScript();
134};
135
136HTMLArea.loadScript(_editor_url + "dialog.js");
137HTMLArea.loadScript(_editor_url + "inline-dialog.js");
138HTMLArea.loadScript(_editor_url + "popupwin.js");
139HTMLArea.loadScript(_editor_url + "lang/" + _editor_lang + ".js");
140
141// cache some regexps
142HTMLArea.RE_tagName = /(<\/|<)\s*([^ \t\n>]+)/ig;
143HTMLArea.RE_doctype = /(<!doctype((.|\n)*?)>)\n?/i;
144HTMLArea.RE_head    = /<head>((.|\n)*?)<\/head>/i;
145HTMLArea.RE_body    = /<body>((.|\n)*?)<\/body>/i;
146HTMLArea.RE_Specials = /([\/\^$*+?.()|{}[\]])/g;
147
148HTMLArea.Config = function () {
149  var cfg = this;
150  this.version = "3.0";
151
152  this.width = "auto";
153  this.height = "auto";
154
155  // enable creation of a status bar?
156  this.statusBar = true;
157
158  // intercept ^V and use the HTMLArea paste command
159  // If false, then passes ^V through to browser editor widget
160  this.htmlareaPaste = false;
161
162  // maximum size of the undo queue
163  this.undoSteps = 20;
164
165  // the time interval at which undo samples are taken
166  this.undoTimeout = 500;       // 1/2 sec.
167
168  // the next parameter specifies whether the toolbar should be included
169  // in the size or not.
170  this.sizeIncludesToolbar = true;
171
172  // if true then HTMLArea will retrieve the full HTML, starting with the
173  // <HTML> tag.
174  this.fullPage = false;
175
176  // style included in the iframe document
177  this.pageStyle = "";
178
179  // external stylesheets to load (REFERENCE THESE ABSOLUTELY)
180  this.pageStyleSheets = [ ];
181
182  // specify a base href for relative links
183  this.baseHref  = null;
184
185  // we can strip the base href out of relative links to leave them relative, reason for this
186  //   especially if you don't specify a baseHref is that mozilla at least (& IE ?) will prefix
187  //   the baseHref to any relative links to make them absolute, which isn't what you want most the time.
188  this.stripBaseHref = true;
189
190  // and we can strip the url of the editor page from named links (eg <a href="#top">...</a>)
191  //  reason for this is that mozilla at least (and IE ?) prefixes location.href to any
192  //  that don't have a url prefixing them
193  this.stripSelfNamedAnchors = true;
194
195  // sometimes we want to be able to replace some string in the html comng in and going out
196  //  so that in the editor we use the "internal" string, and outside and in the source view
197  //  we use the "external" string  this is useful for say making special codes for
198  //  your absolute links, your external string might be some special code, say "{server_url}"
199  //  an you say that the internal represenattion of that should be http://your.server/
200  this.specialReplacements = { }; // { 'external_string' : 'internal_string' }
201
202  // set to true if you want Word code to be cleaned upon Paste
203  this.killWordOnPaste = true;
204
205  // enable the 'Target' field in the Make Link dialog
206  this.makeLinkShowsTarget = true;
207
208  // BaseURL included in the iframe document
209  this.baseURL = document.baseURI || document.URL;
210  if (this.baseURL && this.baseURL.match(/(.*)\/([^\/]+)/))
211    this.baseURL = RegExp.$1 + "/";
212
213  // URL-s
214  this.imgURL = "images/";
215  this.popupURL = "popups/";
216
217  // remove tags (these have to be a regexp, or null if this functionality is not desired)
218  this.htmlRemoveTags = null;
219
220  /** CUSTOMIZING THE TOOLBAR
221   * -------------------------
222   *
223   * It is recommended that you customize the toolbar contents in an
224   * external file (i.e. the one calling HTMLArea) and leave this one
225   * unchanged.  That's because when we (InteractiveTools.com) release a
226   * new official version, it's less likely that you will have problems
227   * upgrading HTMLArea.
228   */
229  this.toolbar =
230  [
231    ["popupeditor","separator"],
232    ["formatblock","fontname","fontsize","bold","italic","underline","strikethrough","separator"],
233    ["forecolor","hilitecolor","textindicator","separator"],
234    ["subscript","superscript"],
235    ["linebreak","justifyleft","justifycenter","justifyright","justifyfull","separator"],
236    ["insertorderedlist","insertunorderedlist","outdent","indent","separator"],
237    ["inserthorizontalrule","createlink","insertimage","inserttable","separator"],
238    ["killword","removeformat","toggleborders","lefttoright", "righttoleft", "separator","htmlmode","about"]
239  ];
240
241  // Width of the "Right Side" panel, when present
242  this.panel_dimensions =
243  {
244    left:   '200px', // Width
245    right:  '200px',
246    top:    '100px', // Height
247    bottom: '100px'
248  }
249
250  /*
251  this.toolbar = [
252    [ "fontname", "space",
253      "fontsize", "space",
254      "formatblock", "space",
255      "bold", "italic", "underline", "strikethrough", "separator",
256      "subscript", "superscript", "separator",
257      "copy", "cut", "paste", "space", "undo", "redo", "space", "removeformat", "killword" ],
258
259    [ "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
260      "lefttoright", "righttoleft", "separator",
261      "orderedlist", "unorderedlist", "outdent", "indent", "separator",
262      "forecolor", "hilitecolor", "separator",
263      "inserthorizontalrule", "createlink", "insertimage", "inserttable", "toggleborders", "htmlmode", "separator",
264      "popupeditor", "separator", "showhelp", "about" ]
265  ];
266  */
267
268  this.fontname = {
269    "&mdash; font &mdash;":         '',
270    "Arial":       'arial,helvetica,sans-serif',
271    "Courier New":         'courier new,courier,monospace',
272    "Georgia":     'georgia,times new roman,times,serif',
273    "Tahoma":      'tahoma,arial,helvetica,sans-serif',
274    "Times New Roman": 'times new roman,times,serif',
275    "Verdana":     'verdana,arial,helvetica,sans-serif',
276    "impact":      'impact',
277    "WingDings":           'wingdings'
278  };
279
280  this.fontsize = {
281    "&mdash; size &mdash;"  : "",
282    "1 (8 pt)" : "1",
283    "2 (10 pt)": "2",
284    "3 (12 pt)": "3",
285    "4 (14 pt)": "4",
286    "5 (18 pt)": "5",
287    "6 (24 pt)": "6",
288    "7 (36 pt)": "7"
289  };
290
291  this.formatblock = {
292    "&mdash; format &mdash;"  : "",
293    "Heading 1": "h1",
294    "Heading 2": "h2",
295    "Heading 3": "h3",
296    "Heading 4": "h4",
297    "Heading 5": "h5",
298    "Heading 6": "h6",
299    "Normal"   : "p",
300    "Address"  : "address",
301    "Formatted": "pre"
302  };
303
304  this.customSelects = {};
305
306  function cut_copy_paste(e, cmd, obj) {
307    e.execCommand(cmd);
308  };
309
310  this.debug = true;
311
312  // ADDING CUSTOM BUTTONS: please read below!
313  // format of the btnList elements is "ID: [ ToolTip, Icon, Enabled in text mode?, ACTION ]"
314  //    - ID: unique ID for the button.  If the button calls document.execCommand
315  //        it's wise to give it the same name as the called command.
316  //    - ACTION: function that gets called when the button is clicked.
317  //              it has the following prototype:
318  //                 function(editor, buttonName)
319  //              - editor is the HTMLArea object that triggered the call
320  //              - buttonName is the ID of the clicked button
321  //              These 2 parameters makes it possible for you to use the same
322  //              handler for more HTMLArea objects or for more different buttons.
323  //    - ToolTip: default tooltip, for cases when it is not defined in the -lang- file (HTMLArea.I18N)
324  //    - Icon: path to an icon image file for the button
325  //            OR; you can use an 18x18 block of a larger image by supllying an array
326  //            that has three elemtents, the first is the larger image, the second is the column
327  //            the third is the row.  The ros and columns numbering starts at 0 but there is
328  //            a header row and header column which have numbering to make life easier.
329  //            See images/buttons_main.gif to see how it's done.
330  //    - Enabled in text mode: if false the button gets disabled for text-only mode; otherwise enabled all the time.
331  this.btnList = {
332    /*
333    bold:          [ "Bold", "ed_format_bold.gif", false, function(e) {e.execCommand("bold");} ],
334    italic:        [ "Italic", "ed_format_italic.gif", false, function(e) {e.execCommand("italic");} ],
335    underline:     [ "Underline", "ed_format_underline.gif", false, function(e) {e.execCommand("underline");} ],
336    strikethrough: [ "Strikethrough", "ed_format_strike.gif", false, function(e) {e.execCommand("strikethrough");} ],
337    subscript:     [ "Subscript", "ed_format_sub.gif", false, function(e) {e.execCommand("subscript");} ],
338    superscript:   [ "Superscript", "ed_format_sup.gif", false, function(e) {e.execCommand("superscript");} ],
339    justifyleft: [ "Justify Left", "ed_align_left.gif", false, function(e) {e.execCommand("justifyleft");} ],
340    justifycenter: [ "Justify Center", "ed_align_center.gif", false, function(e){e.execCommand("justifycenter");}],
341    justifyright: [ "Justify Right", "ed_align_right.gif", false, function(e) {e.execCommand("justifyright");} ],
342    justifyfull: [ "Justify Full", "ed_align_justify.gif", false, function(e) {e.execCommand("justifyfull");} ],
343
344    orderedlist: [ "Ordered List", "ed_list_num.gif", false, function(e) {e.execCommand("insertorderedlist");} ],
345    unorderedlist: [ "Bulleted List", "ed_list_bullet.gif", false, function(e) {e.execCommand("insertunorderedlist");} ],
346    insertorderedlist: [ "Ordered List", "ed_list_num.gif", false, function(e) {e.execCommand("insertorderedlist");} ],
347    insertunorderedlist: [ "Bulleted List", "ed_list_bullet.gif", false, function(e) {e.execCommand("insertunorderedlist");} ],
348
349    outdent: [ "Decrease Indent", "ed_indent_less.gif", false, function(e) {e.execCommand("outdent");} ],
350    indent: [ "Increase Indent", "ed_indent_more.gif", false, function(e) {e.execCommand("indent");} ],
351    forecolor: [ "Font Color", "ed_color_fg.gif", false, function(e) {e.execCommand("forecolor");} ],
352    hilitecolor: [ "Background Color", "ed_color_bg.gif", false, function(e) {e.execCommand("hilitecolor");} ],
353
354    undo: [ "Undoes your last action", "ed_undo.gif", false, function(e) {e.execCommand("undo");} ],
355    redo: [ "Redoes your last action", "ed_redo.gif", false, function(e) {e.execCommand("redo");} ],
356    cut: [ "Cut selection", "ed_cut.gif", false, cut_copy_paste ],
357    copy: [ "Copy selection", "ed_copy.gif", false, cut_copy_paste ],
358    paste: [ "Paste from clipboard", "ed_paste.gif", false, cut_copy_paste ],
359
360    */
361    bold:          [ "Bold",   ["ed_buttons_main.gif",3,2], false, function(e) {e.execCommand("bold");} ],
362    italic:        [ "Italic", ["ed_buttons_main.gif",2,2], false, function(e) {e.execCommand("italic");} ],
363    underline:     [ "Underline", ["ed_buttons_main.gif",2,0], false, function(e) {e.execCommand("underline");} ],
364    strikethrough: [ "Strikethrough", ["ed_buttons_main.gif",3,0], false, function(e) {e.execCommand("strikethrough");} ],
365    subscript:     [ "Subscript", ["ed_buttons_main.gif",3,1], false, function(e) {e.execCommand("subscript");} ],
366    superscript:   [ "Superscript", ["ed_buttons_main.gif",2,1], false, function(e) {e.execCommand("superscript");} ],
367
368    justifyleft:   [ "Justify Left", ["ed_buttons_main.gif",0,0], false, function(e) {e.execCommand("justifyleft");} ],
369    justifycenter: [ "Justify Center", ["ed_buttons_main.gif",1,1], false, function(e){e.execCommand("justifycenter");}],
370    justifyright: [ "Justify Right", ["ed_buttons_main.gif",1,0], false, function(e) {e.execCommand("justifyright");} ],
371    justifyfull: [ "Justify Full", ["ed_buttons_main.gif",0,1], false, function(e) {e.execCommand("justifyfull");} ],
372
373
374    orderedlist: [ "Ordered List", ["ed_buttons_main.gif",0,3], false, function(e) {e.execCommand("insertorderedlist");} ],
375    unorderedlist: [ "Bulleted List", ["ed_buttons_main.gif",1,3], false, function(e) {e.execCommand("insertunorderedlist");} ],
376    insertorderedlist: [ "Ordered List", ["ed_buttons_main.gif",0,3], false, function(e) {e.execCommand("insertorderedlist");} ],
377    insertunorderedlist: [ "Bulleted List", ["ed_buttons_main.gif",1,3], false, function(e) {e.execCommand("insertunorderedlist");} ],
378
379    outdent: [ "Decrease Indent", ["ed_buttons_main.gif",1,2], false, function(e) {e.execCommand("outdent");} ],
380    indent: [ "Increase Indent",["ed_buttons_main.gif",0,2], false, function(e) {e.execCommand("indent");} ],
381    forecolor: [ "Font Color", ["ed_buttons_main.gif",3,3], false, function(e) {e.execCommand("forecolor");} ],
382    hilitecolor: [ "Background Color", ["ed_buttons_main.gif",2,3], false, function(e) {e.execCommand("hilitecolor");} ],
383
384    undo: [ "Undoes your last action", ["ed_buttons_main.gif",4,2], false, function(e) {e.execCommand("undo");} ],
385    redo: [ "Redoes your last action", ["ed_buttons_main.gif",5,2], false, function(e) {e.execCommand("redo");} ],
386    cut: [ "Cut selection", ["ed_buttons_main.gif",5,0], false, cut_copy_paste ],
387    copy: [ "Copy selection", ["ed_buttons_main.gif",4,0], false, cut_copy_paste ],
388    paste: [ "Paste from clipboard", ["ed_buttons_main.gif",4,1], false, cut_copy_paste ],
389
390
391
392    inserthorizontalrule: [ "Horizontal Rule", ["ed_buttons_main.gif",6,0], false, function(e) {e.execCommand("inserthorizontalrule");} ],
393    createlink: [ "Insert Web Link", ["ed_buttons_main.gif",6,1], false, function(e) {e._createLink();} ],
394    insertimage: [ "Insert/Modify Image", ["ed_buttons_main.gif",6,3], false, function(e) {e.execCommand("insertimage");} ],
395    inserttable: [ "Insert Table", ["ed_buttons_main.gif",6,2], false, function(e) {e.execCommand("inserttable");} ],
396
397
398    htmlmode: [ "Toggle HTML Source", ["ed_buttons_main.gif",7,0], true, function(e) {e.execCommand("htmlmode");} ],
399    toggleborders: [ "Toggle Borders", ["ed_buttons_main.gif",7,2], false, function(e) { e._toggleBorders() } ],
400    print:         [ "Print document", ["ed_buttons_main.gif",8,1], false, function(e) {e._iframe.contentWindow.print();} ],
401    popupeditor: [ "Enlarge Editor", "fullscreen_maximize.gif", true,
402      function(e, objname, obj)
403      {
404        e.execCommand("popupeditor");
405      } ],
406    about: [ "About this editor", ["ed_buttons_main.gif",8,2], true, function(e) {e.execCommand("about");} ],
407    showhelp: [ "Help using editor", ["ed_buttons_main.gif",9,2], true, function(e) {e.execCommand("showhelp");} ],
408
409    splitblock:    [ "Split Block", "ed_splitblock.gif", false, function(e) {e._splitBlock();} ],
410    lefttoright: [ "Direction left to right", ["ed_buttons_main.gif",0,4], false, function(e) {e.execCommand("lefttoright");} ],
411    righttoleft: [ "Direction right to left", ["ed_buttons_main.gif",1,4], false, function(e) {e.execCommand("righttoleft");} ],
412
413    wordclean:     [ "MS Word Cleaner", ["ed_buttons_main.gif",5,3], false, function(e) {e._wordClean();} ],
414    clearfonts:    [ "Clear Inline Font Specifications", ["ed_buttons_main.gif",5,4], false, function(e) {e._clearFonts();} ],
415    removeformat:  [ "Remove formatting", ["ed_buttons_main.gif",4,4], false, function(e) {e.execCommand("removeformat");} ],
416    killword:      [ "Clear MSOffice tags", ["ed_buttons_main.gif",4,3], false, function(e) {e.execCommand("killword");} ]
417
418  };
419  /* ADDING CUSTOM BUTTONS
420   * ---------------------
421   *
422   * It is recommended that you add the custom buttons in an external
423   * file and leave this one unchanged.  That's because when we
424   * (InteractiveTools.com) release a new official version, it's less
425   * likely that you will have problems upgrading HTMLArea.
426   *
427   * Example on how to add a custom button when you construct the HTMLArea:
428   *
429   *   var editor = new HTMLArea("your_text_area_id");
430   *   var cfg = editor.config; // this is the default configuration
431   *   cfg.btnList["my-hilite"] =
432   *    [ function(editor) { editor.surroundHTML('<span style="background:yellow">', '</span>'); }, // action
433   *      "Highlight selection", // tooltip
434   *      "my_hilite.gif", // image
435   *      false // disabled in text mode
436   *    ];
437   *   cfg.toolbar.push(["linebreak", "my-hilite"]); // add the new button to the toolbar
438   *
439   * An alternate (also more convenient and recommended) way to
440   * accomplish this is to use the registerButton function below.
441   */
442  // initialize tooltips from the I18N module and generate correct image path
443  for (var i in this.btnList) {
444    var btn = this.btnList[i];
445    if(typeof btn[1] != 'string')
446    {
447      btn[1][0] = _editor_url + this.imgURL + btn[1][0];
448    }
449    else
450    {
451      btn[1] = _editor_url + this.imgURL + btn[1];
452    }
453    try
454    {
455      if (typeof HTMLArea.I18N.tooltips[i] != "undefined")
456      {
457        btn[0] = HTMLArea.I18N.tooltips[i];
458      }
459    }
460    catch(e) { }
461  }
462};
463
464/** Helper function: register a new button with the configuration.  It can be
465 * called with all 5 arguments, or with only one (first one).  When called with
466 * only one argument it must be an object with the following properties: id,
467 * tooltip, image, textMode, action.  Examples:
468 *
469 * 1. config.registerButton("my-hilite", "Hilite text", "my-hilite.gif", false, function(editor) {...});
470 * 2. config.registerButton({
471 *      id       : "my-hilite",      // the ID of your button
472 *      tooltip  : "Hilite text",    // the tooltip
473 *      image    : "my-hilite.gif",  // image to be displayed in the toolbar
474 *      textMode : false,            // disabled in text mode
475 *      action   : function(editor) { // called when the button is clicked
476 *                   editor.surroundHTML('<span class="hilite">', '</span>');
477 *                 },
478 *      context  : "p"               // will be disabled if outside a <p> element
479 *    });
480 */
481HTMLArea.Config.prototype.registerButton = function(id, tooltip, image, textMode, action, context) {
482  var the_id;
483  if (typeof id == "string") {
484    the_id = id;
485  } else if (typeof id == "object") {
486    the_id = id.id;
487  } else {
488    alert("ERROR [HTMLArea.Config::registerButton]:\ninvalid arguments");
489    return false;
490  }
491  // check for existing id
492  if (typeof this.customSelects[the_id] != "undefined") {
493    // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA dropdown with the same ID already exists.");
494  }
495  if (typeof this.btnList[the_id] != "undefined") {
496    // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA button with the same ID already exists.");
497  }
498  switch (typeof id) {
499      case "string": this.btnList[id] = [ tooltip, image, textMode, action, context ]; break;
500      case "object": this.btnList[id.id] = [ id.tooltip, id.image, id.textMode, id.action, id.context ]; break;
501  }
502};
503
504HTMLArea.prototype.registerPanel = function(side, object)
505{
506  if(!side) side = 'right';
507  var panel = this.addPanel(side);
508  if(object)
509  {
510    object.drawPanelIn(panel);
511  }
512}
513
514/** The following helper function registers a dropdown box with the editor
515 * configuration.  You still have to add it to the toolbar, same as with the
516 * buttons.  Call it like this:
517 *
518 * FIXME: add example
519 */
520HTMLArea.Config.prototype.registerDropdown = function(object) {
521  // check for existing id
522  if (typeof this.customSelects[object.id] != "undefined") {
523    // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA dropdown with the same ID already exists.");
524  }
525  if (typeof this.btnList[object.id] != "undefined") {
526    // alert("WARNING [HTMLArea.Config::registerDropdown]:\nA button with the same ID already exists.");
527  }
528  this.customSelects[object.id] = object;
529};
530
531/** Call this function to remove some buttons/drop-down boxes from the toolbar.
532 * Pass as the only parameter a string containing button/drop-down names
533 * delimited by spaces.  Note that the string should also begin with a space
534 * and end with a space.  Example:
535 *
536 *   config.hideSomeButtons(" fontname fontsize textindicator ");
537 *
538 * It's useful because it's easier to remove stuff from the defaul toolbar than
539 * create a brand new toolbar ;-)
540 */
541HTMLArea.Config.prototype.hideSomeButtons = function(remove) {
542  var toolbar = this.toolbar;
543  for (var i = toolbar.length; --i >= 0;) {
544    var line = toolbar[i];
545    for (var j = line.length; --j >= 0; ) {
546      if (remove.indexOf(" " + line[j] + " ") >= 0) {
547        var len = 1;
548        if (/separator|space/.test(line[j + 1])) {
549          len = 2;
550        }
551        line.splice(j, len);
552      }
553    }
554  }
555};
556
557/** Helper function: replace all TEXTAREA-s in the document with HTMLArea-s. */
558HTMLArea.replaceAll = function(config) {
559  var tas = document.getElementsByTagName("textarea");
560  for (var i = tas.length; i > 0; (new HTMLArea(tas[--i], config)).generate());
561};
562
563/** Helper function: replaces the TEXTAREA with the given ID with HTMLArea. */
564HTMLArea.replace = function(id, config) {
565  var ta = HTMLArea.getElementById("textarea", id);
566  return ta ? (new HTMLArea(ta, config)).generate() : null;
567};
568
569// Creates the toolbar and appends it to the _htmlarea
570HTMLArea.prototype._createToolbar = function () {
571  var editor = this;    // to access this in nested functions
572
573  var toolbar = document.createElement("div");
574  this._toolbar = toolbar;
575  toolbar.className = "toolbar";
576  toolbar.unselectable = "1";
577
578  var tb_row = null;
579  var tb_objects = new Object();
580  this._toolbarObjects = tb_objects;
581
582  // creates a new line in the toolbar
583  function newLine() {
584    var table = document.createElement("table");
585    table.border = "0px";
586    table.cellSpacing = "0px";
587    table.cellPadding = "0px";
588    toolbar.appendChild(table);
589    // TBODY is required for IE, otherwise you don't see anything
590    // in the TABLE.
591    var tb_body = document.createElement("tbody");
592    table.appendChild(tb_body);
593    tb_row = document.createElement("tr");
594    tb_body.appendChild(tb_row);
595  }; // END of function: newLine
596  // init first line
597  newLine();
598
599  // updates the state of a toolbar element.  This function is member of
600  // a toolbar element object (unnamed objects created by createButton or
601  // createSelect functions below).
602  function setButtonStatus(id, newval) {
603    var oldval = this[id];
604    var el = this.element;
605    if (oldval != newval) {
606      switch (id) {
607          case "enabled":
608        if (newval) {
609          HTMLArea._removeClass(el, "buttonDisabled");
610          el.disabled = false;
611        } else {
612          HTMLArea._addClass(el, "buttonDisabled");
613          el.disabled = true;
614        }
615        break;
616          case "active":
617        if (newval) {
618          HTMLArea._addClass(el, "buttonPressed");
619        } else {
620          HTMLArea._removeClass(el, "buttonPressed");
621        }
622        break;
623      }
624      this[id] = newval;
625    }
626  }; // END of function: setButtonStatus
627
628  // this function will handle creation of combo boxes.  Receives as
629  // parameter the name of a button as defined in the toolBar config.
630  // This function is called from createButton, above, if the given "txt"
631  // doesn't match a button.
632  function createSelect(txt) {
633    var options = null;
634    var el = null;
635    var cmd = null;
636    var customSelects = editor.config.customSelects;
637    var context = null;
638    var tooltip = "";
639    switch (txt) {
640        case "fontsize":
641        case "fontname":
642        case "formatblock":
643      // the following line retrieves the correct
644      // configuration option because the variable name
645      // inside the Config object is named the same as the
646      // button/select in the toolbar.  For instance, if txt
647      // == "formatblock" we retrieve config.formatblock (or
648      // a different way to write it in JS is
649      // config["formatblock"].
650      options = editor.config[txt];
651      cmd = txt;
652      break;
653        default:
654      // try to fetch it from the list of registered selects
655      cmd = txt;
656      var dropdown = customSelects[cmd];
657      if (typeof dropdown != "undefined") {
658        options = dropdown.options;
659        context = dropdown.context;
660        if (typeof dropdown.tooltip != "undefined") {
661          tooltip = dropdown.tooltip;
662        }
663      } else {
664        alert("ERROR [createSelect]:\nCan't find the requested dropdown definition");
665      }
666      break;
667    }
668    if (options) {
669      el = document.createElement("select");
670      el.title = tooltip;
671      var obj = {
672        name    : txt, // field name
673        element : el,   // the UI element (SELECT)
674        enabled : true, // is it enabled?
675        text    : false, // enabled in text mode?
676        cmd     : cmd, // command ID
677        state   : setButtonStatus, // for changing state
678        context : context
679      };
680      tb_objects[txt] = obj;
681      for (var i in options) {
682        var op = document.createElement("option");
683        op.innerHTML = i;
684        op.value = options[i];
685        el.appendChild(op);
686      }
687      HTMLArea._addEvent(el, "change", function () {
688        editor._comboSelected(el, txt);
689      });
690    }
691    return el;
692  }; // END of function: createSelect
693
694  // appends a new button to toolbar
695  function createButton(txt) {
696    // the element that will be created
697    var el = null;
698    var btn = null;
699    switch (txt) {
700        case "separator":
701      el = document.createElement("div");
702      el.className = "separator";
703      break;
704        case "space":
705      el = document.createElement("div");
706      el.className = "space";
707      break;
708        case "linebreak":
709      newLine();
710      return false;
711        case "textindicator":
712      el = document.createElement("div");
713      el.appendChild(document.createTextNode("A"));
714      el.className = "indicator";
715      el.title = HTMLArea.I18N.tooltips.textindicator;
716      var obj = {
717        name    : txt, // the button name (i.e. 'bold')
718        element : el, // the UI element (DIV)
719        enabled : true, // is it enabled?
720        active  : false, // is it pressed?
721        text    : false, // enabled in text mode?
722        cmd     : "textindicator", // the command ID
723        state   : setButtonStatus // for changing state
724      };
725      tb_objects[txt] = obj;
726      break;
727        default:
728      btn = editor.config.btnList[txt];
729    }
730    if (!el && btn) {
731      el = document.createElement("a");
732      el.style.display = 'block';
733      el.href = 'javascript:void(0)';
734      el.style.textDecoration = 'none';
735      el.title = btn[0];
736      el.className = "button";
737      // let's just pretend we have a button object, and
738      // assign all the needed information to it.
739      var obj = {
740        name    : txt, // the button name (i.e. 'bold')
741        element : el, // the UI element (DIV)
742        enabled : true, // is it enabled?
743        active  : false, // is it pressed?
744        text    : btn[2], // enabled in text mode?
745        cmd     : btn[3], // the command ID
746        state   : setButtonStatus, // for changing state
747        context : btn[4] || null // enabled in a certain context?
748      };
749      tb_objects[txt] = obj;
750      // handlers to emulate nice flat toolbar buttons
751      /* -- This is now handled by a :hover pseudo class in htmlarea.css
752      HTMLArea._addEvent(el, "mouseover", function () {
753        if (obj.enabled) {
754          HTMLArea._addClass(el, "buttonHover");
755        }
756      });
757      */
758      HTMLArea._addEvent(el, "mouseout", function () {
759        if (obj.enabled) with (HTMLArea) {
760          //_removeClass(el, "buttonHover");
761          _removeClass(el, "buttonActive");
762          (obj.active) && _addClass(el, "buttonPressed");
763        }
764      });
765
766      HTMLArea._addEvent(el, "mousedown", function (ev) {
767        if (obj.enabled) with (HTMLArea) {
768          _addClass(el, "buttonActive");
769          _removeClass(el, "buttonPressed");
770          _stopEvent(is_ie ? window.event : ev);
771        }
772      });
773      // when clicked, do the following:
774      HTMLArea._addEvent(el, "click", function (ev) {
775        if (obj.enabled) with (HTMLArea) {
776          _removeClass(el, "buttonActive");
777          //_removeClass(el, "buttonHover");
778          if(HTMLArea.is_gecko)
779          {
780            editor.activateEditor();
781          }
782          obj.cmd(editor, obj.name, obj);
783          _stopEvent(is_ie ? window.event : ev);
784        }
785      });
786
787      var i_contain = null;
788      if(HTMLArea.is_ie && ((!document.compatMode) || (document.compatMode && document.compatMode == "BackCompat")))
789      {
790        i_contain = document.createElement('span');
791      }
792      else
793      {
794        i_contain = document.createElement('div');
795        i_contain.style.position = 'relative';
796      }
797
798      i_contain.style.overflow = 'hidden';
799      i_contain.style.width = "18px";
800      i_contain.style.height = "18px";
801
802      var img = document.createElement("img");
803      if(typeof btn[1] == 'string')
804      {
805        img.src = btn[1];
806        img.style.width = "18px";
807        img.style.height = "18px";
808      }
809      else
810      {
811        img.src = btn[1][0];
812        img.style.position = 'relative';
813        img.style.top  = btn[1][2] ? ('-' + (18 * (btn[1][2] + 1)) + 'px') : '-18px';
814        img.style.left = btn[1][1] ? ('-' + (18 * (btn[1][1] + 1)) + 'px') : '-18px';
815      }
816      i_contain.appendChild(img);
817      el.appendChild(i_contain);
818
819      obj.imgel = img;
820      obj.swapImage = function(newimg)
821      {
822        if(typeof newimg != 'string')
823        {
824          img.src = newimg[0];
825          img.style.position = 'relative';
826          img.style.top  = newimg[2] ? ('-' + (18 * (newimg[2] + 1)) + 'px') : '-18px';
827          img.style.left = newimg[1] ? ('-' + (18 * (newimg[1] + 1)) + 'px') : '-18px';
828        }
829        else
830        {
831          obj.imgel.src = newimg;
832          img.style.top = '0px';
833          img.style.left = '0px';
834        }
835      }
836
837    } else if (!el) {
838      el = createSelect(txt);
839    }
840    if (el) {
841      var tb_cell = document.createElement("td");
842      tb_row.appendChild(tb_cell);
843      tb_cell.appendChild(el);
844    } else {
845      alert("FIXME: Unknown toolbar item: " + txt);
846    }
847    return el;
848  };
849
850  var first = true;
851  for (var i = 0; i < this.config.toolbar.length; ++i) {
852    if (!first) {
853      // createButton("linebreak");
854    } else {
855      first = false;
856    }
857    var group = this.config.toolbar[i];
858    for (var j = 0; j < group.length; ++j) {
859      var code = group[j];
860      if (/^([IT])\[(.*?)\]/.test(code)) {
861        // special case, create text label
862        var l7ed = RegExp.$1 == "I"; // localized?
863        var label = RegExp.$2;
864        if (l7ed) {
865          label = HTMLArea.I18N.custom[label];
866        }
867        var tb_cell = document.createElement("td");
868        tb_row.appendChild(tb_cell);
869        tb_cell.className = "label";
870        tb_cell.innerHTML = label;
871      } else {
872        createButton(code);
873      }
874    }
875  }
876
877  this._htmlArea.appendChild(toolbar);
878};
879
880HTMLArea.prototype._createStatusBar = function() {
881  var statusbar = document.createElement("div");
882  statusbar.className = "statusBar";
883  this._htmlArea.appendChild(statusbar);
884  this._statusBar = statusbar;
885  // statusbar.appendChild(document.createTextNode(HTMLArea.I18N.msg["Path"] + ": "));
886  // creates a holder for the path view
887  div = document.createElement("span");
888  div.className = "statusBarTree";
889  div.innerHTML = HTMLArea.I18N.msg["Path"] + ": ";
890  this._statusBarTree = div;
891  this._statusBar.appendChild(div);
892  if (!this.config.statusBar) {
893    // disable it...
894    statusbar.style.display = "none";
895  }
896};
897
898// Creates the HTMLArea object and replaces the textarea with it.
899HTMLArea.prototype.generate = function ()
900{
901  var editor = this;    // we'll need "this" in some nested functions
902
903  // get the textarea
904  var textarea = this._textArea;
905  if (typeof textarea == "string")
906  {
907    this._textArea = textarea = HTMLArea.getElementById("textarea", textarea);
908  }
909  this._ta_size =
910  {
911    w: textarea.offsetWidth,
912    h: textarea.offsetHeight
913  };
914
915  // create the editor framework
916  var htmlarea = document.createElement("div");
917  htmlarea.className = "htmlarea";
918  this._htmlArea = htmlarea;
919  if(this.config.width != 'auto' && this.config.width != 'toolbar')
920  {
921    htmlarea.style.width = this.config.width;
922  }
923
924  // insert the editor before the textarea.
925  textarea.parentNode.insertBefore(htmlarea, textarea);
926
927  // creates & appends the toolbar
928  this._createToolbar();
929
930  // Create containing div (to hold editor and stylist)
931  var innerEditor = document.createElement('div');
932  htmlarea.appendChild(innerEditor);
933  innerEditor.style.position = 'relative';
934  this.innerEditor = innerEditor;
935
936  // extract the textarea and insert it into the htmlarea
937  textarea.parentNode.removeChild(textarea);
938  innerEditor.appendChild(textarea);
939
940  // create the IFRAME & add to container
941  var iframe = document.createElement("iframe");
942  innerEditor.appendChild(iframe);
943  iframe.src = _editor_url + "popups/blank.html";
944  this._iframe = iframe;
945
946
947  // - I don't think this is required, see the .htmlarea iframe in htmlarea.css
948  // remove the default border as it keeps us from computing correctly
949  // the sizes.  (somebody tell me why doesn't this work in IE)
950  // if (!HTMLArea.is_ie) {
951  //   iframe.style.borderWidth = "0px";
952  // }
953
954
955  // Add the panels
956  for(var i in this._panels)
957  {
958    innerEditor.appendChild(this._panels[i].div);
959  }
960
961  // creates & appends the status bar
962  this._createStatusBar();
963
964
965  // Set up event listeners for saving the iframe content to the textarea
966  if (textarea.form) {
967    // we have a form, on submit get the HTMLArea content and
968    // update original textarea.
969    var f = textarea.form;
970    if (typeof f.onsubmit == "function") {
971      var funcref = f.onsubmit;
972      if (typeof f.__msh_prevOnSubmit == "undefined") {
973        f.__msh_prevOnSubmit = [];
974      }
975      f.__msh_prevOnSubmit.push(funcref);
976    }
977    f.onsubmit = function() {
978      editor._textArea.value = editor.outwardHtml(editor.getHTML());
979      var a = this.__msh_prevOnSubmit;
980      // call previous submit methods if they were there.
981      if (typeof a != "undefined") {
982        for (var i = a.length; --i >= 0;) {
983          a[i]();
984        }
985      }
986    };
987    if (typeof f.onreset == "function") {
988      var funcref = f.onreset;
989      if (typeof f.__msh_prevOnReset == "undefined") {
990        f.__msh_prevOnReset = [];
991      }
992      f.__msh_prevOnReset.push(funcref);
993    }
994    f.onreset = function() {
995      editor.setHTML(editor._textArea.value);
996      editor.updateToolbar();
997      var a = this.__msh_prevOnReset;
998      // call previous reset methods if they were there.
999      if (typeof a != "undefined") {
1000        for (var i = a.length; --i >= 0;) {
1001          a[i]();
1002        }
1003      }
1004    };
1005  }
1006
1007  // add a handler for the "back/forward" case -- on body.unload we save
1008  // the HTML content into the original textarea.
1009  try {
1010    HTMLArea._addEvent(window, 'unload', function() {textarea.value = editor.outwardHtml(editor.getHTML());} );
1011  } catch(e) {};
1012
1013  // Hide textarea
1014  textarea.style.display = "none";
1015
1016  // Calculate the starting size, EXCLUDING THE TOOLBAR & STATUS BAR (always)
1017  var height = null;
1018  var width  = null;
1019
1020  switch(this.config.height)
1021  {
1022    // "auto" means the same height as the original textarea
1023    case 'auto' : { height = parseInt(this._ta_size.h);    break; }
1024    // otherwise we expect it to be a PIXEL height
1025    default     : { height = parseInt(this.config.height); break; }
1026  }
1027
1028  switch(this.config.width)
1029  {
1030    // toolbar means the width is the same as the toolbar
1031    case 'toolbar': {width = parseInt(this._toolbar.offsetWidth); break; }
1032    // auto means the same as the textarea
1033    case 'auto'   : {width = parseInt(this._ta_size.w);          break; }
1034    // otherwise it is expected to be a PIXEL width
1035    default       : {width = parseInt(this.config.width);        break; }
1036  }
1037
1038  if (this.config.sizeIncludesToolbar)
1039  {
1040    // substract toolbar height
1041    height -= this._toolbar.offsetHeight;
1042    height -= this._statusBar.offsetHeight;
1043  }
1044
1045  // Minimal size = 100x100
1046  width  = Math.max(width, 100);
1047  height = Math.max(height,100);
1048
1049  this.setInnerSize(width,height);
1050  this.notifyOn('panel_change',function(){editor.setInnerSize();});
1051
1052
1053  // IMPORTANT: we have to allow Mozilla a short time to recognize the
1054  // new frame.  Otherwise we get a stupid exception.
1055
1056  setTimeout(function() { editor.initIframe()}, 50);
1057};
1058
1059  /** Size the htmlArea according to the available space
1060   *   Width and Height include toolbar!
1061   **/
1062
1063  HTMLArea.prototype.getInnerSize = function()
1064  {
1065    return this._innerSize;
1066  }
1067
1068  HTMLArea.prototype.setInnerSize = function(width, height)
1069  {
1070    if(typeof width == 'undefined' || width == null)
1071    {
1072      width  = this._innerSize.width;
1073    }
1074
1075    if(typeof height == 'undefined' || height == null)
1076    {
1077      height  = this._innerSize.height;
1078    }
1079
1080    this._innerSize = {'width':width,'height':height};
1081
1082    var editorWidth  = width;
1083    var editorHeight = height;
1084    var editorLeft   = 0;
1085    var editorTop    = 0;
1086    var panels = this._panels;
1087
1088    var panel = panels.right;
1089    if(panel.on && panel.panels.length && HTMLArea.hasDisplayedChildren(panel.div))
1090    {
1091      panel.div.style.position = 'absolute';
1092      panel.div.style.width    = parseInt(this.config.panel_dimensions.right) + (HTMLArea.ie_ie ? -1 : -2) + 'px';
1093      panel.div.style.height   = height + (HTMLArea.is_ie ? -1 : -1) + 'px';
1094      panel.div.style.top      = '0px';
1095      panel.div.style.right    = (HTMLArea.is_ie ? 1 : 2) + 'px';
1096      panel.div.style.padding  = "0px";
1097      panel.div.style.overflow = "auto";
1098      panel.div.style.display  = 'block';
1099      editorWidth -= parseInt(this.config.panel_dimensions.right) + (HTMLArea.is_ie ? 2 : 0);
1100    }
1101    else
1102    {
1103      panel.div.style.display  = 'none';
1104    }
1105
1106    var panel = panels.left;
1107    if(panel.on && panel.panels.length && HTMLArea.hasDisplayedChildren(panel.div))
1108    {
1109      panel.div.style.position = 'absolute';
1110      panel.div.style.width    = parseInt(this.config.panel_dimensions.left) + (HTMLArea.ie_ie ? -1 : -1) + 'px';
1111      panel.div.style.height   = height + (HTMLArea.is_ie ? -1 : -1) + 'px';
1112      panel.div.style.top      = '0px';
1113      panel.div.style.left     = (HTMLArea.is_ie ? 0 : 0) + 'px';
1114      panel.div.style.padding  = "0px";
1115      panel.div.style.overflow = "auto";
1116      panel.div.style.display  = "block";
1117      editorWidth -= parseInt(this.config.panel_dimensions.left) + (HTMLArea.is_ie ? 2 : 0);
1118      editorLeft   = parseInt(this.config.panel_dimensions.left) + (HTMLArea.is_ie ? 2 : 0) + 'px';
1119    }
1120    else
1121    {
1122      panel.div.style.display  = 'none';
1123    }
1124
1125    var panel = panels.top;
1126    if(panel.on && panel.panels.length && HTMLArea.hasDisplayedChildren(panel.div))
1127    {
1128      panel.div.style.position = 'absolute';
1129      panel.div.style.top      = '0px';
1130      panel.div.style.left     = '0px';
1131      panel.div.style.width    = width  + 'px';
1132      panel.div.style.height   = parseInt(this.config.panel_dimensions.top) + 'px';
1133      panel.div.style.padding  = "0px";
1134      panel.div.style.overflow = "auto";
1135      panel.div.style.display  = "block";
1136      editorHeight -= parseInt(this.config.panel_dimensions.top);
1137      editorTop     = parseInt(this.config.panel_dimensions.top) + 'px';
1138    }
1139    else
1140    {
1141      panel.div.style.display  = 'none';
1142    }
1143
1144    var panel = panels.bottom;
1145    if(panel.on && panel.panels.length && HTMLArea.hasDisplayedChildren(panel.div))
1146    {
1147      panel.div.style.position = 'absolute';
1148      panel.div.style.bottom   = '0px';
1149      panel.div.style.left     = '0px';
1150      panel.div.style.width    = width  + 'px';
1151      panel.div.style.height   = parseInt(this.config.panel_dimensions.bottom) + 'px';
1152      panel.div.style.padding  = "0px";
1153      panel.div.style.overflow = "auto";
1154      panel.div.style.display  = "block";
1155      editorHeight -= parseInt(this.config.panel_dimensions.bottom);
1156    }
1157    else
1158    {
1159      panel.div.style.display  = 'none';
1160    }
1161
1162    // Set the dimensions of the container
1163    this.innerEditor.style.width  = width  + 'px';
1164    this.innerEditor.style.height = height + 'px';
1165    this.innerEditor.style.position = 'relative';
1166
1167    // and the iframe
1168    this._iframe.style.width  = editorWidth  + 'px';
1169    this._iframe.style.height = editorHeight + 'px';
1170    this._iframe.style.position = 'absolute';
1171    this._iframe.style.left = editorLeft;
1172    this._iframe.style.top  = editorTop;
1173
1174
1175    // the editor including the toolbar now have the same size as the
1176    // original textarea.. which means that we need to reduce that a bit.
1177    this._textArea.style.width  = editorWidth  + 'px';
1178    this._textArea.style.height = editorHeight + 'px';
1179    this._textArea.style.position = 'absolute';
1180    this._textArea.style.left = editorLeft;
1181    this._textArea.style.top  = editorTop;
1182
1183    this.notifyOf('resize', {'width':width,'height':height,'editorWidth':editorWidth,'editorHeight':editorHeight,'editorTop':editorTop,'editorLeft':editorLeft});
1184  }
1185
1186  HTMLArea.prototype.addPanel = function(side)
1187  {
1188    var div = document.createElement('div');
1189    div.side = side;
1190    HTMLArea.addClasses(div, 'panel');
1191    this._panels[side].panels.push(div);
1192    this._panels[side].div.appendChild(div);
1193
1194    this.notifyOf('panel_change', {'action':'add','panel':div});
1195
1196    return div;
1197  }
1198
1199  HTMLArea.prototype.removePanel = function(panel)
1200  {
1201    panel.side.div.removeChild(panel);
1202    var clean = [ ];
1203    for(var i = 0; i < panel.side.panels.length; i++)
1204    {
1205      if(panel.side.panels[i] != panel)
1206      {
1207        clean.push(panel.side.panels[i]);
1208      }
1209    }
1210    panel.side.panels = clean;
1211    this.notifyOf('panel_change', {'action':'add','panel':panel});
1212  }
1213
1214  HTMLArea.prototype.hidePanel = function(panel)
1215  {
1216    panel.style.display = 'none';
1217    this.notifyOf('panel_change', {'action':'hide','panel':panel});
1218  }
1219
1220  HTMLArea.prototype.showPanel = function(panel)
1221  {
1222    panel.style.display = '';
1223    this.notifyOf('panel_change', {'action':'show','panel':panel});
1224  }
1225
1226  HTMLArea.prototype.hidePanels = function(sides)
1227  {
1228    if(typeof sides == 'undefined')
1229    {
1230      sides = ['left','right','top','bottom'];
1231    }
1232
1233    var reShow = [];
1234    for(var i = 0; i < sides.length;i++)
1235    {
1236      if(this._panels[sides[i]].on)
1237      {
1238        reShow.push(sides[i]);
1239        this._panels[sides[i]].on = false;
1240      }
1241    }
1242    this.notifyOf('panel_change', {'action':'multi_hide','sides':sides});
1243  }
1244
1245  HTMLArea.prototype.showPanels = function(sides)
1246  {
1247    if(typeof sides == 'undefined')
1248    {
1249      sides = ['left','right','top','bottom'];
1250    }
1251
1252    var reHide = [];
1253    for(var i = 0; i < sides.length;i++)
1254    {
1255      if(!this._panels[sides[i]].on)
1256      {
1257        reHide.push(sides[i]);
1258        this._panels[sides[i]].on = true;
1259      }
1260    }
1261    this.notifyOf('panel_change', {'action':'multi_show','sides':sides});
1262  }
1263
1264  HTMLArea.objectProperties = function(obj)
1265  {
1266    var props = [ ];
1267    for(var x in obj)
1268    {
1269      props[props.length] = x;
1270    }
1271    return props;
1272  }
1273
1274  HTMLArea.prototype.activateEditor = function()
1275  {
1276    if (HTMLArea.is_gecko && this._doc.designMode != 'on')
1277    {
1278      try{HTMLArea.last_on.designMode = 'off';} catch(e) { }
1279      if(this._iframe.style.display == 'none')
1280      {
1281        this._iframe.style.display = '';
1282        this._doc.designMode = 'on';
1283        this._iframe.style.display = 'none';
1284      }
1285      else
1286      {
1287
1288        this._doc.designMode = 'on';
1289      }
1290    }
1291    else
1292    {
1293      this._doc.body.contentEditable = true;
1294    }
1295    HTMLArea.last_on = this._doc;
1296  }
1297
1298  HTMLArea.prototype.deactivateEditor = function()
1299  {
1300    if(HTMLArea.is_gecko && this._doc.designMode == 'on')
1301    {
1302      this._doc.designMode = 'off';
1303      HTMLArea.last_on = null;
1304    }
1305    else
1306    {
1307      this._doc.body.contentEditable = false;
1308    }
1309  }
1310
1311  HTMLArea.prototype.initIframe = function()
1312  {
1313    var doc = null;
1314    var editor = this;
1315    try
1316    {
1317      doc = editor._iframe.contentWindow.document;
1318      if (!doc) {
1319        // Try again..
1320        // FIXME: don't know what else to do here.  Normally
1321        // we'll never reach this point.
1322        if (HTMLArea.is_gecko) {
1323          setTimeout(function() { editor.initIframe()}, 50);
1324          return false;
1325        } else {
1326          alert("ERROR: IFRAME can't be initialized.");
1327        }
1328      }
1329    }
1330    catch(e)
1331    {
1332      setTimeout(function() { editor.initIframe()}, 50);
1333    }
1334
1335    if (!editor.config.fullPage) {
1336      doc.open();
1337      var html = "<html>\n";
1338      html += "<head>\n";
1339      if(typeof editor.config.baseHref != 'undefined')
1340      {
1341        html += "<base href=\"" + editor.config.baseHref + "\"/>";
1342      }
1343      html += "<style title=\"table borders\">"
1344           + ".htmtableborders, .htmtableborders td, .htmtableborders th {border : 1px dashed lightgrey ! important;} \n"
1345           + "</style>\n";
1346      html += "<style>"
1347           + editor.config.pageStyle + "\n"
1348           + "html, body { border: 0px; } \n"
1349           + "span.macro, span.macro ul, span.macro div, span.macro p {background : #CCCCCC;}\n"
1350           + "</style>\n";
1351      if(typeof editor.config.pageStyleSheets !== 'undefined')
1352      {
1353        for(style_i = 0; style_i < editor.config.pageStyleSheets.length; style_i++)
1354        {
1355          if(editor.config.pageStyleSheets[style_i].length > 0)
1356              html += "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + editor.config.pageStyleSheets[style_i] + "\">";
1357            //html += "<style> @import url('" + editor.config.pageStyleSheets[style_i] + "'); </style>\n";
1358        }
1359      }
1360      html += "</head>\n";
1361      html += "<body>\n";
1362      html +=   editor.inwardHtml(editor._textArea.value);
1363      html += "</body>\n";
1364      html += "</html>";
1365      doc.write(html);
1366      doc.close();
1367    } else {
1368      var html = editor.inwardHtml(editor._textArea.value);
1369      if (html.match(HTMLArea.RE_doctype)) {
1370        editor.setDoctype(RegExp.$1);
1371        html = html.replace(HTMLArea.RE_doctype, "");
1372      }
1373      doc.open();
1374      doc.write(html);
1375      doc.close();
1376    }
1377
1378    this._doc = doc;
1379
1380    // If we have multiple editors some bug in Mozilla makes some lose editing ability
1381    if(HTMLArea.is_gecko)
1382    {
1383      HTMLArea._addEvents(
1384        editor._iframe.contentWindow,
1385        ["mousedown"],
1386        function() { editor.activateEditor();  }
1387      );
1388    }
1389    else
1390    {
1391      editor.activateEditor();
1392    }
1393
1394    // editor.focusEditor();
1395    // intercept some events; for updating the toolbar & keyboard handlers
1396    HTMLArea._addEvents
1397      (doc, ["keydown", "keypress", "mousedown", "mouseup", "drag"],
1398       function (event) {
1399         return editor._editorEvent(HTMLArea.is_ie ? editor._iframe.contentWindow.event : event);
1400       });
1401
1402    // check if any plugins have registered refresh handlers
1403    for (var i in editor.plugins) {
1404      var plugin = editor.plugins[i].instance;
1405      if (typeof plugin.onGenerate == "function")
1406        plugin.onGenerate();
1407      if (typeof plugin.onGenerateOnce == "function") {
1408        plugin.onGenerateOnce();
1409        plugin.onGenerateOnce = null;
1410      }
1411    }
1412
1413    if(typeof editor._onGenerate == "function") { editor._onGenerate();}
1414
1415    setTimeout(function() {
1416      editor.updateToolbar();
1417    }, 250);
1418
1419    if (typeof editor.onGenerate == "function")
1420      editor.onGenerate();
1421  }
1422
1423// Switches editor mode; parameter can be "textmode" or "wysiwyg".  If no
1424// parameter was passed this function toggles between modes.
1425HTMLArea.prototype.setMode = function(mode) {
1426  if (typeof mode == "undefined") {
1427    mode = ((this._editMode == "textmode") ? "wysiwyg" : "textmode");
1428  }
1429  switch (mode) {
1430    case "textmode":
1431    {
1432      var html = this.outwardHtml(this.getHTML());
1433      this._textArea.value = html;
1434
1435      // Hide the iframe
1436      this.deactivateEditor();
1437      this._iframe.style.display   = 'none';
1438      this._textArea.style.display = "block";
1439      if (this.config.statusBar)
1440      {
1441        this._statusBar.innerHTML = HTMLArea.I18N.msg["TEXT_MODE"];
1442      }
1443
1444      this.notifyOf('modechange', {'mode':'text'});
1445      break;
1446    }
1447
1448    case "wysiwyg":
1449    {
1450      var html = this.inwardHtml(this.getHTML());
1451      this.deactivateEditor();
1452      if (!this.config.fullPage)
1453      {
1454        this._doc.body.innerHTML = html;
1455      }
1456      else
1457      {
1458        this.setFullHTML(html);
1459      }
1460      this._iframe.style.display   = '';
1461      this._textArea.style.display = "none";
1462      this.activateEditor();
1463      if (this.config.statusBar)
1464      {
1465        this._statusBar.innerHTML = '';
1466        this._statusBar.appendChild(this._statusBarTree);
1467      }
1468
1469      this.notifyOf('modechange', {'mode':'wysiwyg'});
1470      break;
1471    }
1472
1473    default:
1474    {
1475      alert("Mode <" + mode + "> not defined!");
1476      return false;
1477    }
1478  }
1479  this._editMode = mode;
1480  // this.focusEditor();
1481
1482  for (var i in this.plugins) {
1483    var plugin = this.plugins[i].instance;
1484    if (typeof plugin.onMode == "function") plugin.onMode(mode);
1485  }
1486};
1487
1488HTMLArea.prototype.setFullHTML = function(html) {
1489  var save_multiline = RegExp.multiline;
1490  RegExp.multiline = true;
1491  if (html.match(HTMLArea.RE_doctype)) {
1492    this.setDoctype(RegExp.$1);
1493    html = html.replace(HTMLArea.RE_doctype, "");
1494  }
1495  RegExp.multiline = save_multiline;
1496  if (!HTMLArea.is_ie) {
1497    if (html.match(HTMLArea.RE_head))
1498      this._doc.getElementsByTagName("head")[0].innerHTML = RegExp.$1;
1499    if (html.match(HTMLArea.RE_body))
1500      this._doc.getElementsByTagName("body")[0].innerHTML = RegExp.$1;
1501  } else {
1502    var html_re = /<html>((.|\n)*?)<\/html>/i;
1503    html = html.replace(html_re, "$1");
1504    this._doc.open();
1505    this._doc.write(html);
1506    this._doc.close();
1507    this.activateEditor();
1508    // this._doc.body.contentEditable = true;
1509    return true;
1510  }
1511};
1512
1513/***************************************************
1514 *  Category: PLUGINS
1515 ***************************************************/
1516
1517// Create the specified plugin and register it with this HTMLArea
1518HTMLArea.prototype.registerPlugin = function() {
1519  var plugin = arguments[0];
1520  var args = [];
1521  for (var i = 1; i < arguments.length; ++i)
1522    args.push(arguments[i]);
1523  this.registerPlugin2(plugin, args);
1524};
1525
1526// this is the variant of the function above where the plugin arguments are
1527// already packed in an array.  Externally, it should be only used in the
1528// full-screen editor code, in order to initialize plugins with the same
1529// parameters as in the opener window.
1530HTMLArea.prototype.registerPlugin2 = function(plugin, args) {
1531  if (typeof plugin == "string")
1532    plugin = eval(plugin);
1533  if (typeof plugin == "undefined") {
1534    /* FIXME: This should never happen. But why does it do? */
1535    return false;
1536  }
1537  var obj = new plugin(this, args);
1538  if (obj) {
1539    var clone = {};
1540    var info = plugin._pluginInfo;
1541    for (var i in info)
1542      clone[i] = info[i];
1543    clone.instance = obj;
1544    clone.args = args;
1545    this.plugins[plugin._pluginInfo.name] = clone;
1546  } else
1547    alert("Can't register plugin " + plugin.toString() + ".");
1548};
1549
1550// static function that loads the required plugin and lang file, based on the
1551// language loaded already for HTMLArea.  You better make sure that the plugin
1552// _has_ that language, otherwise shit might happen ;-)
1553HTMLArea.getPluginDir = function(pluginName) {
1554  return _editor_url + "plugins/" + pluginName;
1555};
1556
1557HTMLArea.loadPlugin = function(pluginName) {
1558  var dir = this.getPluginDir(pluginName);
1559  var plugin = pluginName.replace(/([a-z])([A-Z])([a-z])/g,
1560          function (str, l1, l2, l3) {
1561            return l1 + "-" + l2.toLowerCase() + l3;
1562          }).toLowerCase() + ".js";
1563  var plugin_file = dir + "/" + plugin;
1564  var plugin_lang = dir + "/lang/" + _editor_lang + ".js";
1565  document.write("<script type='text/javascript' src='" + plugin_file + "'></script>");
1566  document.write("<script type='text/javascript' src='" + plugin_lang + "'></script>");
1567  //this.loadScript(plugin_file);
1568  //this.loadScript(plugin_lang);
1569};
1570
1571HTMLArea.loadStyle = function(style, plugin) {
1572  var url = _editor_url || '';
1573  if (typeof plugin != "undefined") {
1574    url += "plugins/" + plugin + "/";
1575  }
1576  url += style;
1577  if (/^\//.test(style))
1578    url = style;
1579  var head = document.getElementsByTagName("head")[0];
1580  var link = document.createElement("link");
1581  link.rel = "stylesheet";
1582  link.href = url;
1583  head.appendChild(link);
1584  //document.write("<style type='text/css'>@import url(" + url + ");</style>");
1585};
1586HTMLArea.loadStyle(typeof _editor_css == "string" ? _editor_css : "htmlarea.css");
1587
1588/***************************************************
1589 *  Category: EDITOR UTILITIES
1590 ***************************************************/
1591
1592HTMLArea.prototype.debugTree = function() {
1593  var ta = document.createElement("textarea");
1594  ta.style.width = "100%";
1595  ta.style.height = "20em";
1596  ta.value = "";
1597  function debug(indent, str) {
1598    for (; --indent >= 0;)
1599      ta.value += " ";
1600    ta.value += str + "\n";
1601  };
1602  function _dt(root, level) {
1603    var tag = root.tagName.toLowerCase(), i;
1604    var ns = HTMLArea.is_ie ? root.scopeName : root.prefix;
1605    debug(level, "- " + tag + " [" + ns + "]");
1606    for (i = root.firstChild; i; i = i.nextSibling)
1607      if (i.nodeType == 1)
1608        _dt(i, level + 2);
1609  };
1610  _dt(this._doc.body, 0);
1611  document.body.appendChild(ta);
1612};
1613
1614HTMLArea.getInnerText = function(el) {
1615  var txt = '', i;
1616  for (i = el.firstChild; i; i = i.nextSibling) {
1617    if (i.nodeType == 3)
1618      txt += i.data;
1619    else if (i.nodeType == 1)
1620      txt += HTMLArea.getInnerText(i);
1621  }
1622  return txt;
1623};
1624
1625HTMLArea.prototype._wordClean = function() {
1626  var
1627    editor = this,
1628    stats = {
1629      empty_tags : 0,
1630      mso_class  : 0,
1631      mso_style  : 0,
1632      mso_xmlel  : 0,
1633      orig_len   : this._doc.body.innerHTML.length,
1634      T          : (new Date()).getTime()
1635    },
1636    stats_txt = {
1637      empty_tags : "Empty tags removed: ",
1638      mso_class  : "MSO class names removed: ",
1639      mso_style  : "MSO inline style removed: ",
1640      mso_xmlel  : "MSO XML elements stripped: "
1641    };
1642  function showStats() {
1643    var txt = "HTMLArea word cleaner stats: \n\n";
1644    for (var i in stats)
1645      if (stats_txt[i])
1646        txt += stats_txt[i] + stats[i] + "\n";
1647    txt += "\nInitial document length: " + stats.orig_len + "\n";
1648    txt += "Final document length: " + editor._doc.body.innerHTML.length + "\n";
1649    txt += "Clean-up took " + (((new Date()).getTime() - stats.T) / 1000) + " seconds";
1650    alert(txt);
1651  };
1652  function clearClass(node) {
1653    var newc = node.className.replace(/(^|\s)mso.*?(\s|$)/ig, ' ');
1654    if (newc != node.className) {
1655      node.className = newc;
1656      if (!/\S/.test(node.className)) {
1657        node.removeAttribute("className");
1658        ++stats.mso_class;
1659      }
1660    }
1661  };
1662  function clearStyle(node) {
1663    var declarations = node.style.cssText.split(/\s*;\s*/);
1664    for (var i = declarations.length; --i >= 0;)
1665      if (/^mso|^tab-stops/i.test(declarations[i]) ||
1666          /^margin\s*:\s*0..\s+0..\s+0../i.test(declarations[i])) {
1667        ++stats.mso_style;
1668        declarations.splice(i, 1);
1669      }
1670    node.style.cssText = declarations.join("; ");
1671  };
1672  function stripTag(el) {
1673    if (HTMLArea.is_ie)
1674      el.outerHTML = HTMLArea.htmlEncode(el.innerText);
1675    else {
1676      var txt = document.createTextNode(HTMLArea.getInnerText(el));
1677      el.parentNode.insertBefore(txt, el);
1678      el.parentNode.removeChild(el);
1679    }
1680    ++stats.mso_xmlel;
1681  };
1682  function checkEmpty(el) {
1683    if (/^(a|span|b|strong|i|em|font)$/i.test(el.tagName) &&
1684        !el.firstChild) {
1685      el.parentNode.removeChild(el);
1686      ++stats.empty_tags;
1687    }
1688  };
1689  function parseTree(root) {
1690    var tag = root.tagName.toLowerCase(), i, next;
1691    if ((HTMLArea.is_ie && root.scopeName != 'HTML') || (!HTMLArea.is_ie && /:/.test(tag))) {
1692      stripTag(root);
1693      return false;
1694    } else {
1695      clearClass(root);
1696      clearStyle(root);
1697      for (i = root.firstChild; i; i = next) {
1698        next = i.nextSibling;
1699        if (i.nodeType == 1 && parseTree(i))
1700          checkEmpty(i);
1701      }
1702    }
1703    return true;
1704  };
1705  parseTree(this._doc.body);
1706  // showStats();
1707  // this.debugTree();
1708  // this.setHTML(this.getHTML());
1709  // this.setHTML(this.getInnerHTML());
1710  // this.forceRedraw();
1711  this.updateToolbar();
1712};
1713
1714HTMLArea.prototype._clearFonts = function() {
1715  var D = this.getInnerHTML();
1716
1717  if(confirm('Would you like to clear font typefaces?'))
1718  {
1719    D = D.replace(/face="[^"]*"/gi, '');
1720    D = D.replace(/font-family:[^;}"']+;?/gi, '');
1721  }
1722
1723  if(confirm('Would you like to clear font sizes?'))
1724  {
1725    D = D.replace(/size="[^"]*"/gi, '');
1726    D = D.replace(/font-size:[^;}"']+;?/gi, '');
1727  }
1728
1729  if(confirm('Would you like to clear font colours?'))
1730  {
1731    D = D.replace(/color="[^"]*"/gi, '');
1732    D = D.replace(/([^-])color:[^;}"']+;?/gi, '$1');
1733  }
1734
1735  D = D.replace(/(style|class)="\s*"/gi, '');
1736  D = D.replace(/<(font|span)\s*>/gi, '');
1737  this.setHTML(D);
1738  this.updateToolbar();
1739}
1740
1741HTMLArea.prototype._splitBlock = function()
1742{
1743  this._doc.execCommand('formatblock', false, '<div>');
1744}
1745
1746HTMLArea.prototype.forceRedraw = function() {
1747  this._doc.body.style.visibility = "hidden";
1748  this._doc.body.style.visibility = "visible";
1749  // this._doc.body.innerHTML = this.getInnerHTML();
1750};
1751
1752// focuses the iframe window.  returns a reference to the editor document.
1753HTMLArea.prototype.focusEditor = function() {
1754  switch (this._editMode) {
1755      // notice the try { ... } catch block to avoid some rare exceptions in FireFox
1756      // (perhaps also in other Gecko browsers). Manual focus by user is required in
1757        // case of an error. Somebody has an idea?
1758      case "wysiwyg" :
1759      try
1760      {
1761        // We don't want to focus the field unless at least one field has been activated.
1762        if(HTMLArea.last_on)
1763        {
1764          this.activateEditor();
1765          this._iframe.contentWindow.focus();
1766        }
1767
1768      } catch (e) {} break;
1769      case "textmode": try { this._textArea.focus() } catch (e) {} break;
1770      default      : alert("ERROR: mode " + this._editMode + " is not defined");
1771  }
1772  return this._doc;
1773};
1774
1775// takes a snapshot of the current text (for undo)
1776HTMLArea.prototype._undoTakeSnapshot = function() {
1777  ++this._undoPos;
1778  if (this._undoPos >= this.config.undoSteps) {
1779    // remove the first element
1780    this._undoQueue.shift();
1781    --this._undoPos;
1782  }
1783  // use the fasted method (getInnerHTML);
1784  var take = true;
1785  var txt = this.getInnerHTML();
1786  if (this._undoPos > 0)
1787    take = (this._undoQueue[this._undoPos - 1] != txt);
1788  if (take) {
1789    this._undoQueue[this._undoPos] = txt;
1790  } else {
1791    this._undoPos--;
1792  }
1793};
1794
1795HTMLArea.prototype.undo = function() {
1796  if (this._undoPos > 0) {
1797    var txt = this._undoQueue[--this._undoPos];
1798    if (txt) this.setHTML(txt);
1799    else ++this._undoPos;
1800  }
1801};
1802
1803HTMLArea.prototype.redo = function() {
1804  if (this._undoPos < this._undoQueue.length - 1) {
1805    var txt = this._undoQueue[++this._undoPos];
1806    if (txt) this.setHTML(txt);
1807    else --this._undoPos;
1808  }
1809};
1810
1811HTMLArea.prototype.disableToolbar = function(except)
1812{
1813  if(typeof except == 'undefined')
1814  {
1815    except = [ ];
1816  }
1817  else if(typeof except != 'object')
1818  {
1819    except = [except];
1820  }
1821
1822  for (var i in this._toolbarObjects)
1823  {
1824    var btn = this._toolbarObjects[i];
1825    if(except.contains(i))
1826    {
1827      continue;
1828    }
1829    btn.state("enabled", false);
1830  }
1831}
1832
1833HTMLArea.prototype.enableToolbar = function()
1834{
1835  this.updateToolbar();
1836}
1837
1838if(!Array.prototype.contains)
1839{
1840  Array.prototype.contains = function(needle)
1841  {
1842   var haystack = this;
1843   for(var i = 0; i < haystack.length; i++)
1844    {
1845      if(needle == haystack[i]) return true;
1846    }
1847
1848    return false;
1849  }
1850
1851}
1852
1853
1854// updates enabled/disable/active state of the toolbar elements
1855HTMLArea.prototype.updateToolbar = function(noStatus) {
1856  var doc = this._doc;
1857  var text = (this._editMode == "textmode");
1858  var ancestors = null;
1859  if (!text) {
1860    ancestors = this.getAllAncestors();
1861    if (this.config.statusBar && !noStatus) {
1862      this._statusBarTree.innerHTML = HTMLArea.I18N.msg["Path"] + ": "; // clear
1863      for (var i = ancestors.length; --i >= 0;) {
1864        var el = ancestors[i];
1865        if (!el) {
1866          // hell knows why we get here; this
1867          // could be a classic example of why
1868          // it's good to check for conditions
1869          // that are impossible to happen ;-)
1870          continue;
1871        }
1872        var a = document.createElement("a");
1873        a.href = "javascript:void(0)";
1874        a.el = el;
1875        a.editor = this;
1876        a.onclick = function() {
1877          this.blur();
1878          this.editor.selectNodeContents(this.el);
1879          this.editor.updateToolbar(true);
1880          return false;
1881        };
1882        a.oncontextmenu = function() {
1883          // TODO: add context menu here
1884          this.blur();
1885          var info = "Inline style:\n\n";
1886          info += this.el.style.cssText.split(/;\s*/).join(";\n");
1887          alert(info);
1888          return false;
1889        };
1890        var txt = el.tagName.toLowerCase();
1891        a.title = el.style.cssText;
1892        if (el.id) {
1893          txt += "#" + el.id;
1894        }
1895        if (el.className) {
1896          txt += "." + el.className;
1897        }
1898        a.appendChild(document.createTextNode(txt));
1899        this._statusBarTree.appendChild(a);
1900        if (i != 0) {
1901          this._statusBarTree.appendChild(document.createTextNode(String.fromCharCode(0xbb)));
1902        }
1903      }
1904    }
1905  }
1906
1907  for (var i in this._toolbarObjects) {
1908    var btn = this._toolbarObjects[i];
1909    var cmd = i;
1910    var inContext = true;
1911    if (btn.context && !text) {
1912      inContext = false;
1913      var context = btn.context;
1914      var attrs = [];
1915      if (/(.*)\[(.*?)\]/.test(context)) {
1916        context = RegExp.$1;
1917        attrs = RegExp.$2.split(",");
1918      }
1919      context = context.toLowerCase();
1920      var match = (context == "*");
1921      for (var k = 0; k < ancestors.length; ++k) {
1922        if (!ancestors[k]) {
1923          // the impossible really happens.
1924          continue;
1925        }
1926        if (match || (ancestors[k].tagName.toLowerCase() == context)) {
1927          inContext = true;
1928          for (var ka = 0; ka < attrs.length; ++ka) {
1929            if (!eval("ancestors[k]." + attrs[ka])) {
1930              inContext = false;
1931              break;
1932            }
1933          }
1934          if (inContext) {
1935            break;
1936          }
1937        }
1938      }
1939    }
1940    btn.state("enabled", (!text || btn.text) && inContext);
1941    if (typeof cmd == "function") {
1942      continue;
1943    }
1944    // look-it-up in the custom dropdown boxes
1945    var dropdown = this.config.customSelects[cmd];
1946    if ((!text || btn.text) && (typeof dropdown != "undefined")) {
1947      dropdown.refresh(this);
1948      continue;
1949    }
1950    switch (cmd) {
1951        case "fontname":
1952        case "fontsize":
1953      if (!text) try {
1954        var value = ("" + doc.queryCommandValue(cmd)).toLowerCase();
1955        if (!value) {
1956          btn.element.selectedIndex = 0;
1957          break;
1958        }
1959        // HACK -- retrieve the config option for this
1960        // combo box.  We rely on the fact that the
1961        // variable in config has the same name as
1962        // button name in the toolbar.
1963        var options = this.config[cmd];
1964        var k = 0;
1965        for (var j in options) {
1966          // FIXME: the following line is scary.
1967          if ((j.toLowerCase() == value) ||
1968              (options[j].substr(0, value.length).toLowerCase() == value)) {
1969            btn.element.selectedIndex = k;
1970            throw "ok";
1971          }
1972          ++k;
1973        }
1974        btn.element.selectedIndex = 0;
1975      } catch(e) {};
1976
1977      // It's better to search for the format block by tag name from the
1978      //  current selection upwards, because IE has a tendancy to return
1979      //  things like 'heading 1' for 'h1', which breaks things if you want
1980      //  to call your heading blocks 'header 1'.  Stupid MS.
1981      case "formatblock"  :
1982        var blocks = [ ];
1983        for(var i in this.config['formatblock'])
1984        {
1985          blocks[blocks.length] = this.config['formatblock'][i];
1986        }
1987
1988        var deepestAncestor = this._getFirstAncestor(this._getSelection(), blocks);
1989        if(deepestAncestor)
1990        {
1991          for(var x= 0; x < blocks.length; x++)
1992          {
1993            if(blocks[x].toLowerCase() == deepestAncestor.tagName.toLowerCase())
1994            {
1995              btn.element.selectedIndex = x;
1996            }
1997          }
1998        }
1999        else
2000        {
2001          btn.element.selectedIndex = 0;
2002        }
2003        break;
2004
2005      break;
2006        case "textindicator":
2007      if (!text) {
2008        try {with (btn.element.style) {
2009          backgroundColor = HTMLArea._makeColor(
2010            doc.queryCommandValue(HTMLArea.is_ie ? "backcolor" : "hilitecolor"));
2011          if (/transparent/i.test(backgroundColor)) {
2012            // Mozilla
2013            backgroundColor = HTMLArea._makeColor(doc.queryCommandValue("backcolor"));
2014          }
2015          color = HTMLArea._makeColor(doc.queryCommandValue("forecolor"));
2016          fontFamily = doc.queryCommandValue("fontname");
2017          fontWeight = doc.queryCommandState("bold") ? "bold" : "normal";
2018          fontStyle = doc.queryCommandState("italic") ? "italic" : "normal";
2019        }} catch (e) {
2020          // alert(e + "\n\n" + cmd);
2021        }
2022      }
2023      break;
2024        case "htmlmode": btn.state("active", text); break;
2025        case "lefttoright":
2026        case "righttoleft":
2027      var el = this.getParentElement();
2028      while (el && !HTMLArea.isBlockElement(el))
2029        el = el.parentNode;
2030      if (el)
2031        btn.state("active", (el.style.direction == ((cmd == "righttoleft") ? "rtl" : "ltr")));
2032      break;
2033        default:
2034      cmd = cmd.replace(/(un)?orderedlist/i, "insert$1orderedlist");
2035      try {
2036        btn.state("active", (!text && doc.queryCommandState(cmd)));
2037      } catch (e) {}
2038    }
2039  }
2040  // take undo snapshots
2041  if (this._customUndo && !this._timerUndo) {
2042    this._undoTakeSnapshot();
2043    var editor = this;
2044    this._timerUndo = setTimeout(function() {
2045      editor._timerUndo = null;
2046    }, this.config.undoTimeout);
2047  }
2048
2049  // Insert a space in certain locations, this is just to make editing a little
2050  // easier (to "get out of" tags), it's not essential.
2051  if(HTMLArea.is_gecko)
2052  {
2053    var s = this._getSelection();
2054    if(s && s.isCollapsed && s.anchorNode && s.anchorNode.nodeType == 3)
2055    {
2056      if(s.anchorOffset == s.anchorNode.length)
2057      {
2058        if(HTMLArea.isBlockElement(s.anchorNode.parentNode))
2059        {
2060          if(s.anchorNode.data != '\xA0' && !s.anchorNode.nextSibling)
2061          {
2062            s.anchorNode.parentNode.insertBefore(this._doc.createTextNode('\xA0'), s.anchorNode.nextSibling);
2063          }
2064        }
2065        else
2066        {
2067          if(!s.anchorNode.parentNode.nextSibling)
2068          {
2069            s.anchorNode.parentNode.parentNode.insertBefore(this._doc.createTextNode('\xA0'), s.anchorNode.parentNode.nextSibling);
2070          }
2071        }
2072      }
2073    }
2074  }
2075
2076  // check if any plugins have registered refresh handlers
2077  for (var i in this.plugins) {
2078    var plugin = this.plugins[i].instance;
2079    if (typeof plugin.onUpdateToolbar == "function")
2080      plugin.onUpdateToolbar();
2081  }
2082
2083};
2084
2085/** Returns a node after which we can insert other nodes, in the current
2086 * selection.  The selection is removed.  It splits a text node, if needed.
2087 */
2088HTMLArea.prototype.insertNodeAtSelection = function(toBeInserted) {
2089  if (!HTMLArea.is_ie) {
2090    var sel = this._getSelection();
2091    var range = this._createRange(sel);
2092    // remove the current selection
2093    sel.removeAllRanges();
2094    range.deleteContents();
2095    var node = range.startContainer;
2096    var pos = range.startOffset;
2097    switch (node.nodeType) {
2098        case 3: // Node.TEXT_NODE
2099      // we have to split it at the caret position.
2100      if (toBeInserted.nodeType == 3) {
2101        // do optimized insertion
2102        node.insertData(pos, toBeInserted.data);
2103        range = this._createRange();
2104        range.setEnd(node, pos + toBeInserted.length);
2105        range.setStart(node, pos + toBeInserted.length);
2106        sel.addRange(range);
2107      } else {
2108        node = node.splitText(pos);
2109        var selnode = toBeInserted;
2110        if (toBeInserted.nodeType == 11 /* Node.DOCUMENT_FRAGMENT_NODE */) {
2111          selnode = selnode.firstChild;
2112        }
2113        node.parentNode.insertBefore(toBeInserted, node);
2114        this.selectNodeContents(selnode);
2115        this.updateToolbar();
2116      }
2117      break;
2118        case 1: // Node.ELEMENT_NODE
2119      var selnode = toBeInserted;
2120      if (toBeInserted.nodeType == 11 /* Node.DOCUMENT_FRAGMENT_NODE */) {
2121        selnode = selnode.firstChild;
2122      }
2123      node.insertBefore(toBeInserted, node.childNodes[pos]);
2124      this.selectNodeContents(selnode);
2125      this.updateToolbar();
2126      break;
2127    }
2128  } else {
2129    return null;        // this function not yet used for IE <FIXME>
2130  }
2131};
2132
2133// Returns the deepest node that contains both endpoints of the selection.
2134HTMLArea.prototype.getParentElement = function(sel) {
2135  if(typeof sel == 'undefined')
2136  {
2137    sel = this._getSelection();
2138  }
2139  var range = this._createRange(sel);
2140  if (HTMLArea.is_ie) {
2141    switch (sel.type) {
2142        case "Text":
2143        case "None":
2144      // It seems that even for selection of type "None",
2145      // there _is_ a parent element and it's value is not
2146      // only correct, but very important to us.  MSIE is
2147      // certainly the buggiest browser in the world and I
2148      // wonder, God, how can Earth stand it?
2149      return range.parentElement();
2150        case "Control":
2151      return range.item(0);
2152        default:
2153      return this._doc.body;
2154    }
2155  } else try {
2156    var p = range.commonAncestorContainer;
2157    if (!range.collapsed && range.startContainer == range.endContainer &&
2158        range.startOffset - range.endOffset <= 1 && range.startContainer.hasChildNodes())
2159      p = range.startContainer.childNodes[range.startOffset];
2160    /*
2161    alert(range.startContainer + ":" + range.startOffset + "\n" +
2162          range.endContainer + ":" + range.endOffset);
2163    */
2164    while (p.nodeType == 3) {
2165      p = p.parentNode;
2166    }
2167    return p;
2168  } catch (e) {
2169    return null;
2170  }
2171};
2172
2173// Returns an array with all the ancestor nodes of the selection.
2174HTMLArea.prototype.getAllAncestors = function() {
2175  var p = this.getParentElement();
2176  var a = [];
2177  while (p && (p.nodeType == 1) && (p.tagName.toLowerCase() != 'body')) {
2178    a.push(p);
2179    p = p.parentNode;
2180  }
2181  a.push(this._doc.body);
2182  return a;
2183};
2184
2185// Returns the deepest ancestor of the selection that is of the current type
2186HTMLArea.prototype._getFirstAncestor = function(sel, types)
2187{
2188  var prnt = this._activeElement(sel);
2189  if(prnt == null)
2190  {
2191    try
2192    {
2193      prnt = (HTMLArea.is_ie ? this._createRange(sel).parentElement() : this._createRange(sel).commonAncestorContainer);
2194    }
2195    catch(e)
2196    {
2197      return null;
2198    }
2199  }
2200
2201  if(typeof types == 'string')
2202  {
2203    types = [types];
2204  }
2205
2206  while(prnt)
2207  {
2208    if(prnt.nodeType == 1)
2209    {
2210      if(types == null) return prnt;
2211      if(types.contains(prnt.tagName.toLowerCase()))
2212      {
2213
2214        return prnt;
2215      }
2216      if(prnt.tagName.toLowerCase() == 'body') break;
2217      if(prnt.tagName.toLowerCase() == 'table') break;
2218    }
2219    prnt = prnt.parentNode;
2220  }
2221
2222  return null;
2223}
2224
2225/**
2226 * Returns the selected element, if any.  That is,
2227 * the element that you have last selected in the "path"
2228 * at the bottom of the editor, or a "control" (eg image)
2229 *
2230 * @returns null | element
2231 */
2232HTMLArea.prototype._activeElement = function(sel)
2233{
2234  if(sel == null) return null;
2235  if(this._selectionEmpty(sel)) return null;
2236
2237  if(HTMLArea.is_ie)
2238  {
2239    if(sel.type.toLowerCase() == "control")
2240    {
2241      return sel.createRange().item(0);
2242    }
2243    else
2244    {
2245
2246      // If it's not a control, then we need to see if
2247      // the selection is the _entire_ text of a parent node
2248      // (this happens when a node is clicked in the tree)
2249      var range = sel.createRange();
2250      var p_elm = this.getParentElement(sel);
2251      if(p_elm.innerHTML == range.htmlText)
2252      {
2253        return p_elm;
2254      }
2255      /*
2256      if(p_elm)
2257      {
2258        var p_rng = this._doc.body.createTextRange();
2259        p_rng.moveToElementText(p_elm);
2260        if(p_rng.isEqual(range))
2261        {
2262          return p_elm;
2263        }
2264      }
2265
2266      if(range.parentElement())
2267      {
2268        var prnt_range = this._doc.body.createTextRange();
2269        prnt_range.moveToElementText(range.parentElement());
2270        if(prnt_range.isEqual(range))
2271        {
2272          return range.parentElement();
2273        }
2274      }
2275      */
2276      return null;
2277    }
2278  }
2279  else
2280  {
2281    // For Mozilla we just see if the selection is not collapsed (something is selected)
2282    // and that the anchor (start of selection) is an element.  This might not be totally
2283    // correct, we possibly should do a simlar check to IE?
2284    if(! sel.isCollapsed)
2285    {
2286      if(sel.anchorNode.nodeType == 1)
2287      {
2288        return sel.anchorNode;
2289      }
2290    }
2291    return null;
2292  }
2293}
2294
2295
2296HTMLArea.prototype._selectionEmpty = function(sel)
2297{
2298  if(!sel) return true;
2299
2300  if(HTMLArea.is_ie)
2301  {
2302    return this._createRange(sel).htmlText == '';
2303  }
2304  else if(typeof sel.isCollapsed != 'undefined')
2305  {
2306    return sel.isCollapsed;
2307  }
2308
2309  return true;
2310}
2311
2312HTMLArea.prototype._getAncestorBlock = function(sel)
2313{
2314  // Scan upwards to find a block level element that we can change or apply to
2315  var prnt = (HTMLArea.is_ie ? this._createRange(sel).parentElement : this._createRange(sel).commonAncestorContainer);
2316
2317  while(prnt && (prnt.nodeType == 1))
2318  {
2319    switch(prnt.tagName.toLowerCase())
2320    {
2321      case 'div' :
2322      case 'p'   :
2323      case 'address'    :
2324      case 'blockquote' :
2325      case 'center'  :
2326      case 'del'     :
2327      case 'ins'     :
2328      case 'pre'     :
2329      case 'h1'      :
2330      case 'h2'      :
2331      case 'h3'      :
2332      case 'h4'      :
2333      case 'h5'      :
2334      case 'h6'      :
2335      case 'h7'      :
2336        // Block Element
2337        return prnt;
2338
2339      case 'body'     :
2340      case 'noframes' :
2341      case 'dd'  :
2342      case 'li'  :
2343      case 'th'  :
2344      case 'td'  :
2345      case 'noscript' :
2346        // Halting element (stop searching)
2347        return null;
2348
2349      default :
2350        // Keep lookin
2351        break;
2352    }
2353  }
2354
2355  return null;
2356}
2357
2358HTMLArea.prototype._createImplicitBlock = function(type)
2359{
2360  // expand it until we reach a block element in either direction
2361  // then wrap the selection in a block and return
2362  var sel = this._getSelection();
2363  if(HTMLArea.is_ie)
2364  {
2365    sel.empty();
2366  }
2367  else
2368  {
2369    sel.collapseToStart();
2370  }
2371
2372  var rng = this._createRange(sel);
2373
2374  // Expand UP
2375
2376  // Expand DN
2377}
2378
2379HTMLArea.prototype._formatBlock = function(block_format)
2380{
2381  var ancestors = this.getAllAncestors();
2382  var apply_to = null;
2383
2384  // Block format can be a tag followed with class defs
2385  //  eg div.blue.left
2386  var target_tag = null;
2387  var target_classNames = [ ];
2388
2389  if(block_format.indexOf('.') >= 0)
2390  {
2391    target_tag = block_format.substr(0, block_format.indexOf('.')).toLowerCase();;
2392
2393    target_classNames = block_format.substr(block_format.indexOf('.'), block_format.length - block_format.indexOf('.')).replace(/\./g, '').replace(/^\s*/, '').replace(/\s*$/, '').split(' ');
2394  }
2395  else
2396  {
2397    target_tag = block_format.toLowerCase();
2398  }
2399
2400  var sel = this._getSelection();
2401  var rng = this._createRange(sel);
2402  var apply_to = null;
2403
2404  if(HTMLArea.is_gecko)
2405  {
2406    if(sel.isCollapsed)
2407    {
2408      // With no selection we want to apply to the whole contents of the ancestor block
2409      apply_to = this._getAncestorBlock(sel);
2410      if(apply_to == null)
2411      {
2412        // If there wasn't an ancestor, make one.
2413        apply_to = this._createImplicitBlock(sel, target_tag);
2414      }
2415    }
2416    else
2417    {
2418      // With a selection it's more tricky
2419      switch(target_tag)
2420      {
2421
2422        case 'h1'      :
2423        case 'h2'      :
2424        case 'h3'      :
2425        case 'h4'      :
2426        case 'h5'      :
2427        case 'h6'      :
2428        case 'h7'      :
2429          apply_to = [ ];
2430          var search_tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7'];
2431          for(var y = 0; y < search_tags.length; y++)
2432          {
2433            var headers = this._doc.getElementsByTagName(search_tag[y]);
2434            for(var x = 0; x < headers.length; x++)
2435            {
2436              if(sel.containsNode(headers[x]))
2437              {
2438                apply_to[apply_to.length] = headers[x];
2439              }
2440            }
2441          }
2442          if(apply_to.length > 0) break;
2443          // If there wern't any in the selection drop through
2444        case 'div' :
2445          apply_to = this._doc.createElement(target_tag);
2446          apply_to.appendChild(rng.extractContents());
2447          rng.insertNode(apply_to);
2448          break;
2449
2450        case 'p'   :
2451        case 'center'  :
2452        case 'pre' :
2453        case 'ins' :
2454        case 'del' :
2455        case 'blockquote' :
2456        case 'address'    :
2457          apply_to = [ ];
2458          var paras = this._doc.getElementsByTagName(target_tag);
2459          for(var x = 0; x < paras.length; x++)
2460          {
2461            if(sel.containsNode(paras[x]))
2462            {
2463              apply_to[apply_to.length] = paras[x];
2464            }
2465          }
2466
2467          if(apply_to.length == 0)
2468          {
2469            sel.collapseToStart();
2470            return this._formatBlock(block_format);
2471          }
2472          break;
2473      }
2474    }
2475  }
2476
2477}
2478
2479// Selects the contents inside the given node
2480HTMLArea.prototype.selectNodeContents = function(node, pos) {
2481  this.focusEditor();
2482  this.forceRedraw();
2483  var range;
2484  var collapsed = (typeof pos != "undefined");
2485  if (HTMLArea.is_ie) {
2486    // Tables and Images get selected as "objects" rather than the text contents
2487    if(!collapsed && node.tagName && node.tagName.toLowerCase().match(/table|img/))
2488    {
2489      range = this._doc.body.createControlRange();
2490      range.add(node);
2491    }
2492    else
2493    {
2494      range = this._doc.body.createTextRange();
2495      range.moveToElementText(node);
2496      (collapsed) && range.collapse(pos);
2497    }
2498    range.select();
2499  } else {
2500    var sel = this._getSelection();
2501    range = this._doc.createRange();
2502    // Tables and Images get selected as "objects" rather than the text contents
2503    if(!collapsed && node.tagName && node.tagName.toLowerCase().match(/table|img/))
2504    {
2505      range.selectNode(node);
2506      (collapsed) && range.collapse(pos);
2507    }
2508    else
2509    {
2510      range.selectNodeContents(node);
2511      (collapsed) && range.collapse(pos);
2512    }
2513    sel.removeAllRanges();
2514    sel.addRange(range);
2515  }
2516};
2517
2518/** Call this function to insert HTML code at the current position.  It deletes
2519 * the selection, if any.
2520 */
2521HTMLArea.prototype.insertHTML = function(html) {
2522  var sel = this._getSelection();
2523  var range = this._createRange(sel);
2524  if (HTMLArea.is_ie) {
2525    range.pasteHTML(html);
2526  } else {
2527    // construct a new document fragment with the given HTML
2528    var fragment = this._doc.createDocumentFragment();
2529    var div = this._doc.createElement("div");
2530    div.innerHTML = html;
2531    while (div.firstChild) {
2532      // the following call also removes the node from div
2533      fragment.appendChild(div.firstChild);
2534    }
2535    // this also removes the selection
2536    var node = this.insertNodeAtSelection(fragment);
2537  }
2538};
2539
2540/**
2541 *  Call this function to surround the existing HTML code in the selection with
2542 *  your tags.  FIXME: buggy!  This function will be deprecated "soon".
2543 */
2544HTMLArea.prototype.surroundHTML = function(startTag, endTag) {
2545  var html = this.getSelectedHTML();
2546  // the following also deletes the selection
2547  this.insertHTML(startTag + html + endTag);
2548};
2549
2550/// Retrieve the selected block
2551HTMLArea.prototype.getSelectedHTML = function() {
2552  var sel = this._getSelection();
2553  var range = this._createRange(sel);
2554  var existing = null;
2555  if (HTMLArea.is_ie) {
2556    existing = range.htmlText;
2557  } else {
2558    existing = HTMLArea.getHTML(range.cloneContents(), false, this);
2559  }
2560  return existing;
2561};
2562
2563/// Return true if we have some selection
2564HTMLArea.prototype.hasSelectedText = function() {
2565  // FIXME: come _on_ mishoo, you can do better than this ;-)
2566  return this.getSelectedHTML() != '';
2567};
2568
2569HTMLArea.prototype._createLink = function(link) {
2570  var editor = this;
2571  var outparam = null;
2572  if (typeof link == "undefined") {
2573    link = this.getParentElement();
2574    if (link) {
2575      if (/^img$/i.test(link.tagName))
2576        link = link.parentNode;
2577      if (!/^a$/i.test(link.tagName))
2578        link = null;
2579    }
2580  }
2581  if (!link) {
2582    var sel = editor._getSelection();
2583    var range = editor._createRange(sel);
2584    var compare = 0;
2585    if (HTMLArea.is_ie) {
2586      compare = range.compareEndPoints("StartToEnd", range);
2587    } else {
2588      compare = range.compareBoundaryPoints(range.START_TO_END, range);
2589    }
2590    if (compare == 0) {
2591      alert("You need to select some text before creating a link");
2592      return;
2593    }
2594    outparam = {
2595      f_href : '',
2596      f_title : '',
2597      f_target : '',
2598      f_usetarget : editor.config.makeLinkShowsTarget
2599    };
2600  } else
2601    outparam = {
2602      f_href   : HTMLArea.is_ie ? editor.stripBaseURL(link.href) : link.getAttribute("href"),
2603      f_title  : link.title,
2604      f_target : link.target,
2605      f_usetarget : editor.config.makeLinkShowsTarget
2606    };
2607  this._popupDialog("link.html", function(param) {
2608    if (!param)
2609      return false;
2610    var a = link;
2611    if (!a) try {
2612      editor._doc.execCommand("createlink", false, param.f_href);
2613      a = editor.getParentElement();
2614      var sel = editor._getSelection();
2615      var range = editor._createRange(sel);
2616      if (!HTMLArea.is_ie) {
2617        a = range.startContainer;
2618        if (!/^a$/i.test(a.tagName)) {
2619          a = a.nextSibling;
2620          if (a == null)
2621            a = range.startContainer.parentNode;
2622        }
2623      }
2624    } catch(e) {}
2625    else {
2626      var href = param.f_href.trim();
2627      editor.selectNodeContents(a);
2628      if (href == "") {
2629        editor._doc.execCommand("unlink", false, null);
2630        editor.updateToolbar();
2631        return false;
2632      }
2633      else {
2634        a.href = href;
2635      }
2636    }
2637    if (!(a && /^a$/i.test(a.tagName)))
2638      return false;
2639    a.target = param.f_target.trim();
2640    a.title = param.f_title.trim();
2641    editor.selectNodeContents(a);
2642    editor.updateToolbar();
2643  }, outparam);
2644};
2645
2646// Called when the user clicks on "InsertImage" button.  If an image is already
2647// there, it will just modify it's properties.
2648HTMLArea.prototype._insertImage = function(image) {
2649  var editor = this;    // for nested functions
2650  var outparam = null;
2651  if (typeof image == "undefined") {
2652    image = this.getParentElement();
2653    if (image && !/^img$/i.test(image.tagName))
2654      image = null;
2655  }
2656  if (image) outparam = {
2657    f_base   : editor.config.baseURL,
2658    f_url    : HTMLArea.is_ie ? editor.stripBaseURL(image.src) : image.getAttribute("src"),
2659    f_alt    : image.alt,
2660    f_border : image.border,
2661    f_align  : image.align,
2662    f_vert   : image.vspace,
2663    f_horiz  : image.hspace
2664  };
2665  this._popupDialog("insert_image.html", function(param) {
2666    if (!param) {       // user must have pressed Cancel
2667      return false;
2668    }
2669    var img = image;
2670    if (!img) {
2671      var sel = editor._getSelection();
2672      var range = editor._createRange(sel);
2673      editor._doc.execCommand("insertimage", false, param.f_url);
2674      if (HTMLArea.is_ie) {
2675        img = range.parentElement();
2676        // wonder if this works...
2677        if (img.tagName.toLowerCase() != "img") {
2678          img = img.previousSibling;
2679        }
2680      } else {
2681        img = range.startContainer.previousSibling;
2682      }
2683    } else {
2684      img.src = param.f_url;
2685    }
2686
2687    for (var field in param) {
2688      var value = param[field];
2689      switch (field) {
2690          case "f_alt"    : img.alt      = value; break;
2691          case "f_border" : img.border = parseInt(value || "0"); break;
2692          case "f_align"  : img.align    = value; break;
2693          case "f_vert"   : img.vspace = parseInt(value || "0"); break;
2694          case "f_horiz"  : img.hspace = parseInt(value || "0"); break;
2695      }
2696    }
2697  }, outparam);
2698};
2699
2700// Called when the user clicks the Insert Table button
2701HTMLArea.prototype._insertTable = function() {
2702  var sel = this._getSelection();
2703  var range = this._createRange(sel);
2704  var editor = this;    // for nested functions
2705  this._popupDialog("insert_table.html", function(param) {
2706    if (!param) {       // user must have pressed Cancel
2707      return false;
2708    }
2709    var doc = editor._doc;
2710    // create the table element
2711    var table = doc.createElement("table");
2712    // assign the given arguments
2713
2714    for (var field in param) {
2715      var value = param[field];
2716      if (!value) {
2717        continue;
2718      }
2719      switch (field) {
2720          case "f_width"   : table.style.width = value + param["f_unit"]; break;
2721          case "f_align"   : table.align         = value; break;
2722          case "f_border"  : table.border        = parseInt(value); break;
2723          case "f_spacing" : table.cellSpacing = parseInt(value); break;
2724          case "f_padding" : table.cellPadding = parseInt(value); break;
2725      }
2726    }
2727    var cellwidth = 0;
2728    if (param.f_fixed)
2729      cellwidth = Math.floor(100 / parseInt(param.f_cols));
2730    var tbody = doc.createElement("tbody");
2731    table.appendChild(tbody);
2732    for (var i = 0; i < param["f_rows"]; ++i) {
2733      var tr = doc.createElement("tr");
2734      tbody.appendChild(tr);
2735      for (var j = 0; j < param["f_cols"]; ++j) {
2736        var td = doc.createElement("td");
2737        if (cellwidth)
2738          td.style.width = cellwidth + "%";
2739        tr.appendChild(td);
2740        // Mozilla likes to see something inside the cell.
2741        (HTMLArea.is_gecko) && td.appendChild(doc.createElement("br"));
2742      }
2743    }
2744    if (HTMLArea.is_ie) {
2745      range.pasteHTML(table.outerHTML);
2746    } else {
2747      // insert the table
2748      editor.insertNodeAtSelection(table);
2749    }
2750    return true;
2751  }, null);
2752};
2753
2754/***************************************************
2755 *  Category: EVENT HANDLERS
2756 ***************************************************/
2757
2758// el is reference to the SELECT object
2759// txt is the name of the select field, as in config.toolbar
2760HTMLArea.prototype._comboSelected = function(el, txt) {
2761  this.focusEditor();
2762  var value = el.options[el.selectedIndex].value;
2763  switch (txt) {
2764      case "fontname":
2765      case "fontsize": this.execCommand(txt, false, value); break;
2766      case "formatblock":
2767    // (HTMLArea.is_ie) && (value = "<" + value + ">");
2768    value = "<" + value + ">"
2769    this.execCommand(txt, false, value);
2770    break;
2771      default:
2772    // try to look it up in the registered dropdowns
2773    var dropdown = this.config.customSelects[txt];
2774    if (typeof dropdown != "undefined") {
2775      dropdown.action(this);
2776    } else {
2777      alert("FIXME: combo box " + txt + " not implemented");
2778    }
2779  }
2780};
2781
2782// the execCommand function (intercepts some commands and replaces them with
2783// our own implementation)
2784HTMLArea.prototype.execCommand = function(cmdID, UI, param) {
2785  var editor = this;    // for nested functions
2786  this.focusEditor();
2787  cmdID = cmdID.toLowerCase();
2788  if (HTMLArea.is_gecko) try { this._doc.execCommand('useCSS', false, true); } catch (e) {};
2789  switch (cmdID) {
2790      case "htmlmode" : this.setMode(); break;
2791      case "hilitecolor":
2792    (HTMLArea.is_ie) && (cmdID = "backcolor");
2793      case "forecolor":
2794    this._popupDialog("select_color.html", function(color) {
2795      if (color) { // selection not canceled
2796        editor._doc.execCommand(cmdID, false, "#" + color);
2797      }
2798    }, HTMLArea._colorToRgb(this._doc.queryCommandValue(cmdID)));
2799    break;
2800      case "createlink":
2801    this._createLink();
2802    break;
2803      case "popupeditor":
2804    // this object will be passed to the newly opened window
2805    HTMLArea._object = this;
2806    if (HTMLArea.is_ie) {
2807      //if (confirm(HTMLArea.I18N.msg["IE-sucks-full-screen"]))
2808      {
2809        window.open(this.popupURL("fullscreen.html"), "ha_fullscreen",
2810              "toolbar=no,location=no,directories=no,status=no,menubar=no," +
2811              "scrollbars=no,resizable=yes,width=640,height=480");
2812      }
2813    } else {
2814      window.open(this.popupURL("fullscreen.html"), "ha_fullscreen",
2815            "toolbar=no,menubar=no,personalbar=no,width=640,height=480," +
2816            "scrollbars=no,resizable=yes");
2817    }
2818    break;
2819      case "undo":
2820      case "redo":
2821    if (this._customUndo)
2822      this[cmdID]();
2823    else
2824      this._doc.execCommand(cmdID, UI, param);
2825    break;
2826      case "inserttable": this._insertTable(); break;
2827      case "insertimage": this._insertImage(); break;
2828      case "about"    : this._popupDialog("about.html", null, this); break;
2829      case "showhelp" : window.open(_editor_url + "reference.html", "ha_help"); break;
2830
2831      case "killword": this._wordClean(); break;
2832
2833      case "cut":
2834      case "copy":
2835      case "paste":
2836    try {
2837      this._doc.execCommand(cmdID, UI, param);
2838      if (this.config.killWordOnPaste)
2839        this._wordClean();
2840    } catch (e) {
2841      if (HTMLArea.is_gecko) {
2842        if (typeof HTMLArea.I18N.msg["Moz-Clipboard"] == "undefined") {
2843          HTMLArea.I18N.msg["Moz-Clipboard"] =
2844            "Unprivileged scripts cannot access Cut/Copy/Paste programatically " +
2845            "for security reasons.  Click OK to see a technical note at mozilla.org " +
2846            "which shows you how to allow a script to access the clipboard.\n\n" +
2847            "[FIXME: please translate this message in your language definition file.]";
2848        }
2849        if (confirm(HTMLArea.I18N.msg["Moz-Clipboard"]))
2850          window.open("http://mozilla.org/editor/midasdemo/securityprefs.html");
2851      }
2852    }
2853    break;
2854      case "lefttoright":
2855      case "righttoleft":
2856    var dir = (cmdID == "righttoleft") ? "rtl" : "ltr";
2857    var el = this.getParentElement();
2858    while (el && !HTMLArea.isBlockElement(el))
2859      el = el.parentNode;
2860    if (el) {
2861      if (el.style.direction == dir)
2862        el.style.direction = "";
2863      else
2864        el.style.direction = dir;
2865    }
2866    break;
2867      default: try { this._doc.execCommand(cmdID, UI, param); }
2868    catch(e) { if (this.config.debug) { alert(e + "\n\nby execCommand(" + cmdID + ");"); } }
2869  }
2870  this.updateToolbar();
2871  return false;
2872};
2873
2874/** A generic event handler for things that happen in the IFRAME's document.
2875 * This function also handles key bindings. */
2876HTMLArea.prototype._editorEvent = function(ev) {
2877  var editor = this;
2878  var keyEvent = (HTMLArea.is_ie && ev.type == "keydown") || (!HTMLArea.is_ie && ev.type == "keypress");
2879
2880  if (keyEvent)
2881    for (var i in editor.plugins) {
2882      var plugin = editor.plugins[i].instance;
2883      if (typeof plugin.onKeyPress == "function")
2884        if (plugin.onKeyPress(ev))
2885          return false;
2886    }
2887  if (keyEvent && ev.ctrlKey && !ev.altKey) {
2888    var sel = null;
2889    var range = null;
2890    var key = String.fromCharCode(HTMLArea.is_ie ? ev.keyCode : ev.charCode).toLowerCase();
2891    var cmd = null;
2892    var value = null;
2893    switch (key) {
2894        case 'a':
2895      if (!HTMLArea.is_ie) {
2896        // KEY select all
2897        sel = this._getSelection();
2898        sel.removeAllRanges();
2899        range = this._createRange();
2900        range.selectNodeContents(this._doc.body);
2901        sel.addRange(range);
2902        HTMLArea._stopEvent(ev);
2903      }
2904      break;
2905
2906      // simple key commands follow
2907
2908        case 'b': cmd = "bold"; break;
2909        case 'i': cmd = "italic"; break;
2910        case 'u': cmd = "underline"; break;
2911        case 's': cmd = "strikethrough"; break;
2912        case 'l': cmd = "justifyleft"; break;
2913        case 'e': cmd = "justifycenter"; break;
2914        case 'r': cmd = "justifyright"; break;
2915        case 'j': cmd = "justifyfull"; break;
2916        case 'z': cmd = "undo"; break;
2917        case 'y': cmd = "redo"; break;
2918        case 'v': if (HTMLArea.is_ie || editor.config.htmlareaPaste) { cmd = "paste"; } break;
2919        case 'n': cmd = "formatblock"; value = HTMLArea.is_ie ? "<p>" : "p"; break;
2920
2921        case '0': cmd = "killword"; break;
2922
2923      // headings
2924        case '1':
2925        case '2':
2926        case '3':
2927        case '4':
2928        case '5':
2929        case '6':
2930      cmd = "formatblock";
2931      value = "h" + key;
2932      if (HTMLArea.is_ie)
2933        value = "<" + value + ">";
2934      break;
2935    }
2936    if (cmd) {
2937      // execute simple command
2938      this.execCommand(cmd, false, value);
2939      HTMLArea._stopEvent(ev);
2940    }
2941  }
2942  else if (keyEvent) {
2943    // other keys here
2944    switch (ev.keyCode) {
2945        case 13: // KEY enter
2946      if (HTMLArea.is_gecko && !ev.shiftKey) {
2947        this.dom_checkInsertP();
2948        HTMLArea._stopEvent(ev);
2949      }
2950      break;
2951        case 8: // KEY backspace
2952        case 46: // KEY delete
2953      if (HTMLArea.is_gecko && !ev.shiftKey) {
2954        if (this.dom_checkBackspace())
2955          HTMLArea._stopEvent(ev);
2956      } else if (HTMLArea.is_ie) {
2957        if (this.ie_checkBackspace())
2958          HTMLArea._stopEvent(ev);
2959      }
2960      break;
2961    }
2962  }
2963
2964  // update the toolbar state after some time
2965  if (editor._timerToolbar) {
2966    clearTimeout(editor._timerToolbar);
2967  }
2968  editor._timerToolbar = setTimeout(function() {
2969    editor.updateToolbar();
2970    editor._timerToolbar = null;
2971  }, 100);
2972};
2973
2974HTMLArea.prototype.convertNode = function(el, newTagName) {
2975  var newel = this._doc.createElement(newTagName);
2976  while (el.firstChild)
2977    newel.appendChild(el.firstChild);
2978  return newel;
2979};
2980
2981HTMLArea.prototype.ie_checkBackspace = function() {
2982  var sel = this._getSelection();
2983  var range = this._createRange(sel);
2984  var r2 = range.duplicate();
2985  r2.moveStart("character", -1);
2986  var a = r2.parentElement();
2987  if (a != range.parentElement() &&
2988      /^a$/i.test(a.tagName)) {
2989    r2.collapse(true);
2990    r2.moveEnd("character", 1);
2991    r2.pasteHTML('');
2992    r2.select();
2993    return true;
2994  }
2995};
2996
2997HTMLArea.prototype.dom_checkBackspace = function() {
2998  var self = this;
2999  setTimeout(function() {
3000    var sel = self._getSelection();
3001    var range = self._createRange(sel);
3002    var SC = range.startContainer;
3003    var SO = range.startOffset;
3004    var EC = range.endContainer;
3005    var EO = range.endOffset;
3006    var newr = SC.nextSibling;
3007    if (SC.nodeType == 3)
3008      SC = SC.parentNode;
3009    if (!/\S/.test(SC.tagName)) {
3010      var p = document.createElement("p");
3011      while (SC.firstChild)
3012        p.appendChild(SC.firstChild);
3013      SC.parentNode.insertBefore(p, SC);
3014      SC.parentNode.removeChild(SC);
3015      var r = range.cloneRange();
3016      r.setStartBefore(newr);
3017      r.setEndAfter(newr);
3018      r.extractContents();
3019      sel.removeAllRanges();
3020      sel.addRange(r);
3021    }
3022  }, 10);
3023};
3024
3025/** The idea here is
3026 * 1. See if we are in a block element
3027 * 2. If we are not, then wrap the current "block" of text into a paragraph
3028 * 3. Now that we have a block element, select all the text between the insertion point
3029 *    and just AFTER the end of the block
3030 *    eg <p>The quick |brown fox jumped over the lazy dog.</p>|
3031 *                     ---------------------------------------
3032 * 4. Extract that from the document, making
3033 *       <p>The quick </p>
3034 *    and a document fragment with
3035 *       <p>brown fox jumped over the lazy dog.</p>
3036 * 5. Reinsert it just after the block element
3037 *       <p>The quick </p><p>brown fox jumped over the lazy dog.</p>
3038 *
3039 * Along the way, allow inserting blank paragraphs, which will look like <p><br/></p>
3040 */
3041
3042HTMLArea.prototype.dom_checkInsertP = function() {
3043
3044  // Get the insertion point, we'll scrub any highlighted text the user wants rid of while we are there.
3045  var sel = this._getSelection();
3046  var range = this._createRange(sel);
3047  if (!range.collapsed)
3048  {
3049    range.deleteContents();
3050  }
3051  this.deactivateEditor();
3052  //sel.removeAllRanges();
3053  //sel.addRange(range);
3054
3055  var SC = range.startContainer;
3056  var SO = range.startOffset;
3057  var EC = range.endContainer;
3058  var EO = range.endOffset;
3059
3060  // If the insertion point is character 0 of the
3061  // document, then insert a space character that we will wrap into a paragraph
3062  // in a bit.
3063  if (SC == EC && SC == body && !SO && !EO)
3064  {
3065    p = this._doc.createTextNode(" ");
3066    body.insertBefore(p, body.firstChild);
3067    range.selectNodeContents(p);
3068    SC = range.startContainer;
3069    SO = range.startOffset;
3070    EC = range.endContainer;
3071    EO = range.endOffset;
3072  }
3073
3074  // See if we are in a block element, if so, great.
3075  var p     = this.getAllAncestors();
3076
3077  var block = null;
3078  var body = this._doc.body;
3079  for (var i = 0; i < p.length; ++i)
3080  {
3081    if(HTMLArea.isParaContainer(p[i]))
3082    {
3083      break;
3084    }
3085    else if (HTMLArea.isBlockElement(p[i]) && !/body|html/i.test(p[i].tagName))
3086    {
3087      block = p[i];
3088      break;
3089    }
3090  }
3091
3092  // If not in a block element, we'll have to turn some stuff into a paragraph
3093  if (!block)
3094  {
3095    // We want to wrap as much stuff as possible into the paragraph in both directions
3096    // from the insertion point.  We start with the start container and walk back up to the
3097    // node just before any of the paragraph containers.
3098    var wrap = range.startContainer;
3099    while(wrap.parentNode && !HTMLArea.isParaContainer(wrap.parentNode))
3100    {
3101      wrap = wrap.parentNode;
3102    }
3103    var start = wrap;
3104    var end   = wrap;
3105
3106    // Now we walk up the sibling list until we hit the top of the document
3107    // or an element that we shouldn't put in a p (eg other p, div, ul, ol, table)
3108    while(start.previousSibling)
3109    {
3110      if(start.previousSibling.tagName)
3111      {
3112        if(!HTMLArea.isBlockElement(start.previousSibling))
3113        {
3114          start = start.previousSibling;
3115        }
3116        else
3117        {
3118          break;
3119        }
3120      }
3121      else
3122      {
3123        start = start.previousSibling;
3124      }
3125    }
3126
3127    // Same down the list
3128    while(end.nextSibling)
3129    {
3130      if(end.nextSibling.tagName)
3131      {
3132        if(!HTMLArea.isBlockElement(end.nextSibling))
3133        {
3134          end = end.nextSibling;
3135        }
3136        else
3137        {
3138          break;
3139        }
3140      }
3141      else
3142      {
3143        end = end.nextSibling;
3144      }
3145    }
3146
3147    // Select the entire block
3148    range.setStartBefore(start);
3149    range.setEndAfter(end);
3150
3151    // Make it a paragraph
3152    range.surroundContents(this._doc.createElement('p'));
3153
3154    // Which becomes the block element
3155    block = range.startContainer.firstChild;
3156
3157    // And finally reset the insertion point to where it was originally
3158    range.setStart(SC, SO);
3159  }
3160
3161  // The start point is the insertion point, so just move the end point to immediatly
3162  // after the block
3163  range.setEndAfter(block);
3164
3165  // Extract the range, to split the block
3166  // If we just did range.extractContents() then Mozilla does wierd stuff
3167  // with selections, but if we clone, then remove the original range and extract
3168  // the clone, it's quite happy.
3169  var r2 = range.cloneRange();
3170  sel.removeRange(range);
3171  var df = r2.extractContents();
3172
3173  if(df.childNodes.length == 0)
3174  {
3175    df.appendChild(this._doc.createElement('p'));
3176    df.firstChild.appendChild(this._doc.createElement('br'));
3177  }
3178
3179  if(df.childNodes.length > 1)
3180  {
3181    var nb = this._doc.createElement('p');
3182    while(df.firstChild)
3183    {
3184      var s = df.firstChild;
3185      df.removeChild(s);
3186      nb.appendChild(s);
3187    }
3188    df.appendChild(nb);
3189  }
3190
3191  // If the original block is empty, put a nsbp in it.
3192  if (!/\S/.test(block.innerHTML))
3193    block.innerHTML = "&nbsp;";
3194
3195  p = df.firstChild;
3196  if (!/\S/.test(p.innerHTML))
3197    p.innerHTML = "<br />";
3198
3199  // If the new block is empty and it's a heading, make it a paragraph
3200  // note, the new block is empty when you are hitting enter at the end of the existing block
3201  if (/^\s*<br\s*\/?>\s*$/.test(p.innerHTML) && /^h[1-6]$/i.test(p.tagName))
3202  {
3203    df.appendChild(this.convertNode(p, "p"));
3204    df.removeChild(p);
3205  }
3206
3207  var newblock = block.parentNode.insertBefore(df.firstChild, block.nextSibling);
3208
3209  /*
3210  if(block.nextSibling)
3211  {
3212    block.parentNode.insertBefore(df, block.nextSibling);
3213  }
3214  else
3215  {
3216    block.parentNode.appendChild(df);
3217  }
3218  */
3219
3220  // Select the range (to set the insertion)
3221  // collapse to the start of the new block
3222  //  (remember the block might be <p><br/></p>, so if we collapsed to the end the <br/> would be noticable)
3223
3224  //range.selectNode(newblock.firstChild);
3225  //range.collapse(true);
3226
3227  this.activateEditor();
3228
3229  var sel = this._getSelection();
3230  sel.removeAllRanges();
3231  sel.collapse(newblock,0);
3232
3233  // scroll into view
3234  this.scrollToElement(newblock);
3235
3236  //this.forceRedraw();
3237
3238};
3239
3240HTMLArea.prototype.scrollToElement = function(e)
3241{
3242  if(HTMLArea.is_gecko)
3243  {
3244    var top  = 0;
3245    var left = 0;
3246    while(e)
3247    {
3248      top  += e.offsetTop;
3249      left += e.offsetLeft;
3250      if(e.offsetParent && e.offsetParent.tagName.toLowerCase() != 'body')
3251      {
3252        e = e.offsetParent;
3253      }
3254      else
3255      {
3256        e = null;
3257      }
3258    }
3259    this._iframe.contentWindow.scrollTo(left, top);
3260  }
3261}
3262
3263// retrieve the HTML
3264HTMLArea.prototype.getHTML = function() {
3265  var html = '';
3266  switch (this._editMode) {
3267      case "wysiwyg"  :
3268        {
3269          if (!this.config.fullPage)
3270            html = HTMLArea.getHTML(this._doc.body, false, this);
3271          else
3272            html = this.doctype + "\n" + HTMLArea.getHTML(this._doc.documentElement, true, this);
3273          break;
3274        }
3275      case "textmode" :
3276        {
3277          html = this._textArea.value;
3278          break;
3279        }
3280      default           :
3281        {
3282          alert("Mode <" + mode + "> not defined!");
3283          return false;
3284        }
3285  }
3286  return html;
3287};
3288
3289HTMLArea.prototype.outwardHtml = function(html)
3290{
3291  html = html.replace(/<(\/?)b(\s|>|\/)/ig, "<$1strong$2");
3292  html = html.replace(/<(\/?)i(\s|>|\/)/ig, "<$1em$2");
3293
3294  // Figure out what our server name is, and how it's referenced
3295  var serverBase = location.href.replace(/(https?:\/\/[^\/]*)\/.*/, '$1') + '/';
3296
3297  // IE puts this in can't figure out why
3298  html = html.replace(/https?:\/\/null\//g, serverBase);
3299
3300  // Make semi-absolute links to be truely absolute
3301  //  we do this just to standardize so that special replacements knows what
3302  //  to expect
3303  html = html.replace(/((href|src|background)=[\'\"])\/+/ig, '$1' + serverBase);
3304
3305  html = this.outwardSpecialReplacements(html);
3306
3307  html = this.fixRelativeLinks(html);
3308  return html;
3309}
3310
3311HTMLArea.prototype.inwardHtml = function(html)
3312{
3313  // Midas uses b and i instead of strong and em, um, hello,
3314  // mozilla, this is the 21st century calling!
3315  if (HTMLArea.is_gecko) {
3316    html = html.replace(/<(\/?)strong(\s|>|\/)/ig, "<$1b$2");
3317    html = html.replace(/<(\/?)em(\s|>|\/)/ig, "<$1i$2");
3318  }
3319  html = this.inwardSpecialReplacements(html);
3320
3321  // For IE's sake, make any URLs that are semi-absolute (="/....") to be
3322  // truely absolute
3323  var nullRE = new RegExp('((href|src|background)=[\'"])/+', 'gi');
3324  html = html.replace(nullRE, '$1' + location.href.replace(/(https?:\/\/[^\/]*)\/.*/, '$1') + '/');
3325
3326  html = this.fixRelativeLinks(html);
3327  return html;
3328}
3329
3330HTMLArea.prototype.outwardSpecialReplacements = function(html)
3331{
3332  for(var i in this.config.specialReplacements)
3333  {
3334    var from = this.config.specialReplacements[i];
3335    var to   = i;
3336    // alert('out : ' + from + '=>' + to);
3337    var reg = new RegExp(from.replace(HTMLArea.RE_Specials, '\\$1'), 'g');
3338    html = html.replace(reg, to.replace(/\$/g, '$$$$'));
3339    //html = html.replace(from, to);
3340  }
3341  return html;
3342}
3343
3344HTMLArea.prototype.inwardSpecialReplacements = function(html)
3345{
3346  // alert("inward");
3347  for(var i in this.config.specialReplacements)
3348  {
3349    var from = i;
3350    var to   = this.config.specialReplacements[i];
3351    // alert('in : ' + from + '=>' + to);
3352    //
3353    // html = html.replace(reg, to);
3354    // html = html.replace(from, to);
3355    var reg = new RegExp(from.replace(HTMLArea.RE_Specials, '\\$1'), 'g');
3356    html = html.replace(reg, to.replace(/\$/g, '$$$$')); // IE uses doubled dollar signs to escape backrefs, also beware that IE also implements $& $_ and $' like perl.
3357  }
3358  return html;
3359}
3360
3361
3362HTMLArea.prototype.fixRelativeLinks = function(html)
3363{
3364
3365  if(typeof this.config.stripSelfNamedAnchors != 'undefined' && this.config.stripSelfNamedAnchors)
3366  {
3367    var stripRe = new RegExp(document.location.href.replace(HTMLArea.RE_Specials, '\\$1') + '(#.*)', 'g');
3368    html = html.replace(stripRe, '$1');
3369  }
3370
3371
3372  if(typeof this.config.stripBaseHref != 'undefined' && this.config.stipBaseHref)
3373  {
3374    var baseRe = null
3375    if(typeof this.config.baseHref != 'undefined' && this.config.baseHref != null)
3376    {
3377      baseRe = new RegExp(this.config.baseHref.replace(HTMLArea.RE_Specials, '\\$1'), 'g');
3378    }
3379    else
3380    {
3381      baseRe = new RegExp(document.location.href.replace(/([^\/]*\/?)$/, '').replace(HTMLArea.RE_Specials, '\\$1'), 'g');
3382    }
3383
3384    html = html.replace(baseRe, '');
3385  }
3386
3387  if(HTMLArea.is_ie)
3388  {
3389    // This is now done in inward & outward
3390    // Don't know why but IE is doing this (putting http://null/ on links?!
3391    // alert(html);
3392    // var nullRE = new RegExp('https?:\/\/null\/', 'g');
3393    // html = html.replace(nullRE, location.href.replace(/(https?:\/\/[^\/]*\/).*/, '$1'));
3394    // alert(html);
3395  }
3396
3397  return html;
3398}
3399
3400// retrieve the HTML (fastest version, but uses innerHTML)
3401HTMLArea.prototype.getInnerHTML = function() {
3402  if(!this._doc.body) return '';
3403  switch (this._editMode) {
3404      case "wysiwyg"  :
3405        if (!this.config.fullPage)
3406          // return this._doc.body.innerHTML;
3407          html = this._doc.body.innerHTML;
3408        else
3409          html = this.doctype + "\n" + this._doc.documentElement.innerHTML;
3410        break;
3411      case "textmode" :
3412        html = this._textArea.value;
3413        break;
3414      default       :
3415        alert("Mode <" + mode + "> not defined!");
3416        return false;
3417  }
3418
3419  return html;
3420};
3421
3422// completely change the HTML inside
3423HTMLArea.prototype.setHTML = function(html) {
3424  switch (this._editMode) {
3425      case "wysiwyg"  :
3426    if (!this.config.fullPage)
3427      this._doc.body.innerHTML = html;
3428    else
3429      // this._doc.documentElement.innerHTML = html;
3430      this._doc.body.innerHTML = html;
3431    break;
3432      case "textmode" : this._textArea.value = html; break;
3433      default       : alert("Mode <" + mode + "> not defined!");
3434  }
3435  return false;
3436};
3437
3438// sets the given doctype (useful when config.fullPage is true)
3439HTMLArea.prototype.setDoctype = function(doctype) {
3440  this.doctype = doctype;
3441};
3442
3443/***************************************************
3444 *  Category: UTILITY FUNCTIONS
3445 ***************************************************/
3446
3447// variable used to pass the object to the popup editor window.
3448HTMLArea._object = null;
3449
3450// function that returns a clone of the given object
3451HTMLArea.cloneObject = function(obj) {
3452  if (!obj) return null;
3453  var newObj = new Object;
3454
3455  // check for array objects
3456  if (obj.constructor.toString().indexOf("function Array(") == 1) {
3457    newObj = obj.constructor();
3458  }
3459
3460  // check for function objects (as usual, IE is fucked up)
3461  if (obj.constructor.toString().indexOf("function Function(") == 1) {
3462    newObj = obj; // just copy reference to it
3463  } else for (var n in obj) {
3464    var node = obj[n];
3465    if (typeof node == 'object') { newObj[n] = HTMLArea.cloneObject(node); }
3466    else                         { newObj[n] = node; }
3467  }
3468
3469  return newObj;
3470};
3471
3472// FIXME!!! this should return false for IE < 5.5
3473HTMLArea.checkSupportedBrowser = function() {
3474  if (HTMLArea.is_gecko) {
3475    if (navigator.productSub < 20021201) {
3476      alert("You need at least Mozilla-1.3 Alpha.\n" +
3477            "Sorry, your Gecko is not supported.");
3478      return false;
3479    }
3480    if (navigator.productSub < 20030210) {
3481      alert("Mozilla < 1.3 Beta is not supported!\n" +
3482            "I'll try, though, but it might not work.");
3483    }
3484  }
3485  return HTMLArea.is_gecko || HTMLArea.is_ie;
3486};
3487
3488// selection & ranges
3489
3490// returns the current selection object
3491HTMLArea.prototype._getSelection = function() {
3492  if (HTMLArea.is_ie) {
3493    return this._doc.selection;
3494  } else {
3495    return this._iframe.contentWindow.getSelection();
3496  }
3497};
3498
3499// returns a range for the current selection
3500HTMLArea.prototype._createRange = function(sel) {
3501  if (HTMLArea.is_ie) {
3502    return sel.createRange();
3503  } else {
3504    this.focusEditor();
3505    if (typeof sel != "undefined") {
3506      try {
3507        return sel.getRangeAt(0);
3508      } catch(e) {
3509        return this._doc.createRange();
3510      }
3511    } else {
3512      return this._doc.createRange();
3513    }
3514  }
3515};
3516
3517// event handling
3518
3519HTMLArea._addEvent = function(el, evname, func) {
3520  if (HTMLArea.is_ie) {
3521    el.attachEvent("on" + evname, func);
3522  } else {
3523    el.addEventListener(evname, func, true);
3524  }
3525};
3526
3527HTMLArea._addEvents = function(el, evs, func) {
3528  for (var i = evs.length; --i >= 0;) {
3529    HTMLArea._addEvent(el, evs[i], func);
3530  }
3531};
3532
3533HTMLArea._removeEvent = function(el, evname, func) {
3534  if (HTMLArea.is_ie) {
3535    el.detachEvent("on" + evname, func);
3536  } else {
3537    el.removeEventListener(evname, func, true);
3538  }
3539};
3540
3541HTMLArea._removeEvents = function(el, evs, func) {
3542  for (var i = evs.length; --i >= 0;) {
3543    HTMLArea._removeEvent(el, evs[i], func);
3544  }
3545};
3546
3547HTMLArea._stopEvent = function(ev) {
3548  if (HTMLArea.is_ie) {
3549    ev.cancelBubble = true;
3550    ev.returnValue = false;
3551  } else {
3552    ev.preventDefault();
3553    ev.stopPropagation();
3554  }
3555};
3556
3557
3558HTMLArea.prototype.notifyOn = function(ev, fn)
3559{
3560  if(typeof this._notifyListeners[ev] == 'undefined')
3561  {
3562    this._notifyListeners[ev] = [ ];
3563  }
3564
3565  this._notifyListeners[ev].push(fn);
3566}
3567
3568HTMLArea.prototype.notifyOf = function(ev, args)
3569{
3570
3571  if(this._notifyListeners[ev])
3572  {
3573
3574    for(var i = 0; i < this._notifyListeners[ev].length; i++)
3575    {
3576      this._notifyListeners[ev][i](ev, args);
3577    }
3578  }
3579}
3580
3581
3582HTMLArea._removeClass = function(el, className) {
3583  if (!(el && el.className)) {
3584    return;
3585  }
3586  var cls = el.className.split(" ");
3587  var ar = new Array();
3588  for (var i = cls.length; i > 0;) {
3589    if (cls[--i] != className) {
3590      ar[ar.length] = cls[i];
3591    }
3592  }
3593  el.className = ar.join(" ");
3594};
3595
3596HTMLArea._addClass = function(el, className) {
3597  // remove the class first, if already there
3598  HTMLArea._removeClass(el, className);
3599  el.className += " " + className;
3600};
3601
3602HTMLArea._hasClass = function(el, className) {
3603  if (!(el && el.className)) {
3604    return false;
3605  }
3606  var cls = el.className.split(" ");
3607  for (var i = cls.length; i > 0;) {
3608    if (cls[--i] == className) {
3609      return true;
3610    }
3611  }
3612  return false;
3613};
3614
3615HTMLArea._blockTags = " body form textarea fieldset ul ol dl li div " +
3616"p h1 h2 h3 h4 h5 h6 quote pre table thead " +
3617"tbody tfoot tr td th iframe address blockquote";
3618HTMLArea.isBlockElement = function(el) {
3619  return el && el.nodeType == 1 && (HTMLArea._blockTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
3620};
3621
3622HTMLArea._paraContainerTags = " body td th caption fieldset div";
3623HTMLArea.isParaContainer = function(el)
3624{
3625  return el && el.nodeType == 1 && (HTMLArea._paraContainerTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
3626}
3627
3628HTMLArea._closingTags = " head script style div span tr td tbody table em strong b i code cite dfn abbr acronym font a title ";
3629HTMLArea.needsClosingTag = function(el) {
3630  return el && el.nodeType == 1 && (HTMLArea._closingTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
3631};
3632
3633// performs HTML encoding of some given string
3634HTMLArea.htmlEncode = function(str) {
3635  if(typeof str.replace == 'undefined') str = str.toString();
3636  // we don't need regexp for that, but.. so be it for now.
3637  str = str.replace(/&/ig, "&amp;");
3638  str = str.replace(/</ig, "&lt;");
3639  str = str.replace(/>/ig, "&gt;");
3640  str = str.replace(/\xA0/g, "&nbsp;"); // Decimal 160, non-breaking-space
3641  str = str.replace(/\x22/g, "&quot;");
3642  // \x22 means '"' -- we use hex reprezentation so that we don't disturb
3643  // JS compressors (well, at least mine fails.. ;)
3644  return str;
3645};
3646
3647// Retrieves the HTML code from the given node.  This is a replacement for
3648// getting innerHTML, using standard DOM calls.
3649// Wrapper catch a Mozilla-Exception with non well formed html source code
3650HTMLArea.getHTML = function(root, outputRoot, editor){
3651    try{
3652        return HTMLArea.getHTMLWrapper(root,outputRoot,editor);
3653    }
3654    catch(e){
3655        alert('Your Document is not well formed. Check JavaScript console for details.');
3656        return editor._iframe.contentWindow.document.body.innerHTML;
3657    }
3658}
3659
3660HTMLArea.getHTMLWrapper = function(root, outputRoot, editor) {
3661  var html = "";
3662  switch (root.nodeType) {
3663    case 10:// Node.DOCUMENT_TYPE_NODE
3664    case 6: // Node.ENTITY_NODE
3665    case 12:// Node.NOTATION_NODE
3666      // this all are for the document type, probably not necessary
3667      break;
3668
3669    case 2: // Node.ATTRIBUTE_NODE
3670      // Never get here, this has to be handled in the ELEMENT case because
3671      // of IE crapness requring that some attributes are grabbed directly from
3672      // the attribute (nodeValue doesn't return correct values), see
3673      //http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=3porgu4mc4ofcoa1uqkf7u8kvv064kjjb4%404ax.com
3674      // for information
3675      break;
3676
3677    case 4: // Node.CDATA_SECTION_NODE
3678      // Mozilla seems to convert CDATA into a comment when going into wysiwyg mode,
3679      //  don't know about IE
3680      html += '<![CDATA[' + root.data + ']]>';
3681      break;
3682
3683    case 5: // Node.ENTITY_REFERENCE_NODE
3684      html += '&' + root.nodeValue + ';';
3685      break;
3686
3687    case 7: // Node.PROCESSING_INSTRUCTION_NODE
3688      // PI's don't seem to survive going into the wysiwyg mode, (at least in moz)
3689      // so this is purely academic
3690      html += '<?' + root.target + ' ' + root.data + ' ?>';
3691      break;
3692
3693
3694      case 1: // Node.ELEMENT_NODE
3695      case 11: // Node.DOCUMENT_FRAGMENT_NODE
3696      case 9: // Node.DOCUMENT_NODE
3697      {
3698    var closed;
3699    var i;
3700    var root_tag = (root.nodeType == 1) ? root.tagName.toLowerCase() : '';
3701    if (root_tag == 'br' && !root.nextSibling)
3702      break;
3703    if (outputRoot)
3704      outputRoot = !(editor.config.htmlRemoveTags && editor.config.htmlRemoveTags.test(root_tag));
3705    if (HTMLArea.is_ie && root_tag == "head") {
3706      if (outputRoot)
3707        html += "<head>";
3708      // lowercasize
3709      var save_multiline = RegExp.multiline;
3710      RegExp.multiline = true;
3711      var txt = root.innerHTML.replace(HTMLArea.RE_tagName, function(str, p1, p2) {
3712        return p1 + p2.toLowerCase();
3713      });
3714      RegExp.multiline = save_multiline;
3715      html += txt;
3716      if (outputRoot)
3717        html += "</head>";
3718      break;
3719    } else if (outputRoot) {
3720      closed = (!(root.hasChildNodes() || HTMLArea.needsClosingTag(root)));
3721      html = "<" + root.tagName.toLowerCase();
3722      var attrs = root.attributes;
3723      for (i = 0; i < attrs.length; ++i) {
3724        var a = attrs.item(i);
3725        if (!a.specified) {
3726          continue;
3727        }
3728        var name = a.nodeName.toLowerCase();
3729        if (/_moz_editor_bogus_node/.test(name)) {
3730          html = "";
3731          break;
3732        }
3733        if (/(_moz)|(contenteditable)|(_msh)/.test(name)) {
3734          // avoid certain attributes
3735          continue;
3736        }
3737        var value;
3738        if (name != "style") {
3739          // IE5.5 reports 25 when cellSpacing is
3740          // 1; other values might be doomed too.
3741          // For this reason we extract the
3742          // values directly from the root node.
3743          // I'm starting to HATE JavaScript
3744          // development.  Browser differences
3745          // suck.
3746          //
3747          // Using Gecko the values of href and src are converted to absolute links
3748          // unless we get them using nodeValue()
3749          if (typeof root[a.nodeName] != "undefined" && name != "href" && name != "src" && !/^on/.test(name)) {
3750            value = root[a.nodeName];
3751          } else {
3752            value = a.nodeValue;
3753            // IE seems not willing to return the original values - it converts to absolute
3754            // links using a.nodeValue, a.value, a.stringValue, root.getAttribute("href")
3755            // So we have to strip the baseurl manually :-/
3756            if (HTMLArea.is_ie && (name == "href" || name == "src")) {
3757              value = editor.stripBaseURL(value);
3758            }
3759          }
3760        } else { // IE fails to put style in attributes list
3761          // FIXME: cssText reported by IE is UPPERCASE
3762          value = root.style.cssText;
3763        }
3764        if (/^(_moz)?$/.test(value)) {
3765          // Mozilla reports some special tags
3766          // here; we don't need them.
3767          continue;
3768        }
3769        html += " " + name + '="' + HTMLArea.htmlEncode(value) + '"';
3770      }
3771      if (html != "") {
3772        html += closed ? " />" : ">";
3773      }
3774    }
3775    for (i = root.firstChild; i; i = i.nextSibling) {
3776      html += HTMLArea.getHTMLWrapper(i, true, editor);
3777    }
3778    if (outputRoot && !closed) {
3779      html += "</" + root.tagName.toLowerCase() + ">";
3780    }
3781    break;
3782      }
3783      case 3: // Node.TEXT_NODE
3784
3785    // If a text node is alone in an element and all spaces, replace it with an non breaking one
3786    // This partially undoes the damage done by moz, which translates '&nbsp;'s into spaces in the data element
3787
3788    html = /^script|style$/i.test(root.parentNode.tagName) ? root.data : HTMLArea.htmlEncode(root.data);
3789    break;
3790
3791      case 8: // Node.COMMENT_NODE
3792    html = "<!--" + root.data + "-->";
3793    break;              // skip comments, for now.
3794  }
3795  return html;
3796};
3797
3798HTMLArea.prototype.stripBaseURL = function(string) {
3799  var baseurl = this.config.baseURL;
3800
3801  // strip to last directory in case baseurl points to a file
3802  baseurl = baseurl.replace(/[^\/]+$/, '');
3803  var basere = new RegExp(baseurl);
3804  string = string.replace(basere, "");
3805
3806  // strip host-part of URL which is added by MSIE to links relative to server root
3807  baseurl = baseurl.replace(/^(https?:\/\/[^\/]+)(.*)$/, '$1');
3808  basere = new RegExp(baseurl);
3809  return string.replace(basere, "");
3810};
3811
3812String.prototype.trim = function() {
3813  return this.replace(/^\s+/, '').replace(/\s+$/, '');
3814};
3815
3816// creates a rgb-style color from a number
3817HTMLArea._makeColor = function(v) {
3818  if (typeof v != "number") {
3819    // already in rgb (hopefully); IE doesn't get here.
3820    return v;
3821  }
3822  // IE sends number; convert to rgb.
3823  var r = v & 0xFF;
3824  var g = (v >> 8) & 0xFF;
3825  var b = (v >> 16) & 0xFF;
3826  return "rgb(" + r + "," + g + "," + b + ")";
3827};
3828
3829// returns hexadecimal color representation from a number or a rgb-style color.
3830HTMLArea._colorToRgb = function(v) {
3831  if (!v)
3832    return '';
3833
3834  // returns the hex representation of one byte (2 digits)
3835  function hex(d) {
3836    return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
3837  };
3838
3839  if (typeof v == "number") {
3840    // we're talking to IE here
3841    var r = v & 0xFF;
3842    var g = (v >> 8) & 0xFF;
3843    var b = (v >> 16) & 0xFF;
3844    return "#" + hex(r) + hex(g) + hex(b);
3845  }
3846
3847  if (v.substr(0, 3) == "rgb") {
3848    // in rgb(...) form -- Mozilla
3849    var re = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/;
3850    if (v.match(re)) {
3851      var r = parseInt(RegExp.$1);
3852      var g = parseInt(RegExp.$2);
3853      var b = parseInt(RegExp.$3);
3854      return "#" + hex(r) + hex(g) + hex(b);
3855    }
3856    // doesn't match RE?!  maybe uses percentages or float numbers
3857    // -- FIXME: not yet implemented.
3858    return null;
3859  }
3860
3861  if (v.substr(0, 1) == "#") {
3862    // already hex rgb (hopefully :D )
3863    return v;
3864  }
3865
3866  // if everything else fails ;)
3867  return null;
3868};
3869
3870// modal dialogs for Mozilla (for IE we're using the showModalDialog() call).
3871
3872// receives an URL to the popup dialog and a function that receives one value;
3873// this function will get called after the dialog is closed, with the return
3874// value of the dialog.
3875HTMLArea.prototype._popupDialog = function(url, action, init) {
3876  Dialog(this.popupURL(url), action, init);
3877};
3878
3879// paths
3880
3881HTMLArea.prototype.imgURL = function(file, plugin) {
3882  if (typeof plugin == "undefined")
3883    return _editor_url + file;
3884  else
3885    return _editor_url + "plugins/" + plugin + "/img/" + file;
3886};
3887
3888HTMLArea.prototype.popupURL = function(file) {
3889  var url = "";
3890  if (file.match(/^plugin:\/\/(.*?)\/(.*)/)) {
3891    var plugin = RegExp.$1;
3892    var popup = RegExp.$2;
3893    if (!/\.html$/.test(popup))
3894      popup += ".html";
3895    url = _editor_url + "plugins/" + plugin + "/popups/" + popup;
3896  } else
3897    url = _editor_url + this.config.popupURL + file;
3898  return url;
3899};
3900
3901/**
3902 * FIX: Internet Explorer returns an item having the _name_ equal to the given
3903 * id, even if it's not having any id.  This way it can return a different form
3904 * field even if it's not a textarea.  This workarounds the problem by
3905 * specifically looking to search only elements having a certain tag name.
3906 */
3907HTMLArea.getElementById = function(tag, id) {
3908  var el, i, objs = document.getElementsByTagName(tag);
3909  for (i = objs.length; --i >= 0 && (el = objs[i]);)
3910    if (el.id == id)
3911      return el;
3912  return null;
3913};
3914
3915
3916/** Use some CSS trickery to toggle borders on tables */
3917
3918HTMLArea.prototype._toggleBorders = function()
3919{
3920  tables = this._doc.getElementsByTagName('TABLE');
3921  if(tables.length != 0)
3922  {
3923   if(!this.borders)
3924   {
3925    name = "bordered";
3926    this.borders = true;
3927   }
3928   else
3929   {
3930     name = "";
3931     this.borders = false;
3932   }
3933
3934   for (var ix=0;ix < tables.length;ix++)
3935   {
3936     if(this.borders)
3937     {
3938       HTMLArea._addClass(tables[ix], 'htmtableborders');
3939     }
3940     else
3941     {
3942       HTMLArea._removeClass(tables[ix], 'htmtableborders');
3943     }
3944   }
3945  }
3946  return true;
3947}
3948
3949
3950HTMLArea.addClasses = function(el, classes)
3951  {
3952    if(el != null)
3953    {
3954      var thiers = el.className.trim().split(' ');
3955      var ours   = classes.split(' ');
3956      for(var x = 0; x < ours.length; x++)
3957      {
3958        var exists = false;
3959        for(var i = 0; exists == false && i < thiers.length; i++)
3960        {
3961          if(thiers[i] == ours[x])
3962          {
3963            exists = true;
3964          }
3965        }
3966        if(exists == false)
3967        {
3968          thiers[thiers.length] = ours[x];
3969        }
3970      }
3971      el.className = thiers.join(' ').trim();
3972    }
3973  }
3974
3975HTMLArea.removeClasses = function(el, classes)
3976{
3977  var existing    = el.className.trim().split();
3978  var new_classes = [ ];
3979  var remove      = classes.trim().split();
3980
3981  for(var i = 0; i < existing.length; i++)
3982  {
3983    var found = false;
3984    for(var x = 0; x < remove.length && !found; x++)
3985    {
3986      if(existing[i] == remove[x])
3987      {
3988        found = true;
3989      }
3990    }
3991    if(!found)
3992    {
3993      new_classes[new_classes.length] = existing[i];
3994    }
3995  }
3996  return new_classes.join(' ');
3997}
3998
3999/** Alias these for convenience */
4000HTMLArea.addClass       = HTMLArea._addClass;
4001HTMLArea.removeClass    = HTMLArea._removeClass;
4002HTMLArea._addClasses    = HTMLArea.addClasses;
4003HTMLArea._removeClasses = HTMLArea.removeClasses;
4004
4005/** Use XML HTTPRequest to post some data back to the server and do something
4006 * with the response (asyncronously!), this is used by such things as the tidy functions
4007 */
4008HTMLArea._postback = function(url, data, handler)
4009{
4010  var req = null;
4011  if(HTMLArea.is_ie)
4012  {
4013   req = new ActiveXObject("Microsoft.XMLHTTP");
4014  }
4015  else
4016  {
4017   req = new XMLHttpRequest();
4018  }
4019
4020  var content = '';
4021  for(var i in data)
4022  {
4023    content += (content.length ? '&' : '') + i + '=' + escape(data[i]);
4024  }
4025
4026  function callBack()
4027  {
4028    if(req.readyState == 4)
4029    {
4030      if(req.status == 200)
4031      {
4032        handler(req.responseText, req);
4033      }
4034      else
4035      {
4036        alert('An error has occurred: ' + req.statusText);
4037      }
4038    }
4039  }
4040
4041  req.onreadystatechange = callBack;
4042
4043  req.open('POST', url, true);
4044  req.setRequestHeader
4045  (
4046      'Content-Type',
4047      'application/x-www-form-urlencoded; charset=UTF-8'
4048  );
4049  //alert(content);
4050  req.send(content);
4051}
4052
4053HTMLArea._getback = function(url, handler)
4054{
4055  var req = null;
4056  if(HTMLArea.is_ie)
4057  {
4058   req = new ActiveXObject("Microsoft.XMLHTTP");
4059  }
4060  else
4061  {
4062   req = new XMLHttpRequest();
4063  }
4064
4065  function callBack()
4066  {
4067    if(req.readyState == 4)
4068    {
4069      if(req.status == 200)
4070      {
4071        handler(req.responseText, req);
4072      }
4073      else
4074      {
4075        alert('An error has occurred: ' + req.statusText);
4076      }
4077    }
4078  }
4079
4080  req.onreadystatechange = callBack;
4081  req.open('GET', url, true);
4082  req.send(null);
4083}
4084
4085HTMLArea._geturlcontent = function(url)
4086{
4087  var req = null;
4088  if(HTMLArea.is_ie)
4089  {
4090   req = new ActiveXObject("Microsoft.XMLHTTP");
4091  }
4092  else
4093  {
4094   req = new XMLHttpRequest();
4095  }
4096
4097  // Synchronous!
4098  req.open('GET', url, false);
4099  req.send(null);
4100  if(req.status == 200)
4101  {
4102    return req.responseText;
4103  }
4104  else
4105  {
4106    return '';
4107  }
4108
4109}
4110
4111/**
4112 * Unless somebody already has, make a little function to debug things
4113 */
4114if(typeof dump == 'undefined')
4115{
4116  function dump(o) {
4117    var s = '';
4118    for (var prop in o) {
4119      s += prop + ' = ' + o[prop] + '\n';
4120    }
4121
4122    x = window.open("", "debugger");
4123    x.document.write('<pre>' + s + '</pre>');
4124  }
4125}
4126
4127
4128HTMLArea.arrayContainsArray = function(a1, a2)
4129{
4130  var all_found = true;
4131  for(var x = 0; x < a2.length; x++)
4132  {
4133    var found = false;
4134    for(var i = 0; i < a1.length; i++)
4135    {
4136      if(a1[i] == a2[x])
4137      {
4138        found = true;
4139        break;
4140      }
4141    }
4142    if(!found)
4143    {
4144      all_found = false;
4145      break;
4146    }
4147  }
4148  return all_found;
4149}
4150
4151HTMLArea.arrayFilter = function(a1, filterfn)
4152{
4153  var new_a = [ ];
4154  for(var x = 0; x < a1.length; x++)
4155  {
4156    if(filterfn(a1[x]))
4157      new_a[new_a.length] = a1[x];
4158  }
4159
4160  return new_a;
4161}
4162
4163HTMLArea.uniq_count = 0;
4164HTMLArea.uniq = function(prefix)
4165{
4166  return prefix + HTMLArea.uniq_count++;
4167}
4168
4169/** New language handling functions **/
4170
4171
4172/** Load a language file.
4173 *  This function should not be used directly, HTMLArea._lc will use it when necessary.
4174 * @param context Case sensitive context name, eg 'HTMLArea', 'TableOperations', ...
4175 * @TODO  Make this useful.
4176 */
4177HTMLArea._loadlang = function(context)
4178{
4179  return { };
4180}
4181
4182/** Return a localised string.
4183 * @param string    English language string
4184 * @param context   Case sensitive context name, eg 'HTMLArea' (default), 'TableOperations'...
4185 */
4186HTMLArea._lc = function(string, context)
4187{
4188  if(typeof HTMLArea._lc_catalog == 'undefined')
4189  {
4190    HTMLArea._lc_catalog = [ ];
4191  }
4192
4193  if(typeof context == 'undefined')
4194  {
4195    context = 'HTMLArea';
4196  }
4197
4198  if(typeof HTMLArea._lc_catalog[context] == 'undefined')
4199  {
4200    HTMLArea._lc_catalog[context] = HTMLArea._loadlang(context);
4201  }
4202
4203  if(typeof HTMLArea._lc_catalog[context][string] == 'undefined')
4204  {
4205    return string; // Indicate it's untranslated
4206  }
4207  else
4208  {
4209    return HTMLArea._lc_catalog[context][string];
4210  }
4211}
4212
4213HTMLArea.hasDisplayedChildren = function(el)
4214{
4215  var children = el.childNodes;
4216  for(var i =0; i < children.length;i++)
4217  {
4218    if(children[i].tagName)
4219    {
4220      if(children[i].style.display != 'none')
4221      {
4222        return true;
4223      }
4224    }
4225  }
4226  return false;
4227}
4228
4229
4230HTMLArea._loadback = function(src, callback)
4231{
4232  var head = document.getElementsByTagName("head")[0];
4233  var evt = HTMLArea.is_ie ? "onreadystatechange" : "onload";
4234
4235  var script = document.createElement("script");
4236  script.type = "text/javascript";
4237  script.src = src;
4238  script[evt] = function()
4239  {
4240    if(HTMLArea.is_ie && !/loaded|complete/.test(window.event.srcElement.readyState))  return;
4241    callback();
4242  }
4243  head.appendChild(script);
4244};
4245
4246HTMLArea.collectionToArray = function(collection)
4247{
4248  var array = [ ];
4249  for(var i = 0; i < collection.length; i++)
4250  {
4251    array.push(collection.item(i));
4252  }
4253  return array;
4254}
4255
4256if(!Array.prototype.append)
4257{
4258  Array.prototype.append  = function(a)
4259  {
4260    for(var i = 0; i<a.length;i++)
4261    {
4262      this.push(a[i]);
4263    }
4264    return this;
4265  }
4266}
4267
4268
4269
4270HTMLArea.init();
4271// EOF
4272// Local variables: //
4273// c-basic-offset:8 //
4274// indent-tabs-mode:t //
4275// End: //
Note: See TracBrowser for help on using the repository browser.