* Removed the Kevin Roth rich text editor and replaced it with TinyMCE.
[citadel.git] / webcit / tiny_mce / tiny_mce_src.js
1 /**
2  * $RCSfile$
3  * $Revision$
4  * $Date$
5  *
6  * @author Moxiecode
7  * @copyright Copyright © 2004, Moxiecode Systems AB, All rights reserved.
8  */
9
10 function TinyMCE() {
11         this.majorVersion = "2";
12         this.minorVersion = "0RC2";
13         this.releaseDate = "2005-09-12";
14
15         this.instances = new Array();
16         this.stickyClassesLookup = new Array();
17         this.windowArgs = new Array();
18         this.loadedFiles = new Array();
19         this.configs = new Array();
20         this.currentConfig = 0;
21         this.eventHandlers = new Array();
22
23         // Browser check
24         this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
25         this.isMSIE5 = this.isMSIE && (navigator.userAgent.indexOf('MSIE 5') != -1);
26         this.isMSIE5_0 = this.isMSIE && (navigator.userAgent.indexOf('MSIE 5.0') != -1);
27         this.isGecko = navigator.userAgent.indexOf('Gecko') != -1;
28         this.isSafari = navigator.userAgent.indexOf('Safari') != -1;
29         this.isMac = navigator.userAgent.indexOf('Mac') != -1;
30         this.dialogCounter = 0;
31
32         // TinyMCE editor id instance counter
33         this.idCounter = 0;
34 };
35
36 TinyMCE.prototype.defParam = function(key, def_val) {
37         this.settings[key] = tinyMCE.getParam(key, def_val);
38 };
39
40 TinyMCE.prototype.init = function(settings) {
41         var theme;
42
43         this.settings = settings;
44
45         // Check if valid browser has execcommand support
46         if (typeof(document.execCommand) == 'undefined')
47                 return;
48
49         // Get script base path
50         if (!tinyMCE.baseURL) {
51                 var elements = document.getElementsByTagName('script');
52
53                 for (var i=0; i<elements.length; i++) {
54                         if (elements[i].src && (elements[i].src.indexOf("tiny_mce.js") != -1 || elements[i].src.indexOf("tiny_mce_src.js") != -1 || elements[i].src.indexOf("tiny_mce_gzip.php") != -1)) {
55                                 var src = elements[i].src;
56
57                                 tinyMCE.srcMode = (src.indexOf('_src') != -1) ? '_src' : '';
58                                 src = src.substring(0, src.lastIndexOf('/'));
59
60                                 tinyMCE.baseURL = src;
61                                 break;
62                         }
63                 }
64         }
65
66         // Get document base path
67         this.documentBasePath = document.location.href;
68         if (this.documentBasePath.indexOf('?') != -1)
69                 this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.indexOf('?'));
70         this.documentURL = this.documentBasePath;
71         this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.lastIndexOf('/'));
72
73         // If not HTTP absolute
74         if (tinyMCE.baseURL.indexOf('://') == -1 && tinyMCE.baseURL.charAt(0) != '/') {
75                 // If site absolute
76                 tinyMCE.baseURL = this.documentBasePath + "/" + tinyMCE.baseURL;
77         }
78
79         // Set default values on settings
80         this.defParam("mode", "none");
81         this.defParam("theme", "advanced");
82         this.defParam("plugins", "", true);
83         this.defParam("language", "en");
84         this.defParam("docs_language", this.settings['language']);
85         this.defParam("elements", "");
86         this.defParam("textarea_trigger", "mce_editable");
87         this.defParam("editor_selector", "");
88         this.defParam("editor_deselector", "mceNoEditor");
89         this.defParam("valid_elements", "+a[id|style|rel|rev|charset|hreflang|dir|lang|tabindex|accesskey|type|name|href|target|title|class|onfocus|onblur|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup],-strong/b[class|style],-em/i[class|style],-strike[class|style],-u[class|style],+p[style|dir|class|align],-ol[class],-ul[class],-li[class],br,img[id|dir|lang|longdesc|usemap|style|class|src|onmouseover|onmouseout|border=0|alt|title|hspace|vspace|width|height|align],-sub[style|class],-sup[style|class],-blockquote[dir|style],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|style|dir|id|lang|bgcolor|background|bordercolor],-tr[id|lang|dir|class|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor],tbody[id|class],thead[id|class],tfoot[id|class],-td[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor],-th[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style],caption[id|lang|dir|class|style],-div[id|dir|class|align|style],-span[style|class|align],-pre[class|align],address[class|align],-h1[style|dir|class|align],-h2[style|dir|class|align],-h3[style|dir|class|align],-h4[style|dir|class|align],-h5[style|dir|class|align],-h6[style|dir|class|align],hr[class]");
90         this.defParam("extended_valid_elements", "");
91         this.defParam("invalid_elements", "");
92         this.defParam("encoding", "");
93         this.defParam("urlconverter_callback", tinyMCE.getParam("urlconvertor_callback", "TinyMCE.prototype.convertURL"));
94         this.defParam("save_callback", "");
95         this.defParam("debug", false);
96         this.defParam("force_br_newlines", false);
97         this.defParam("force_p_newlines", true);
98         this.defParam("add_form_submit_trigger", true);
99         this.defParam("relative_urls", true);
100         this.defParam("remove_script_host", true);
101         this.defParam("focus_alert", true);
102         this.defParam("document_base_url", this.documentURL);
103         this.defParam("visual", true);
104         this.defParam("visual_table_class", "mceVisualAid");
105         this.defParam("setupcontent_callback", "");
106         this.defParam("fix_content_duplication", true);
107         this.defParam("custom_undo_redo", true);
108         this.defParam("custom_undo_redo_levels", -1);
109         this.defParam("custom_undo_redo_keyboard_shortcuts", true);
110         this.defParam("verify_css_classes", false);
111         this.defParam("verify_html", true);
112         this.defParam("apply_source_formatting", false);
113         this.defParam("directionality", "ltr");
114         this.defParam("cleanup_on_startup", false);
115         this.defParam("inline_styles", false);
116         this.defParam("convert_newlines_to_brs", false);
117         this.defParam("auto_reset_designmode", true);
118         this.defParam("entities", "160,nbsp,38,amp,34,quot,162,cent,8364,euro,163,pound,165,yen,169,copy,174,reg,8482,trade,8240,permil,181,micro,183,middot,8226,bull,8230,hellip,8242,prime,8243,Prime,167,sect,182,para,223,szlig,8249,lsaquo,8250,rsaquo,171,laquo,187,raquo,8216,lsquo,8217,rsquo,8220,ldquo,8221,rdquo,8218,sbquo,8222,bdquo,60,lt,62,gt,8804,le,8805,ge,8211,ndash,8212,mdash,175,macr,8254,oline,164,curren,166,brvbar,168,uml,161,iexcl,191,iquest,710,circ,732,tilde,176,deg,8722,minus,177,plusmn,247,divide,8260,frasl,215,times,185,sup1,178,sup2,179,sup3,188,frac14,189,frac12,190,frac34,402,fnof,8747,int,8721,sum,8734,infin,8730,radic,8764,sim,8773,cong,8776,asymp,8800,ne,8801,equiv,8712,isin,8713,notin,8715,ni,8719,prod,8743,and,8744,or,172,not,8745,cap,8746,cup,8706,part,8704,forall,8707,exist,8709,empty,8711,nabla,8727,lowast,8733,prop,8736,ang,180,acute,184,cedil,170,ordf,186,ordm,8224,dagger,8225,Dagger,192,Agrave,194,Acirc,195,Atilde,196,Auml,197,Aring,198,AElig,199,Ccedil,200,Egrave,202,Ecirc,203,Euml,204,Igrave,206,Icirc,207,Iuml,208,ETH,209,Ntilde,210,Ograve,212,Ocirc,213,Otilde,214,Ouml,216,Oslash,338,OElig,217,Ugrave,219,Ucirc,220,Uuml,376,Yuml,222,THORN,224,agrave,226,acirc,227,atilde,228,auml,229,aring,230,aelig,231,ccedil,232,egrave,234,ecirc,235,euml,236,igrave,238,icirc,239,iuml,240,eth,241,ntilde,242,ograve,244,ocirc,245,otilde,246,ouml,248,oslash,339,oelig,249,ugrave,251,ucirc,252,uuml,254,thorn,255,yuml,914,Beta,915,Gamma,916,Delta,917,Epsilon,918,Zeta,919,Eta,920,Theta,921,Iota,922,Kappa,923,Lambda,924,Mu,925,Nu,926,Xi,927,Omicron,928,Pi,929,Rho,931,Sigma,932,Tau,933,Upsilon,934,Phi,935,Chi,936,Psi,937,Omega,945,alpha,946,beta,947,gamma,948,delta,949,epsilon,950,zeta,951,eta,952,theta,953,iota,954,kappa,955,lambda,956,mu,957,nu,958,xi,959,omicron,960,pi,961,rho,962,sigmaf,963,sigma,964,tau,965,upsilon,966,phi,967,chi,968,psi,969,omega,8501,alefsym,982,piv,8476,real,977,thetasym,978,upsih,8472,weierp,8465,image,8592,larr,8593,uarr,8594,rarr,8595,darr,8596,harr,8629,crarr,8656,lArr,8657,uArr,8658,rArr,8659,dArr,8660,hArr,8756,there4,8834,sub,8835,sup,8836,nsub,8838,sube,8839,supe,8853,oplus,8855,otimes,8869,perp,8901,sdot,8968,lceil,8969,rceil,8970,lfloor,8971,rfloor,9001,lang,9002,rang,9674,loz,9824,spades,9827,clubs,9829,hearts,9830,diams,8194,ensp,8195,emsp,8201,thinsp,8204,zwnj,8205,zwj,8206,lrm,8207,rlm,173,shy,233,eacute,237,iacute,243,oacute,250,uacute,193,Aacute,225,aacute,201,Eacute,205,Iacute,211,Oacute,218,Uacute,221,Yacute,253,yacute");
119         this.defParam("entity_encoding", "named");
120         this.defParam("cleanup_callback", "");
121         this.defParam("add_unload_trigger", true);
122         this.defParam("ask", false);
123         this.defParam("nowrap", false);
124         this.defParam("auto_resize", false);
125         this.defParam("auto_focus", false);
126         this.defParam("cleanup", true);
127         this.defParam("remove_linebreaks", true);
128         this.defParam("button_tile_map", false);
129         this.defParam("submit_patch", true);
130         this.defParam("browsers", "msie,safari,gecko");
131         this.defParam("dialog_type", "window");
132         this.defParam("convert_fonts_to_styles", true);
133
134         // Browser check IE
135         if (this.isMSIE && this.settings['browsers'].indexOf('msie') == -1)
136                 return;
137
138         // Browser check Gecko
139         if (this.isGecko && this.settings['browsers'].indexOf('gecko') == -1)
140                 return;
141
142         // Browser check Safari
143         if (this.isSafari && this.settings['browsers'].indexOf('safari') == -1)
144                 return;
145
146         // Setup baseHREF
147         var baseHREF = tinyMCE.settings['document_base_url'];
148         if (baseHREF.indexOf('?') != -1)
149                 baseHREF = baseHREF.substring(0, baseHREF.indexOf('?'));
150         this.settings['base_href'] = baseHREF.substring(0, baseHREF.lastIndexOf('/')) + "/";
151
152         theme = this.settings['theme'];
153
154         this.blockRegExp = new RegExp("^(h[1-6]|p|div|address|pre|form|table|li|ol|ul|td)$", "i");
155         this.posKeyCodes = new Array(13,45,36,35,33,34,37,38,39,40);
156
157         // Theme url
158         this.settings['theme_href'] = tinyMCE.baseURL + "/themes/" + theme;
159
160         if (!tinyMCE.isMSIE)
161                 this.settings['force_br_newlines'] = false;
162
163         if (tinyMCE.getParam("content_css", false)) {
164                 var cssPath = tinyMCE.getParam("content_css", "");
165
166                 // Is relative
167                 if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')
168                         this.settings['content_css'] = this.documentBasePath + "/" + cssPath;
169                 else
170                         this.settings['content_css'] = cssPath;
171         } else
172                 this.settings['content_css'] = '';
173
174         if (tinyMCE.getParam("popups_css", false)) {
175                 var cssPath = tinyMCE.getParam("popups_css", "");
176
177                 // Is relative
178                 if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')
179                         this.settings['popups_css'] = this.documentBasePath + "/" + cssPath;
180                 else
181                         this.settings['popups_css'] = cssPath;
182         } else
183                 this.settings['popups_css'] = tinyMCE.baseURL + "/themes/" + theme + "/css/editor_popup.css";
184
185         if (tinyMCE.getParam("editor_css", false)) {
186                 var cssPath = tinyMCE.getParam("editor_css", "");
187
188                 // Is relative
189                 if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')
190                         this.settings['editor_css'] = this.documentBasePath + "/" + cssPath;
191                 else
192                         this.settings['editor_css'] = cssPath;
193         } else
194                 this.settings['editor_css'] = tinyMCE.baseURL + "/themes/" + theme + "/css/editor_ui.css";
195
196         if (tinyMCE.settings['debug']) {
197                 var msg = "Debug: \n";
198
199                 msg += "baseURL: " + this.baseURL + "\n";
200                 msg += "documentBasePath: " + this.documentBasePath + "\n";
201                 msg += "content_css: " + this.settings['content_css'] + "\n";
202                 msg += "popups_css: " + this.settings['popups_css'] + "\n";
203                 msg += "editor_css: " + this.settings['editor_css'] + "\n";
204
205                 alert(msg);
206         }
207
208         // Init HTML cleanup
209         this._initCleanup();
210
211         // Only do this once
212         if (this.configs.length == 0) {
213                 // Is Safari enabled
214                 if (this.isSafari && this.getParam('safari_warning', true))
215                         alert("Safari support is very limited and should be considered experimental.\nSo there is no need to even submit bugreports on this early version.");
216
217                 tinyMCE.addEvent(window, "load", TinyMCE.prototype.onLoad);
218
219                 if (tinyMCE.isMSIE) {
220                         if (tinyMCE.settings['add_unload_trigger']) {
221                                 tinyMCE.addEvent(window, "unload", TinyMCE.prototype.unloadHandler);
222                                 tinyMCE.addEvent(window.document, "beforeunload", TinyMCE.prototype.unloadHandler);
223                         }
224                 } else {
225                         if (tinyMCE.settings['add_unload_trigger'])
226                                 tinyMCE.addEvent(window, "unload", function () {tinyMCE.triggerSave(true, true);});
227                 }
228         }
229
230         this.loadScript(tinyMCE.baseURL + '/themes/' + this.settings['theme'] + '/editor_template' + tinyMCE.srcMode + '.js');
231         this.loadScript(tinyMCE.baseURL + '/langs/' + this.settings['language'] +  '.js');
232         this.loadCSS(this.settings['editor_css']);
233
234         // Add theme plugins
235         var themePlugins = tinyMCE.getParam('plugins', '', true, ',');
236         if (this.settings['plugins'] != '') {
237                 for (var i=0; i<themePlugins.length; i++)
238                         this.loadScript(tinyMCE.baseURL + '/plugins/' + themePlugins[i] + '/editor_plugin' + tinyMCE.srcMode + '.js');
239         }
240
241         // Save away this config
242         settings['index'] = this.configs.length;
243         this.configs[this.configs.length] = settings;
244 };
245
246 TinyMCE.prototype.loadScript = function(url) {
247         for (var i=0; i<this.loadedFiles.length; i++) {
248                 if (this.loadedFiles[i] == url)
249                         return;
250         }
251
252         document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></script>');
253
254         this.loadedFiles[this.loadedFiles.length] = url;
255 };
256
257 TinyMCE.prototype.loadCSS = function(url) {
258         for (var i=0; i<this.loadedFiles.length; i++) {
259                 if (this.loadedFiles[i] == url)
260                         return;
261         }
262
263         document.write('<link href="' + url + '" rel="stylesheet" type="text/css" />');
264
265         this.loadedFiles[this.loadedFiles.length] = url;
266 };
267
268 TinyMCE.prototype.importCSS = function(doc, css_file) {
269         if (css_file == '')
270                 return;
271
272         if (tinyMCE.isMSIE)
273                 var styleSheet = doc.createStyleSheet(css_file);
274         else {
275                 var elm = doc.createElement("link");
276
277                 elm.rel = "stylesheet";
278                 elm.href = css_file;
279
280                 if (headArr = doc.getElementsByTagName("head"))
281                         headArr[0].appendChild(elm);
282         }
283 };
284
285 TinyMCE.prototype.confirmAdd = function(e, settings) {
286         var elm = tinyMCE.isMSIE ? event.srcElement : e.target;
287         var elementId = elm.name ? elm.name : elm.id;
288
289         tinyMCE.settings = settings;
290
291         if (!elm.getAttribute('mce_noask') && confirm(tinyMCELang['lang_edit_confirm']))
292                 tinyMCE.addMCEControl(elm, elementId);
293
294         elm.setAttribute('mce_noask', 'true');
295 };
296
297 TinyMCE.prototype.updateContent = function(form_element_name) {
298         // Find MCE instance linked to given form element and copy it's value
299         var formElement = document.getElementById(form_element_name);
300         for (var n in tinyMCE.instances) {
301                 var inst = tinyMCE.instances[n];
302
303                 inst.switchSettings();
304
305                 if (inst.formElement == formElement) {
306                         var doc = inst.getDoc();
307         
308                         tinyMCE._setHTML(doc, inst.formElement.value);
309
310                         if (!tinyMCE.isMSIE)
311                                 doc.body.innerHTML = tinyMCE._cleanupHTML(inst, doc, this.settings, doc.body, inst.visualAid);
312                 }
313         }
314 };
315
316 TinyMCE.prototype.addMCEControl = function(replace_element, form_element_name, target_document) {
317         var id = "mce_editor_" + tinyMCE.idCounter++;
318         var inst = new TinyMCEControl(tinyMCE.settings);
319
320         inst.editorId = id;
321         this.instances[id] = inst;
322
323         inst.onAdd(replace_element, form_element_name, target_document);
324 };
325
326 TinyMCE.prototype.triggerSave = function(skip_cleanup, skip_callback) {
327         // Cleanup and set all form fields
328         for (var n in tinyMCE.instances) {
329                 var inst = tinyMCE.instances[n];
330
331                 inst.switchSettings();
332
333                 tinyMCE.settings['preformatted'] = false;
334
335                 // Default to false
336                 if (typeof(skip_cleanup) == "undefined")
337                         skip_cleanup = false;
338
339                 // Default to false
340                 if (typeof(skip_callback) == "undefined")
341                         skip_callback = false;
342
343                 tinyMCE._setHTML(inst.getDoc(), inst.getBody().innerHTML);
344
345                 // Remove visual aids when cleanup is disabled
346                 if (inst.settings['cleanup'] == false) {
347                         tinyMCE.handleVisualAid(inst.getBody(), true, false, inst);
348                         tinyMCE._setEventsEnabled(inst.getBody(), false);
349                 }
350
351                 tinyMCE._customCleanup(inst, "submit_content_dom", inst.contentWindow.document.body);
352                 var htm = skip_cleanup ? inst.getBody().innerHTML : tinyMCE._cleanupHTML(inst, inst.getDoc(), this.settings, inst.getBody(), this.visualAid, true);
353                 htm = tinyMCE._customCleanup(inst, "submit_content", htm);
354
355                 if (tinyMCE.settings["encoding"] == "xml" || tinyMCE.settings["encoding"] == "html")
356                         htm = tinyMCE.convertStringToXML(htm);
357
358                 if (!skip_callback && tinyMCE.settings['save_callback'] != "")
359                         var content = eval(tinyMCE.settings['save_callback'] + "(inst.formTargetElementId,htm,inst.getBody());");
360
361                 // Use callback content if available
362                 if ((typeof(content) != "undefined") && content != null)
363                         htm = content;
364
365                 // Replace some weird entities (Bug: #1056343)
366                 htm = tinyMCE.regexpReplace(htm, "&#40;", "(", "gi");
367                 htm = tinyMCE.regexpReplace(htm, "&#41;", ")", "gi");
368                 htm = tinyMCE.regexpReplace(htm, "&#59;", ";", "gi");
369                 htm = tinyMCE.regexpReplace(htm, "&#34;", "&quot;", "gi");
370                 htm = tinyMCE.regexpReplace(htm, "&#94;", "^", "gi");
371
372                 if (inst.formElement)
373                         inst.formElement.value = htm;
374         }
375 };
376
377 TinyMCE.prototype._setEventsEnabled = function(node, state) {
378         var events = new Array('onfocus','onblur','onclick','ondblclick',
379                                 'onmousedown','onmouseup','onmouseover','onmousemove',
380                                 'onmouseout','onkeypress','onkeydown','onkeydown','onkeyup');
381
382         var elms = node.getElementsByTagName("a");
383         for (var i=0; i<elms.length; i++) {
384                 var event = "";
385
386                 for (var x=0; x<events.length; x++) {
387                         if ((event = tinyMCE.getAttrib(elms[i], events[x])) != '') {
388                                 event = tinyMCE.cleanupEventStr("" + event);
389
390                                 if (state)
391                                         event = "return true;" + event;
392                                 else
393                                         event = event.replace(/^return true;/gi, '');
394
395                                 elms[i].removeAttribute(events[x]);
396                                 elms[i].setAttribute(events[x], event);
397                         }
398                 }
399         }
400 };
401
402 TinyMCE.prototype.resetForm = function(form_index) {
403         var formObj = document.forms[form_index];
404
405         for (var n in tinyMCE.instances) {
406                 var inst = tinyMCE.instances[n];
407
408                 inst.switchSettings();
409
410                 for (var i=0; i<formObj.elements.length; i++) {
411                         if (inst.formTargetElementId == formObj.elements[i].name) {
412                                 inst.getBody().innerHTML = formObj.elements[i].value;
413                                 return;
414                         }
415                 }
416         }
417 };
418
419 TinyMCE.prototype.execInstanceCommand = function(editor_id, command, user_interface, value, focus) {
420         var inst = tinyMCE.getInstanceById(editor_id);
421         if (inst) {
422                 if (typeof(focus) == "undefined")
423                         focus = true;
424
425                 if (focus)
426                         inst.contentWindow.focus();
427
428                 // Reset design mode if lost
429                 inst.autoResetDesignMode();
430
431                 this.selectedElement = inst.getFocusElement();
432                 this.selectedInstance = inst;
433                 tinyMCE.execCommand(command, user_interface, value);
434         }
435 };
436
437 TinyMCE.prototype.execCommand = function(command, user_interface, value) {
438         // Default input
439         user_interface = user_interface ? user_interface : false;
440         value = value ? value : null;
441
442         if (tinyMCE.selectedInstance)
443                 tinyMCE.selectedInstance.switchSettings();
444
445         switch (command) {
446                 case 'mceHelp':
447                         var template = new Array();
448
449                         template['file']   = 'about.htm';
450                         template['width']  = 480;
451                         template['height'] = 380;
452
453                         tinyMCE.openWindow(template, {
454                                 tinymce_version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion,
455                                 tinymce_releasedate : tinyMCE.releaseDate,
456                                 inline : "yes"
457                         });
458                 return;
459
460                 case 'mceFocus':
461                         var inst = tinyMCE.getInstanceById(value);
462                         if (inst)
463                                 inst.contentWindow.focus();
464                 return;
465
466                 case "mceAddControl":
467                 case "mceAddEditor":
468                         tinyMCE.addMCEControl(tinyMCE._getElementById(value), value);
469                         return;
470
471                 case "mceAddFrameControl":
472                         tinyMCE.addMCEControl(tinyMCE._getElementById(value), value['element'], value['document']);
473                         return;
474
475                 case "mceRemoveControl":
476                 case "mceRemoveEditor":
477                         tinyMCE.removeMCEControl(value);
478                         return;
479
480                 case "mceResetDesignMode":
481                         // Resets the designmode state of the editors in Gecko
482                         if (!tinyMCE.isMSIE) {
483                                 for (var n in tinyMCE.instances) {
484                                         try {
485                                                 tinyMCE.instances[n].getDoc().designMode = "on";
486                                         } catch (e) {
487                                                 // Ignore any errors
488                                         }
489                                 }
490                         }
491
492                         return;
493         }
494
495         if (this.selectedInstance)
496                 this.selectedInstance.execCommand(command, user_interface, value);
497         else if (tinyMCE.settings['focus_alert'])
498                 alert(tinyMCELang['lang_focus_alert']);
499 };
500
501 TinyMCE.prototype.eventPatch = function(editor_id) {
502         // Remove odd, error
503         if (typeof(tinyMCE) == "undefined")
504                 return true;
505
506         for (var i=0; i<document.frames.length; i++) {
507                 if (document.frames[i].event) {
508                         var event = document.frames[i].event;
509
510                         event.target = event.srcElement;
511
512                         TinyMCE.prototype.handleEvent(event);
513                         return;
514                 }
515         }
516 };
517
518 TinyMCE.prototype.unloadHandler = function() {
519         tinyMCE.triggerSave(true, true);
520 };
521
522 TinyMCE.prototype.addEventHandlers = function(editor_id) {
523         if (tinyMCE.isMSIE) {
524                 var doc = document.frames[editor_id].document;
525
526                 // Event patch
527                 tinyMCE.addEvent(doc, "keypress", TinyMCE.prototype.eventPatch);
528                 tinyMCE.addEvent(doc, "keyup", TinyMCE.prototype.eventPatch);
529                 tinyMCE.addEvent(doc, "keydown", TinyMCE.prototype.eventPatch);
530                 tinyMCE.addEvent(doc, "mouseup", TinyMCE.prototype.eventPatch);
531                 tinyMCE.addEvent(doc, "click", TinyMCE.prototype.eventPatch);
532         } else {
533                 var inst = tinyMCE.instances[editor_id];
534                 var doc = inst.getDoc();
535
536                 inst.switchSettings();
537
538                 tinyMCE.addEvent(doc, "keypress", tinyMCE.handleEvent);
539                 tinyMCE.addEvent(doc, "keydown", tinyMCE.handleEvent);
540                 tinyMCE.addEvent(doc, "keyup", tinyMCE.handleEvent);
541                 tinyMCE.addEvent(doc, "click", tinyMCE.handleEvent);
542                 tinyMCE.addEvent(doc, "mouseup", tinyMCE.handleEvent);
543                 tinyMCE.addEvent(doc, "mousedown", tinyMCE.handleEvent);
544                 tinyMCE.addEvent(doc, "focus", tinyMCE.handleEvent);
545                 tinyMCE.addEvent(doc, "blur", tinyMCE.handleEvent);
546
547                 eval('try { doc.designMode = "On"; } catch(e) {}');
548         }
549 };
550
551 TinyMCE.prototype._createIFrame = function(replace_element) {
552         var iframe = document.createElement("iframe");
553         var id = replace_element.getAttribute("id");
554
555         iframe.setAttribute("id", id);
556         //iframe.setAttribute("className", "mceEditorArea");
557         iframe.setAttribute("border", "0");
558         iframe.setAttribute("frameBorder", "0");
559         iframe.setAttribute("marginWidth", "0");
560         iframe.setAttribute("marginHeight", "0");
561         iframe.setAttribute("leftMargin", "0");
562         iframe.setAttribute("topMargin", "0");
563         iframe.setAttribute("width", tinyMCE.settings['area_width']);
564         iframe.setAttribute("height", tinyMCE.settings['area_height']);
565         iframe.setAttribute("allowtransparency", "true");
566
567         if (tinyMCE.settings["auto_resize"])
568                 iframe.setAttribute("scrolling", "no");
569
570         // Must have a src element in MSIE HTTPs breaks aswell as absoute URLs
571         if (tinyMCE.isMSIE)
572                 iframe.setAttribute("src", this.settings['default_document']);
573
574         iframe.style.width = tinyMCE.settings['area_width'];
575         iframe.style.height = tinyMCE.settings['area_height'];
576
577         // MSIE 5.0 issue
578         if (tinyMCE.isMSIE)
579                 replace_element.outerHTML = iframe.outerHTML;
580         else
581                 replace_element.parentNode.replaceChild(iframe, replace_element);
582
583         if (tinyMCE.isMSIE)
584                 return window.frames[id];
585         else
586                 return iframe;
587 };
588
589 TinyMCE.prototype.setupContent = function(editor_id) {
590         var inst = tinyMCE.instances[editor_id];
591         var doc = inst.getDoc();
592         var head = doc.getElementsByTagName('head').item(0);
593         var content = inst.startContent;
594
595         inst.switchSettings();
596
597         // Not loaded correctly hit it again, Mozilla bug #997860
598         if (!tinyMCE.isMSIE && doc.title != "blank_page") {
599                 // This part will remove the designMode status
600                 doc.location.href = tinyMCE.baseURL + "/blank.htm";
601                 window.setTimeout("tinyMCE.setupContent('" + editor_id + "');", 1000);
602                 return;
603         }
604
605         if (!head) {
606                 window.setTimeout("tinyMCE.setupContent('" + editor_id + "');", 10);
607                 return;
608         }
609
610         // Import theme specific content CSS the user specific
611         tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/themes/" + inst.settings['theme'] + "/css/editor_content.css");
612         tinyMCE.importCSS(inst.getDoc(), inst.settings['content_css']);
613         tinyMCE.executeCallback('init_instance_callback', '_initInstance', 0, inst);
614
615         if (tinyMCE.settings['nowrap'])
616                 doc.body.style.whiteSpace = "nowrap";
617
618         doc.body.dir = this.settings['directionality'];
619         doc.editorId = editor_id;
620
621         // Add on document element in Mozilla
622         if (!tinyMCE.isMSIE)
623                 doc.documentElement.editorId = editor_id;
624
625         // Setup base element
626         base = doc.createElement("base");
627         base.setAttribute('href', tinyMCE.settings['base_href']);
628         head.appendChild(base);
629
630         // Replace new line characters to BRs
631         if (tinyMCE.settings['convert_newlines_to_brs']) {
632                 content = tinyMCE.regexpReplace(content, "\r\n", "<br />", "gi");
633                 content = tinyMCE.regexpReplace(content, "\r", "<br />", "gi");
634                 content = tinyMCE.regexpReplace(content, "\n", "<br />", "gi");
635         }
636
637         // Call custom cleanup code
638         content = tinyMCE._customCleanup(inst, "insert_to_editor", content);
639
640         if (tinyMCE.isMSIE) {
641                 // Ugly!!!
642                 window.setInterval('try{tinyMCE.getCSSClasses(document.frames["' + editor_id + '"].document, "' + editor_id + '");}catch(e){}', 500);
643
644                 if (tinyMCE.settings["force_br_newlines"])
645                         document.frames[editor_id].document.styleSheets[0].addRule("p", "margin: 0px;");
646
647                 var body = document.frames[editor_id].document.body;
648
649                 tinyMCE.addEvent(body, "beforepaste", TinyMCE.prototype.eventPatch);
650                 tinyMCE.addEvent(body, "beforecut", TinyMCE.prototype.eventPatch);
651
652                 body.editorId = editor_id;
653         }
654
655         // Fix for bug #958637
656         if (!tinyMCE.isMSIE) {
657                 var contentElement = inst.getDoc().createElement("body");
658                 var doc = inst.getDoc();
659
660                 contentElement.innerHTML = content;
661
662                 // Remove weridness!
663                 if (tinyMCE.settings['force_p_newlines'])
664                         content = content.replace(new RegExp('&lt;&gt;', 'g'), "");
665
666                 if (tinyMCE.settings['cleanup_on_startup'])
667                         inst.getBody().innerHTML = tinyMCE._cleanupHTML(inst, doc, this.settings, contentElement);
668                 else {
669                         // Convert all strong/em to b/i
670                         content = tinyMCE.regexpReplace(content, "<strong", "<b", "gi");
671                         content = tinyMCE.regexpReplace(content, "<em(/?)>", "<i$1>", "gi");
672                         content = tinyMCE.regexpReplace(content, "<em ", "<i ", "gi");
673                         content = tinyMCE.regexpReplace(content, "</strong>", "</b>", "gi");
674                         content = tinyMCE.regexpReplace(content, "</em>", "</i>", "gi");
675                         inst.getBody().innerHTML = content;
676                 }
677
678                 inst.convertAllRelativeURLs();
679         } else {
680                 if (tinyMCE.settings['cleanup_on_startup']) {
681                         tinyMCE._setHTML(inst.getDoc(), content);
682
683                         // Produces permission denied error in MSIE 5.5
684                         eval('try {inst.getBody().innerHTML = tinyMCE._cleanupHTML(inst, inst.contentDocument, this.settings, inst.getBody());} catch(e) {}');
685                 } else
686                         tinyMCE._setHTML(inst.getDoc(), content);
687         }
688
689         // Fix for bug #957681
690         //inst.getDoc().designMode = inst.getDoc().designMode;
691
692         // Setup element references
693         var parentElm = document.getElementById(inst.editorId + '_parent');
694         if (parentElm.lastChild.nodeName.toLowerCase() == "input")
695                 inst.formElement = parentElm.lastChild;
696         else
697                 inst.formElement = parentElm.nextSibling;
698
699         tinyMCE.handleVisualAid(inst.getBody(), true, tinyMCE.settings['visual'], inst);
700         tinyMCE.executeCallback('setupcontent_callback', '_setupContent', 0, editor_id, inst.getBody(), inst.getDoc());
701
702         // Re-add design mode on mozilla
703         if (!tinyMCE.isMSIE)
704                 TinyMCE.prototype.addEventHandlers(editor_id);
705
706         // Add blur handler
707         if (tinyMCE.isMSIE)
708                 tinyMCE.addEvent(inst.getBody(), "blur", TinyMCE.prototype.eventPatch);
709
710         // Trigger node change, this call locks buttons for tables and so forth
711         tinyMCE.selectedInstance = inst;
712         tinyMCE.selectedElement = inst.contentWindow.document.body;
713         tinyMCE.triggerNodeChange(false, true);
714
715         // Call custom DOM cleanup
716         tinyMCE._customCleanup(inst, "insert_to_editor_dom", inst.getBody());
717         tinyMCE._customCleanup(inst, "setup_content_dom", inst.getBody());
718         tinyMCE._setEventsEnabled(inst.getBody(), true);
719
720         inst.startContent = tinyMCE.trim(inst.getBody().innerHTML);
721         inst.undoLevels[inst.undoLevels.length] = inst.startContent;
722 };
723
724 TinyMCE.prototype.cancelEvent = function(e) {
725         if (tinyMCE.isMSIE) {
726                 e.returnValue = false;
727                 e.cancelBubble = true;
728         } else
729                 e.preventDefault();
730 };
731
732 TinyMCE.prototype.removeTinyMCEFormElements = function(form_obj) {
733         // Disable all UI form elements that TinyMCE created
734         for (var i=0; i<form_obj.elements.length; i++) {
735                 var elementId = form_obj.elements[i].name ? form_obj.elements[i].name : form_obj.elements[i].id;
736
737                 if (elementId.indexOf('mce_editor_') == 0)
738                         form_obj.elements[i].disabled = true;
739         }
740 };
741
742 TinyMCE.prototype.accessibleEventHandler = function(e) {
743         var win = this._win;
744         e = tinyMCE.isMSIE ? win.event : e;
745         var elm = tinyMCE.isMSIE ? e.srcElement : e.target;
746
747         // Piggyback onchange
748         if (elm.nodeName == "SELECT" && !elm.oldonchange) {
749                 elm.oldonchange = elm.onchange;
750                 elm.onchange = null;
751         }
752
753         // Execute onchange and remove piggyback
754         if (e.keyCode == 13) {
755                 elm.onchange = elm.oldonchange;
756                 elm.onchange();
757                 elm.oldonchange = null;
758                 tinyMCE.cancelEvent(e);
759         }
760 };
761
762 TinyMCE.prototype.addSelectAccessibility = function(e, select, win) {
763         // Add event handlers 
764         if (!select._isAccessible) {
765                 select.onkeydown = tinyMCE.accessibleEventHandler;
766                 select._isAccessible = true;
767                 select._win = win;
768         }
769 };
770
771 TinyMCE.prototype.handleEvent = function(e) {
772         // Remove odd, error
773         if (typeof(tinyMCE) == "undefined")
774                 return true;
775
776         //tinyMCE.debug(e.type + " " + e.target.nodeName + " " + (e.relatedTarget ? e.relatedTarget.nodeName : ""));
777
778         switch (e.type) {
779                 case "blur":
780                         if (tinyMCE.selectedInstance)
781                                 tinyMCE.selectedInstance.execCommand('mceEndTyping');
782
783                         return;
784
785                 case "submit":
786                         tinyMCE.removeTinyMCEFormElements(tinyMCE.isMSIE ? window.event.srcElement : e.target);
787                         tinyMCE.triggerSave();
788                         tinyMCE.isNotDirty = true;
789                         return;
790
791                 case "reset":
792                         var formObj = tinyMCE.isMSIE ? window.event.srcElement : e.target;
793
794                         for (var i=0; i<document.forms.length; i++) {
795                                 if (document.forms[i] == formObj)
796                                         window.setTimeout('tinyMCE.resetForm(' + i + ');', 10);
797                         }
798
799                         return;
800
801                 case "keypress":
802                         if (e.target.editorId) {
803                                 tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
804                         } else {
805                                 if (e.target.ownerDocument.editorId)
806                                         tinyMCE.selectedInstance = tinyMCE.instances[e.target.ownerDocument.editorId];
807                         }
808
809                         if (tinyMCE.selectedInstance)
810                                 tinyMCE.selectedInstance.switchSettings();
811
812                         // Insert space instead of &nbsp;
813 /*                      if (tinyMCE.isGecko && e.charCode == 32) {
814                                 if (tinyMCE.selectedInstance._insertSpace()) {
815                                         // Cancel event
816                                         e.preventDefault();
817                                         return false;
818                                 }
819                         }*/
820
821                         // Insert P element
822                         if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && e.keyCode == 13 && !e.shiftKey) {
823                                 // Insert P element instead of BR
824                                 if (tinyMCE.selectedInstance._insertPara(e)) {
825                                         // Cancel event
826                                         tinyMCE.execCommand("mceAddUndoLevel");
827                                         e.preventDefault();
828                                         return false;
829                                 }
830                         }
831
832                         // Handle backspace
833                         if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && (e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey) {
834                                 // Insert P element instead of BR
835                                 if (tinyMCE.selectedInstance._handleBackSpace(e.type)) {
836                                         // Cancel event
837                                         tinyMCE.execCommand("mceAddUndoLevel");
838                                         e.preventDefault();
839                                         return false;
840                                 }
841                         }
842
843                         // Mozilla custom key handling
844                         if (tinyMCE.isGecko && e.ctrlKey && tinyMCE.settings['custom_undo_redo']) {
845                                 if (tinyMCE.settings['custom_undo_redo_keyboard_shortcuts']) {
846                                         if (e.charCode == 122) { // Ctrl+Z
847                                                 tinyMCE.selectedInstance.execCommand("Undo");
848
849                                                 // Cancel event
850                                                 e.preventDefault();
851                                                 return false;
852                                         }
853
854                                         if (e.charCode == 121) { // Ctrl+Y
855                                                 tinyMCE.selectedInstance.execCommand("Redo");
856
857                                                 // Cancel event
858                                                 e.preventDefault();
859                                                 return false;
860                                         }
861                                 }
862
863                                 if (e.charCode == 98) { // Ctrl+B
864                                         tinyMCE.selectedInstance.execCommand("Bold");
865
866                                         // Cancel event
867                                         e.preventDefault();
868                                         return false;
869                                 }
870
871                                 if (e.charCode == 105) { // Ctrl+I
872                                         tinyMCE.selectedInstance.execCommand("Italic");
873
874                                         // Cancel event
875                                         e.preventDefault();
876                                         return false;
877                                 }
878
879                                 if (e.charCode == 117) { // Ctrl+U
880                                         tinyMCE.selectedInstance.execCommand("Underline");
881
882                                         // Cancel event
883                                         e.preventDefault();
884                                         return false;
885                                 }
886                         }
887
888                         // Return key pressed
889                         if (tinyMCE.isMSIE && tinyMCE.settings['force_br_newlines'] && e.keyCode == 13) {
890                                 if (e.target.editorId)
891                                         tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
892
893                                 if (tinyMCE.selectedInstance) {
894                                         var sel = tinyMCE.selectedInstance.getDoc().selection;
895                                         var rng = sel.createRange();
896
897                                         if (tinyMCE.getParentElement(rng.parentElement(), "li") != null)
898                                                 return false;
899
900                                         // Cancel event
901                                         e.returnValue = false;
902                                         e.cancelBubble = true;
903
904                                         // Insert BR element
905                                         rng.pasteHTML("<br />");
906                                         rng.collapse(false);
907                                         rng.select();
908
909                                         tinyMCE.execCommand("mceAddUndoLevel");
910                                         tinyMCE.triggerNodeChange(false);
911                                         return false;
912                                 }
913                         }
914
915                         // Backspace or delete
916                         if (e.keyCode == 8 || e.keyCode == 46) {
917                                 tinyMCE.selectedElement = e.target;
918                                 tinyMCE.linkElement = tinyMCE.getParentElement(e.target, "a");
919                                 tinyMCE.imgElement = tinyMCE.getParentElement(e.target, "img");
920                                 tinyMCE.triggerNodeChange(false);
921                         }
922
923                         return false;
924                 break;
925
926                 case "keyup":
927                 case "keydown":
928                         if (e.target.editorId)
929                                 tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
930                         else
931                                 return;
932
933                         if (tinyMCE.selectedInstance)
934                                 tinyMCE.selectedInstance.switchSettings();
935
936                         var inst = tinyMCE.selectedInstance;
937
938                         // Handle backspace
939                         if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && (e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey) {
940                                 // Insert P element instead of BR
941                                 if (tinyMCE.selectedInstance._handleBackSpace(e.type)) {
942                                         // Cancel event
943                                         tinyMCE.execCommand("mceAddUndoLevel");
944                                         e.preventDefault();
945                                         return false;
946                                 }
947                         }
948
949                         tinyMCE.selectedElement = null;
950                         tinyMCE.selectedNode = null;
951                         var elm = tinyMCE.selectedInstance.getFocusElement();
952                         tinyMCE.linkElement = tinyMCE.getParentElement(elm, "a");
953                         tinyMCE.imgElement = tinyMCE.getParentElement(elm, "img");
954                         tinyMCE.selectedElement = elm;
955
956                         // Update visualaids on tabs
957                         if (tinyMCE.isGecko && e.type == "keyup" && e.keyCode == 9)
958                                 tinyMCE.handleVisualAid(tinyMCE.selectedInstance.getBody(), true, tinyMCE.settings['visual'], tinyMCE.selectedInstance);
959
960                         // Run image/link fix on Gecko if diffrent document base on paste
961                         if (tinyMCE.isGecko && tinyMCE.settings['document_base_url'] != "" + document.location.href && e.type == "keyup" && e.ctrlKey && e.keyCode == 86)
962                                 tinyMCE.selectedInstance.fixBrokenURLs();
963
964                         // Fix empty elements on return/enter, check where enter occured
965                         if (tinyMCE.isMSIE && e.type == "keydown" && e.keyCode == 13)
966                                 tinyMCE.enterKeyElement = tinyMCE.selectedInstance.getFocusElement();
967
968                         // Fix empty elements on return/enter
969                         if (tinyMCE.isMSIE && e.type == "keyup" && e.keyCode == 13) {
970                                 var elm = tinyMCE.enterKeyElement;
971                                 if (elm) {
972                                         var re = new RegExp('^HR|IMG|BR$','g'); // Skip these
973                                         var dre = new RegExp('^H[1-6]$','g'); // Add double on these
974
975                                         if (!elm.hasChildNodes() && !re.test(elm.nodeName)) {
976                                                 if (dre.test(elm.nodeName))
977                                                         elm.innerHTML = "&nbsp;&nbsp;";
978                                                 else
979                                                         elm.innerHTML = "&nbsp;";
980                                         }
981                                 }
982                         }
983
984                         // Check if it's a position key
985                         var keys = tinyMCE.posKeyCodes;
986                         var posKey = false;
987                         for (var i=0; i<keys.length; i++) {
988                                 if (keys[i] == e.keyCode) {
989                                         posKey = true;
990                                         break;
991                                 }
992                         }
993
994                         //tinyMCE.debug(e.keyCode);
995
996                         // MSIE custom key handling
997                         if (tinyMCE.isMSIE && tinyMCE.settings['custom_undo_redo']) {
998                                 var keys = new Array(8,46); // Backspace,Delete
999                                 for (var i=0; i<keys.length; i++) {
1000                                         if (keys[i] == e.keyCode) {
1001                                                 if (e.type == "keyup")
1002                                                         tinyMCE.triggerNodeChange(false);
1003                                         }
1004                                 }
1005
1006                                 if (tinyMCE.settings['custom_undo_redo_keyboard_shortcuts']) {
1007                                         if (e.keyCode == 90 && e.ctrlKey && e.type == "keydown") { // Ctrl+Z
1008                                                 tinyMCE.selectedInstance.execCommand("Undo");
1009                                                 tinyMCE.triggerNodeChange(false);
1010                                         }
1011
1012                                         if (e.keyCode == 89 && e.ctrlKey && e.type == "keydown") { // Ctrl+Y
1013                                                 tinyMCE.selectedInstance.execCommand("Redo");
1014                                                 tinyMCE.triggerNodeChange(false);
1015                                         }
1016
1017                                         if ((e.keyCode == 90 || e.keyCode == 89) && e.ctrlKey) {
1018                                                 // Cancel event
1019                                                 e.returnValue = false;
1020                                                 e.cancelBubble = true;
1021                                                 return false;
1022                                         }
1023                                 }
1024                         }
1025
1026                         // Handle Undo/Redo when typing content
1027
1028                         // Start typing (non position key)
1029                         if (!posKey && e.type == "keyup")
1030                                 tinyMCE.execCommand("mceStartTyping");
1031
1032                         // End typing (position key) or some Ctrl event
1033                         if (e.type == "keyup" && (posKey || e.ctrlKey))
1034                                 tinyMCE.execCommand("mceEndTyping");
1035
1036                         if (posKey && e.type == "keyup")
1037                                 tinyMCE.triggerNodeChange(false);
1038                 break;
1039
1040                 case "mousedown":
1041                 case "mouseup":
1042                 case "click":
1043                 case "focus":
1044                         if (tinyMCE.selectedInstance)
1045                                 tinyMCE.selectedInstance.switchSettings();
1046
1047                         // Check instance event trigged on
1048                         var targetBody = tinyMCE.getParentElement(e.target, "body");
1049                         for (var instanceName in tinyMCE.instances) {
1050                                 var inst = tinyMCE.instances[instanceName];
1051
1052                                 // Reset design mode if lost (on everything just in case)
1053                                 inst.autoResetDesignMode();
1054
1055                                 if (inst.getBody() == targetBody) {
1056                                         tinyMCE.selectedInstance = inst;
1057                                         tinyMCE.selectedElement = e.target;
1058                                         tinyMCE.linkElement = tinyMCE.getParentElement(tinyMCE.selectedElement, "a");
1059                                         tinyMCE.imgElement = tinyMCE.getParentElement(tinyMCE.selectedElement, "img");
1060                                         break;
1061                                 }
1062                         }
1063
1064                         if (tinyMCE.isSafari) {
1065                                 tinyMCE.selectedInstance.lastSafariSelection = tinyMCE.selectedInstance.getBookmark();
1066                                 tinyMCE.selectedInstance.lastSafariSelectedElement = tinyMCE.selectedElement;
1067
1068                                 var lnk = tinyMCE.getParentElement(tinyMCE.selectedElement, "a");
1069
1070                                 // Patch the darned link
1071                                 if (lnk && e.type == "mousedown") {
1072                                         lnk.setAttribute("mce_real_href", lnk.getAttribute("href"));
1073                                         lnk.setAttribute("href", "javascript:void(0);");
1074                                 }
1075
1076                                 // Patch back
1077                                 if (lnk && e.type == "click") {
1078                                         window.setTimeout(function() {
1079                                                 lnk.setAttribute("href", lnk.getAttribute("mce_real_href"));
1080                                                 lnk.removeAttribute("mce_real_href");
1081                                         }, 10);
1082                                 }
1083                         }
1084
1085                         // Reset selected node
1086                         if (e.type != "focus")
1087                                 tinyMCE.selectedNode = null;
1088
1089                         tinyMCE.triggerNodeChange(false);
1090                         tinyMCE.execCommand("mceEndTyping");
1091
1092                         if (e.type == "mouseup")
1093                                 tinyMCE.execCommand("mceAddUndoLevel");
1094
1095                         // Just in case
1096                         if (!tinyMCE.selectedInstance && e.target.editorId)
1097                                 tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];
1098
1099                         // Run image/link fix on Gecko if diffrent document base
1100                         if (tinyMCE.isGecko && tinyMCE.settings['document_base_url'] != "" + document.location.href)
1101                                 window.setTimeout('tinyMCE.getInstanceById("' + inst.editorId + '").fixBrokenURLs();', 10);
1102
1103                         return false;
1104                 break;
1105     } // end switch
1106 }; // end function
1107
1108 TinyMCE.prototype.switchClass = function(element, class_name, lock_state) {
1109         var lockChanged = false;
1110
1111         if (typeof(lock_state) != "undefined" && element != null) {
1112                 element.classLock = lock_state;
1113                 lockChanged = true;
1114         }
1115
1116         if (element != null && (lockChanged || !element.classLock)) {
1117                 element.oldClassName = element.className;
1118                 element.className = class_name;
1119         }
1120 };
1121
1122 TinyMCE.prototype.restoreAndSwitchClass = function(element, class_name) {
1123         if (element != null && !element.classLock) {
1124                 this.restoreClass(element);
1125                 this.switchClass(element, class_name);
1126         }
1127 };
1128
1129 TinyMCE.prototype.switchClassSticky = function(element_name, class_name, lock_state) {
1130         var element, lockChanged = false;
1131
1132         // Performance issue
1133         if (!this.stickyClassesLookup[element_name])
1134                 this.stickyClassesLookup[element_name] = document.getElementById(element_name);
1135
1136 //      element = document.getElementById(element_name);
1137         element = this.stickyClassesLookup[element_name];
1138
1139         if (typeof(lock_state) != "undefined" && element != null) {
1140                 element.classLock = lock_state;
1141                 lockChanged = true;
1142         }
1143
1144         if (element != null && (lockChanged || !element.classLock)) {
1145                 element.className = class_name;
1146                 element.oldClassName = class_name;
1147         }
1148 };
1149
1150 TinyMCE.prototype.restoreClass = function(element) {
1151         if (element != null && element.oldClassName && !element.classLock) {
1152                 element.className = element.oldClassName;
1153                 element.oldClassName = null;
1154         }
1155 };
1156
1157 TinyMCE.prototype.setClassLock = function(element, lock_state) {
1158         if (element != null)
1159                 element.classLock = lock_state;
1160 };
1161
1162 TinyMCE.prototype.addEvent = function(obj, name, handler) {
1163         if (tinyMCE.isMSIE) {
1164                 obj.attachEvent("on" + name, handler);
1165         } else
1166                 obj.addEventListener(name, handler, false);
1167 };
1168
1169 TinyMCE.prototype.submitPatch = function() {
1170         tinyMCE.removeTinyMCEFormElements(this);
1171         tinyMCE.triggerSave();
1172         this.oldSubmit();
1173         tinyMCE.isNotDirty = true;
1174 };
1175
1176 TinyMCE.prototype.onLoad = function() {
1177         for (var c=0; c<tinyMCE.configs.length; c++) {
1178                 tinyMCE.settings = tinyMCE.configs[c];
1179
1180                 var selector = tinyMCE.getParam("editor_selector");
1181                 var deselector = tinyMCE.getParam("editor_deselector");
1182                 var elementRefAr = new Array();
1183
1184                 // Add submit triggers
1185                 if (document.forms && tinyMCE.settings['add_form_submit_trigger'] && !tinyMCE.submitTriggers) {
1186                         for (var i=0; i<document.forms.length; i++) {
1187                                 var form = document.forms[i];
1188
1189                                 tinyMCE.addEvent(form, "submit", TinyMCE.prototype.handleEvent);
1190                                 tinyMCE.addEvent(form, "reset", TinyMCE.prototype.handleEvent);
1191                                 tinyMCE.submitTriggers = true; // Do it only once
1192
1193                                 // Patch the form.submit function
1194                                 if (tinyMCE.settings['submit_patch']) {
1195                                         try {
1196                                                 form.oldSubmit = form.submit;
1197                                                 form.submit = TinyMCE.prototype.submitPatch;
1198                                         } catch (e) {
1199                                                 // Do nothing
1200                                         }
1201                                 }
1202                         }
1203                 }
1204
1205                 // Add editor instances based on mode
1206                 var mode = tinyMCE.settings['mode'];
1207                 switch (mode) {
1208                         case "exact":
1209                                 var elements = tinyMCE.getParam('elements', '', true, ',');
1210
1211                                 for (var i=0; i<elements.length; i++) {
1212                                         var element = tinyMCE._getElementById(elements[i]);
1213                                         var trigger = element ? element.getAttribute(tinyMCE.settings['textarea_trigger']) : "";
1214
1215                                         if (tinyMCE.getAttrib(element, "class").indexOf(deselector) != -1)
1216                                                 continue;
1217
1218                                         if (trigger == "false")
1219                                                 continue;
1220
1221                                         if (tinyMCE.settings['ask'] && element) {
1222                                                 elementRefAr[elementRefAr.length] = element;
1223                                                 continue;
1224                                         }
1225
1226                                         if (element)
1227                                                 tinyMCE.addMCEControl(element, elements[i]);
1228                                         else if (tinyMCE.settings['debug'])
1229                                                 alert("Error: Could not find element by id or name: " + elements[i]);
1230                                 }
1231                         break;
1232
1233                         case "specific_textareas":
1234                         case "textareas":
1235                                 var nodeList = document.getElementsByTagName("textarea");
1236
1237                                 for (var i=0; i<nodeList.length; i++) {
1238                                         var elm = nodeList.item(i);
1239                                         var trigger = elm.getAttribute(tinyMCE.settings['textarea_trigger']);
1240
1241                                         if (selector != '' && tinyMCE.getAttrib(elm, "class").indexOf(selector) == -1)
1242                                                 continue;
1243
1244                                         if (tinyMCE.getAttrib(elm, "class").indexOf(deselector) != -1)
1245                                                 continue;
1246
1247                                         if ((mode == "specific_textareas" && trigger == "true") || (mode == "textareas" && trigger != "false"))
1248                                                 elementRefAr[elementRefAr.length] = elm;
1249                                 }
1250                         break;
1251                 }
1252
1253                 for (var i=0; i<elementRefAr.length; i++) {
1254                         var element = elementRefAr[i];
1255                         var elementId = element.name ? element.name : element.id;
1256
1257                         if (tinyMCE.settings['ask']) {
1258                                 // Focus breaks in Mozilla
1259                                 if (tinyMCE.isGecko) {
1260                                         var settings = tinyMCE.settings;
1261
1262                                         tinyMCE.addEvent(element, "focus", function (e) {window.setTimeout(function() {TinyMCE.prototype.confirmAdd(e, settings);}, 10);});
1263                                 } else {
1264                                         var settings = tinyMCE.settings;
1265
1266                                         tinyMCE.addEvent(element, "focus", function () { TinyMCE.prototype.confirmAdd(null, settings); });
1267                                 }
1268                         } else
1269                                 tinyMCE.addMCEControl(element, elementId);
1270                 }
1271
1272                 // Handle auto focus
1273                 if (tinyMCE.settings['auto_focus']) {
1274                         window.setTimeout(function () {
1275                                 var inst = tinyMCE.getInstanceById(tinyMCE.settings['auto_focus']);
1276                                 inst.selectNode(inst.getBody(), true, true);
1277                                 inst.contentWindow.focus();
1278                         }, 10);
1279                 }
1280
1281                 tinyMCE.executeCallback('oninit', '_oninit', 0);
1282         }
1283 };
1284
1285 TinyMCE.prototype.removeMCEControl = function(editor_id) {
1286         var inst = tinyMCE.getInstanceById(editor_id);
1287
1288         if (inst) {
1289                 inst.switchSettings();
1290
1291                 editor_id = inst.editorId;
1292                 var html = tinyMCE.getContent(editor_id);
1293
1294                 // Remove editor instance from instances array
1295                 var tmpInstances = new Array();
1296                 for (var instanceName in tinyMCE.instances) {
1297                         var instance = tinyMCE.instances[instanceName];
1298                         if (instanceName != editor_id)
1299                                         tmpInstances[instanceName] = instance;
1300                 }
1301                 tinyMCE.instances = tmpInstances;
1302
1303                 tinyMCE.selectedElement = null;
1304                 tinyMCE.selectedInstance = null;
1305
1306                 // Remove element
1307                 var replaceElement = document.getElementById(editor_id + "_parent");
1308                 var oldTargetElement = inst.oldTargetElement;
1309                 var targetName = oldTargetElement.nodeName.toLowerCase();
1310
1311                 if (targetName == "textarea" || targetName == "input") {
1312                         // Just show the old text area
1313                         replaceElement.parentNode.removeChild(replaceElement);
1314                         oldTargetElement.style.display = "inline";
1315                         oldTargetElement.value = html;
1316                 } else {
1317                         oldTargetElement.innerHTML = html;
1318
1319                         replaceElement.parentNode.insertBefore(oldTargetElement, replaceElement);
1320                         replaceElement.parentNode.removeChild(replaceElement);
1321                 }
1322         }
1323 };
1324
1325 TinyMCE.prototype._cleanupElementName = function(element_name, element) {
1326         var name = "";
1327
1328         element_name = element_name.toLowerCase();
1329
1330         // Never include body
1331         if (element_name == "body")
1332                 return null;
1333
1334         // If verification mode
1335         if (tinyMCE.cleanup_verify_html) {
1336                 // Check if invalid element
1337                 for (var i=0; i<tinyMCE.cleanup_invalidElements.length; i++) {
1338                         if (tinyMCE.cleanup_invalidElements[i] == element_name)
1339                                 return null;
1340                 }
1341
1342                 // Check if valid element
1343                 var validElement = false;
1344                 var elementAttribs = null;
1345                 for (var i=0; i<tinyMCE.cleanup_validElements.length && !elementAttribs; i++) {
1346                         for (var x=0, n=tinyMCE.cleanup_validElements[i][0].length; x<n; x++) {
1347                                 var elmMatch = tinyMCE.cleanup_validElements[i][0][x];
1348
1349                                 if (elmMatch.charAt(0) == '+' || elmMatch.charAt(0) == '-')
1350                                         elmMatch = elmMatch.substring(1);
1351
1352                                 // Handle wildcard/regexp
1353                                 if (elmMatch.match(new RegExp('\\*|\\?|\\+', 'g')) != null) {
1354                                         elmMatch = elmMatch.replace(new RegExp('\\?', 'g'), '(\\S?)');
1355                                         elmMatch = elmMatch.replace(new RegExp('\\+', 'g'), '(\\S+)');
1356                                         elmMatch = elmMatch.replace(new RegExp('\\*', 'g'), '(\\S*)');
1357                                         elmMatch = "^" + elmMatch + "$";
1358                                         if (element_name.match(new RegExp(elmMatch, 'g'))) {
1359                                                 elementAttribs = tinyMCE.cleanup_validElements[i];
1360                                                 validElement = true;
1361                                                 break;
1362                                         }
1363                                 }
1364
1365                                 // Handle non regexp
1366                                 if (element_name == elmMatch) {
1367                                         elementAttribs = tinyMCE.cleanup_validElements[i];
1368                                         validElement = true;
1369                                         element_name = elementAttribs[0][0];
1370                                         break;
1371                                 }
1372                         }
1373                 }
1374
1375                 if (!validElement)
1376                         return null;
1377         }
1378
1379         if (element_name.charAt(0) == '+' || element_name.charAt(0) == '-')
1380                 name = element_name.substring(1);
1381
1382         // Special Mozilla stuff
1383         if (!tinyMCE.isMSIE) {
1384                 // Fix for bug #958498
1385                 if (name == "strong" && !tinyMCE.cleanup_on_save)
1386                         element_name = "b";
1387                 else if (name == "em" && !tinyMCE.cleanup_on_save)
1388                         element_name = "i";
1389         }
1390
1391         var elmData = new Object();
1392
1393         elmData.element_name = element_name;
1394         elmData.valid_attribs = elementAttribs;
1395
1396         return elmData;
1397 };
1398
1399 /**
1400  * This function moves CSS styles to/from attributes.
1401  */
1402 TinyMCE.prototype._moveStyle = function(elm, style, attrib) {
1403         if (tinyMCE.cleanup_inline_styles) {
1404                 var val = tinyMCE.getAttrib(elm, attrib);
1405
1406                 if (val != '') {
1407                         val = '' + val;
1408
1409                         switch (attrib) {
1410                                 case "background":
1411                                         val = "url('" + val + "');";
1412                                         break;
1413
1414                                 case "bordercolor":
1415                                         if (elm.style.borderStyle == '' || elm.style.borderStyle == 'none')
1416                                                 elm.style.borderStyle = 'solid';
1417                                         break;
1418
1419                                 case "border":
1420                                 case "width":
1421                                 case "height":
1422                                         if (attrib == "border" && elm.style.borderWidth > 0)
1423                                                 return;
1424
1425                                         if (val.indexOf('%') == -1)
1426                                                 val += 'px';
1427                                         break;
1428
1429                                 case "vspace":
1430                                 case "hspace":
1431                                         elm.style.marginTop = val + "px";
1432                                         elm.style.marginBottom = val + "px";
1433                                         elm.removeAttribute(attrib);
1434                                         return;
1435
1436                                 case "align":
1437                                         if (elm.nodeName == "IMG") {
1438                                                 if (tinyMCE.isMSIE)
1439                                                         elm.style.styleFloat = val;
1440                                                 else
1441                                                         elm.style.cssFloat = val;
1442                                         } else
1443                                                 elm.style.textAlign = val;
1444
1445                                         elm.removeAttribute(attrib);
1446                                         return;
1447                         }
1448
1449                         if (val != '') {
1450                                 eval('elm.style.' + style + ' = val;');
1451                                 elm.removeAttribute(attrib);
1452                         }
1453                 }
1454         } else {
1455                 if (style == '')
1456                         return;
1457
1458                 var val = eval('elm.style.' + style) == '' ? tinyMCE.getAttrib(elm, attrib) : eval('elm.style.' + style);
1459                 val = val == null ? '' : '' + val;
1460
1461                 switch (attrib) {
1462                         // Always move background to style
1463                         case "background":
1464                                 if (val.indexOf('url') == -1 && val != '')
1465                                         val = "url('" + val + "');";
1466
1467                                 if (val != '') {
1468                                         elm.style.backgroundImage = val;
1469                                         elm.removeAttribute(attrib);
1470                                 }
1471                                 return;
1472
1473                         case "border":
1474                         case "width":
1475                         case "height":
1476                                 val = val.replace('px', '');
1477                                 break;
1478
1479                         case "align":
1480                                 if (tinyMCE.getAttrib(elm, 'align') == '') {
1481                                         if (elm.nodeName == "IMG") {
1482                                                 if (tinyMCE.isMSIE && elm.style.styleFloat != '') {
1483                                                         val = elm.style.styleFloat;
1484                                                         style = 'styleFloat';
1485                                                 } else if (tinyMCE.isGecko && elm.style.cssFloat != '') {
1486                                                         val = elm.style.cssFloat;
1487                                                         style = 'cssFloat';
1488                                                 }
1489                                         }
1490                                 }
1491                                 break;
1492                 }
1493
1494                 if (val != '') {
1495                         elm.removeAttribute(attrib);
1496                         elm.setAttribute(attrib, val);
1497                         eval('elm.style.' + style + ' = "";');
1498                 }
1499         }
1500 };
1501
1502 TinyMCE.prototype._cleanupAttribute = function(valid_attributes, element_name, attribute_node, element_node) {
1503         var attribName = attribute_node.nodeName.toLowerCase();
1504         var attribValue = attribute_node.nodeValue;
1505         var attribMustBeValue = null;
1506         var verified = false;
1507
1508         // Mozilla attibute, remove them
1509         if (attribName.indexOf('moz_') != -1)
1510                 return null;
1511
1512         // Mozilla fix for drag-drop/copy/paste images
1513         if (!tinyMCE.isMSIE && (attribName == "mce_real_href" || attribName == "mce_real_src")) {
1514                 if (!tinyMCE.cleanup_on_save) {
1515                         var attrib = new Object();
1516
1517                         attrib.name = attribName;
1518                         attrib.value = attribValue;
1519
1520                         return attrib;
1521                 } else
1522                         return null;
1523         }
1524
1525         // Auto verify 
1526         if (attribName == "mce_onclick")
1527                 verified = true;
1528
1529         // Verify attrib
1530         if (tinyMCE.cleanup_verify_html && !verified) {
1531                 for (var i=1; i<valid_attributes.length; i++) {
1532                         var attribMatch = valid_attributes[i][0];
1533                         var re = null;
1534
1535                         // Build regexp from wildcard
1536                         if (attribMatch.match(new RegExp('\\*|\\?|\\+', 'g')) != null) {
1537                                 attribMatch = attribMatch.replace(new RegExp('\\?', 'g'), '(\\S?)');
1538                                 attribMatch = attribMatch.replace(new RegExp('\\+', 'g'), '(\\S+)');
1539                                 attribMatch = attribMatch.replace(new RegExp('\\*', 'g'), '(\\S*)');
1540                                 attribMatch = "^" + attribMatch + "$";
1541                                 re = new RegExp(attribMatch, 'g');
1542                         }
1543
1544                         if ((re && attribName.match(re) != null) || attribName == attribMatch) {
1545                                 verified = true;
1546                                 attribMustBeValue = valid_attributes[i][3];
1547                                 break;
1548                         }
1549                 }
1550
1551                 if (!verified)
1552                         return false;
1553         } else
1554                 verified = true;
1555
1556         // Treat some attribs diffrent
1557         switch (attribName) {
1558                 case "size":
1559                         if (tinyMCE.isMSIE5 && element_name == "font")
1560                                 attribValue = element_node.size;
1561                         break;
1562
1563                 case "width":
1564                 case "height":
1565                 case "border":
1566                         // Old MSIE needs this
1567                         if (tinyMCE.isMSIE5)
1568                                 attribValue = eval("element_node." + attribName);
1569                         break;
1570
1571                 case "color":
1572                         if (tinyMCE.isMSIE5 && element_name == "font")
1573                                 attribValue = element_node.color;
1574                         break;
1575
1576                 case "class":
1577                         if (element_name == "table" || element_name == "td") {
1578                                 // Handle visual aid
1579                                 if (tinyMCE.cleanup_visual_table_class != "")
1580                                         attribValue = tinyMCE.getVisualAidClass(attribValue, !tinyMCE.cleanup_on_save);
1581                         }
1582
1583                         if (!tinyMCE._verifyClass(element_node) || attribValue == "")
1584                                 return null;
1585
1586                         break;
1587
1588                 case "onfocus":
1589                 case "onblur":
1590                 case "onclick":
1591                 case "ondblclick":
1592                 case "onmousedown":
1593                 case "onmouseup":
1594                 case "onmouseover":
1595                 case "onmousemove":
1596                 case "onmouseout":
1597                 case "onkeypress":
1598                 case "onkeydown":
1599                 case "onkeydown":
1600                 case "onkeyup":
1601                         attribValue = tinyMCE.cleanupEventStr("" + attribValue);
1602
1603                         if (attribValue.indexOf('return false;') == 0)
1604                                 attribValue = attribValue.substring(14);
1605
1606                         break;
1607
1608                 case "style":
1609                         attribValue = tinyMCE.serializeStyle(tinyMCE.parseStyle(element_node.style.cssText));
1610                         break;
1611
1612                 // Convert the URLs of these
1613                 case "href":
1614                 case "src":
1615                         // Fix for dragdrop/copy paste Mozilla issue
1616                         if (!tinyMCE.isMSIE && attribName == "href" && element_node.getAttribute("mce_real_href"))
1617                                 attribValue = element_node.getAttribute("mce_real_href");
1618
1619                         // Fix for dragdrop/copy paste Mozilla issue
1620                         if (!tinyMCE.isMSIE && attribName == "src" && element_node.getAttribute("mce_real_src"))
1621                                 attribValue = element_node.getAttribute("mce_real_src");
1622
1623                         // Force absolute URLs in Firefox
1624                         if (tinyMCE.isGecko && !tinyMCE.settings['relative_urls'])
1625                                 attribValue = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], attribValue);
1626
1627                         attribValue = eval(tinyMCE.cleanup_urlconverter_callback + "(attribValue, element_node, tinyMCE.cleanup_on_save);");
1628                         break;
1629
1630                 case "colspan":
1631                 case "rowspan":
1632                         // Not needed
1633                         if (attribValue == "1")
1634                                 return null;
1635                         break;
1636
1637                 // Skip these
1638                 case "_moz-userdefined":
1639                 case "editorid":
1640                 case "mce_real_href":
1641                 case "mce_real_src":
1642                         return null;
1643         }
1644
1645         // Not the must be value
1646         if (attribMustBeValue != null) {
1647                 var isCorrect = false;
1648                 for (var i=0; i<attribMustBeValue.length; i++) {
1649                         if (attribValue == attribMustBeValue[i]) {
1650                                 isCorrect = true;
1651                                 break;
1652                         }
1653                 }
1654
1655                 if (!isCorrect)
1656                         return null;
1657         }
1658
1659         var attrib = new Object();
1660
1661         attrib.name = attribName;
1662         attrib.value = attribValue;
1663
1664         return attrib;
1665 };
1666
1667 TinyMCE.prototype.parseStyle = function(str) {
1668         var ar = new Array();
1669         var st = str.split(';');
1670
1671         for (var i=0; i<st.length; i++) {
1672                 if (st[i] == '')
1673                         continue;
1674
1675                 var re = new RegExp('^\\s*([^:]*):\\s*(.*)\\s*$');
1676                 var pa = st[i].replace(re, '$1||$2').split('||');
1677 //tinyMCE.debug(str, pa[0] + "=" + pa[1], st[i].replace(re, '$1||$2'));
1678                 if (pa.length == 2)
1679                         ar[pa[0].toLowerCase()] = pa[1];
1680         }
1681
1682         return ar;
1683 };
1684
1685 TinyMCE.prototype.compressStyle = function(ar, pr, sf, res) {
1686         var box = new Array();
1687
1688         box[0] = ar[pr + '-top' + sf];
1689         box[1] = ar[pr + '-left' + sf];
1690         box[2] = ar[pr + '-right' + sf];
1691         box[3] = ar[pr + '-bottom' + sf];
1692
1693         for (var i=0; i<box.length; i++) {
1694                 if (box[i] == null)
1695                         return;
1696
1697                 for (var a=0; a<box.length; a++) {
1698                         if (box[a] != box[i])
1699                                 return;
1700                 }
1701         }
1702
1703         // They are all the same
1704         ar[res] = box[0];
1705         ar[pr + '-top' + sf] = null;
1706         ar[pr + '-left' + sf] = null;
1707         ar[pr + '-right' + sf] = null;
1708         ar[pr + '-bottom' + sf] = null;
1709 };
1710
1711 TinyMCE.prototype.serializeStyle = function(ar) {
1712         var str = "";
1713
1714         // Compress box
1715         tinyMCE.compressStyle(ar, "border", "", "border");
1716         tinyMCE.compressStyle(ar, "border", "-width", "border-width");
1717         tinyMCE.compressStyle(ar, "border", "-color", "border-color");
1718
1719         for (var key in ar) {
1720                 var val = ar[key];
1721
1722                 if (val != null && val != '') {
1723                         val = '' + val; // Force string
1724
1725                         // Fix style URL
1726                         val = val.replace(new RegExp("url\\(\\'?([^\\']*)\\'?\\)", 'gi'), "url('$1')");
1727
1728                         if (val != "url('')")
1729                                 str += key.toLowerCase() + ": " + val + "; ";
1730                 }
1731         }
1732
1733         if (new RegExp('; $').test(str))
1734                 str = str.substring(0, str.length - 2);
1735
1736         return str;
1737 };
1738
1739 TinyMCE.prototype._verifyClass = function(node) {
1740         // Sometimes the class gets set to null, weird Gecko bug?
1741         if (tinyMCE.isGecko) {
1742                 var className = node.getAttribute('class');
1743                 if (!className)
1744                         return false;
1745         }
1746
1747         // Trim CSS class
1748         if (tinyMCE.isMSIE)
1749                 var className = node.getAttribute('className');
1750
1751         if (tinyMCE.cleanup_verify_css_classes && tinyMCE.cleanup_on_save) {
1752                 var csses = tinyMCE.getCSSClasses();
1753                 nonDefinedCSS = true;
1754                 for (var c=0; c<csses.length; c++) {
1755                         if (csses[c] == className) {
1756                                 nonDefinedCSS = false;
1757                                 break;
1758                         }
1759                 }
1760
1761                 if (nonDefinedCSS && className.indexOf('mce_') != 0) {
1762                         node.removeAttribute('className');
1763                         node.removeAttribute('class');
1764                         return false;
1765                 }
1766         }
1767
1768         return true;
1769 };
1770
1771 TinyMCE.prototype.cleanupNode = function(node) {
1772         var output = "";
1773
1774         switch (node.nodeType) {
1775                 case 1: // Element
1776                         var elementData = tinyMCE._cleanupElementName(node.nodeName, node);
1777                         var elementName = elementData ? elementData.element_name : null;
1778                         var elementValidAttribs = elementData ? elementData.valid_attribs : null;
1779                         var elementAttribs = "";
1780                         var openTag = false, nonEmptyTag = false;
1781
1782                         if (elementName != null && elementName.charAt(0) == '+') {
1783                                 elementName = elementName.substring(1);
1784                                 openTag = true;
1785                         }
1786
1787                         if (elementName != null && elementName.charAt(0) == '-') {
1788                                 elementName = elementName.substring(1);
1789                                 nonEmptyTag = true;
1790                         }
1791
1792                         // Checking DOM tree for MSIE weirdness!!
1793                         if (tinyMCE.isMSIE && tinyMCE.settings['fix_content_duplication']) {
1794                                 var lookup = tinyMCE.cleanup_elementLookupTable;
1795
1796                                 for (var i=0; i<lookup.length; i++) {
1797                                         // Found element reference else were, hmm?
1798                                         if (lookup[i] == node)
1799                                                 return output;
1800                                 }
1801
1802                                 // Add element to lookup table
1803                                 lookup[lookup.length] = node;
1804                         }
1805
1806                         // Element not valid (only render children)
1807                         if (!elementName) {
1808                                 if (node.hasChildNodes()) {
1809                                         for (var i=0; i<node.childNodes.length; i++)
1810                                                 output += this.cleanupNode(node.childNodes[i]);
1811                                 }
1812
1813                                 return output;
1814                         }
1815
1816                         if (tinyMCE.cleanup_on_save) {
1817                                 if (node.nodeName == "A" && node.className == "mceItemAnchor")
1818                                         return '<a name="' + this.convertStringToXML(node.getAttribute("name")) + '"></a>';
1819                         }
1820
1821                         // Handle inline/outline styles
1822                         if (tinyMCE.cleanup_inline_styles) {
1823                                 var re = new RegExp("^(TABLE|TD|TR|IMG|HR)$");
1824                                 if (re.test(node.nodeName)) {
1825                                         tinyMCE._moveStyle(node, 'width', 'width');
1826                                         tinyMCE._moveStyle(node, 'height', 'height');
1827                                         tinyMCE._moveStyle(node, 'borderWidth', 'border');
1828                                         tinyMCE._moveStyle(node, '', 'vspace');
1829                                         tinyMCE._moveStyle(node, '', 'hspace');
1830                                         tinyMCE._moveStyle(node, 'textAlign', 'align');
1831                                         tinyMCE._moveStyle(node, 'backgroundColor', 'bgColor');
1832                                         tinyMCE._moveStyle(node, 'borderColor', 'borderColor');
1833                                         tinyMCE._moveStyle(node, 'backgroundImage', 'background');
1834
1835                                         // Refresh element in old MSIE
1836                                         if (tinyMCE.isMSIE5)
1837                                                 node.outerHTML = node.outerHTML;
1838                                 } else if (tinyMCE.isBlockElement(node))
1839                                         tinyMCE._moveStyle(node, 'textAlign', 'align');
1840
1841                                 if (node.nodeName == "FONT")
1842                                         tinyMCE._moveStyle(node, 'color', 'color');
1843                         }
1844
1845                         // Set attrib data
1846                         if (elementValidAttribs) {
1847                                 for (var a=1; a<elementValidAttribs.length; a++) {
1848                                         var attribName, attribDefaultValue, attribForceValue, attribValue;
1849
1850                                         attribName = elementValidAttribs[a][0];
1851                                         attribDefaultValue = elementValidAttribs[a][1];
1852                                         attribForceValue = elementValidAttribs[a][2];
1853
1854                                         if (attribDefaultValue != null || attribForceValue != null) {
1855                                                 var attribValue = node.getAttribute(attribName);
1856
1857                                                 if (node.getAttribute(attribName) == null || node.getAttribute(attribName) == "")
1858                                                         attribValue = attribDefaultValue;
1859
1860                                                 attribValue = attribForceValue ? attribForceValue : attribValue;
1861
1862                                                 // Is to generate id
1863                                                 if (attribValue == "{$uid}")
1864                                                         attribValue = "uid_" + (tinyMCE.cleanup_idCount++);
1865
1866                                                 // Add visual aid class
1867                                                 if (attribName == "class")
1868                                                         attribValue = tinyMCE.getVisualAidClass(attribValue, tinyMCE.cleanup_on_save);
1869
1870                                                 node.setAttribute(attribName, attribValue);
1871                                                 //alert(attribName + "=" + attribValue);
1872                                         }
1873                                 }
1874                         }
1875
1876                         // Remove empty tables
1877                         if (elementName == "table" && !node.hasChildNodes())
1878                                 return "";
1879
1880                         // Handle element attributes
1881                         if (node.attributes.length > 0) {
1882                                 for (var i=0; i<node.attributes.length; i++) {
1883                                         if (node.attributes[i].specified) {
1884                                                 // tinyMCE.debug(node.attributes[i].nodeName + "=" + node.attributes[i].nodeValue);
1885                                                 var attrib = tinyMCE._cleanupAttribute(elementValidAttribs, elementName, node.attributes[i], node);
1886                                                 if (attrib && attrib.value != "")
1887                                                         elementAttribs += " " + attrib.name + "=" + '"' + this.convertStringToXML("" + attrib.value) + '"';
1888                                         }
1889                                 }
1890                         }
1891
1892                         // MSIE table summary fix
1893                         if (tinyMCE.isMSIE && elementName == "table" && node.getAttribute("summary") != null && elementAttribs.indexOf('summary') == -1) {
1894                                 elementAttribs += " summary=" + '"' + this.convertStringToXML("" + node.getAttribute("summary")) + '"';
1895                         }
1896
1897                         // MSIE form element issue
1898                         if (tinyMCE.isMSIE && elementName == "input") {
1899                                 if (node.type) {
1900                                         if (!elementAttribs.match(/ type=/g))
1901                                                 elementAttribs += " type=" + '"' + node.type + '"';
1902                                 }
1903
1904                                 if (node.value) {
1905                                         if (!elementAttribs.match(/ value=/g))
1906                                                 elementAttribs += " value=" + '"' + node.value + '"';
1907                                 }
1908                         }
1909
1910                         // Add nbsp to some elements
1911                         if ((elementName == "p" || elementName == "td") && (node.innerHTML == "" || node.innerHTML == "&nbsp;"))
1912                                 return "<" + elementName + elementAttribs + ">" + this.convertStringToXML(String.fromCharCode(160)) + "</" + elementName + ">";
1913
1914                         // Is MSIE script element
1915                         if (tinyMCE.isMSIE && elementName == "script")
1916                                 return "<" + elementName + elementAttribs + ">" + node.text + "</" + elementName + ">";
1917
1918                         // Clean up children
1919                         if (node.hasChildNodes()) {
1920                                 // Force BR
1921                                 if (elementName == "p" && tinyMCE.cleanup_force_br_newlines)
1922                                         output += "<div" + elementAttribs + ">";
1923                                 else
1924                                         output += "<" + elementName + elementAttribs + ">";
1925
1926                                 for (var i=0; i<node.childNodes.length; i++)
1927                                         output += this.cleanupNode(node.childNodes[i]);
1928
1929                                 // Force BR
1930                                 if (elementName == "p" && tinyMCE.cleanup_force_br_newlines)
1931                                         output += "</div><br />";
1932                                 else
1933                                         output += "</" + elementName + ">";
1934                         } else {
1935                                 if (!nonEmptyTag) {
1936                                         if (openTag)
1937                                                 output += "<" + elementName + elementAttribs + "></" + elementName + ">";
1938                                         else
1939                                                 output += "<" + elementName + elementAttribs + " />";
1940                                 }
1941                         }
1942
1943                         return output;
1944
1945                 case 3: // Text
1946                         // Do not convert script elements
1947                         if (node.parentNode.nodeName.toLowerCase() == "script")
1948                                 return node.nodeValue;
1949
1950                         return this.convertStringToXML(node.nodeValue);
1951
1952                 case 8: // Comment
1953                         return "<!--" + node.nodeValue + "-->";
1954
1955                 default: // Unknown
1956                         return "[UNKNOWN NODETYPE " + node.nodeType + "]";
1957         }
1958 };
1959
1960 TinyMCE.prototype.convertStringToXML = function(html_data) {
1961     var output = "";
1962
1963         for (var i=0; i<html_data.length; i++) {
1964                 var chr = html_data.charCodeAt(i);
1965
1966                 // Numeric entities
1967                 if (tinyMCE.settings['entity_encoding'] == "numeric") {
1968                         if (chr > 127)
1969                                 output += '&#' + chr + ";";
1970                         else
1971                                 output += String.fromCharCode(chr);
1972
1973                         continue;
1974                 }
1975
1976                 // Raw entities
1977                 if (tinyMCE.settings['entity_encoding'] == "raw") {
1978                         output += String.fromCharCode(chr);
1979                         continue;
1980                 }
1981
1982                 // Named entities
1983                 if (typeof(tinyMCE.cleanup_entities["c" + chr]) != 'undefined' && tinyMCE.cleanup_entities["c" + chr] != '')
1984                         output += '&' + tinyMCE.cleanup_entities["c" + chr] + ';';
1985                 else
1986                         output += '' + String.fromCharCode(chr);
1987     }
1988
1989     return output;
1990 };
1991
1992 TinyMCE.prototype._getCleanupElementName = function(chunk) {
1993         var pos;
1994
1995         if (chunk.charAt(0) == '+')
1996                 chunk = chunk.substring(1);
1997
1998         if (chunk.charAt(0) == '-')
1999                 chunk = chunk.substring(1);
2000
2001         if ((pos = chunk.indexOf('/')) != -1)
2002                 chunk = chunk.substring(0, pos);
2003
2004         if ((pos = chunk.indexOf('[')) != -1)
2005                 chunk = chunk.substring(0, pos);
2006
2007         return chunk;
2008 };
2009
2010 TinyMCE.prototype._initCleanup = function() {
2011         // Parse valid elements and attributes
2012         var validElements = tinyMCE.settings["valid_elements"];
2013         validElements = validElements.split(',');
2014
2015         // Handle extended valid elements
2016         var extendedValidElements = tinyMCE.settings["extended_valid_elements"];
2017         extendedValidElements = extendedValidElements.split(',');
2018         for (var i=0; i<extendedValidElements.length; i++) {
2019                 var elementName = this._getCleanupElementName(extendedValidElements[i]);
2020                 var skipAdd = false;
2021
2022                 // Check if it's defined before, if so override that one
2023                 for (var x=0; x<validElements.length; x++) {
2024                         if (this._getCleanupElementName(validElements[x]) == elementName) {
2025                                 validElements[x] = extendedValidElements[i];
2026                                 skipAdd = true;
2027                                 break;
2028                         }
2029                 }
2030
2031                 if (!skipAdd)
2032                         validElements[validElements.length] = extendedValidElements[i];
2033         }
2034
2035         for (var i=0; i<validElements.length; i++) {
2036                 var item = validElements[i];
2037
2038                 item = item.replace('[','|');
2039                 item = item.replace(']','');
2040
2041                 // Split and convert
2042                 var attribs = item.split('|');
2043                 for (var x=0; x<attribs.length; x++)
2044                         attribs[x] = attribs[x].toLowerCase();
2045
2046                 // Handle change elements
2047                 attribs[0] = attribs[0].split('/');
2048
2049                 // Handle default attribute values
2050                 for (var x=1; x<attribs.length; x++) {
2051                         var attribName = attribs[x];
2052                         var attribDefault = null;
2053                         var attribForce = null;
2054                         var attribMustBe = null;
2055
2056                         // Default value
2057                         if ((pos = attribName.indexOf('=')) != -1) {
2058                                 attribDefault = attribName.substring(pos+1);
2059                                 attribName = attribName.substring(0, pos);
2060                         }
2061
2062                         // Force check
2063                         if ((pos = attribName.indexOf(':')) != -1) {
2064                                 attribForce = attribName.substring(pos+1);
2065                                 attribName = attribName.substring(0, pos);
2066                         }
2067
2068                         // Force check
2069                         if ((pos = attribName.indexOf('<')) != -1) {
2070                                 attribMustBe = attribName.substring(pos+1).split('?');
2071                                 attribName = attribName.substring(0, pos);
2072                         }
2073
2074                         attribs[x] = new Array(attribName, attribDefault, attribForce, attribMustBe);
2075                 }
2076
2077                 validElements[i] = attribs;
2078         }
2079
2080         var invalidElements = tinyMCE.settings['invalid_elements'].split(',');
2081         for (var i=0; i<invalidElements.length; i++)
2082                 invalidElements[i] = invalidElements[i].toLowerCase();
2083
2084         // Set these for performance
2085         tinyMCE.settings['cleanup_validElements'] = validElements;
2086         tinyMCE.settings['cleanup_invalidElements'] = invalidElements;
2087
2088         // Setup entities
2089         tinyMCE.settings['cleanup_entities'] = new Array();
2090         var entities = tinyMCE.getParam('entities', '', true, ',');
2091         for (var i=0; i<entities.length; i+=2)
2092                 tinyMCE.settings['cleanup_entities']['c' + entities[i]] = entities[i+1];
2093 };
2094
2095 TinyMCE.prototype._cleanupHTML = function(inst, doc, config, element, visual, on_save) {
2096         if (!tinyMCE.settings['cleanup'])
2097                 return element.innerHTML;
2098
2099         // Call custom cleanup code
2100         tinyMCE._customCleanup(inst, on_save ? "get_from_editor_dom" : "insert_to_editor_dom", doc.body);
2101
2102         // Set these for performance
2103         tinyMCE.cleanup_validElements = tinyMCE.settings['cleanup_validElements'];
2104         tinyMCE.cleanup_entities = tinyMCE.settings['cleanup_entities'];
2105         tinyMCE.cleanup_invalidElements = tinyMCE.settings['cleanup_invalidElements'];
2106         tinyMCE.cleanup_verify_html = tinyMCE.settings['verify_html'];
2107         tinyMCE.cleanup_force_br_newlines = tinyMCE.settings['force_br_newlines'];
2108         tinyMCE.cleanup_urlconverter_callback = tinyMCE.settings['urlconverter_callback'];
2109         tinyMCE.cleanup_verify_css_classes = tinyMCE.settings['verify_css_classes'];
2110         tinyMCE.cleanup_visual_table_class = tinyMCE.settings['visual_table_class'];
2111         tinyMCE.cleanup_apply_source_formatting = tinyMCE.settings['apply_source_formatting'];
2112         tinyMCE.cleanup_inline_styles = tinyMCE.settings['inline_styles'];
2113         tinyMCE.cleanup_visual_aid = visual;
2114         tinyMCE.cleanup_on_save = on_save;
2115         tinyMCE.cleanup_idCount = 0;
2116         tinyMCE.cleanup_elementLookupTable = new Array();
2117
2118         var startTime = new Date().getTime();
2119
2120         // Cleanup madness that breaks the editor in MSIE
2121         if (tinyMCE.isMSIE) {
2122                 // Remove null ids from HR elements, results in runtime error
2123                 var nodes = element.getElementsByTagName("hr");
2124                 for (var i=0; i<nodes.length; i++) {
2125                         if (nodes[i].id == "null")
2126                                 nodes[i].removeAttribute("id");
2127                 }
2128
2129                 element.innerHTML = tinyMCE.regexpReplace(element.innerHTML, '<p>[ \n\r]*<hr.*>[ \n\r]*</p>', '<hr />', 'gi');
2130                 element.innerHTML = tinyMCE.regexpReplace(element.innerHTML, '<!([^-(DOCTYPE)]* )|<!/[^-]*>', '', 'gi');
2131         }
2132
2133         var html = this.cleanupNode(element);
2134
2135         if (tinyMCE.settings['debug'])
2136                 tinyMCE.debug("Cleanup process executed in: " + (new Date().getTime()-startTime) + " ms.");
2137
2138         // Remove pesky HR paragraphs
2139         html = tinyMCE.regexpReplace(html, '<p><hr /></p>', '<hr />');
2140         html = tinyMCE.regexpReplace(html, '<p>&nbsp;</p><hr /><p>&nbsp;</p>', '<hr />');
2141         html = tinyMCE.regexpReplace(html, '<td>\\s*<br />\\s*</td>', '<td>&nbsp;</td>');
2142
2143         // Remove empty achors
2144         html = html.replace(new RegExp('<a>(.*?)</a>', 'gi'), '$1');
2145
2146         // Remove some mozilla crap
2147         if (!tinyMCE.isMSIE)
2148                 html = html.replace(new RegExp('<o:p _moz-userdefined="" />', 'g'), "");
2149
2150         if (tinyMCE.settings['apply_source_formatting']) {
2151                 html = html.replace(new RegExp('<(p|div)([^>]*)>', 'g'), "\n<$1$2>\n");
2152                 html = html.replace(new RegExp('<\/(p|div)([^>]*)>', 'g'), "\n</$1$2>\n");
2153                 html = html.replace(new RegExp('<br />', 'g'), "<br />\n");
2154         }
2155
2156         if (tinyMCE.settings['force_br_newlines']) {
2157                 var re = new RegExp('<p>&nbsp;</p>', 'g');
2158                 html = html.replace(re, "<br />");
2159         }
2160
2161         if (tinyMCE.settings['force_p_newlines']) {
2162                 // Remove weridness!
2163                 var re = new RegExp('&lt;&gt;', 'g');
2164                 html = html.replace(re, "");
2165         }
2166
2167         if (tinyMCE.settings['remove_linebreaks'])
2168                 html = html.replace(new RegExp('\r|\n', 'g'), ' ');
2169
2170         // Call custom cleanup code
2171         html = tinyMCE._customCleanup(inst, on_save ? "get_from_editor" : "insert_to_editor", html);
2172
2173         // Emtpy node, return empty
2174         var chk = tinyMCE.regexpReplace(html, "[ \t\r\n]", "").toLowerCase();
2175         if (chk == "<br/>" || chk == "<br>" || chk == "<p>&nbsp;</p>" || chk == "<p>&#160;</p>" || chk == "<p></p>")
2176                 html = "";
2177
2178         if (tinyMCE.settings["preformatted"])
2179                 return "<pre>" + html + "</pre>";
2180
2181         return html;
2182 };
2183
2184 TinyMCE.prototype.insertLink = function(href, target, title, onclick, style_class) {
2185         tinyMCE.execCommand('mceBeginUndoLevel');
2186
2187         if (this.selectedInstance && this.selectedElement && this.selectedElement.nodeName.toLowerCase() == "img") {
2188                 var doc = this.selectedInstance.getDoc();
2189                 var linkElement = tinyMCE.getParentElement(this.selectedElement, "a");
2190                 var newLink = false;
2191
2192                 if (!linkElement) {
2193                         linkElement = doc.createElement("a");
2194                         newLink = true;
2195                 }
2196
2197                 href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, linkElement);");
2198                 tinyMCE.setAttrib(linkElement, 'href', href);
2199                 tinyMCE.setAttrib(linkElement, 'target', target);
2200                 tinyMCE.setAttrib(linkElement, 'title', title);
2201         tinyMCE.setAttrib(linkElement, 'onclick', onclick);
2202                 tinyMCE.setAttrib(linkElement, 'class', style_class);
2203
2204                 if (newLink) {
2205                         linkElement.appendChild(this.selectedElement.cloneNode(true));
2206                         this.selectedElement.parentNode.replaceChild(linkElement, this.selectedElement);
2207                 }
2208
2209                 return;
2210         }
2211
2212         if (!this.linkElement && this.selectedInstance) {
2213                 if (tinyMCE.isSafari) {
2214                         tinyMCE.execCommand("mceInsertContent", false, '<a href="#mce_temp_url#">' + this.selectedInstance.getSelectedHTML() + '</a>');
2215                 } else
2216                         this.selectedInstance.contentDocument.execCommand("createlink", false, "#mce_temp_url#");
2217
2218                 tinyMCE.linkElement = this.getElementByAttributeValue(this.selectedInstance.contentDocument.body, "a", "href", "#mce_temp_url#");
2219
2220                 var elementArray = this.getElementsByAttributeValue(this.selectedInstance.contentDocument.body, "a", "href", "#mce_temp_url#");
2221
2222                 for (var i=0; i<elementArray.length; i++) {
2223                         href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, elementArray[i]);");
2224                         tinyMCE.setAttrib(elementArray[i], 'href', href);
2225                         tinyMCE.setAttrib(elementArray[i], 'mce_real_href', href);
2226                         tinyMCE.setAttrib(elementArray[i], 'target', target);
2227                         tinyMCE.setAttrib(elementArray[i], 'title', title);
2228             tinyMCE.setAttrib(elementArray[i], 'onclick', onclick);
2229                         tinyMCE.setAttrib(elementArray[i], 'class', style_class);
2230                 }
2231
2232                 tinyMCE.linkElement = elementArray[0];
2233         }
2234
2235         if (this.linkElement) {
2236                 href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, this.linkElement);");
2237                 tinyMCE.setAttrib(this.linkElement, 'href', href);
2238                 tinyMCE.setAttrib(this.linkElement, 'mce_real_href', href);
2239                 tinyMCE.setAttrib(this.linkElement, 'target', target);
2240                 tinyMCE.setAttrib(this.linkElement, 'title', title);
2241         tinyMCE.setAttrib(this.linkElement, 'onclick', onclick);
2242                 tinyMCE.setAttrib(this.linkElement, 'class', style_class);
2243         }
2244
2245         tinyMCE.execCommand('mceEndUndoLevel');
2246 };
2247
2248 TinyMCE.prototype.insertImage = function(src, alt, border, hspace, vspace, width, height, align, title, onmouseover, onmouseout) {
2249         tinyMCE.execCommand('mceBeginUndoLevel');
2250
2251         if (src == "")
2252                 return;
2253
2254         if (!this.imgElement && tinyMCE.isSafari) {
2255                 var html = "";
2256
2257                 html += '<img src="' + src + '" alt="' + alt + '"';
2258                 html += ' border="' + border + '" hspace="' + hspace + '"';
2259                 html += ' vspace="' + vspace + '" width="' + width + '"';
2260                 html += ' height="' + height + '" align="' + align + '" title="' + title + '" onmouseover="' + onmouseover + '" onmouseout="' + onmouseout + '" />';
2261
2262                 tinyMCE.execCommand("mceInsertContent", false, html);
2263         } else {
2264                 if (!this.imgElement && this.selectedInstance) {
2265                         if (tinyMCE.isSafari)
2266                                 tinyMCE.execCommand("mceInsertContent", false, '<img src="#mce_temp_url#" />');
2267                         else
2268                                 this.selectedInstance.contentDocument.execCommand("insertimage", false, "#mce_temp_url#");
2269
2270                         tinyMCE.imgElement = this.getElementByAttributeValue(this.selectedInstance.contentDocument.body, "img", "src", "#mce_temp_url#");
2271                 }
2272         }
2273
2274         if (this.imgElement) {
2275                 var needsRepaint = false;
2276
2277                 src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, tinyMCE.imgElement);");
2278
2279                 if (onmouseover && onmouseover != "")
2280                         onmouseover = "this.src='" + eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseover, tinyMCE.imgElement);") + "';";
2281
2282                 if (onmouseout && onmouseout != "")
2283                         onmouseout = "this.src='" + eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseout, tinyMCE.imgElement);") + "';";
2284
2285                 // Use alt as title if it's undefined
2286                 if (typeof(title) == "undefined")
2287                         title = alt;
2288
2289                 if (width != this.imgElement.getAttribute("width") || height != this.imgElement.getAttribute("height") || align != this.imgElement.getAttribute("align"))
2290                         needsRepaint = true;
2291
2292                 tinyMCE.setAttrib(this.imgElement, 'src', src);
2293                 tinyMCE.setAttrib(this.imgElement, 'mce_real_src', src);
2294                 tinyMCE.setAttrib(this.imgElement, 'alt', alt);
2295                 tinyMCE.setAttrib(this.imgElement, 'title', title);
2296                 tinyMCE.setAttrib(this.imgElement, 'align', align);
2297                 tinyMCE.setAttrib(this.imgElement, 'border', border, true);
2298                 tinyMCE.setAttrib(this.imgElement, 'hspace', hspace, true);
2299                 tinyMCE.setAttrib(this.imgElement, 'vspace', vspace, true);
2300                 tinyMCE.setAttrib(this.imgElement, 'width', width, true);
2301                 tinyMCE.setAttrib(this.imgElement, 'height', height, true);
2302                 tinyMCE.setAttrib(this.imgElement, 'onmouseover', onmouseover);
2303                 tinyMCE.setAttrib(this.imgElement, 'onmouseout', onmouseout);
2304
2305                 // Fix for bug #989846 - Image resize bug
2306                 if (width && width != "")
2307                         this.imgElement.style.pixelWidth = width;
2308
2309                 if (height && height != "")
2310                         this.imgElement.style.pixelHeight = height;
2311
2312                 if (needsRepaint)
2313                         tinyMCE.selectedInstance.repaint();
2314         }
2315
2316         tinyMCE.execCommand('mceEndUndoLevel');
2317 };
2318
2319 TinyMCE.prototype.getElementByAttributeValue = function(node, element_name, attrib, value) {
2320         var elements = this.getElementsByAttributeValue(node, element_name, attrib, value);
2321         if (elements.length == 0)
2322                 return null;
2323
2324         return elements[0];
2325 };
2326
2327 TinyMCE.prototype.getElementsByAttributeValue = function(node, element_name, attrib, value) {
2328         var elements = new Array();
2329
2330         if (node && node.nodeName.toLowerCase() == element_name) {
2331                 if (node.getAttribute(attrib) && node.getAttribute(attrib).indexOf(value) != -1)
2332                         elements[elements.length] = node;
2333         }
2334
2335         if (node.hasChildNodes) {
2336                 for (var x=0, n=node.childNodes.length; x<n; x++) {
2337                         var childElements = this.getElementsByAttributeValue(node.childNodes[x], element_name, attrib, value);
2338                         for (var i=0, m=childElements.length; i<m; i++)
2339                                 elements[elements.length] = childElements[i];
2340                 }
2341         }
2342
2343         return elements;
2344 };
2345
2346 TinyMCE.prototype.isBlockElement = function(node) {
2347         return node != null && node.nodeType == 1 && this.blockRegExp.test(node.nodeName);
2348 };
2349
2350 TinyMCE.prototype.getParentBlockElement = function(node) {
2351         // Search up the tree for block element
2352         while (node) {
2353                 if (this.blockRegExp.test(node.nodeName))
2354                         return node;
2355
2356                 node = node.parentNode;
2357         }
2358
2359         return null;
2360 };
2361
2362 TinyMCE.prototype.getNodeTree = function(node, node_array, type, node_name) {
2363         if (typeof(type) == "undefined" || node.nodeType == type && (typeof(node_name) == "undefined" || node.nodeName == node_name))
2364                 node_array[node_array.length] = node;
2365
2366         if (node.hasChildNodes()) {
2367                 for (var i=0; i<node.childNodes.length; i++)
2368                         tinyMCE.getNodeTree(node.childNodes[i], node_array, type, node_name);
2369         }
2370
2371         return node_array;
2372 };
2373
2374 TinyMCE.prototype.getParentElement = function(node, names, attrib_name, attrib_value) {
2375         if (typeof(names) == "undefined") {
2376                 if (node.nodeType == 1)
2377                         return node;
2378
2379                 // Find parent node that is a element
2380                 while ((node = node.parentNode) != null && node.nodeType != 1) ;
2381
2382                 return node;
2383         }
2384
2385         var namesAr = names.split(',');
2386
2387         if (node == null)
2388                 return null;
2389
2390         do {
2391                 for (var i=0; i<namesAr.length; i++) {
2392                         if (node.nodeName.toLowerCase() == namesAr[i].toLowerCase() || names == "*") {
2393                                 if (typeof(attrib_name) == "undefined")
2394                                         return node;
2395                                 else if (node.getAttribute(attrib_name)) {
2396                                         if (typeof(attrib_value) == "undefined") {
2397                                                 if (node.getAttribute(attrib_name) != "")
2398                                                         return node;
2399                                         } else if (node.getAttribute(attrib_name) == attrib_value)
2400                                                 return node;
2401                                 }
2402                         }
2403                 }
2404         } while (node = node.parentNode);
2405
2406         return null;
2407 };
2408
2409 TinyMCE.prototype.convertURL = function(url, node, on_save) {
2410         var prot = document.location.protocol;
2411         var host = document.location.hostname;
2412         var port = document.location.port;
2413
2414         var fileProto = (prot == "file:");
2415
2416         // Something is wrong, remove weirdness
2417         url = tinyMCE.regexpReplace(url, '(http|https):///', '/');
2418
2419         // Mailto link or anchor (Pass through)
2420         if (url.indexOf('mailto:') != -1 || url.indexOf('javascript:') != -1 || tinyMCE.regexpReplace(url,'[ \t\r\n\+]|%20','').charAt(0) == "#")
2421                 return url;
2422
2423         // Fix relative/Mozilla
2424         if (!tinyMCE.isMSIE && !on_save && url.indexOf("://") == -1 && url.charAt(0) != '/')
2425                 return tinyMCE.settings['base_href'] + url;
2426
2427         // Handle absolute url anchors
2428         if (!tinyMCE.settings['relative_urls']) {
2429                 var urlParts = tinyMCE.parseURL(url);
2430                 var baseUrlParts = tinyMCE.parseURL(tinyMCE.settings['base_href']);
2431
2432                 // If anchor and path is the same page
2433                 if (urlParts['anchor'] && urlParts['path'] == baseUrlParts['path'])
2434                         return "#" + urlParts['anchor'];
2435         }
2436
2437         // Convert to relative urls
2438         if (on_save && tinyMCE.settings['relative_urls']) {
2439                 var urlParts = tinyMCE.parseURL(url);
2440
2441                 // If not absolute url, do nothing (Mozilla)
2442                 // WEIRD STUFF?!
2443 /*              if (!urlParts['protocol'] && !tinyMCE.isMSIE) {
2444                         var urlPrefix = "http://";
2445                         urlPrefix += host;
2446                         if (port != "")
2447                                 urlPrefix += ":" + port;
2448
2449                         url = urlPrefix + url;
2450                         urlParts = tinyMCE.parseURL(url);
2451                 }*/
2452
2453                 var tmpUrlParts = tinyMCE.parseURL(tinyMCE.settings['document_base_url']);
2454
2455                 // Link is within this site
2456                 if (urlParts['host'] == tmpUrlParts['host'] && (!urlParts['port'] || urlParts['port'] == tmpUrlParts['port']))
2457                         return tinyMCE.convertAbsoluteURLToRelativeURL(tinyMCE.settings['document_base_url'], url);
2458         }
2459
2460         // Remove current domain
2461         if (!fileProto && tinyMCE.settings['remove_script_host']) {
2462                 var start = "", portPart = "";
2463
2464                 if (port != "")
2465                         portPart = ":" + port;
2466
2467                 start = prot + "//" + host + portPart + "/";
2468
2469                 if (url.indexOf(start) == 0)
2470                         url = url.substring(start.length-1);
2471
2472                 // Add first slash if missing on a absolute URL
2473                 if (!tinyMCE.settings['relative_urls'] && url.indexOf('://') == -1 && url.charAt(0) != '/')
2474                         url = '/' + url;
2475         }
2476
2477         return url;
2478 };
2479
2480 /**
2481  * Parses a URL in to its diffrent components.
2482  */
2483 TinyMCE.prototype.parseURL = function(url_str) {
2484         var urlParts = new Array();
2485
2486         if (url_str) {
2487                 var pos, lastPos;
2488
2489                 // Parse protocol part
2490                 pos = url_str.indexOf('://');
2491                 if (pos != -1) {
2492                         urlParts['protocol'] = url_str.substring(0, pos);
2493                         lastPos = pos + 3;
2494                 }
2495
2496                 // Find port or path start
2497                 for (var i=lastPos; i<url_str.length; i++) {
2498                         var chr = url_str.charAt(i);
2499
2500                         if (chr == ':')
2501                                 break;
2502
2503                         if (chr == '/')
2504                                 break;
2505                 }
2506                 pos = i;
2507
2508                 // Get host
2509                 urlParts['host'] = url_str.substring(lastPos, pos);
2510
2511                 // Get port
2512                 lastPos = pos;
2513                 if (url_str.charAt(pos) == ':') {
2514                         pos = url_str.indexOf('/', lastPos);
2515                         urlParts['port'] = url_str.substring(lastPos+1, pos);
2516                 }
2517
2518                 // Get path
2519                 lastPos = pos;
2520                 pos = url_str.indexOf('?', lastPos);
2521
2522                 if (pos == -1)
2523                         pos = url_str.indexOf('#', lastPos);
2524
2525                 if (pos == -1)
2526                         pos = url_str.length;
2527
2528                 urlParts['path'] = url_str.substring(lastPos, pos);
2529
2530                 // Get query
2531                 lastPos = pos;
2532                 if (url_str.charAt(pos) == '?') {
2533                         pos = url_str.indexOf('#');
2534                         pos = (pos == -1) ? url_str.length : pos;
2535                         urlParts['query'] = url_str.substring(lastPos+1, pos);
2536                 }
2537
2538                 // Get anchor
2539                 lastPos = pos;
2540                 if (url_str.charAt(pos) == '#') {
2541                         pos = url_str.length;
2542                         urlParts['anchor'] = url_str.substring(lastPos+1, pos);
2543                 }
2544         }
2545
2546         return urlParts;
2547 };
2548
2549 /**
2550  * Converts an absolute path to relative path.
2551  */
2552 TinyMCE.prototype.convertAbsoluteURLToRelativeURL = function(base_url, url_to_relative) {
2553         var strTok1;
2554         var strTok2;
2555         var breakPoint = 0;
2556         var outputString = "";
2557
2558         // Crop away last path part
2559         base_url = base_url.substring(0, base_url.lastIndexOf('/'));
2560         strTok1 = base_url.split('/');
2561         strTok2 = url_to_relative.split('/');
2562
2563         if (strTok1.length >= strTok2.length) {
2564                 for (var i=0; i<strTok1.length; i++) {
2565                         if (i >= strTok2.length || strTok1[i] != strTok2[i]) {
2566                                 breakPoint = i + 1;
2567                                 break;
2568                         }
2569                 }
2570         }
2571
2572         if (strTok1.length < strTok2.length) {
2573                 for (var i=0; i<strTok2.length; i++) {
2574                         if (i >= strTok1.length || strTok1[i] != strTok2[i]) {
2575                                 breakPoint = i + 1;
2576                                 break;
2577                         }
2578                 }
2579         }
2580
2581         if (breakPoint == 1)
2582                 return url_to_relative;
2583
2584         for (var i=0; i<(strTok1.length-(breakPoint-1)); i++)
2585                 outputString += "../";
2586
2587         for (var i=breakPoint-1; i<strTok2.length; i++) {
2588                 if (i != (breakPoint-1))
2589                         outputString += "/" + strTok2[i];
2590                 else
2591                         outputString += strTok2[i];
2592         }
2593
2594         return outputString;
2595 };
2596
2597 TinyMCE.prototype.convertRelativeToAbsoluteURL = function(base_url, relative_url) {
2598         var baseURL = TinyMCE.prototype.parseURL(base_url);
2599         var relURL = TinyMCE.prototype.parseURL(relative_url);
2600
2601         if (relative_url == "" || relative_url.charAt(0) == '/' || relative_url.indexOf('://') != -1 || relative_url.indexOf('mailto:') != -1 || relative_url.indexOf('javascript:') != -1 || tinyMCE.regexpReplace(relative_url,'[ \t\r\n\+]|%20','').charAt(0) == "#")
2602                 return relative_url;
2603
2604         // Split parts
2605         baseURLParts = baseURL['path'].split('/');
2606         relURLParts = relURL['path'].split('/');
2607
2608         // Remove empty chunks
2609         var newBaseURLParts = new Array();
2610         for (var i=baseURLParts.length-1; i>=0; i--) {
2611                 if (baseURLParts[i].length == 0)
2612                         continue;
2613
2614                 newBaseURLParts[newBaseURLParts.length] = baseURLParts[i];
2615         }
2616         baseURLParts = newBaseURLParts.reverse();
2617
2618         // Merge relURLParts chunks
2619         var newRelURLParts = new Array();
2620         var numBack = 0;
2621         for (var i=relURLParts.length-1; i>=0; i--) {
2622                 if (relURLParts[i].length == 0 || relURLParts[i] == ".")
2623                         continue;
2624
2625                 if (relURLParts[i] == '..') {
2626                         numBack++;
2627                         continue;
2628                 }
2629
2630                 if (numBack > 0) {
2631                         numBack--;
2632                         continue;
2633                 }
2634
2635                 newRelURLParts[newRelURLParts.length] = relURLParts[i];
2636         }
2637
2638         relURLParts = newRelURLParts.reverse();
2639
2640         // Remove end from absolute path
2641         var len = baseURLParts.length-numBack;
2642         var absPath = (len <= 0 ? "" : "/") + baseURLParts.slice(0, len).join('/') + "/" + relURLParts.join('/');
2643         var start = "", end = "";
2644
2645         // Build start part
2646         if (baseURL['protocol'])
2647                 start += baseURL['protocol'] + "://";
2648
2649         if (baseURL['host'])
2650                 start += baseURL['host'];
2651
2652         if (baseURL['port'])
2653                 start += ":" + baseURL['port'];
2654
2655         // Build end part
2656         if (relURL['query'])
2657                 end += "?" + relURL['query'];
2658
2659         if (relURL['anchor'])
2660                 end += "#" + relURL['anchor'];
2661
2662         // Re-add trailing slash if it's removed
2663         if (relative_url.charAt(relative_url.length-1) == "/")
2664                 end += "/";
2665
2666         return start + absPath + end;
2667 };
2668
2669 TinyMCE.prototype.getParam = function(name, default_value, strip_whitespace, split_chr) {
2670         var value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];
2671
2672         // Fix bool values
2673         if (value == "true" || value == "false")
2674                 return (value == "true");
2675
2676         if (strip_whitespace)
2677                 value = tinyMCE.regexpReplace(value, "[ \t\r\n]", "");
2678
2679         if (typeof(split_chr) != "undefined" && split_chr != null) {
2680                 value = value.split(split_chr);
2681                 var outArray = new Array();
2682
2683                 for (var i=0; i<value.length; i++) {
2684                         if (value[i] && value[i] != "")
2685                                 outArray[outArray.length] = value[i];
2686                 }
2687
2688                 value = outArray;
2689         }
2690
2691         return value;
2692 };
2693
2694 TinyMCE.prototype.getLang = function(name, default_value, parse_entities) {
2695         var value = (typeof(tinyMCELang[name]) == "undefined") ? default_value : tinyMCELang[name];
2696
2697         if (parse_entities) {
2698                 var el = document.createElement("div");
2699                 el.innerHTML = value;
2700                 value = el.innerHTML;
2701         }
2702
2703         return value;
2704 };
2705
2706 TinyMCE.prototype.addToLang = function(prefix, ar) {
2707         for (var key in ar)
2708                 tinyMCELang[(key.indexOf('lang_') == -1 ? 'lang_' : '') + (prefix != '' ? (prefix + "_") : '') + key] = ar[key];
2709
2710 //      for (var key in ar)
2711 //              tinyMCELang[(key.indexOf('lang_') == -1 ? 'lang_' : '') + (prefix != '' ? (prefix + "_") : '') + key] = "|" + ar[key] + "|";
2712 };
2713
2714 TinyMCE.prototype.replaceVar = function(replace_haystack, replace_var, replace_str) {
2715         var re = new RegExp('{\\\$' + replace_var + '}', 'g');
2716         return replace_haystack.replace(re, replace_str);
2717 };
2718
2719 TinyMCE.prototype.replaceVars = function(replace_haystack, replace_vars) {
2720         for (var key in replace_vars) {
2721                 var value = replace_vars[key];
2722                 replace_haystack = tinyMCE.replaceVar(replace_haystack, key, value);
2723         }
2724
2725         return replace_haystack;
2726 };
2727
2728 TinyMCE.prototype.triggerNodeChange = function(focus, setup_content) {
2729         if (tinyMCE.settings['handleNodeChangeCallback']) {
2730                 if (tinyMCE.selectedInstance) {
2731                         var inst = tinyMCE.selectedInstance;
2732                         var editorId = inst.editorId;
2733                         var elm = (typeof(setup_content) != "undefined" && setup_content) ? tinyMCE.selectedElement : inst.getFocusElement();
2734                         var undoIndex = -1;
2735                         var undoLevels = -1;
2736                         var anySelection = false;
2737                         var selectedText = inst.getSelectedText();
2738
2739                         if (tinyMCE.settings["auto_resize"]) {
2740                                 var doc = inst.getDoc();
2741
2742                                 inst.iframeElement.style.width = doc.body.offsetWidth + "px";
2743                                 inst.iframeElement.style.height = doc.body.offsetHeight + "px";
2744                         }
2745
2746                         if (tinyMCE.selectedElement)
2747                                 anySelection = (tinyMCE.selectedElement.nodeName.toLowerCase() == "img") || (selectedText && selectedText.length > 0);
2748
2749                         if (tinyMCE.settings['custom_undo_redo']) {
2750                                 undoIndex = inst.undoIndex;
2751                                 undoLevels = inst.undoLevels.length;
2752                         }
2753
2754                         tinyMCE.executeCallback('handleNodeChangeCallback', '_handleNodeChange', 0, editorId, elm, undoIndex, undoLevels, inst.visualAid, anySelection);
2755                 }
2756         }
2757
2758         if (this.selectedInstance && (typeof(focus) == "undefined" || focus))
2759                 this.selectedInstance.contentWindow.focus();
2760 };
2761
2762 TinyMCE.prototype._customCleanup = function(inst, type, content) {
2763         // Call custom cleanup
2764         var customCleanup = tinyMCE.settings['cleanup_callback'];
2765         if (customCleanup != "" && eval("typeof(" + customCleanup + ")") != "undefined")
2766                 content = eval(customCleanup + "(type, content, inst);");
2767
2768         // Trigger plugin cleanups
2769         var plugins = tinyMCE.getParam('plugins', '', true, ',');
2770         for (var i=0; i<plugins.length; i++) {
2771                 if (eval("typeof(TinyMCE_" + plugins[i] +  "_cleanup)") != "undefined")
2772                         content = eval("TinyMCE_" + plugins[i] +  "_cleanup(type, content, inst);");
2773         }
2774
2775         return content;
2776 };
2777
2778 TinyMCE.prototype.getContent = function(editor_id) {
2779         if (typeof(editor_id) != "undefined")
2780                 tinyMCE.selectedInstance = tinyMCE.getInstanceById(editor_id);
2781
2782         if (tinyMCE.selectedInstance)
2783                 return tinyMCE._cleanupHTML(this.selectedInstance, this.selectedInstance.getDoc(), tinyMCE.settings, this.selectedInstance.getBody(), false, true);
2784
2785         return null;
2786 };
2787
2788 TinyMCE.prototype.setContent = function(html_content) {
2789         if (tinyMCE.selectedInstance) {
2790                 tinyMCE.selectedInstance.execCommand('mceSetContent', false, html_content);
2791                 tinyMCE.selectedInstance.repaint();
2792         }
2793 };
2794
2795 TinyMCE.prototype.importThemeLanguagePack = function(name) {
2796         if (typeof(name) == "undefined")
2797                 name = tinyMCE.settings['theme'];
2798
2799         tinyMCE.loadScript(tinyMCE.baseURL + '/themes/' + name + '/langs/' + tinyMCE.settings['language'] + '.js');
2800 };
2801
2802 TinyMCE.prototype.importPluginLanguagePack = function(name, valid_languages) {
2803         var lang = "en";
2804
2805         valid_languages = valid_languages.split(',');
2806         for (var i=0; i<valid_languages.length; i++) {
2807                 if (tinyMCE.settings['language'] == valid_languages[i])
2808                         lang = tinyMCE.settings['language'];
2809         }
2810
2811         tinyMCE.loadScript(tinyMCE.baseURL + '/plugins/' + name + '/langs/' + lang +  '.js');
2812 };
2813
2814 /**
2815  * Adds themeurl, settings and lang to HTML code.
2816  */
2817 TinyMCE.prototype.applyTemplate = function(html, args) {
2818         html = tinyMCE.replaceVar(html, "themeurl", tinyMCE.themeURL);
2819
2820         if (typeof(args) != "undefined")
2821                 html = tinyMCE.replaceVars(html, args);
2822
2823         html = tinyMCE.replaceVars(html, tinyMCE.settings);
2824         html = tinyMCE.replaceVars(html, tinyMCELang);
2825
2826         return html;
2827 };
2828
2829 TinyMCE.prototype.openWindow = function(template, args) {
2830         var html, width, height, x, y, resizable, scrollbars, url;
2831
2832         args['mce_template_file'] = template['file'];
2833         args['mce_width'] = template['width'];
2834         args['mce_height'] = template['height'];
2835         tinyMCE.windowArgs = args;
2836
2837         html = template['html'];
2838         if (!(width = parseInt(template['width'])))
2839                 width = 320;
2840
2841         if (!(height = parseInt(template['height'])))
2842                 height = 200;
2843
2844         // Add to height in M$ due to SP2 WHY DON'T YOU GUYS IMPLEMENT innerWidth of windows!!
2845         if (tinyMCE.isMSIE)
2846                 height += 40;
2847         else
2848                 height += 20;
2849
2850         x = parseInt(screen.width / 2.0) - (width / 2.0);
2851         y = parseInt(screen.height / 2.0) - (height / 2.0);
2852
2853         resizable = (args && args['resizable']) ? args['resizable'] : "no";
2854         scrollbars = (args && args['scrollbars']) ? args['scrollbars'] : "no";
2855
2856         if (template['file'].charAt(0) != '/' && template['file'].indexOf('://') == -1)
2857                 url = tinyMCE.baseURL + "/themes/" + tinyMCE.getParam("theme") + "/" + template['file'];
2858         else
2859                 url = template['file'];
2860
2861         // Replace all args as variables in URL
2862         for (var name in args)
2863                 url = tinyMCE.replaceVar(url, name, escape(args[name]));
2864
2865         if (html) {
2866                 html = tinyMCE.replaceVar(html, "css", this.settings['popups_css']);
2867                 html = tinyMCE.applyTemplate(html, args);
2868
2869                 var win = window.open("", "mcePopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=yes,minimizable=" + resizable + ",modal=yes,width=" + width + ",height=" + height + ",resizable=" + resizable);
2870                 if (win == null) {
2871                         alert(tinyMCELang['lang_popup_blocked']);
2872                         return;
2873                 }
2874
2875                 win.document.write(html);
2876                 win.document.close();
2877                 win.resizeTo(width, height);
2878                 win.focus();
2879         } else {
2880                 if (tinyMCE.isMSIE && resizable != 'yes' && tinyMCE.settings["dialog_type"] == "modal") {
2881             var features = "resizable:" + resizable 
2882                 + ";scroll:"
2883                 + scrollbars + ";status:yes;center:yes;help:no;dialogWidth:"
2884                 + width + "px;dialogHeight:" + height + "px;";
2885
2886                         window.showModalDialog(url, window, features);
2887                 } else {
2888                         var modal = (resizable == "yes") ? "no" : "yes";
2889
2890                         if (tinyMCE.isGecko && tinyMCE.isMac)
2891                                 modal = "no";
2892
2893                         var win = window.open(url, "mcePopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=" + modal + ",minimizable=" + resizable + ",modal=" + modal + ",width=" + width + ",height=" + height + ",resizable=" + resizable);
2894                         if (win == null) {
2895                                 alert(tinyMCELang['lang_popup_blocked']);
2896                                 return;
2897                         }
2898
2899                         eval('try { win.resizeTo(width, height); } catch(e) { }');
2900
2901                         // Make it bigger if statusbar is forced
2902                         if (tinyMCE.isGecko) {
2903                                 if (win.document.defaultView.statusbar.visible)
2904                                         win.resizeBy(0, tinyMCE.isMac ? 10 : 24);
2905                         }
2906
2907                         win.focus();
2908                 }
2909         }
2910 };
2911
2912 TinyMCE.prototype.closeWindow = function(win) {
2913         win.close();
2914 };
2915
2916 TinyMCE.prototype.getVisualAidClass = function(class_name, state) {
2917         var aidClass = tinyMCE.settings['visual_table_class'];
2918
2919         if (typeof(state) == "undefined")
2920                 state = tinyMCE.settings['visual'];
2921
2922         // Split
2923         var classNames = new Array();
2924         var ar = class_name.split(' ');
2925         for (var i=0; i<ar.length; i++) {
2926                 if (ar[i] == aidClass)
2927                         ar[i] = "";
2928
2929                 if (ar[i] != "")
2930                         classNames[classNames.length] = ar[i];
2931         }
2932
2933         if (state)
2934                 classNames[classNames.length] = aidClass;
2935
2936         // Glue
2937         var className = "";
2938         for (var i=0; i<classNames.length; i++) {
2939                 if (i > 0)
2940                         className += " ";
2941
2942                 className += classNames[i];
2943         }
2944
2945         return className;
2946 };
2947
2948 TinyMCE.prototype.handleVisualAid = function(element, deep, state, inst) {
2949         if (!element)
2950                 return;
2951
2952         var tableElement = null;
2953
2954         switch (element.nodeName) {
2955                 case "TABLE":
2956                         var oldW = element.style.width;
2957                         var oldH = element.style.height;
2958
2959                         element.className = tinyMCE.getVisualAidClass(element.className, state && element.getAttribute("border") == 0);
2960
2961                         element.style.width = oldW;
2962                         element.style.height = oldH;
2963
2964                         for (var y=0; y<element.rows.length; y++) {
2965                                 for (var x=0; x<element.rows[y].cells.length; x++) {
2966                                         var className = tinyMCE.getVisualAidClass(element.rows[y].cells[x].className, state && element.getAttribute("border") == 0);
2967                                         element.rows[y].cells[x].className = className;
2968                                 }
2969                         }
2970
2971                         break;
2972
2973                 case "A":
2974                         var anchorName = tinyMCE.getAttrib(element, "name");
2975
2976                         if (anchorName != '' && state) {
2977                                 element.title = anchorName;
2978                                 element.className = 'mceItemAnchor';
2979                         } else if (anchorName != '' && !state)
2980                                 element.className = '';
2981
2982                         break;
2983         }
2984
2985         if (deep && element.hasChildNodes()) {
2986                 for (var i=0; i<element.childNodes.length; i++)
2987                         tinyMCE.handleVisualAid(element.childNodes[i], deep, state, inst);
2988         }
2989 };
2990
2991 TinyMCE.prototype.getAttrib = function(elm, name, default_value) {
2992         if (typeof(default_value) == "undefined")
2993                 default_value = "";
2994
2995         // Not a element
2996         if (!elm || elm.nodeType != 1)
2997                 return default_value;
2998
2999         var v = elm.getAttribute(name);
3000
3001         // Try className for class attrib
3002         if (name == "class" && !v)
3003                 v = elm.className;
3004
3005         if (name == "style")
3006                 v = elm.style.cssText;
3007
3008         return (v && v != "") ? v : default_value;
3009 };
3010
3011 TinyMCE.prototype.setAttrib = function(element, name, value, fix_value) {
3012         if (typeof(value) == "number" && value != null)
3013                 value = "" + value;
3014
3015         if (fix_value) {
3016                 if (value == null)
3017                         value = "";
3018
3019                 var re = new RegExp('[^0-9%]', 'g');
3020                 value = value.replace(re, '');
3021         }
3022
3023         if (name == "style")
3024                 element.style.cssText = value;
3025
3026         if (name == "class")
3027                 element.className = value;
3028
3029         if (value != null && value != "" && value != -1)
3030                 element.setAttribute(name, value);
3031         else
3032                 element.removeAttribute(name);
3033 };
3034
3035 TinyMCE.prototype._setHTML = function(doc, html_content) {
3036         // Weird MSIE bug, <p><hr /></p> breaks runtime?
3037         if (tinyMCE.isMSIE) {
3038                 var re = new RegExp('<p><hr /></p>', 'g');
3039                 html_content = html_content.replace(re, "<hr>");
3040         }
3041
3042         // Try innerHTML if it fails use pasteHTML in MSIE
3043         try {
3044                 doc.body.innerHTML = html_content;
3045         } catch (e) {
3046                 if (this.isMSIE)
3047                         doc.body.createTextRange().pasteHTML(html_content);
3048         }
3049
3050         // Content duplication bug fix
3051         if (tinyMCE.isMSIE && tinyMCE.settings['fix_content_duplication']) {
3052                 // Remove P elements in P elements
3053                 var paras = doc.getElementsByTagName("P");
3054                 for (var i=0; i<paras.length; i++) {
3055                         var node = paras[i];
3056                         while ((node = node.parentNode) != null) {
3057                                 if (node.nodeName.toLowerCase() == "p")
3058                                         node.outerHTML = node.innerHTML;
3059                         }
3060                 }
3061
3062                 // Content duplication bug fix (Seems to be word crap)
3063                 var html = doc.body.innerHTML;
3064
3065                 if (html.indexOf('="mso') != -1) {
3066                         for (var i=0; i<doc.body.all.length; i++) {
3067                                 var el = doc.body.all[i];
3068                                 el.removeAttribute("className","",0);
3069                                 el.removeAttribute("style","",0);
3070                         }
3071
3072                         html = doc.body.innerHTML;
3073                         html = tinyMCE.regexpReplace(html, "<o:p><\/o:p>", "<br />");
3074                         html = tinyMCE.regexpReplace(html, "<o:p>&nbsp;<\/o:p>", "");
3075                         html = tinyMCE.regexpReplace(html, "<st1:.*?>", "");
3076                         html = tinyMCE.regexpReplace(html, "<p><\/p>", "");
3077                         html = tinyMCE.regexpReplace(html, "<p><\/p>\r\n<p><\/p>", "");
3078                         html = tinyMCE.regexpReplace(html, "<p>&nbsp;<\/p>", "<br />");
3079                         html = tinyMCE.regexpReplace(html, "<p>\s*(<p>\s*)?", "<p>");
3080                         html = tinyMCE.regexpReplace(html, "<\/p>\s*(<\/p>\s*)?", "</p>");
3081                 }
3082
3083                 // Always set the htmlText output
3084                 doc.body.innerHTML = html;
3085         }
3086 };
3087
3088 TinyMCE.prototype.getImageSrc = function(str) {
3089         var pos = -1;
3090
3091         if (!str)
3092                 return "";
3093
3094         if ((pos = str.indexOf('this.src=')) != -1) {
3095                 var src = str.substring(pos + 10);
3096
3097                 src = src.substring(0, src.indexOf('\''));
3098
3099                 return src;
3100         }
3101
3102         return "";
3103 };
3104
3105 TinyMCE.prototype._getElementById = function(element_id) {
3106         var elm = document.getElementById(element_id);
3107         if (!elm) {
3108                 // Check for element in forms
3109                 for (var j=0; j<document.forms.length; j++) {
3110                         for (var k=0; k<document.forms[j].elements.length; k++) {
3111                                 if (document.forms[j].elements[k].name == element_id) {
3112                                         elm = document.forms[j].elements[k];
3113                                         break;
3114                                 }
3115                         }
3116                 }
3117         }
3118
3119         return elm;
3120 };
3121
3122 TinyMCE.prototype.getEditorId = function(form_element) {
3123         var inst = this.getInstanceById(form_element);
3124         if (!inst)
3125                 return null;
3126
3127         return inst.editorId;
3128 };
3129
3130 TinyMCE.prototype.getInstanceById = function(editor_id) {
3131         var inst = this.instances[editor_id];
3132         if (!inst) {
3133                 for (var instanceName in tinyMCE.instances) {
3134                         var instance = tinyMCE.instances[instanceName];
3135                         if (instance.formTargetElementId == editor_id) {
3136                                 inst = instance;
3137                                 break;
3138                         }
3139                 }
3140         }
3141
3142         return inst;
3143 };
3144
3145 TinyMCE.prototype.queryInstanceCommandValue = function(editor_id, command) {
3146         var inst = tinyMCE.getInstanceById(editor_id);
3147         if (inst)
3148                 return inst.queryCommandValue(command);
3149
3150         return false;
3151 };
3152
3153 TinyMCE.prototype.queryInstanceCommandState = function(editor_id, command) {
3154         var inst = tinyMCE.getInstanceById(editor_id);
3155         if (inst)
3156                 return inst.queryCommandState(command);
3157
3158         return null;
3159 };
3160
3161 TinyMCE.prototype.setWindowArg = function(name, value) {
3162         this.windowArgs[name] = value;
3163 };
3164
3165 TinyMCE.prototype.getWindowArg = function(name, default_value) {
3166         return (typeof(this.windowArgs[name]) == "undefined") ? default_value : this.windowArgs[name];
3167 };
3168
3169 TinyMCE.prototype.getCSSClasses = function(editor_id, doc) {
3170         var output = new Array();
3171
3172         // Is cached, use that
3173         if (typeof(tinyMCE.cssClasses) != "undefined")
3174                 return tinyMCE.cssClasses;
3175
3176         if (typeof(editor_id) == "undefined" && typeof(doc) == "undefined") {
3177                 var instance;
3178
3179                 for (var instanceName in tinyMCE.instances) {
3180                         instance = tinyMCE.instances[instanceName];
3181                         break;
3182                 }
3183
3184                 doc = instance.getDoc();
3185         }
3186
3187         if (typeof(doc) == "undefined") {
3188                 var instance = tinyMCE.getInstanceById(editor_id);
3189                 doc = instance.getDoc();
3190         }
3191
3192         if (doc) {
3193                 var styles = tinyMCE.isMSIE ? doc.styleSheets : doc.styleSheets;
3194
3195                 if (styles && styles.length > 0) {
3196                         for (var x=0; x<styles.length; x++) {
3197                                 var csses = null;
3198
3199                                 // Just ignore any errors
3200                                 eval("try {var csses = tinyMCE.isMSIE ? doc.styleSheets(" + x + ").rules : doc.styleSheets[" + x + "].cssRules;} catch(e) {}");
3201                                 if (!csses)
3202                                         return new Array();
3203
3204                                 for (var i=0; i<csses.length; i++) {
3205                                         var selectorText = csses[i].selectorText;
3206
3207                                         // Can be multiple rules per selector
3208                                         if (selectorText) {
3209                                                 var rules = selectorText.split(',');
3210                                                 for (var c=0; c<rules.length; c++) {
3211                                                         // Invalid rule
3212                                                         if (rules[c].indexOf(' ') != -1 || rules[c].indexOf(':') != -1 || rules[c].indexOf('mceItem') != -1)
3213                                                                 continue;
3214
3215                                                         if (rules[c] == "." + tinyMCE.settings['visual_table_class'])
3216                                                                 continue;
3217
3218                                                         // Is class rule
3219                                                         if (rules[c].indexOf('.') != -1) {
3220                                                                 //alert(rules[c].substring(rules[c].indexOf('.')));
3221                                                                 output[output.length] = rules[c].substring(rules[c].indexOf('.')+1);
3222                                                         }
3223                                                 }
3224                                         }
3225                                 }
3226                         }
3227                 }
3228         }
3229
3230         // Cache em
3231         if (output.length > 0)
3232                 tinyMCE.cssClasses = output;
3233
3234         return output;
3235 };
3236
3237 TinyMCE.prototype.regexpReplace = function(in_str, reg_exp, replace_str, opts) {
3238         if (typeof(opts) == "undefined")
3239                 opts = 'g';
3240
3241         var re = new RegExp(reg_exp, opts);
3242         return in_str.replace(re, replace_str);
3243 };
3244
3245 TinyMCE.prototype.trim = function(str) {
3246         return str.replace(/^\s*|\s*$/g, "");
3247 };
3248
3249 TinyMCE.prototype.cleanupEventStr = function(str) {
3250         str = "" + str;
3251         str = str.replace('function anonymous()\n{\n', '');
3252         str = str.replace('\n}', '');
3253         str = str.replace(/^return true;/gi, '');
3254
3255         return str;
3256 };
3257
3258 TinyMCE.prototype.getAbsPosition = function(node) {
3259         var pos = new Object();
3260
3261         pos.absLeft = pos.absTop = 0;
3262
3263         var parentNode = node;
3264         while (parentNode) {
3265                 pos.absLeft += parentNode.offsetLeft;
3266                 pos.absTop += parentNode.offsetTop;
3267
3268                 parentNode = parentNode.offsetParent;
3269         }
3270
3271         return pos;
3272 };
3273
3274 TinyMCE.prototype.getControlHTML = function(control_name) {
3275         var themePlugins = tinyMCE.getParam('plugins', '', true, ',');
3276         var templateFunction;
3277
3278         // Is it defined in any plugins
3279         for (var i=themePlugins.length; i>=0; i--) {
3280                 templateFunction = 'TinyMCE_' + themePlugins[i] + "_getControlHTML";
3281                 if (eval("typeof(" + templateFunction + ")") != 'undefined') {
3282                         var html = eval(templateFunction + "('" + control_name + "');");
3283                         if (html != "")
3284                                 return tinyMCE.replaceVar(html, "pluginurl", tinyMCE.baseURL + "/plugins/" + themePlugins[i]);
3285                 }
3286         }
3287
3288         return eval('TinyMCE_' + tinyMCE.settings['theme'] + "_getControlHTML" + "('" + control_name + "');");
3289 };
3290
3291 TinyMCE.prototype._themeExecCommand = function(editor_id, element, command, user_interface, value) {
3292         var themePlugins = tinyMCE.getParam('plugins', '', true, ',');
3293         var templateFunction;
3294
3295         // Is it defined in any plugins
3296         for (var i=themePlugins.length; i>=0; i--) {
3297                 templateFunction = 'TinyMCE_' + themePlugins[i] + "_execCommand";
3298                 if (eval("typeof(" + templateFunction + ")") != 'undefined') {
3299                         if (eval(templateFunction + "(editor_id, element, command, user_interface, value);"))
3300                                 return true;
3301                 }
3302         }
3303
3304         // Theme funtion
3305         templateFunction = 'TinyMCE_' + tinyMCE.settings['theme'] + "_execCommand";
3306         if (eval("typeof(" + templateFunction + ")") != 'undefined')
3307                 return eval(templateFunction + "(editor_id, element, command, user_interface, value);");
3308
3309         // Pass to normal
3310         return false;
3311 };
3312
3313 TinyMCE.prototype._getThemeFunction = function(suffix, skip_plugins) {
3314         if (skip_plugins)
3315                 return 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;
3316
3317         var themePlugins = tinyMCE.getParam('plugins', '', true, ',');
3318         var templateFunction;
3319
3320         // Is it defined in any plugins
3321         for (var i=themePlugins.length; i>=0; i--) {
3322                 templateFunction = 'TinyMCE_' + themePlugins[i] + suffix;
3323                 if (eval("typeof(" + templateFunction + ")") != 'undefined')
3324                         return templateFunction;
3325         }
3326
3327         return 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;
3328 };
3329
3330
3331 TinyMCE.prototype.isFunc = function(func_name) {
3332         if (func_name == null || func_name == "")
3333                 return false;
3334
3335         return eval("typeof(" + func_name + ")") != "undefined";
3336 };
3337
3338 TinyMCE.prototype.exec = function(func_name, args) {
3339         var str = func_name + '(';
3340
3341         // Add all arguments
3342         for (var i=3; i<args.length; i++) {
3343                 str += 'args[' + i + ']';
3344
3345                 if (i < args.length-1)
3346                         str += ',';
3347         }
3348
3349         str += ');';
3350
3351         return eval(str);
3352 };
3353
3354 TinyMCE.prototype.executeCallback = function(param, suffix, mode) {
3355         switch (mode) {
3356                 // No chain
3357                 case 0:
3358                         var state = false;
3359
3360                         // Execute each plugin callback
3361                         var plugins = tinyMCE.getParam('plugins', '', true, ',');
3362                         for (var i=0; i<plugins.length; i++) {
3363                                 var func = "TinyMCE_" + plugins[i] + suffix;
3364                                 if (tinyMCE.isFunc(func)) {
3365                                         tinyMCE.exec(func, this.executeCallback.arguments);
3366                                         state = true;
3367                                 }
3368                         }
3369
3370                         // Execute theme callback
3371                         var func = 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;
3372                         if (tinyMCE.isFunc(func)) {
3373                                 tinyMCE.exec(func, this.executeCallback.arguments);
3374                                 state = true;
3375                         }
3376
3377                         // Execute settings callback
3378                         var func = tinyMCE.getParam(param, '');
3379                         if (tinyMCE.isFunc(func)) {
3380                                 tinyMCE.exec(func, this.executeCallback.arguments);
3381                                 state = true;
3382                         }
3383
3384                         return state;
3385
3386                 // Chain mode
3387                 case 1:
3388                         // Execute each plugin callback
3389                         var plugins = tinyMCE.getParam('plugins', '', true, ',');
3390                         for (var i=0; i<plugins.length; i++) {
3391                                 var func = "TinyMCE_" + plugins[i] + suffix;
3392                                 if (tinyMCE.isFunc(func)) {
3393                                         if (tinyMCE.exec(func, this.executeCallback.arguments))
3394                                                 return true;
3395                                 }
3396                         }
3397
3398                         // Execute theme callback
3399                         var func = 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;
3400                         if (tinyMCE.isFunc(func)) {
3401                                 if (tinyMCE.exec(func, this.executeCallback.arguments))
3402                                         return true;
3403                         }
3404
3405                         // Execute settings callback
3406                         var func = tinyMCE.getParam(param, '');
3407                         if (tinyMCE.isFunc(func)) {
3408                                 if (tinyMCE.exec(func, this.executeCallback.arguments))
3409                                         return true;
3410                         }
3411
3412                         return false;
3413         }
3414 };
3415
3416 TinyMCE.prototype.debug = function() {
3417         var msg = "";
3418
3419         var elm = document.getElementById("tinymce_debug");
3420         if (!elm) {
3421                 var debugDiv = document.createElement("div");
3422                 debugDiv.setAttribute("className", "debugger");
3423                 debugDiv.className = "debugger";
3424                 debugDiv.innerHTML = '\
3425                         Debug output:\
3426                         <textarea id="tinymce_debug" style="width: 100%; height: 300px"></textarea>';
3427
3428                 document.body.appendChild(debugDiv);
3429                 elm = document.getElementById("tinymce_debug");
3430         }
3431
3432         var args = this.debug.arguments;
3433         for (var i=0; i<args.length; i++) {
3434                 msg += args[i];
3435                 if (i<args.length-1)
3436                         msg += ', ';
3437         }
3438
3439         elm.value += msg + "\n";
3440 };
3441
3442 // TinyMCEControl
3443 function TinyMCEControl(settings) {
3444         // Undo levels
3445         this.undoLevels = new Array();
3446         this.undoIndex = 0;
3447         this.typingUndoIndex = -1;
3448         this.undoRedo = true;
3449
3450         // Default settings
3451         this.settings = settings;
3452         this.settings['theme'] = tinyMCE.getParam("theme", "default");
3453         this.settings['width'] = tinyMCE.getParam("width", -1);
3454         this.settings['height'] = tinyMCE.getParam("height", -1);
3455 };
3456
3457 TinyMCEControl.prototype.repaint = function() {
3458         if (tinyMCE.isMSIE)
3459                 return;
3460
3461         this.getBody().style.display = 'none';
3462         this.getBody().style.display = 'block';
3463 };
3464
3465 TinyMCEControl.prototype.switchSettings = function() {
3466         if (tinyMCE.configs.length > 1 && tinyMCE.currentConfig != this.settings['index']) {
3467                 tinyMCE.settings = this.settings;
3468                 tinyMCE.currentConfig = this.settings['index'];
3469         }
3470 };
3471
3472 TinyMCEControl.prototype.fixBrokenURLs = function() {
3473         var body = this.getBody();
3474
3475         var elms = body.getElementsByTagName("img");
3476         for (var i=0; i<elms.length; i++) {
3477                 var src = elms[i].getAttribute('mce_real_src');
3478                 if (src && src != "")
3479                         elms[i].setAttribute("src", src);
3480         }
3481
3482         var elms = body.getElementsByTagName("a");
3483         for (var i=0; i<elms.length; i++) {
3484                 var href = elms[i].getAttribute('mce_real_href');
3485                 if (href && href != "")
3486                         elms[i].setAttribute("href", href);
3487         }
3488 };
3489
3490 TinyMCEControl.prototype.convertAllRelativeURLs = function() {
3491         var body = this.getBody();
3492
3493         // Convert all image URL:s to absolute URL
3494         var elms = body.getElementsByTagName("img");
3495         for (var i=0; i<elms.length; i++) {
3496                 var src = elms[i].getAttribute('src');
3497                 if (src && src != "") {
3498                         src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], src);
3499                         elms[i].setAttribute("src", src);
3500                         elms[i].setAttribute("mce_real_src", src);
3501                 }
3502         }
3503
3504         // Convert all link URL:s to absolute URL
3505         var elms = body.getElementsByTagName("a");
3506         for (var i=0; i<elms.length; i++) {
3507                 var href = elms[i].getAttribute('href');
3508                 if (href && href != "") {
3509                         href = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], href);
3510                         elms[i].setAttribute("href", href);
3511                         elms[i].setAttribute("mce_real_href", href);
3512                 }
3513         }
3514 };
3515
3516 TinyMCEControl.prototype.getSelectedHTML = function() {
3517         if (tinyMCE.isSafari) {
3518                 // Not realy perfect!!
3519
3520                 return this.getRng().toString();
3521         }
3522
3523         var elm = document.createElement("body");
3524
3525         if (tinyMCE.isGecko)
3526                 elm.appendChild(this.getRng().cloneContents());
3527         else
3528                 elm.innerHTML = this.getRng().htmlText;
3529
3530         return tinyMCE._cleanupHTML(this, this.contentDocument, this.settings, elm, this.visualAid);
3531 };
3532
3533 TinyMCEControl.prototype.getBookmark = function() {
3534         var rng = this.getRng();
3535
3536         if (tinyMCE.isSafari)
3537                 return rng;
3538
3539         if (tinyMCE.isMSIE)
3540                 return rng;
3541
3542         if (tinyMCE.isGecko)
3543                 return rng.cloneRange();
3544
3545         return null;
3546 };
3547
3548 TinyMCEControl.prototype.moveToBookmark = function(bookmark) {
3549         if (tinyMCE.isSafari) {
3550                 var sel = this.getSel().realSelection;
3551
3552                 sel.setBaseAndExtent(bookmark.startContainer, bookmark.startOffset, bookmark.endContainer, bookmark.endOffset);
3553
3554                 return true;
3555         }
3556
3557         if (tinyMCE.isMSIE)
3558                 return bookmark.select();
3559
3560         if (tinyMCE.isGecko) {
3561                 var rng = this.getDoc().createRange();
3562                 var sel = this.getSel();
3563
3564                 rng.setStart(bookmark.startContainer, bookmark.startOffset);
3565                 rng.setEnd(bookmark.endContainer, bookmark.endOffset);
3566
3567                 sel.removeAllRanges();
3568                 sel.addRange(rng);
3569
3570                 return true;
3571         }
3572
3573         return false;
3574 };
3575
3576 TinyMCEControl.prototype.getSelectedText = function() {
3577         if (tinyMCE.isMSIE) {
3578                 var doc = this.getDoc();
3579
3580                 if (doc.selection.type == "Text") {
3581                         var rng = doc.selection.createRange();
3582                         selectedText = rng.text;
3583                 } else
3584                         selectedText = '';
3585         } else {
3586                 var sel = this.getSel();
3587
3588                 if (sel && sel.toString)
3589                         selectedText = sel.toString();
3590                 else
3591                         selectedText = '';
3592         }
3593
3594         return selectedText;
3595 };
3596
3597 TinyMCEControl.prototype.selectNode = function(node, collapse, select_text_node, to_start) {
3598         if (!node)
3599                 return;
3600
3601         if (typeof(collapse) == "undefined")
3602                 collapse = true;
3603
3604         if (typeof(select_text_node) == "undefined")
3605                 select_text_node = false;
3606
3607         if (typeof(to_start) == "undefined")
3608                 to_start = true;
3609
3610         if (tinyMCE.isMSIE) {
3611                 var rng = this.getBody().createTextRange();
3612
3613                 try {
3614                         rng.moveToElementText(node);
3615
3616                         if (collapse)
3617                                 rng.collapse(to_start);
3618
3619                         rng.select();
3620                 } catch (e) {
3621                         // Throws illigal agrument in MSIE some times
3622                 }
3623         } else {
3624                 var sel = this.getSel();
3625
3626                 if (!sel)
3627                         return;
3628
3629                 if (tinyMCE.isSafari) {
3630                         sel.realSelection.setBaseAndExtent(node, 0, node, node.innerText.length);
3631
3632                         if (collapse) {
3633                                 if (to_start)
3634                                         sel.realSelection.collapseToStart();
3635                                 else
3636                                         sel.realSelection.collapseToEnd();
3637                         }
3638
3639                         this.scrollToNode(node);
3640
3641                         return;
3642                 }
3643
3644                 var rng = this.getDoc().createRange();
3645
3646                 if (select_text_node) {
3647                         // Find first textnode in tree
3648                         var nodes = tinyMCE.getNodeTree(node, new Array(), 3);
3649                         if (nodes.length > 0)
3650                                 rng.selectNodeContents(nodes[0]);
3651                         else
3652                                 rng.selectNodeContents(node);
3653                 } else
3654                         rng.selectNode(node);
3655
3656                 if (collapse) {
3657                         // Special treatment of textnode collapse
3658                         if (!to_start && node.nodeType == 3) {
3659                                 rng.setStart(node, node.nodeValue.length);
3660                                 rng.setEnd(node, node.nodeValue.length);
3661                         } else
3662                                 rng.collapse(to_start);
3663                 }
3664
3665                 sel.removeAllRanges();
3666                 sel.addRange(rng);
3667         }
3668
3669         this.scrollToNode(node);
3670
3671         // Set selected element
3672         tinyMCE.selectedElement = null;
3673         if (node.nodeType == 1)
3674                 tinyMCE.selectedElement = node;
3675 };
3676
3677 TinyMCEControl.prototype.scrollToNode = function(node) {
3678         // Scroll to node position
3679         var pos = tinyMCE.getAbsPosition(node);
3680         var doc = this.getDoc();
3681         var scrollX = doc.body.scrollLeft + doc.documentElement.scrollLeft;
3682         var scrollY = doc.body.scrollTop + doc.documentElement.scrollTop;
3683         var height = tinyMCE.isMSIE ? document.getElementById(this.editorId).style.pixelHeight : this.targetElement.clientHeight;
3684
3685         // Only scroll if out of visible area
3686         if (!tinyMCE.settings['auto_resize'] && !(node.absTop > scrollY && node.absTop < (scrollY - 25 + height)))
3687                 this.contentWindow.scrollTo(pos.absLeft, pos.absTop - height + 25);
3688 };
3689
3690 TinyMCEControl.prototype.getBody = function() {
3691         return this.getDoc().body;
3692 };
3693
3694 TinyMCEControl.prototype.getDoc = function() {
3695         return this.contentWindow.document;
3696 };
3697
3698 TinyMCEControl.prototype.getWin = function() {
3699         return this.contentWindow;
3700 };
3701
3702 TinyMCEControl.prototype.getSel = function() {
3703         if (tinyMCE.isMSIE)
3704                 return this.getDoc().selection;
3705
3706         var sel = this.contentWindow.getSelection();
3707
3708         // Fake getRangeAt
3709         if (tinyMCE.isSafari && !sel.getRangeAt) {
3710                 var newSel = new Object();
3711                 var doc = this.getDoc();
3712
3713                 function getRangeAt(idx) {
3714                         var rng = new Object();
3715
3716                         rng.startContainer = this.focusNode;
3717                         rng.endContainer = this.anchorNode;
3718                         rng.commonAncestorContainer = this.focusNode;
3719                         rng.createContextualFragment = function (html) {
3720                                 // Seems to be a tag
3721                                 if (html.charAt(0) == '<') {
3722                                         var elm = doc.createElement("div");
3723
3724                                         elm.innerHTML = html;
3725
3726                                         return elm.firstChild;
3727                                 }
3728
3729                                 return doc.createTextNode("UNSUPPORTED, DUE TO LIMITATIONS IN SAFARI!");
3730                         };
3731
3732                         rng.deleteContents = function () {
3733                                 doc.execCommand("Delete", false, "");
3734                         };
3735
3736                         return rng;
3737                 }
3738
3739                 // Patch selection
3740
3741                 newSel.focusNode = sel.baseNode;
3742                 newSel.focusOffset = sel.baseOffset;
3743                 newSel.anchorNode = sel.extentNode;
3744                 newSel.anchorOffset = sel.extentOffset;
3745                 newSel.getRangeAt = getRangeAt;
3746                 newSel.text = "" + sel;
3747                 newSel.realSelection = sel;
3748
3749                 newSel.toString = function () {return this.text;};
3750
3751                 return newSel;
3752         }
3753
3754         return sel;
3755 };
3756
3757 TinyMCEControl.prototype.getRng = function() {
3758         var sel = this.getSel();
3759         if (sel == null)
3760                 return null;
3761
3762         if (tinyMCE.isMSIE)
3763                 return sel.createRange();
3764
3765         if (tinyMCE.isSafari) {
3766                 var rng = this.getDoc().createRange();
3767                 var sel = this.getSel().realSelection;
3768
3769                 rng.setStart(sel.baseNode, sel.baseOffset);
3770                 rng.setEnd(sel.extentNode, sel.extentOffset);
3771
3772                 return rng;
3773         }
3774
3775         return this.getSel().getRangeAt(0);
3776 };
3777
3778 TinyMCEControl.prototype._insertPara = function(e) {
3779         function isEmpty(para) {
3780                 function isEmptyHTML(html) {
3781                         return html.replace(new RegExp('[ \t\r\n]+', 'g'), '').toLowerCase() == "";
3782                 }
3783
3784                 // Check for images
3785                 if (para.getElementsByTagName("img").length > 0)
3786                         return false;
3787
3788                 // Check for tables
3789                 if (para.getElementsByTagName("table").length > 0)
3790                         return false;
3791
3792                 // Check for HRs
3793                 if (para.getElementsByTagName("hr").length > 0)
3794                         return false;
3795
3796                 // Check all textnodes
3797                 var nodes = tinyMCE.getNodeTree(para, new Array(), 3);
3798                 for (var i=0; i<nodes.length; i++) {
3799                         if (!isEmptyHTML(nodes[i].nodeValue))
3800                                 return false;
3801                 }
3802
3803                 // No images, no tables, no hrs, no text content then it's empty
3804                 return true;
3805         }
3806
3807         var doc = this.getDoc();
3808         var sel = this.getSel();
3809         var win = this.contentWindow;
3810         var rng = sel.getRangeAt(0);
3811         var body = doc.body;
3812         var rootElm = doc.documentElement;
3813         var self = this;
3814         var blockName = "P";
3815
3816 //      debug(e.target, sel.anchorNode.nodeName, sel.focusNode.nodeName, rng.startContainer, rng.endContainer, rng.commonAncestorContainer, sel.anchorOffset, sel.focusOffset, rng.toString());
3817
3818         // Setup before range
3819         var rngBefore = doc.createRange();
3820         rngBefore.setStart(sel.anchorNode, sel.anchorOffset);
3821         rngBefore.collapse(true);
3822
3823         // Setup after range
3824         var rngAfter = doc.createRange();
3825         rngAfter.setStart(sel.focusNode, sel.focusOffset);
3826         rngAfter.collapse(true);
3827
3828         // Setup start/end points
3829         var direct = rngBefore.compareBoundaryPoints(rngBefore.START_TO_END, rngAfter) < 0;
3830         var startNode = direct ? sel.anchorNode : sel.focusNode;
3831         var startOffset = direct ? sel.anchorOffset : sel.focusOffset;
3832         var endNode = direct ? sel.focusNode : sel.anchorNode;
3833         var endOffset = direct ? sel.focusOffset : sel.anchorOffset;
3834
3835         // Get block elements
3836         var startBlock = tinyMCE.getParentBlockElement(startNode);
3837         var endBlock = tinyMCE.getParentBlockElement(endNode);
3838
3839         // Use current block name
3840         if (startBlock != null) {
3841                 blockName = startBlock.nodeName.toUpperCase();
3842
3843                 // Use P instead
3844                 if (blockName == "TD" || blockName == "TABLE")
3845                         blockName = "P";
3846         }
3847
3848         // Within a list item (use normal behavior)
3849         if ((startBlock != null && startBlock.nodeName.toLowerCase() == "li") || (endBlock != null && endBlock.nodeName.toLowerCase() == "li"))
3850                 return false;
3851
3852         // Within a table create new paragraphs
3853         if ((startBlock != null && startBlock.nodeName.toLowerCase() == "table") || (endBlock != null && endBlock.nodeName.toLowerCase() == "table"))
3854                 startBlock = endBlock = null;
3855
3856         // Setup new paragraphs
3857         var paraBefore = (startBlock != null && startBlock.nodeName.toUpperCase() == blockName) ? startBlock.cloneNode(false) : doc.createElement(blockName);
3858         var paraAfter = (endBlock != null && endBlock.nodeName.toUpperCase() == blockName) ? endBlock.cloneNode(false) : doc.createElement(blockName);
3859
3860         // Setup chop nodes
3861         var startChop = startNode;
3862         var endChop = endNode;
3863
3864         // Get startChop node
3865         node = startChop;
3866         do {
3867                 if (node == body || node.nodeType == 9 || tinyMCE.isBlockElement(node))
3868                         break;
3869
3870                 startChop = node;
3871         } while ((node = node.previousSibling ? node.previousSibling : node.parentNode));
3872
3873         // Get endChop node
3874         node = endChop;
3875         do {
3876                 if (node == body || node.nodeType == 9 || tinyMCE.isBlockElement(node))
3877                         break;
3878
3879                 endChop = node;
3880         } while ((node = node.nextSibling ? node.nextSibling : node.parentNode));
3881
3882         // If not in a block element
3883         if (startBlock == null) {
3884                 // Delete selection
3885                 rng.deleteContents();
3886                 sel.removeAllRanges();
3887
3888                 if (startChop != rootElm && endChop != rootElm) {
3889                         // Insert paragraph before
3890                         rngBefore = rng.cloneRange();
3891
3892                         if (startChop == body)
3893                                 rngBefore.setStart(startChop, 0);
3894                         else
3895                                 rngBefore.setStartBefore(startChop);
3896
3897                         paraBefore.appendChild(rngBefore.cloneContents());
3898
3899                         // Insert paragraph after
3900                         if (endChop.parentNode.nodeName == blockName)
3901                                 endChop = endChop.parentNode;
3902
3903                         rng.setEndAfter(endChop);
3904
3905                         var contents = rng.cloneContents();
3906                         if (contents.firstChild && (contents.firstChild.nodeName == blockName || contents.firstChild.nodeName.toLowerCase() == "body")) {
3907                                 var nodes = contents.firstChild.childNodes;
3908                                 for (var i=0; i<nodes.length; i++) {
3909                                         if (nodes[i].nodeName.toLowerCase() != "body")
3910                                                 paraAfter.appendChild(nodes[i]);
3911                                 }
3912                         } else
3913                                 paraAfter.appendChild(contents);
3914
3915                         // Check if it's a empty paragraph
3916                         if (isEmpty(paraBefore))
3917                                 paraBefore.innerHTML = "&nbsp;";
3918
3919                         // Check if it's a empty paragraph
3920                         if (isEmpty(paraAfter))
3921                                 paraAfter.innerHTML = "&nbsp;";
3922
3923                         // Delete old contents
3924                         rng.deleteContents();
3925                         rngAfter.deleteContents();
3926                         rngBefore.deleteContents();
3927
3928                         // Insert new paragraphs
3929                         paraAfter.normalize();
3930                         rngBefore.insertNode(paraAfter);
3931                         paraBefore.normalize();
3932                         rngBefore.insertNode(paraBefore);
3933
3934 //                      tinyMCE.debug("1: ", paraBefore.innerHTML, paraAfter.innerHTML);
3935                 } else {
3936                         body.innerHTML = "<" + blockName + ">&nbsp;</" + blockName + "><" + blockName + ">&nbsp;</" + blockName + ">";
3937                         paraAfter = body.childNodes[1];
3938                 }
3939
3940                 this.selectNode(paraAfter, true, true);
3941
3942                 return true;
3943         }
3944
3945         // Place first part within new paragraph
3946         if (startChop.nodeName == blockName)
3947                 rngBefore.setStart(startChop, 0);
3948         else
3949                 rngBefore.setStartBefore(startChop);
3950         rngBefore.setEnd(startNode, startOffset);
3951         paraBefore.appendChild(rngBefore.cloneContents());
3952
3953         // Place secound part within new paragraph
3954         rngAfter.setEndAfter(endChop);
3955         rngAfter.setStart(endNode, endOffset);
3956         var contents = rngAfter.cloneContents();
3957         if (contents.firstChild && contents.firstChild.nodeName == blockName) {
3958                 var nodes = contents.firstChild.childNodes;
3959                 for (var i=0; i<nodes.length; i++) {
3960                         if (nodes[i].nodeName.toLowerCase() != "body")
3961                                 paraAfter.appendChild(nodes[i]);
3962                 }
3963         } else
3964                 paraAfter.appendChild(contents);
3965
3966         // Check if it's a empty paragraph
3967         if (isEmpty(paraBefore))
3968                 paraBefore.innerHTML = "&nbsp;";
3969
3970         // Check if it's a empty paragraph
3971         if (isEmpty(paraAfter))
3972                 paraAfter.innerHTML = "&nbsp;";
3973
3974         // Create a range around everything
3975         var rng = doc.createRange();
3976
3977         if (!startChop.previousSibling && startChop.parentNode.nodeName.toUpperCase() == blockName) {
3978                 rng.setStartBefore(startChop.parentNode);
3979         } else {
3980                 if (rngBefore.startContainer.nodeName.toUpperCase() == blockName && rngBefore.startOffset == 0)
3981                         rng.setStartBefore(rngBefore.startContainer);
3982                 else
3983                         rng.setStart(rngBefore.startContainer, rngBefore.startOffset);
3984         }
3985
3986         if (!endChop.nextSibling && endChop.parentNode.nodeName.toUpperCase() == blockName)
3987                 rng.setEndAfter(endChop.parentNode);
3988         else
3989                 rng.setEnd(rngAfter.endContainer, rngAfter.endOffset);
3990
3991         // Delete all contents and insert new paragraphs
3992         rng.deleteContents();
3993         rng.insertNode(paraAfter);
3994         rng.insertNode(paraBefore);
3995         // debug("2", paraBefore.innerHTML, paraAfter.innerHTML);
3996
3997         // Normalize
3998         paraAfter.normalize();
3999         paraBefore.normalize();
4000
4001         this.selectNode(paraAfter, true, true);
4002
4003         return true;
4004 };
4005
4006 TinyMCEControl.prototype._handleBackSpace = function(evt_type) {
4007         var doc = this.getDoc();
4008         var sel = this.getSel();
4009         if (sel == null)
4010                 return false;
4011
4012         var rng = sel.getRangeAt(0);
4013         var node = rng.startContainer;
4014         var elm = node.nodeType == 3 ? node.parentNode : node;
4015
4016         if (node == null)
4017                 return;
4018
4019         // Empty node, wrap contents in paragraph
4020         if (elm && elm.nodeName == "") {
4021                 var para = doc.createElement("p");
4022
4023                 while (elm.firstChild)
4024                         para.appendChild(elm.firstChild);
4025
4026                 elm.parentNode.insertBefore(para, elm);
4027                 elm.parentNode.removeChild(elm);
4028
4029                 var rng = rng.cloneRange();
4030                 rng.setStartBefore(node.nextSibling);
4031                 rng.setEndAfter(node.nextSibling);
4032                 rng.extractContents();
4033
4034                 this.selectNode(node.nextSibling, true, true);
4035         }
4036
4037         // Remove empty paragraphs
4038         var para = tinyMCE.getParentBlockElement(node);
4039         if (para != null && para.nodeName.toLowerCase() == 'p' && evt_type == "keypress") {
4040                 var htm = para.innerHTML;
4041                 var block = tinyMCE.getParentBlockElement(node);
4042
4043                 // Empty node, we do the killing!!
4044                 if (htm == "" || htm == "&nbsp;" || block.nodeName.toLowerCase() == "li") {
4045                         var prevElm = para.previousSibling;
4046
4047                         while (prevElm != null && prevElm.nodeType != 1)
4048                                 prevElm = prevElm.previousSibling;
4049
4050                         if (prevElm == null)
4051                                 return false;
4052
4053                         // Get previous elements last text node
4054                         var nodes = tinyMCE.getNodeTree(prevElm, new Array(), 3);
4055                         var lastTextNode = nodes.length == 0 ? null : nodes[nodes.length-1];
4056
4057                         // Select the last text node and move curstor to end
4058                         if (lastTextNode != null)
4059                                 this.selectNode(lastTextNode, true, false, false);
4060
4061                         // Remove the empty paragrapsh
4062                         para.parentNode.removeChild(para);
4063
4064                         //debug("within p element" + para.innerHTML);
4065                         //showHTML(this.getBody().innerHTML);
4066                         return true;
4067                 }
4068         }
4069
4070         // Remove BR elements
4071 /*      while (node != null && (node = node.nextSibling) != null) {
4072                 if (node.nodeName.toLowerCase() == 'br')
4073                         node.parentNode.removeChild(node);
4074                 else if (node.nodeType == 1) // Break at other element
4075                         break;
4076         }*/
4077
4078         //showHTML(this.getBody().innerHTML);
4079
4080         return false;
4081 };
4082
4083 TinyMCEControl.prototype._insertSpace = function() {
4084         return true;
4085 };
4086
4087 TinyMCEControl.prototype.autoResetDesignMode = function() {
4088         // Add fix for tab/style.display none/block problems in Gecko
4089         if (!tinyMCE.isMSIE && tinyMCE.settings['auto_reset_designmode']) {
4090                 var sel = this.getSel();
4091
4092                 // Weird, wheres that cursor selection?
4093                 if (!sel || !sel.rangeCount || sel.rangeCount == 0)
4094                         eval('try { this.getDoc().designMode = "On"; } catch(e) {}');
4095         }
4096 };
4097
4098 TinyMCEControl.prototype.isDirty = function() {
4099         // Is content modified and not in a submit procedure
4100         return this.startContent != tinyMCE.trim(this.getBody().innerHTML) && !tinyMCE.isNotDirty;
4101 };
4102
4103 TinyMCEControl.prototype._mergeElements = function(pa, ch, override) {
4104         ch = ch.cloneNode(true);
4105         var st = tinyMCE.parseStyle(tinyMCE.getAttrib(pa, "style"));
4106         var stc = tinyMCE.parseStyle(tinyMCE.getAttrib(ch, "style"));
4107         var className = tinyMCE.getAttrib(pa, "class");
4108
4109         className += " " + tinyMCE.getAttrib(ch, "class");
4110
4111         if (override) {
4112                 for (var n in st)
4113                         stc[n] = st[n];
4114         } else {
4115                 for (var n in stc)
4116                         st[n] = stc[n];
4117         }
4118
4119         tinyMCE.setAttrib(ch, "style", tinyMCE.serializeStyle(st));
4120         tinyMCE.setAttrib(ch, "class", tinyMCE.trim(className));
4121         pa.parentNode.replaceChild(ch, pa);
4122 };
4123
4124 TinyMCEControl.prototype.execCommand = function(command, user_interface, value) {
4125         var doc = this.getDoc();
4126         var win = this.getWin();
4127         var focusElm = this.getFocusElement();
4128
4129         if (this.lastSafariSelection && !new RegExp('mceStartTyping|mceEndTyping|mceBeginUndoLevel|mceEndUndoLevel|mceAddUndoLevel', 'gi').test(command)) {
4130                 this.moveToBookmark(this.lastSafariSelection);
4131                 tinyMCE.selectedElement = this.lastSafariSelectedElement;
4132         }
4133
4134         // Mozilla issue
4135         if (!tinyMCE.isMSIE && !this.useCSS) {
4136                 doc.execCommand("useCSS", false, true);
4137                 this.useCSS = true;
4138         }
4139
4140         //debug("command: " + command + ", user_interface: " + user_interface + ", value: " + value);
4141         this.contentDocument = doc; // <-- Strange, unless this is applied Mozilla 1.3 breaks
4142
4143         // Call theme execcommand
4144         if (tinyMCE._themeExecCommand(this.editorId, this.getBody(), command, user_interface, value))
4145                 return;
4146
4147         // Fix align on images
4148         if (focusElm && focusElm.nodeName == "IMG") {
4149                 var align = focusElm.getAttribute('align');
4150                 var img = command == "JustifyCenter" ? focusElm.cloneNode(false) : focusElm;
4151
4152                 switch (command) {
4153                         case "JustifyLeft":
4154                                 if (align == 'left')
4155                                         img.removeAttribute('align');
4156                                 else
4157                                         img.setAttribute('align', 'left');
4158
4159                                 // Remove the div
4160                                 var div = focusElm.parentNode;
4161                                 if (div && div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)
4162                                         div.parentNode.replaceChild(img, div);
4163
4164                                 this.selectNode(img);
4165                                 this.repaint();
4166                                 tinyMCE.triggerNodeChange();
4167                                 return;
4168
4169                         case "JustifyCenter":
4170                                 img.removeAttribute('align');
4171
4172                                 // Is centered
4173                                 var div = tinyMCE.getParentElement(focusElm, "div");
4174                                 if (div && div.style.textAlign == "center") {
4175                                         // Remove div
4176                                         if (div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)
4177                                                 div.parentNode.replaceChild(img, div);
4178                                 } else {
4179                                         // Add div
4180                                         var div = this.getDoc().createElement("div");
4181                                         div.style.textAlign = 'center';
4182                                         div.appendChild(img);
4183                                         focusElm.parentNode.replaceChild(div, focusElm);
4184                                 }
4185
4186                                 this.selectNode(img);
4187                                 this.repaint();
4188                                 tinyMCE.triggerNodeChange();
4189                                 return;
4190
4191                         case "JustifyRight":
4192                                 if (align == 'right')
4193                                         img.removeAttribute('align');
4194                                 else
4195                                         img.setAttribute('align', 'right');
4196
4197                                 // Remove the div
4198                                 var div = focusElm.parentNode;
4199                                 if (div && div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)
4200                                         div.parentNode.replaceChild(img, div);
4201
4202                                 this.selectNode(img);
4203                                 this.repaint();
4204                                 tinyMCE.triggerNodeChange();
4205                                 return;
4206                 }
4207         }
4208
4209         if (tinyMCE.settings['force_br_newlines']) {
4210                 var alignValue = "";
4211
4212                 if (doc.selection.type != "Control") {
4213                         switch (command) {
4214                                         case "JustifyLeft":
4215                                                 alignValue = "left";
4216                                                 break;
4217
4218                                         case "JustifyCenter":
4219                                                 alignValue = "center";
4220                                                 break;
4221
4222                                         case "JustifyFull":
4223                                                 alignValue = "justify";
4224                                                 break;
4225
4226                                         case "JustifyRight":
4227                                                 alignValue = "right";
4228                                                 break;
4229                         }
4230
4231                         if (alignValue != "") {
4232                                 var rng = doc.selection.createRange();
4233
4234                                 if ((divElm = tinyMCE.getParentElement(rng.parentElement(), "div")) != null)
4235                                         divElm.setAttribute("align", alignValue);
4236                                 else if (rng.pasteHTML && rng.htmlText.length > 0)
4237                                         rng.pasteHTML('<div align="' + alignValue + '">' + rng.htmlText + "</div>");
4238
4239                                 tinyMCE.triggerNodeChange();
4240                                 return;
4241                         }
4242                 }
4243         }
4244
4245         switch (command) {
4246                 case "mceRepaint":
4247                         this.repaint();
4248                         return true;
4249
4250                 case "mceStoreSelection":
4251                         this.selectionBookmark = this.getBookmark();
4252                         return true;
4253
4254                 case "mceRestoreSelection":
4255                         this.moveToBookmark(this.selectionBookmark);
4256                         return true;
4257
4258                 case "InsertUnorderedList":
4259                 case "InsertOrderedList":
4260                         var tag = (command == "InsertUnorderedList") ? "ul" : "ol";
4261
4262                         if (tinyMCE.isSafari)
4263                                 this.execCommand("mceInsertContent", false, "<" + tag + "><li>&nbsp;</li><" + tag + ">");
4264                         else
4265                                 this.getDoc().execCommand(command, user_interface, value);
4266
4267                         tinyMCE.triggerNodeChange();
4268                         break;
4269
4270                 case "Strikethrough":
4271                         if (tinyMCE.isSafari)
4272                                 this.execCommand("mceInsertContent", false, "<strike>" + this.getSelectedHTML() + "</strike>");
4273                         else
4274                                 this.getDoc().execCommand(command, user_interface, value);
4275
4276                         tinyMCE.triggerNodeChange();
4277                         break;
4278
4279                 case "mceSelectNode":
4280                         this.selectNode(value);
4281                         tinyMCE.triggerNodeChange();
4282                         tinyMCE.selectedNode = value;
4283                         break;
4284
4285                 case "FormatBlock":
4286                         if (value == null || value == "") {
4287                                 var elm = tinyMCE.getParentElement(this.getFocusElement(), "p,div,h1,h2,h3,h4,h5,h6,pre,address");
4288
4289                                 if (elm)
4290                                         this.execCommand("mceRemoveNode", false, elm);
4291                         } else
4292                                 this.getDoc().execCommand("FormatBlock", false, value);
4293
4294                         tinyMCE.triggerNodeChange();
4295
4296                         break;
4297
4298                 case "mceRemoveNode":
4299                         if (!value)
4300                                 value = tinyMCE.getParentElement(this.getFocusElement());
4301
4302                         if (tinyMCE.isMSIE) {
4303                                 value.outerHTML = value.innerHTML;
4304                         } else {
4305                                 var rng = value.ownerDocument.createRange();
4306                                 rng.setStartBefore(value);
4307                                 rng.setEndAfter(value);
4308                                 rng.deleteContents();
4309                                 rng.insertNode(rng.createContextualFragment(value.innerHTML));
4310                         }
4311
4312                         tinyMCE.triggerNodeChange();
4313
4314                         break;
4315
4316                 case "mceSelectNodeDepth":
4317                         var parentNode = this.getFocusElement();
4318                         for (var i=0; parentNode; i++) {
4319                                 if (parentNode.nodeName.toLowerCase() == "body")
4320                                         break;
4321
4322                                 if (parentNode.nodeName.toLowerCase() == "#text") {
4323                                         i--;
4324                                         parentNode = parentNode.parentNode;
4325                                         continue;
4326                                 }
4327
4328                                 if (i == value) {
4329                                         this.selectNode(parentNode, false);
4330                                         tinyMCE.triggerNodeChange();
4331                                         tinyMCE.selectedNode = parentNode;
4332                                         return;
4333                                 }
4334
4335                                 parentNode = parentNode.parentNode;
4336                         }
4337
4338                         break;
4339
4340                 case "SetStyleInfo":
4341                         var rng = this.getRng();
4342                         var sel = this.getSel();
4343                         var scmd = value['command'];
4344                         var sname = value['name'];
4345                         var svalue = value['value'];
4346                         var wrapper = value['wrapper'] ? value['wrapper'] : "span";
4347                         var parentElm = null;
4348
4349                         // Whole element selected check
4350                         if (tinyMCE.isMSIE) {
4351                                 // Control range
4352                                 if (rng.item)
4353                                         parentElm = rng.item(0);
4354                                 else {
4355                                         var pelm = rng.parentElement();
4356                                         var prng = doc.selection.createRange();
4357                                         prng.moveToElementText(pelm);
4358
4359                                         if (rng.htmlText == prng.htmlText || rng.boundingWidth == 0)
4360                                                 parentElm = pelm;
4361                                 }
4362                         } else {
4363                                 var felm = this.getFocusElement();
4364                                 if (sel.isCollapsed || (/td|tr|tbody|table/ig.test(felm.nodeName) && sel.anchorNode == felm.parentNode))
4365                                         parentElm = felm;
4366                         }
4367
4368                         // Whole element selected
4369                         if (parentElm) {
4370                                 if (scmd == "setstyle")
4371                                         eval("parentElm.style." + sname + " = svalue;");
4372
4373                                 if (scmd == "setattrib")
4374                                         tinyMCE.setAttrib(parentElm, sname, svalue);
4375                         } else {
4376                                 doc.execCommand("fontname", false, "#mce_temp_font#");
4377                                 var elementArray = tinyMCE.getElementsByAttributeValue(this.getBody(), "font", "face", "#mce_temp_font#");
4378
4379                                 // Change them all
4380                                 for (var x=0; x<elementArray.length; x++) {
4381                                         elm = elementArray[x];
4382                                         if (elm) {
4383                                                 var spanElm = doc.createElement(wrapper);
4384
4385                                                 if (scmd == "setstyle")
4386                                                         eval("spanElm.style." + sname + " = svalue;");
4387
4388                                                 if (scmd == "setattrib")
4389                                                         tinyMCE.setAttrib(spanElm, sname, svalue);
4390
4391                                                 if (elm.hasChildNodes()) {
4392                                                         for (var i=0; i<elm.childNodes.length; i++)
4393                                                                 spanElm.appendChild(elm.childNodes[i].cloneNode(true));
4394                                                 }
4395
4396                                                 spanElm.setAttribute("mce_new", "true");
4397                                                 elm.parentNode.replaceChild(spanElm, elm);
4398                                         }
4399                                 }
4400                         }
4401
4402                         // Cleaup wrappers
4403                         var nodes = doc.getElementsByTagName(wrapper);
4404                         for (var i=nodes.length-1; i>=0; i--) {
4405                                 var elm = nodes[i];
4406                                 var isNew = tinyMCE.getAttrib(elm, "mce_new") == "true";
4407
4408                                 elm.removeAttribute("mce_new");
4409
4410                                 // Is only child a element
4411                                 if (elm.childNodes && elm.childNodes.length == 1 && elm.childNodes[0].nodeType == 1) {
4412                                         // tinyMCE.debug("merge1" + isNew);
4413                                         this._mergeElements(elm, elm.childNodes[0], isNew);
4414                                         continue;
4415                                 }
4416
4417                                 // Is I the only child
4418                                 if (elm.parentNode.childNodes.length == 1) {
4419                                         // tinyMCE.debug("merge2" + isNew);
4420                                         this._mergeElements(elm.parentNode, elm, false);
4421                                 }
4422                         }
4423
4424                         // Remove empty wrappers
4425                         var nodes = doc.getElementsByTagName(wrapper);
4426                         for (var i=nodes.length-1; i>=0; i--) {
4427                                 var elm = nodes[i];
4428                                 var isEmpty = true;
4429
4430                                 // Check if it has any attribs
4431                                 var tmp = doc.createElement("body");
4432                                 tmp.appendChild(elm.cloneNode(false));
4433
4434                                 // Is empty span, remove it
4435                                 if (new RegExp('<span>|<span style="">', 'gi').test(tmp.innerHTML)) {
4436                                         for (var i=elm.childNodes.length-1; i>=0; i--) {
4437                                                 if (elm.parentNode != null) {
4438                                                         elm.parentNode.insertBefore(elm.childNodes[i].cloneNode(true), elm);
4439                                                         elm.parentNode.removeChild(elm);
4440                                                 }
4441                                         }
4442                                 }
4443                         }
4444
4445                         tinyMCE.triggerNodeChange();
4446
4447                         break;
4448
4449                 case "FontName":
4450                         if (tinyMCE.getParam("convert_fonts_to_styles"))
4451                                 this.execCommand("SetStyleInfo", false, {command : "setstyle", name : "fontFamily", value : value});
4452                         else
4453                                 this.getDoc().execCommand('FontName', false, value);
4454                         break;
4455
4456                 case "FontSize":
4457                         if (tinyMCE.getParam("convert_fonts_to_styles")) {
4458                                 var sizes = new Array('', 8, 10, 12, 14, 18, 24, 36);
4459                                 var size = sizes[value] == '' ? '' : sizes[value] + 'px';
4460
4461                                 this.execCommand("SetStyleInfo", false, {command : "setstyle", name : "fontSize", value : size});
4462                         } else
4463                                 this.getDoc().execCommand('FontSize', false, value);
4464
4465                         break;
4466
4467                 case "forecolor":
4468                         if (tinyMCE.getParam("convert_fonts_to_styles"))
4469                                 this.execCommand("SetStyleInfo", false, {command : "setstyle", name : "color", value : value});
4470                         else {
4471                                 if (tinyMCE.isGecko) {
4472                                         this.getDoc().execCommand("useCSS", false, true);
4473                                         this.getDoc().execCommand('forecolor', false, value);
4474                                         this.getDoc().execCommand("useCSS", false, true);
4475                                 } else
4476                                         this.getDoc().execCommand('forecolor', false, value);
4477                         }
4478                         break;
4479
4480                 case "HiliteColor":
4481                         if (tinyMCE.getParam("convert_fonts_to_styles"))
4482                                 this.execCommand("SetStyleInfo", false, {command : "setstyle", name : "backgroundColor", value : value});
4483                         else {
4484                                 if (tinyMCE.isGecko) {
4485                                         this.getDoc().execCommand("useCSS", false, false);
4486                                         this.getDoc().execCommand('hilitecolor', false, value);
4487                                         this.getDoc().execCommand("useCSS", false, true);
4488                                 } else
4489                                         this.getDoc().execCommand('BackColor', false, value);
4490                         }
4491
4492                         break;
4493
4494                 case "Cut":
4495                 case "Copy":
4496                 case "Paste":
4497                         var cmdFailed = false;
4498
4499                         // Try executing command
4500                         eval('try {this.getDoc().execCommand(command, user_interface, value);} catch (e) {cmdFailed = true;}');
4501
4502                         // Alert error in gecko if command failed
4503                         if (tinyMCE.isGecko && cmdFailed) {
4504                                 // Confirm more info
4505                                 if (confirm(tinyMCE.getLang('lang_clipboard_msg')))
4506                                         window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', 'mceExternal');
4507
4508                                 return;
4509                         } else
4510                                 tinyMCE.triggerNodeChange();
4511                 break;
4512
4513                 case "mceSetContent":
4514                         if (!value)
4515                                 value = "";
4516
4517                         // Call custom cleanup code
4518                         value = tinyMCE._customCleanup(this, "insert_to_editor", value);
4519                         tinyMCE._setHTML(doc, value);
4520                         doc.body.innerHTML = tinyMCE._cleanupHTML(this, doc, tinyMCE.settings, doc.body);
4521                         tinyMCE.handleVisualAid(doc.body, true, this.visualAid, this);
4522                         tinyMCE._setEventsEnabled(doc.body, true);
4523                         return true;
4524
4525                 case "mceLink":
4526                         var selectedText = "";
4527
4528                         if (tinyMCE.isMSIE) {
4529                                 var rng = doc.selection.createRange();
4530                                 selectedText = rng.text;
4531                         } else
4532                                 selectedText = this.getSel().toString();
4533
4534                         if (!tinyMCE.linkElement) {
4535                                 if ((tinyMCE.selectedElement.nodeName.toLowerCase() != "img") && (selectedText.length <= 0))
4536                                         return;
4537                         }
4538
4539                         var href = "", target = "", title = "", onclick = "", action = "insert", style_class = "";
4540
4541                         if (tinyMCE.selectedElement.nodeName.toLowerCase() == "a")
4542                                 tinyMCE.linkElement = tinyMCE.selectedElement;
4543
4544                         // Is anchor not a link
4545                         if (tinyMCE.linkElement != null && tinyMCE.getAttrib(tinyMCE.linkElement, 'href') == "")
4546                                 tinyMCE.linkElement = null;
4547
4548                         if (tinyMCE.linkElement) {
4549                                 href = tinyMCE.getAttrib(tinyMCE.linkElement, 'href');
4550                                 target = tinyMCE.getAttrib(tinyMCE.linkElement, 'target');
4551                                 title = tinyMCE.getAttrib(tinyMCE.linkElement, 'title');
4552                 onclick = tinyMCE.getAttrib(tinyMCE.linkElement, 'onclick');
4553                                 style_class = tinyMCE.getAttrib(tinyMCE.linkElement, 'class');
4554
4555                                 // Try old onclick to if copy/pasted content
4556                                 if (onclick == "")
4557                                         onclick = tinyMCE.getAttrib(tinyMCE.linkElement, 'onclick');
4558
4559                                 onclick = tinyMCE.cleanupEventStr(onclick);
4560
4561                                 // Fix for drag-drop/copy paste bug in Mozilla
4562                                 mceRealHref = tinyMCE.getAttrib(tinyMCE.linkElement, 'mce_real_href');
4563                                 if (mceRealHref != "")
4564                                         href = mceRealHref;
4565
4566                                 href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, tinyMCE.linkElement, true);");
4567                                 action = "update";
4568                         }
4569
4570                         if (this.settings['insertlink_callback']) {
4571                                 var returnVal = eval(this.settings['insertlink_callback'] + "(href, target, title, onclick, action, style_class);");
4572                                 if (returnVal && returnVal['href'])
4573                                         tinyMCE.insertLink(returnVal['href'], returnVal['target'], returnVal['title'], returnVal['onclick'], returnVal['style_class']);
4574                         } else {
4575                                 tinyMCE.openWindow(this.insertLinkTemplate, {href : href, target : target, title : title, onclick : onclick, action : action, className : style_class});
4576                         }
4577                 break;
4578
4579                 case "mceImage":
4580                         var src = "", alt = "", border = "", hspace = "", vspace = "", width = "", height = "", align = "";
4581                         var title = "", onmouseover = "", onmouseout = "", action = "insert";
4582                         var img = tinyMCE.imgElement;
4583
4584                         if (tinyMCE.selectedElement != null && tinyMCE.selectedElement.nodeName.toLowerCase() == "img") {
4585                                 img = tinyMCE.selectedElement;
4586                                 tinyMCE.imgElement = img;
4587                         }
4588
4589                         if (img) {
4590                                 // Is it a internal MCE visual aid image, then skip this one.
4591                                 if (tinyMCE.getAttrib(img, 'name').indexOf('mce_') == 0)
4592                                         return;
4593
4594                                 src = tinyMCE.getAttrib(img, 'src');
4595                                 alt = tinyMCE.getAttrib(img, 'alt');
4596
4597                                 // Try polling out the title
4598                                 if (alt == "")
4599                                         alt = tinyMCE.getAttrib(img, 'title');
4600
4601                                 // Fix width/height attributes if the styles is specified
4602                                 if (tinyMCE.isGecko) {
4603                                         var w = img.style.width;
4604                                         if (w != null && w != "")
4605                                                 img.setAttribute("width", w);
4606
4607                                         var h = img.style.height;
4608                                         if (h != null && h != "")
4609                                                 img.setAttribute("height", h);
4610                                 }
4611
4612                                 border = tinyMCE.getAttrib(img, 'border');
4613                                 hspace = tinyMCE.getAttrib(img, 'hspace');
4614                                 vspace = tinyMCE.getAttrib(img, 'vspace');
4615                                 width = tinyMCE.getAttrib(img, 'width');
4616                                 height = tinyMCE.getAttrib(img, 'height');
4617                                 align = tinyMCE.getAttrib(img, 'align');
4618                 onmouseover = tinyMCE.getAttrib(img, 'onmouseover');
4619                 onmouseout = tinyMCE.getAttrib(img, 'onmouseout');
4620                 title = tinyMCE.getAttrib(img, 'title');
4621
4622                                 // Is realy specified?
4623                                 if (tinyMCE.isMSIE) {
4624                                         width = img.attributes['width'].specified ? width : "";
4625                                         height = img.attributes['height'].specified ? height : "";
4626                                 }
4627
4628                                 onmouseover = tinyMCE.getImageSrc(tinyMCE.cleanupEventStr(onmouseover));
4629                                 onmouseout = tinyMCE.getImageSrc(tinyMCE.cleanupEventStr(onmouseout));
4630
4631                                 // Fix for drag-drop/copy paste bug in Mozilla
4632                                 mceRealSrc = tinyMCE.getAttrib(img, 'mce_real_src');
4633                                 if (mceRealSrc != "")
4634                                         src = mceRealSrc;
4635
4636                                 src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, img, true);");
4637
4638                                 if (onmouseover != "")
4639                                         onmouseover = eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseover, img, true);");
4640
4641                                 if (onmouseout != "")
4642                                         onmouseout = eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseout, img, true);");
4643
4644                                 action = "update";
4645                         }
4646
4647                         if (this.settings['insertimage_callback']) {
4648                                 var returnVal = eval(this.settings['insertimage_callback'] + "(src, alt, border, hspace, vspace, width, height, align, title, onmouseover, onmouseout, action);");
4649                                 if (returnVal && returnVal['src'])
4650                                         tinyMCE.insertImage(returnVal['src'], returnVal['alt'], returnVal['border'], returnVal['hspace'], returnVal['vspace'], returnVal['width'], returnVal['height'], returnVal['align'], returnVal['title'], returnVal['onmouseover'], returnVal['onmouseout']);
4651                         } else
4652                                 tinyMCE.openWindow(this.insertImageTemplate, {src : src, alt : alt, border : border, hspace : hspace, vspace : vspace, width : width, height : height, align : align, title : title, onmouseover : onmouseover, onmouseout : onmouseout, action : action});
4653                 break;
4654
4655                 case "mceCleanup":
4656                         tinyMCE._setHTML(this.contentDocument, this.getBody().innerHTML);
4657                         this.getBody().innerHTML = tinyMCE._cleanupHTML(this, this.contentDocument, this.settings, this.getBody(), this.visualAid);
4658                         tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);
4659                         tinyMCE._setEventsEnabled(this.getBody(), true);
4660                         this.repaint();
4661                         tinyMCE.triggerNodeChange();
4662                 break;
4663
4664                 case "mceReplaceContent":
4665                         var selectedText = "";
4666
4667                         if (tinyMCE.isMSIE) {
4668                                 var rng = doc.selection.createRange();
4669                                 selectedText = rng.text;
4670                         } else
4671                                 selectedText = this.getSel().toString();
4672
4673                         if (selectedText.length > 0) {
4674                                 value = tinyMCE.replaceVar(value, "selection", selectedText);
4675                                 tinyMCE.execCommand('mceInsertContent', false, value);
4676                         }
4677
4678                         tinyMCE.triggerNodeChange();
4679                 break;
4680
4681                 case "mceSetAttribute":
4682                         if (typeof(value) == 'object') {
4683                                 var targetElms = (typeof(value['targets']) == "undefined") ? "p,img,span,div,td,h1,h2,h3,h4,h5,h6,pre,address" : value['targets'];
4684                                 var targetNode = tinyMCE.getParentElement(this.getFocusElement(), targetElms);
4685
4686                                 if (targetNode) {
4687                                         targetNode.setAttribute(value['name'], value['value']);
4688                                         tinyMCE.triggerNodeChange();
4689                                 }
4690                         }
4691                 break;
4692
4693                 case "mceSetCSSClass":
4694                         this.execCommand("SetStyleInfo", false, {command : "setattrib", name : "class", value : value});
4695                 break;
4696
4697                 case "mceInsertRawHTML":
4698                         var key = 'tiny_mce_marker';
4699
4700                         this.execCommand('mceBeginUndoLevel');
4701
4702                         // Insert marker key
4703                         this.execCommand('mceInsertContent', false, key);
4704
4705                         // Store away scroll pos
4706                         var scrollX = this.getDoc().body.scrollLeft + this.getDoc().documentElement.scrollLeft;
4707                         var scrollY = this.getDoc().body.scrollTop + this.getDoc().documentElement.scrollTop;
4708
4709                         // Find marker and replace with RAW HTML
4710                         var html = this.getBody().innerHTML;
4711                         if ((pos = html.indexOf(key)) != -1)
4712                                 this.getBody().innerHTML = html.substring(0, pos) + value + html.substring(pos + key.length);
4713
4714                         // Restore scoll pos
4715                         this.contentWindow.scrollTo(scrollX, scrollY);
4716
4717                         this.execCommand('mceEndUndoLevel');
4718
4719                         break;
4720
4721                 case "mceInsertContent":
4722                         if (!tinyMCE.isMSIE) {
4723                                 var sel = this.getSel();
4724                                 var rng = this.getRng();
4725                                 var isHTML = value.indexOf('<') != -1;
4726
4727                                 if (isHTML) {
4728                                         if (tinyMCE.isSafari) {
4729                                                 var tmpRng = this.getDoc().createRange();
4730
4731                                                 tmpRng.setStart(this.getBody(), 0);
4732                                                 tmpRng.setEnd(this.getBody(), 0);
4733
4734                                                 value = tmpRng.createContextualFragment(value);
4735                                         } else
4736                                                 value = rng.createContextualFragment(value);
4737                                 } else {
4738                                         // Setup text node
4739                                         var el = document.createElement("div");
4740                                         el.innerHTML = value;
4741                                         value = el.firstChild.nodeValue;
4742                                         value = doc.createTextNode(value);
4743                                 }
4744
4745                                 // Insert plain text in Safari
4746                                 if (tinyMCE.isSafari && !isHTML) {
4747                                         this.execCommand('InsertText', false, value.nodeValue);
4748                                         tinyMCE.triggerNodeChange();
4749                                         return true;
4750                                 } else if (tinyMCE.isSafari && isHTML) {
4751                                         rng.deleteContents();
4752                                         rng.insertNode(value);
4753                                         tinyMCE.triggerNodeChange();
4754                                         return true;
4755                                 }
4756
4757                                 rng.deleteContents();
4758
4759                                 // If target node is text do special treatment, (Mozilla 1.3 fix)
4760                                 if (rng.startContainer.nodeType == 3) {
4761                                         var node = rng.startContainer.splitText(rng.startOffset);
4762                                         node.parentNode.insertBefore(value, node); 
4763                                 } else
4764                                         rng.insertNode(value);
4765
4766                                 if (!isHTML) {
4767                                         // Removes weird selection trails
4768                                         sel.selectAllChildren(doc.body);
4769                                         sel.removeAllRanges();
4770
4771                                         // Move cursor to end of content
4772                                         var rng = doc.createRange();
4773
4774                                         rng.selectNode(value);
4775                                         rng.collapse(false);
4776
4777                                         sel.addRange(rng);
4778                                 } else
4779                                         rng.collapse(false);
4780                         } else {
4781                                 var rng = doc.selection.createRange();
4782
4783                                 if (rng.item)
4784                                         rng.item(0).outerHTML = value;
4785                                 else
4786                                         rng.pasteHTML(value);
4787                         }
4788
4789                         tinyMCE.triggerNodeChange();
4790                 break;
4791
4792                 case "mceStartTyping":
4793                         if (tinyMCE.settings['custom_undo_redo'] && this.typingUndoIndex == -1) {
4794                                 this.typingUndoIndex = this.undoIndex;
4795                                 this.execCommand('mceAddUndoLevel');
4796                                 //tinyMCE.debug("mceStartTyping");
4797                         }
4798                         break;
4799
4800                 case "mceEndTyping":
4801                         if (tinyMCE.settings['custom_undo_redo'] && this.typingUndoIndex != -1) {
4802                                 this.execCommand('mceAddUndoLevel');
4803                                 this.typingUndoIndex = -1;
4804                                 //tinyMCE.debug("mceEndTyping");
4805                         }
4806                         break;
4807
4808                 case "mceBeginUndoLevel":
4809                         this.undoRedo = false;
4810                         break;
4811
4812                 case "mceEndUndoLevel":
4813                         this.undoRedo = true;
4814                         this.execCommand('mceAddUndoLevel');
4815                         break;
4816
4817                 case "mceAddUndoLevel":
4818                         if (tinyMCE.settings['custom_undo_redo'] && this.undoRedo) {
4819                                 // tinyMCE.debug("add level");
4820
4821                                 if (this.typingUndoIndex != -1) {
4822                                         this.undoIndex = this.typingUndoIndex;
4823                                         // tinyMCE.debug("Override: " + this.undoIndex);
4824                                 }
4825
4826                                 var newHTML = tinyMCE.trim(this.getBody().innerHTML);
4827                                 if (newHTML != this.undoLevels[this.undoIndex]) {
4828                                         // tinyMCE.debug("[" + newHTML + "," + this.undoLevels[this.undoIndex] + "]");
4829
4830                                         tinyMCE.executeCallback('onchange_callback', '_onchange', 0, this);
4831
4832                                         // Time to compress
4833                                         var customUndoLevels = tinyMCE.settings['custom_undo_redo_levels'];
4834                                         if (customUndoLevels != -1 && this.undoLevels.length > customUndoLevels) {
4835                                                 for (var i=0; i<this.undoLevels.length-1; i++) {
4836                                                         //tinyMCE.debug(this.undoLevels[i] + "=" + this.undoLevels[i+1]);
4837                                                         this.undoLevels[i] = this.undoLevels[i+1];
4838                                                 }
4839
4840                                                 this.undoLevels.length--;
4841                                                 this.undoIndex--;
4842                                         }
4843
4844                                         this.undoIndex++;
4845                                         this.undoLevels[this.undoIndex] = newHTML;
4846                                         this.undoLevels.length = this.undoIndex + 1;
4847
4848                                         // tinyMCE.debug("level added" + this.undoIndex);
4849                                         tinyMCE.triggerNodeChange(false);
4850
4851                                         // tinyMCE.debug(this.undoIndex + "," + (this.undoLevels.length-1));
4852                                 }
4853                         }
4854                         break;
4855
4856                 case "Undo":
4857                         if (tinyMCE.settings['custom_undo_redo']) {
4858                                 tinyMCE.execCommand("mceEndTyping");
4859
4860                                 // Do undo
4861                                 if (this.undoIndex > 0) {
4862                                         this.undoIndex--;
4863                                         this.getBody().innerHTML = this.undoLevels[this.undoIndex];
4864                                         this.repaint();
4865                                 }
4866
4867                                 // tinyMCE.debug("Undo - undo levels:" + this.undoLevels.length + ", undo index: " + this.undoIndex);
4868                                 tinyMCE.triggerNodeChange();
4869                         } else
4870                                 this.getDoc().execCommand(command, user_interface, value);
4871                         break;
4872
4873                 case "Redo":
4874                         if (tinyMCE.settings['custom_undo_redo']) {
4875                                 tinyMCE.execCommand("mceEndTyping");
4876
4877                                 if (this.undoIndex < (this.undoLevels.length-1)) {
4878                                         this.undoIndex++;
4879                                         this.getBody().innerHTML = this.undoLevels[this.undoIndex];
4880                                         this.repaint();
4881                                         // tinyMCE.debug("Redo - undo levels:" + this.undoLevels.length + ", undo index: " + this.undoIndex);
4882                                 }
4883
4884                                 tinyMCE.triggerNodeChange();
4885                         } else
4886                                 this.getDoc().execCommand(command, user_interface, value);
4887                         break;
4888
4889                 case "mceToggleVisualAid":
4890                         this.visualAid = !this.visualAid;
4891                         tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);
4892                         tinyMCE.triggerNodeChange();
4893                         break;
4894
4895                 case "removeformat":
4896                         var text = this.getSelectedText();
4897
4898                         if (tinyMCE.isMSIE) {
4899                                 try {
4900                                         win.focus();
4901                                         var rng = doc.selection.createRange();
4902                                         rng.execCommand("RemoveFormat", false, null);
4903
4904                                         // If all element contents is selected, move selection around element
4905                                         if (rng.text == rng.parentElement().innerText) {
4906                                                 rng.moveToElementText(rng.parentElement());
4907                                                 rng.select();
4908                                         }
4909
4910                                         rng.pasteHTML(rng.text);
4911                                 } catch (e) {
4912                                         // Do nothing
4913                                 }
4914                         } else
4915                                 this.getDoc().execCommand(command, user_interface, value);
4916
4917                         // Remove class
4918                         if (text.length == 0)
4919                                 this.execCommand("mceSetCSSClass", false, "");
4920
4921                         tinyMCE.triggerNodeChange();
4922                         break;
4923
4924                 default:
4925                         this.getDoc().execCommand(command, user_interface, value);
4926                         tinyMCE.triggerNodeChange();
4927         }
4928
4929         // Add undo level after modification
4930         if (command != "mceAddUndoLevel" && command != "Undo" && command != "Redo" && command != "mceStartTyping" && command != "mceEndTyping")
4931                 tinyMCE.execCommand("mceAddUndoLevel");
4932 };
4933
4934 TinyMCEControl.prototype.queryCommandValue = function(command) {
4935         return this.getDoc().queryCommandValue(command);
4936 };
4937
4938 TinyMCEControl.prototype.queryCommandState = function(command) {
4939         return this.getDoc().queryCommandState(command);
4940 };
4941
4942 TinyMCEControl.prototype.onAdd = function(replace_element, form_element_name, target_document) {
4943         var targetDoc = target_document ? target_document : document;
4944
4945         this.targetDoc = targetDoc;
4946
4947         tinyMCE.themeURL = tinyMCE.baseURL + "/themes/" + this.settings['theme'];
4948         this.settings['themeurl'] = tinyMCE.themeURL;
4949
4950         if (!replace_element) {
4951                 alert("Error: Could not find the target element.");
4952                 return false;
4953         }
4954
4955         var templateFunction = tinyMCE._getThemeFunction('_getInsertLinkTemplate');
4956         if (eval("typeof(" + templateFunction + ")") != 'undefined')
4957                 this.insertLinkTemplate = eval(templateFunction + '(this.settings);');
4958
4959         var templateFunction = tinyMCE._getThemeFunction('_getInsertImageTemplate');
4960         if (eval("typeof(" + templateFunction + ")") != 'undefined')
4961                 this.insertImageTemplate = eval(templateFunction + '(this.settings);');
4962
4963         var templateFunction = tinyMCE._getThemeFunction('_getEditorTemplate');
4964         if (eval("typeof(" + templateFunction + ")") == 'undefined') {
4965                 alert("Error: Could not find the template function: " + templateFunction);
4966                 return false;
4967         }
4968
4969         var editorTemplate = eval(templateFunction + '(this.settings, this.editorId);');
4970
4971         var deltaWidth = editorTemplate['delta_width'] ? editorTemplate['delta_width'] : 0;
4972         var deltaHeight = editorTemplate['delta_height'] ? editorTemplate['delta_height'] : 0;
4973         var html = '<span id="' + this.editorId + '_parent">' + editorTemplate['html'];
4974
4975         var templateFunction = tinyMCE._getThemeFunction('_handleNodeChange', true);
4976         if (eval("typeof(" + templateFunction + ")") != 'undefined')
4977                 this.settings['handleNodeChangeCallback'] = templateFunction;
4978
4979         html = tinyMCE.replaceVar(html, "editor_id", this.editorId);
4980         this.settings['default_document'] = tinyMCE.baseURL + "/blank.htm";
4981
4982         this.settings['old_width'] = this.settings['width'];
4983         this.settings['old_height'] = this.settings['height'];
4984
4985         // Set default width, height
4986         if (this.settings['width'] == -1)
4987                 this.settings['width'] = replace_element.offsetWidth;
4988
4989         if (this.settings['height'] == -1)
4990                 this.settings['height'] = replace_element.offsetHeight;
4991
4992         // Try the style width
4993         if (this.settings['width'] == 0)
4994                 this.settings['width'] = replace_element.style.width;
4995
4996         // Try the style height
4997         if (this.settings['height'] == 0)
4998                 this.settings['height'] = replace_element.style.height; 
4999
5000         // If no width/height then default to 320x240, better than nothing
5001         if (this.settings['width'] == 0)
5002                 this.settings['width'] = 320;
5003
5004         if (this.settings['height'] == 0)
5005                 this.settings['height'] = 240;
5006
5007         this.settings['area_width'] = parseInt(this.settings['width']);
5008         this.settings['area_height'] = parseInt(this.settings['height']);
5009         this.settings['area_width'] += deltaWidth;
5010         this.settings['area_height'] += deltaHeight;
5011
5012         // Special % handling
5013         if (("" + this.settings['width']).indexOf('%') != -1)
5014                 this.settings['area_width'] = "100%";
5015
5016         if (("" + this.settings['height']).indexOf('%') != -1)
5017                 this.settings['area_height'] = "100%";
5018
5019         if (("" + replace_element.style.width).indexOf('%') != -1) {
5020                 this.settings['width'] = replace_element.style.width;
5021                 this.settings['area_width'] = "100%";
5022         }
5023
5024         if (("" + replace_element.style.height).indexOf('%') != -1) {
5025                 this.settings['height'] = replace_element.style.height;
5026                 this.settings['area_height'] = "100%";
5027         }
5028
5029         html = tinyMCE.applyTemplate(html);
5030
5031         this.settings['width'] = this.settings['old_width'];
5032         this.settings['height'] = this.settings['old_height'];
5033
5034         this.visualAid = this.settings['visual'];
5035         this.formTargetElementId = form_element_name;
5036
5037         // Get replace_element contents
5038         if (replace_element.nodeName == "TEXTAREA" || replace_element.nodeName == "INPUT")
5039                 this.startContent = replace_element.value;
5040         else
5041                 this.startContent = replace_element.innerHTML;
5042
5043         // If not text area
5044         if (replace_element.nodeName.toLowerCase() != "textarea") {
5045                 this.oldTargetElement = replace_element.cloneNode(true);
5046
5047                 // Debug mode
5048                 if (tinyMCE.settings['debug'])
5049                         html += '<textarea wrap="off" id="' + form_element_name + '" name="' + form_element_name + '" cols="100" rows="15"></textarea>';
5050                 else
5051                         html += '<input type="hidden" type="text" id="' + form_element_name + '" name="' + form_element_name + '" />';
5052
5053                 html += '</span>';
5054
5055                 // Output HTML and set editable
5056                 if (!tinyMCE.isMSIE) {
5057                         var rng = replace_element.ownerDocument.createRange();
5058                         rng.setStartBefore(replace_element);
5059
5060                         var fragment = rng.createContextualFragment(html);
5061                         replace_element.parentNode.replaceChild(fragment, replace_element);
5062                 } else
5063                         replace_element.outerHTML = html;
5064         } else {
5065                 html += '</span>';
5066
5067                 // Just hide the textarea element
5068                 this.oldTargetElement = replace_element;
5069
5070                 if (!tinyMCE.settings['debug'])
5071                         this.oldTargetElement.style.display = "none";
5072
5073                 // Output HTML and set editable
5074                 if (!tinyMCE.isMSIE) {
5075                         var rng = replace_element.ownerDocument.createRange();
5076                         rng.setStartBefore(replace_element);
5077
5078                         var fragment = rng.createContextualFragment(html);
5079                         replace_element.parentNode.insertBefore(fragment, replace_element);
5080                 } else
5081                         replace_element.insertAdjacentHTML("beforeBegin", html);
5082         }
5083
5084         // Setup iframe
5085         var dynamicIFrame = false;
5086         var tElm = targetDoc.getElementById(this.editorId);
5087
5088         if (!tinyMCE.isMSIE) {
5089                 if (tElm && tElm.nodeName.toLowerCase() == "span") {
5090                         tElm = tinyMCE._createIFrame(tElm);
5091                         dynamicIFrame = true;
5092                 }
5093
5094                 this.targetElement = tElm;
5095                 this.iframeElement = tElm;
5096                 this.contentDocument = tElm.contentDocument;
5097                 this.contentWindow = tElm.contentWindow;
5098
5099                 //this.getDoc().designMode = "on";
5100         } else {
5101                 if (tElm && tElm.nodeName.toLowerCase() == "span")
5102                         tElm = tinyMCE._createIFrame(tElm);
5103                 else
5104                         tElm = targetDoc.frames[this.editorId];
5105
5106                 this.targetElement = tElm;
5107                 this.iframeElement = targetDoc.getElementById(this.editorId);
5108                 this.contentDocument = tElm.window.document;
5109                 this.contentWindow = tElm.window;
5110                 this.getDoc().designMode = "on";
5111         }
5112
5113         // Setup base HTML
5114         var doc = this.contentDocument;
5115         if (dynamicIFrame) {
5116         var html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><base href="' + tinyMCE.settings['base_href'] + '" /><title>blank_page</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body class="mceContentBody"></body></html>';
5117
5118                 try {
5119                         this.getDoc().designMode = "on";
5120                         doc.open();
5121                         doc.write(html);
5122                         doc.close();
5123                 } catch (e) {
5124                         // Failed Mozilla 1.3
5125                         this.getDoc().location.href = tinyMCE.baseURL + "/blank.htm";
5126                 }
5127         }
5128
5129         // This timeout is needed in MSIE 5.5 for some odd reason
5130         // it seems that the document.frames isn't initialized yet?
5131         if (tinyMCE.isMSIE)
5132                 window.setTimeout("TinyMCE.prototype.addEventHandlers('" + this.editorId + "');", 1);
5133
5134         tinyMCE.setupContent(this.editorId, true);
5135
5136         return true;
5137 };
5138
5139 TinyMCEControl.prototype.getFocusElement = function() {
5140         if (tinyMCE.isMSIE) {
5141                 var doc = this.getDoc();
5142                 var rng = doc.selection.createRange();
5143
5144                 if (rng.collapse)
5145                         rng.collapse(true);
5146
5147                 var elm = rng.item ? rng.item(0) : rng.parentElement();
5148         } else {
5149                 var sel = this.getSel();
5150                 var rng = this.getRng();
5151                 var elm = rng.commonAncestorContainer;
5152                 //var elm = (sel && sel.anchorNode) ? sel.anchorNode : null;
5153
5154                 // Handle selection a image or other control like element such as anchors
5155                 if (!rng.collapsed) {
5156                         // Is selection small
5157                         if (rng.startContainer == rng.endContainer) {
5158                                 if (rng.startOffset - rng.endOffset < 2) {
5159                                         if (rng.startContainer.hasChildNodes())
5160                                                 elm = rng.startContainer.childNodes[rng.startOffset];
5161                                 }
5162                         }
5163                 }
5164
5165                 // Get the element parent of the node
5166                 elm = tinyMCE.getParentElement(elm);
5167
5168                 //if (tinyMCE.selectedElement != null && tinyMCE.selectedElement.nodeName.toLowerCase() == "img")
5169                 //      elm = tinyMCE.selectedElement;
5170         }
5171
5172         return elm;
5173 };
5174
5175 // Global instances
5176 var tinyMCE = new TinyMCE();
5177 var tinyMCELang = new Array();