2 var whiteSpaceRe = /^\s*|\s*$/g,
3 undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
10 releaseDate : '2011-04-07',
13 var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v;
15 t.isOpera = win.opera && opera.buildNumber;
17 t.isWebKit = /WebKit/.test(ua);
19 t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);
21 t.isIE6 = t.isIE && /MSIE [56]/.test(ua);
23 t.isGecko = !t.isWebKit && /Gecko/.test(ua);
25 t.isMac = ua.indexOf('Mac') != -1;
27 t.isAir = /adobeair/i.test(ua);
29 t.isIDevice = /(iPad|iPhone)/.test(ua);
31 // TinyMCE .NET webcontrol might be setting the values for TinyMCE
32 if (win.tinyMCEPreInit) {
33 t.suffix = tinyMCEPreInit.suffix;
34 t.baseURL = tinyMCEPreInit.base;
35 t.query = tinyMCEPreInit.query;
39 // Get suffix and base
42 // If base element found, add that infront of baseURL
43 nl = d.getElementsByTagName('base');
44 for (i=0; i<nl.length; i++) {
46 // Host only value like http://site.com or http://site.com:8008
47 if (/^https?:\/\/[^\/]+$/.test(v))
50 base = v ? v.match(/.*\//)[0] : ''; // Get only directory
55 if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) {
56 if (/_(src|dev)\.js/g.test(n.src))
59 if ((p = n.src.indexOf('?')) != -1)
60 t.query = n.src.substring(p + 1);
62 t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));
64 // If path to script is relative and a base href was found add that one infront
65 // the src property will always be an absolute one on non IE browsers and IE 8
66 // so this logic will basically only be executed on older IE versions
67 if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0)
68 t.baseURL = base + t.baseURL;
77 nl = d.getElementsByTagName('script');
78 for (i=0; i<nl.length; i++) {
84 n = d.getElementsByTagName('head')[0];
86 nl = n.getElementsByTagName('script');
87 for (i=0; i<nl.length; i++) {
98 return o !== undefined;
100 if (t == 'array' && (o.hasOwnProperty && o instanceof Array))
103 return typeof(o) == t;
106 makeMap : function(items, delim, map) {
110 delim = delim || ',';
112 if (typeof(items) == "string")
113 items = items.split(delim);
124 each : function(o, cb, s) {
132 if (o.length !== undefined) {
133 // Indexed arrays, needed for Safari
134 for (n=0, l = o.length; n < l; n++) {
135 if (cb.call(s, o[n], n, o) === false)
141 if (o.hasOwnProperty(n)) {
142 if (cb.call(s, o[n], n, o) === false)
153 return (s ? '' + s : '').replace(whiteSpaceRe, '');
156 create : function(s, p, root) {
157 var t = this, sp, ns, cn, scn, c, de = 0;
159 // Parse : <prefix> <class>:<super class>
160 s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
161 cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
163 // Create namespace for new class
164 ns = t.createNS(s[3].replace(/\.\w+$/, ''), root);
166 // Class already exists
170 // Make pure static class
171 if (s[2] == 'static') {
175 this.onCreate(s[2], s[3], ns[cn]);
180 // Create default constructor
182 p[cn] = function() {};
186 // Add constructor and methods
188 t.extend(ns[cn].prototype, p);
192 sp = t.resolve(s[5]).prototype;
193 scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
195 // Extend constructor
198 // Add passthrough constructor
199 ns[cn] = function() {
200 return sp[scn].apply(this, arguments);
203 // Add inherit constructor
204 ns[cn] = function() {
205 this.parent = sp[scn];
206 return c.apply(this, arguments);
209 ns[cn].prototype[cn] = ns[cn];
212 t.each(sp, function(f, n) {
213 ns[cn].prototype[n] = sp[n];
216 // Add overridden methods
217 t.each(p, function(f, n) {
218 // Extend methods if needed
220 ns[cn].prototype[n] = function() {
222 return f.apply(this, arguments);
226 ns[cn].prototype[n] = f;
231 // Add static methods
232 t.each(p['static'], function(f, n) {
237 this.onCreate(s[2], s[3], ns[cn].prototype);
240 walk : function(o, f, n, s) {
247 tinymce.each(o, function(o, i) {
248 if (f.call(s, o, i, n) === false)
251 tinymce.walk(o, f, n, s);
256 createNS : function(n, o) {
262 for (i=0; i<n.length; i++) {
274 resolve : function(n, o) {
280 for (i = 0, l = n.length; i < l; i++) {
290 addUnload : function(f, s) {
293 f = {func : f, scope : s || this};
297 var li = t.unloads, o, n;
300 // Call unload handlers
305 o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
308 // Detach unload function
309 if (win.detachEvent) {
310 win.detachEvent('onbeforeunload', fakeUnload);
311 win.detachEvent('onunload', unload);
312 } else if (win.removeEventListener)
313 win.removeEventListener('unload', unload, false);
315 // Destroy references
316 t.unloads = o = li = w = unload = 0;
318 // Run garbarge collector on IE
319 if (win.CollectGarbage)
324 function fakeUnload() {
327 // Is there things still loading, then do some magic
328 if (d.readyState == 'interactive') {
330 // Prevent memory leak
331 d.detachEvent('onstop', stop);
333 // Call unload handler
340 // Fire unload when the currently loading page is stopped
342 d.attachEvent('onstop', stop);
344 // Remove onstop listener after a while to prevent the unload function
345 // to execute if the user presses cancel in an onbeforeunload
346 // confirm dialog and then presses the browser stop button
347 win.setTimeout(function() {
349 d.detachEvent('onstop', stop);
354 // Attach unload handler
355 if (win.attachEvent) {
356 win.attachEvent('onunload', unload);
357 win.attachEvent('onbeforeunload', fakeUnload);
358 } else if (win.addEventListener)
359 win.addEventListener('unload', unload, false);
361 // Setup initial unload handler array
369 removeUnload : function(f) {
370 var u = this.unloads, r = null;
372 tinymce.each(u, function(o, i) {
373 if (o && o.func == f) {
383 explode : function(s, d) {
384 return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;
387 _addVer : function(u) {
393 v = (u.indexOf('?') == -1 ? '?' : '&') + this.query;
395 if (u.indexOf('#') == -1)
398 return u.replace('#', v + '#');
401 // Fix function for IE 9 where regexps isn't working correctly
402 // Todo: remove me once MS fixes the bug
403 _replace : function(find, replace, str) {
404 // On IE9 we have to fake $x replacement
405 if (isRegExpBroken) {
406 return str.replace(find, function() {
407 var val = replace, args = arguments, i;
409 for (i = 0; i < args.length - 2; i++) {
410 if (args[i] === undefined) {
411 val = val.replace(new RegExp('\\$' + i, 'g'), '');
413 val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);
421 return str.replace(find, replace);
426 // Initialize the API
429 // Expose tinymce namespace to the global namespace (window)
430 win.tinymce = win.tinyMCE = tinymce;
432 // Describe the different namespaces
436 (function($, tinymce) {
437 var is = tinymce.is, attrRegExp = /^(href|src|style)$/i, undefined;
439 // jQuery is undefined
441 return alert("Load jQuery first!");
443 // Stick jQuery into the tinymce namespace
448 patchEditor : function(editor) {
451 // Adapt the css function to make sure that the data-mce-style
452 // attribute gets updated with the new style information
453 function css(name, value) {
456 // Remove data-mce-style when set operation occurs
458 self.removeAttr('data-mce-style');
460 return fn.css.apply(self, arguments);
463 // Apapt the attr function to make sure that it uses the data-mce- prefixed variants
464 function attr(name, value) {
467 // Update/retrive data-mce- attribute variants
468 if (attrRegExp.test(name)) {
469 if (value !== undefined) {
470 // Use TinyMCE behavior when setting the specifc attributes
471 self.each(function(i, node) {
472 editor.dom.setAttrib(node, name, value);
477 return self.attr('data-mce-' + name);
481 return fn.attr.apply(self, arguments);
484 function htmlPatchFunc(func) {
485 // Returns a modified function that processes
486 // the HTML before executing the action this makes sure
487 // that href/src etc gets moved into the data-mce- variants
488 return function(content) {
490 content = editor.dom.processHTML(content);
492 return func.call(this, content);
496 // Patch various jQuery functions to handle tinymce specific attribute and content behavior
497 // we don't patch the jQuery.fn directly since it will most likely break compatibility
498 // with other jQuery logic on the page. Only instances created by TinyMCE should be patched.
500 // Patch some functions, only patch the object once
501 if (jq.css !== css) {
502 // Patch css/attr to use the data-mce- prefixed attribute variants
506 // Patch HTML functions to use the DOMUtils.processHTML filter logic
507 jq.html = htmlPatchFunc(fn.html);
508 jq.append = htmlPatchFunc(fn.append);
509 jq.prepend = htmlPatchFunc(fn.prepend);
510 jq.after = htmlPatchFunc(fn.after);
511 jq.before = htmlPatchFunc(fn.before);
512 jq.replaceWith = htmlPatchFunc(fn.replaceWith);
515 // Each pushed jQuery instance needs to be patched
516 // as well for example when traversing the DOM
517 jq.pushStack = function() {
518 return patch(fn.pushStack.apply(this, arguments));
525 // Add a $ function on each editor instance this one is scoped for the editor document object
526 // this way you can do chaining like this tinymce.get(0).$('p').append('text').css('color', 'red');
527 editor.$ = function(selector, scope) {
528 var doc = editor.getDoc();
530 return patch($(selector || doc, doc || scope));
535 // Patch in core NS functions
536 tinymce.extend = $.extend;
537 tinymce.extend(tinymce, {
539 grep : function(a, f) {return $.grep(a, f || function(){return 1;});},
540 inArray : function(a, v) {return $.inArray(v, a || []);}
542 /* Didn't iterate stylesheets
543 each : function(o, cb, s) {
549 $.each(o, function(nr, el){
550 if (cb.call(s, el, nr, o) === false) {
560 // Patch in functions in various clases
561 // Add a "#ifndefjquery" statement around each core API function you add below
563 'tinymce.dom.DOMUtils' : {
565 addClass : function(e, c) {
566 if (is(e, 'array') && is(e[0], 'string'))
568 return (e && $(is(e, 'string') ? '#' + e : e)
570 .attr('class')) || false;
573 hasClass : function(n, c) {
574 return $(is(n, 'string') ? '#' + n : n).hasClass(c);
577 removeClass : function(e, c) {
583 $(is(e, 'string') ? '#' + e : e)
586 r.push(this.className);
589 return r.length == 1 ? r[0] : r;
593 select : function(pattern, scope) {
596 return $.find(pattern, t.get(scope) || t.get(t.settings.root_element) || t.doc, []);
599 is : function(n, patt) {
600 return $(this.get(n)).is(patt);
605 if (is(e, 'array') && is(e[0], 'string'))
608 $(is(e, 'string') ? '#' + e : e).css('display', 'block');
612 if (is(e, 'array') && is(e[0], 'string'))
615 $(is(e, 'string') ? '#' + e : e).css('display', 'none');
618 isHidden : function(e) {
619 return $(is(e, 'string') ? '#' + e : e).is(':hidden');
622 insertAfter : function(n, e) {
623 return $(is(e, 'string') ? '#' + e : e).after(n);
626 replace : function(o, n, k) {
627 n = $(is(n, 'string') ? '#' + n : n);
630 n.children().appendTo(o);
635 setStyle : function(n, na, v) {
636 if (is(n, 'array') && is(n[0], 'string'))
639 $(is(n, 'string') ? '#' + n : n).css(na, v);
642 getStyle : function(n, na, c) {
643 return $(is(n, 'string') ? '#' + n : n).css(na);
646 setStyles : function(e, o) {
647 if (is(e, 'array') && is(e[0], 'string'))
649 $(is(e, 'string') ? '#' + e : e).css(o);
652 setAttrib : function(e, n, v) {
653 var t = this, s = t.settings;
655 if (is(e, 'array') && is(e[0], 'string'))
658 e = $(is(e, 'string') ? '#' + e : e);
662 e.each(function(i, v){
664 $(v).attr('data-mce-style', v);
678 e.each(function(i, v){
681 v = s.url_converter.call(s.url_converter_scope || t, v, n, v);
683 t.setAttrib(v, 'data-mce-' + n, v);
690 if (v !== null && v.length !== 0)
696 setAttribs : function(e, o) {
699 $.each(o, function(n, v){
707 'tinymce.dom.Event' : {
708 add : function (o, n, f, s) {
712 e.target = e.target || this;
713 f.call(s || this, e);
716 if (is(o, 'array') && is(o[0], 'string'))
718 o = $(is(o, 'string') ? '#' + o : o);
729 lo = this._jqLookup || (this._jqLookup = []);
730 lo.push({func : f, cfunc : cb});
735 remove : function(o, n, f) {
737 $(this._jqLookup).each(function() {
742 if (is(o, 'array') && is(o[0], 'string'))
745 $(is(o, 'string') ? '#' + o : o).unbind(n,f);
753 // Patch functions after a class is created
754 tinymce.onCreate = function(ty, c, p) {
755 tinymce.extend(p, patches[c]);
757 })(window.jQuery, tinymce);
761 tinymce.create('tinymce.util.Dispatcher', {
765 Dispatcher : function(s) {
766 this.scope = s || this;
770 add : function(cb, s) {
771 this.listeners.push({cb : cb, scope : s || this.scope});
776 addToTop : function(cb, s) {
777 this.listeners.unshift({cb : cb, scope : s || this.scope});
782 remove : function(cb) {
783 var l = this.listeners, o = null;
785 tinymce.each(l, function(c, i) {
796 dispatch : function() {
797 var s, a = arguments, i, li = this.listeners, c;
799 // Needs to be a real loop since the listener count might change while looping
800 // And this is also more efficient
801 for (i = 0; i<li.length; i++) {
803 s = c.cb.apply(c.scope, a);
815 var each = tinymce.each;
817 tinymce.create('tinymce.util.URI', {
818 URI : function(u, s) {
819 var t = this, o, a, b;
825 s = t.settings = s || {};
827 // Strange app protocol or local anchor
828 if (/^(mailto|tel|news|javascript|about|data):/i.test(u) || /^\s*#/.test(u)) {
833 // Absolute path with no host, fake host and protocol
834 if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)
835 u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;
837 // Relative path http:// or protocol relative //path
838 if (!/^\w*:?\/\//.test(u))
839 u = (s.base_uri.protocol || 'http') + '://mce_host' + t.toAbsPath(s.base_uri.path, u);
841 // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
842 u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
843 u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
844 each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
847 // Zope 3 workaround, they use @@something
849 s = s.replace(/\(mce_at\)/g, '@@');
854 if (b = s.base_uri) {
856 t.protocol = b.protocol;
859 t.userInfo = b.userInfo;
861 if (!t.port && t.host == 'mce_host')
864 if (!t.host || t.host == 'mce_host')
870 //t.path = t.path || '/';
873 setPath : function(p) {
876 p = /^(.*?)\/?(\w+)?$/.exec(p);
888 toRelative : function(u) {
894 u = new tinymce.util.URI(u, {base_uri : t});
896 // Not on same domain/port or protocol
897 if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
900 o = t.toRelPath(t.path, u.path);
913 toAbsolute : function(u, nh) {
914 var u = new tinymce.util.URI(u, {base_uri : this});
916 return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
919 toRelPath : function(base, path) {
920 var items, bp = 0, out = '', i, l;
923 base = base.substring(0, base.lastIndexOf('/'));
924 base = base.split('/');
925 items = path.split('/');
927 if (base.length >= items.length) {
928 for (i = 0, l = base.length; i < l; i++) {
929 if (i >= items.length || base[i] != items[i]) {
936 if (base.length < items.length) {
937 for (i = 0, l = items.length; i < l; i++) {
938 if (i >= base.length || base[i] != items[i]) {
948 for (i = 0, l = base.length - (bp - 1); i < l; i++)
951 for (i = bp - 1, l = items.length; i < l; i++) {
953 out += "/" + items[i];
961 toAbsPath : function(base, path) {
962 var i, nb = 0, o = [], tr, outPath;
965 tr = /\/$/.test(path) ? '/' : '';
966 base = base.split('/');
967 path = path.split('/');
969 // Remove empty chunks
970 each(base, function(k) {
977 // Merge relURLParts chunks
978 for (i = path.length - 1, o = []; i >= 0; i--) {
980 if (path[i].length == 0 || path[i] == ".")
984 if (path[i] == '..') {
998 i = base.length - nb;
1002 outPath = o.reverse().join('/');
1004 outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
1006 // Add front / if it's needed
1007 if (outPath.indexOf('/') !== 0)
1008 outPath = '/' + outPath;
1010 // Add traling / if it's needed
1011 if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)
1017 getURI : function(nh) {
1021 if (!t.source || nh) {
1026 s += t.protocol + '://';
1029 s += t.userInfo + '@';
1045 s += '#' + t.anchor;
1056 var each = tinymce.each;
1058 tinymce.create('static tinymce.util.Cookie', {
1059 getHash : function(n) {
1060 var v = this.get(n), h;
1063 each(v.split('&'), function(v) {
1066 h[unescape(v[0])] = unescape(v[1]);
1073 setHash : function(n, v, e, p, d, s) {
1076 each(v, function(v, k) {
1077 o += (!o ? '' : '&') + escape(k) + '=' + escape(v);
1080 this.set(n, o, e, p, d, s);
1084 var c = document.cookie, e, p = n + "=", b;
1090 b = c.indexOf("; " + p);
1100 e = c.indexOf(";", b);
1105 return unescape(c.substring(b + p.length, e));
1108 set : function(n, v, e, p, d, s) {
1109 document.cookie = n + "=" + escape(v) +
1110 ((e) ? "; expires=" + e.toGMTString() : "") +
1111 ((p) ? "; path=" + escape(p) : "") +
1112 ((d) ? "; domain=" + d : "") +
1113 ((s) ? "; secure" : "");
1116 remove : function(n, p) {
1119 d.setTime(d.getTime() - 1000);
1121 this.set(n, '', d, p, d);
1127 function serialize(o, quote) {
1130 quote = quote || '"';
1137 if (t == 'string') {
1138 v = '\bb\tt\nn\ff\rr\""\'\'\\\\';
1140 return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {
1141 // Make sure single quotes never get encoded inside double quotes for JSON compatibility
1142 if (quote === '"' && a === "'")
1148 return '\\' + v.charAt(i + 1);
1150 a = b.charCodeAt().toString(16);
1152 return '\\u' + '0000'.substring(a.length) + a;
1156 if (t == 'object') {
1157 if (o.hasOwnProperty && o instanceof Array) {
1158 for (i=0, v = '['; i<o.length; i++)
1159 v += (i > 0 ? ',' : '') + serialize(o[i], quote);
1167 v += typeof o[i] != 'function' ? (v.length > 1 ? ',' + quote : quote) + i + quote +':' + serialize(o[i], quote) : '';
1175 tinymce.util.JSON = {
1176 serialize: serialize,
1178 parse: function(s) {
1180 return eval('(' + s + ')');
1188 tinymce.create('static tinymce.util.XHR', {
1189 send : function(o) {
1190 var x, t, w = window, c = 0;
1193 o.scope = o.scope || this;
1194 o.success_scope = o.success_scope || o.scope;
1195 o.error_scope = o.error_scope || o.scope;
1196 o.async = o.async === false ? false : true;
1197 o.data = o.data || '';
1203 x = new ActiveXObject(s);
1210 x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP');
1213 if (x.overrideMimeType)
1214 x.overrideMimeType(o.content_type);
1216 x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async);
1219 x.setRequestHeader('Content-Type', o.content_type);
1221 x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
1226 if (!o.async || x.readyState == 4 || c++ > 10000) {
1227 if (o.success && c < 10000 && x.status == 200)
1228 o.success.call(o.success_scope, '' + x.responseText, x, o);
1230 o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);
1234 w.setTimeout(ready, 10);
1237 // Syncronous request
1241 // Wait for response, onReadyStateChange can not be used since it leaks memory in IE
1242 t = w.setTimeout(ready, 10);
1248 var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR;
1250 tinymce.create('tinymce.util.JSONRequest', {
1251 JSONRequest : function(s) {
1252 this.settings = extend({
1257 send : function(o) {
1258 var ecb = o.error, scb = o.success;
1260 o = extend(this.settings, o);
1262 o.success = function(c, x) {
1265 if (typeof(c) == 'undefined') {
1267 error : 'JSON Parse error.'
1272 ecb.call(o.error_scope || o.scope, c.error, x);
1274 scb.call(o.success_scope || o.scope, c.result);
1277 o.error = function(ty, x) {
1279 ecb.call(o.error_scope || o.scope, ty, x);
1282 o.data = JSON.serialize({
1283 id : o.id || 'c' + (this.count++),
1288 // JSON content type for Ruby on rails. Bug: #1883287
1289 o.content_type = 'application/json';
1295 sendRPC : function(o) {
1296 return new tinymce.util.JSONRequest().send(o);
1301 (function(tinymce) {
1302 var namedEntities, baseEntities, reverseEntities,
1303 attrsCharsRegExp = /[&\"\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1304 textCharsRegExp = /[<>&\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1305 rawCharsRegExp = /[<>&\"\']/g,
1306 entityRegExp = /&(#)?([\w]+);/g,
1308 128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020",
1309 135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152",
1310 142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022",
1311 150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A",
1312 156 : "\u0153", 158 : "\u017E", 159 : "\u0178"
1324 // Reverse lookup table for raw entities
1333 // Decodes text by using the browser
1334 function nativeDecode(text) {
1337 elm = document.createElement("div");
1338 elm.innerHTML = text;
1340 return elm.textContent || elm.innerText || text;
1343 // Build a two way lookup table for the entities
1344 function buildEntitiesLookup(items, radix) {
1345 var i, chr, entity, lookup = {};
1348 items = items.split(',');
1349 radix = radix || 10;
1351 // Build entities lookup table
1352 for (i = 0; i < items.length; i += 2) {
1353 chr = String.fromCharCode(parseInt(items[i], radix));
1355 // Only add non base entities
1356 if (!baseEntities[chr]) {
1357 entity = '&' + items[i + 1] + ';';
1358 lookup[chr] = entity;
1359 lookup[entity] = chr;
1367 // Unpack entities lookup where the numbers are in radix 32 to reduce the size
1368 namedEntities = buildEntitiesLookup(
1369 '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +
1370 '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +
1371 '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +
1372 '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +
1373 '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +
1374 '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +
1375 '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +
1376 '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +
1377 '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +
1378 '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +
1379 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +
1380 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +
1381 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +
1382 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +
1383 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +
1384 '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +
1385 '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +
1386 '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +
1387 '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +
1388 '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +
1389 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +
1390 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
1391 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
1392 '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
1393 '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro'
1396 tinymce.html = tinymce.html || {};
1398 tinymce.html.Entities = {
1399 encodeRaw : function(text, attr) {
1400 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1401 return baseEntities[chr] || chr;
1405 encodeAllRaw : function(text) {
1406 return ('' + text).replace(rawCharsRegExp, function(chr) {
1407 return baseEntities[chr] || chr;
1411 encodeNumeric : function(text, attr) {
1412 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1413 // Multi byte sequence convert it to a single entity
1415 return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';';
1417 return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
1421 encodeNamed : function(text, attr, entities) {
1422 entities = entities || namedEntities;
1424 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1425 return baseEntities[chr] || entities[chr] || chr;
1429 getEncodeFunc : function(name, entities) {
1430 var Entities = tinymce.html.Entities;
1432 entities = buildEntitiesLookup(entities) || namedEntities;
1434 function encodeNamedAndNumeric(text, attr) {
1435 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1436 return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
1440 function encodeCustomNamed(text, attr) {
1441 return Entities.encodeNamed(text, attr, entities);
1444 // Replace + with , to be compatible with previous TinyMCE versions
1445 name = tinymce.makeMap(name.replace(/\+/g, ','));
1447 // Named and numeric encoder
1448 if (name.named && name.numeric)
1449 return encodeNamedAndNumeric;
1455 return encodeCustomNamed;
1457 return Entities.encodeNamed;
1462 return Entities.encodeNumeric;
1465 return Entities.encodeRaw;
1468 decode : function(text) {
1469 return text.replace(entityRegExp, function(all, numeric, value) {
1471 value = parseInt(value);
1473 // Support upper UTF
1474 if (value > 0xFFFF) {
1477 return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF));
1479 return asciiMap[value] || String.fromCharCode(value);
1482 return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
1488 tinymce.html.Styles = function(settings, schema) {
1489 var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,
1490 urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,
1491 styleRegExp = /\s*([^:]+):\s*([^;]+);?/g,
1492 trimRightRegExp = /\s+$/,
1493 urlColorRegExp = /rgb/,
1494 undef, i, encodingLookup = {}, encodingItems;
1496 settings = settings || {};
1498 encodingItems = '\\" \\\' \\; \\: ; : _'.split(' ');
1499 for (i = 0; i < encodingItems.length; i++) {
1500 encodingLookup[encodingItems[i]] = '_' + i;
1501 encodingLookup['_' + i] = encodingItems[i];
1504 function toHex(match, r, g, b) {
1506 val = parseInt(val).toString(16);
1508 return val.length > 1 ? val : '0' + val; // 0 -> 00
1511 return '#' + hex(r) + hex(g) + hex(b);
1515 toHex : function(color) {
1516 return color.replace(rgbRegExp, toHex);
1519 parse : function(css) {
1520 var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this;
1522 function compress(prefix, suffix) {
1523 var top, right, bottom, left;
1525 // Get values and check it it needs compressing
1526 top = styles[prefix + '-top' + suffix];
1530 right = styles[prefix + '-right' + suffix];
1534 bottom = styles[prefix + '-bottom' + suffix];
1535 if (right != bottom)
1538 left = styles[prefix + '-left' + suffix];
1543 styles[prefix + suffix] = left;
1544 delete styles[prefix + '-top' + suffix];
1545 delete styles[prefix + '-right' + suffix];
1546 delete styles[prefix + '-bottom' + suffix];
1547 delete styles[prefix + '-left' + suffix];
1550 function canCompress(key) {
1551 var value = styles[key], i;
1553 if (!value || value.indexOf(' ') < 0)
1556 value = value.split(' ');
1559 if (value[i] !== value[0])
1563 styles[key] = value[0];
1568 function compress2(target, a, b, c) {
1569 if (!canCompress(a))
1572 if (!canCompress(b))
1575 if (!canCompress(c))
1579 styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
1585 // Encodes the specified string by replacing all \" \' ; : with _<num>
1586 function encode(str) {
1589 return encodingLookup[str];
1592 // Decodes the specified string by replacing all _<num> with it's original value \" \' etc
1593 // It will also decode the \" \' if keep_slashes is set to fale or omitted
1594 function decode(str, keep_slashes) {
1596 str = str.replace(/_[0-9]/g, function(str) {
1597 return encodingLookup[str];
1602 str = str.replace(/\\([\'\";:])/g, "$1");
1608 // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing
1609 css = css.replace(/\\[\"\';:_]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
1610 return str.replace(/[;:]/g, encode);
1614 while (matches = styleRegExp.exec(css)) {
1615 name = matches[1].replace(trimRightRegExp, '').toLowerCase();
1616 value = matches[2].replace(trimRightRegExp, '');
1618 if (name && value.length > 0) {
1619 // Opera will produce 700 instead of bold in their style values
1620 if (name === 'font-weight' && value === '700')
1622 else if (name === 'color' || name === 'background-color') // Lowercase colors like RED
1623 value = value.toLowerCase();
1625 // Convert RGB colors to HEX
1626 value = value.replace(rgbRegExp, toHex);
1628 // Convert URLs and force them into url('value') format
1629 value = value.replace(urlOrStrRegExp, function(match, url, url2, url3, str, str2) {
1635 // Force strings into single quote format
1636 return "'" + str.replace(/\'/g, "\\'") + "'";
1639 url = decode(url || url2 || url3);
1641 // Convert the URL to relative/absolute depending on config
1643 url = urlConverter.call(urlConverterScope, url, 'style');
1645 // Output new URL format
1646 return "url('" + url.replace(/\'/g, "\\'") + "')";
1649 styles[name] = isEncoded ? decode(value, true) : value;
1652 styleRegExp.lastIndex = matches.index + matches[0].length;
1655 // Compress the styles to reduce it's size for example IE will expand styles
1656 compress("border", "");
1657 compress("border", "-width");
1658 compress("border", "-color");
1659 compress("border", "-style");
1660 compress("padding", "");
1661 compress("margin", "");
1662 compress2('border', 'border-width', 'border-style', 'border-color');
1664 // Remove pointless border, IE produces these
1665 if (styles.border === 'medium none')
1666 delete styles.border;
1672 serialize : function(styles, element_name) {
1673 var css = '', name, value;
1675 function serializeStyles(name) {
1676 var styleList, i, l, name, value;
1678 styleList = schema.styles[name];
1680 for (i = 0, l = styleList.length; i < l; i++) {
1681 name = styleList[i];
1682 value = styles[name];
1684 if (value !== undef && value.length > 0)
1685 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1690 // Serialize styles according to schema
1691 if (element_name && schema && schema.styles) {
1692 // Serialize global styles and element specific styles
1693 serializeStyles('*');
1694 serializeStyles(name);
1696 // Output the styles in the order they are inside the object
1697 for (name in styles) {
1698 value = styles[name];
1700 if (value !== undef && value.length > 0)
1701 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1710 (function(tinymce) {
1711 var transitional = {}, boolAttrMap, blockElementsMap, shortEndedElementsMap, nonEmptyElementsMap,
1712 whiteSpaceElementsMap, selfClosingElementsMap, makeMap = tinymce.makeMap, each = tinymce.each;
1714 function split(str, delim) {
1715 return str.split(delim || ',');
1718 function unpack(lookup, data) {
1719 var key, elements = {};
1721 function replace(value) {
1722 return value.replace(/[A-Z]+/g, function(key) {
1723 return replace(lookup[key]);
1728 for (key in lookup) {
1729 if (lookup.hasOwnProperty(key))
1730 lookup[key] = replace(lookup[key]);
1733 // Unpack and parse data into object map
1734 replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) {
1735 attributes = split(attributes, '|');
1738 attributes : makeMap(attributes),
1739 attributesOrder : attributes,
1740 children : makeMap(children, '|', {'#comment' : {}})
1747 // Build a lookup table for block elements both lowercase and uppercase
1748 blockElementsMap = 'h1,h2,h3,h4,h5,h6,hr,p,div,address,pre,form,table,tbody,thead,tfoot,' +
1749 'th,tr,td,li,ol,ul,caption,blockquote,center,dl,dt,dd,dir,fieldset,' +
1750 'noscript,menu,isindex,samp,header,footer,article,section,hgroup';
1751 blockElementsMap = makeMap(blockElementsMap, ',', makeMap(blockElementsMap.toUpperCase()));
1753 // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size
1754 transitional = unpack({
1757 ZG : 'E|span|width|align|char|charoff|valign',
1758 X : 'p|T|div|U|W|isindex|fieldset|table',
1759 ZF : 'E|align|char|charoff|valign',
1760 W : 'pre|hr|blockquote|address|center|noframes',
1761 ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',
1763 U : 'ul|ol|dl|menu|dir',
1764 ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',
1765 T : 'h1|h2|h3|h4|h5|h6',
1771 P : 'ins|del|script',
1772 O : 'input|select|textarea|label|button',
1774 M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',
1777 J : 'tt|i|b|u|s|strike',
1778 I : 'big|small|font|basefont',
1781 F : 'object|applet|img|map|iframe',
1783 D : 'accesskey|tabindex|onfocus|onblur',
1784 C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
1785 B : 'lang|xml:lang|dir',
1786 A : 'id|class|style|title'
1787 }, 'script[id|charset|type|language|src|defer|xml:space][]' +
1788 'style[B|id|type|media|title|xml:space][]' +
1789 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' +
1790 'param[id|name|value|valuetype|type][]' +
1792 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' +
1796 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' +
1797 'h1[E|align][#|S]' +
1798 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' +
1799 'map[B|C|A|name][X|form|Q|area]' +
1800 'h2[E|align][#|S]' +
1801 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' +
1802 'h3[E|align][#|S]' +
1811 'font[A|B|size|color|face][#|S]' +
1812 'basefont[id|size|color|face][]' +
1826 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' +
1827 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' +
1828 'optgroup[E|disabled|label][option]' +
1829 'option[E|selected|disabled|label|value][]' +
1830 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' +
1831 'label[E|for|accesskey|onfocus|onblur][#|S]' +
1832 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' +
1833 'h4[E|align][#|S]' +
1834 'ins[E|cite|datetime][#|Y]' +
1835 'h5[E|align][#|S]' +
1836 'del[E|cite|datetime][#|Y]' +
1837 'h6[E|align][#|S]' +
1838 'div[E|align][#|Y]' +
1839 'ul[E|type|compact][li]' +
1840 'li[E|type|value][#|Y]' +
1841 'ol[E|type|compact|start][li]' +
1842 'dl[E|compact][dt|dd]' +
1845 'menu[E|compact][li]' +
1846 'dir[E|compact][li]' +
1847 'pre[E|width|xml:space][#|ZA]' +
1848 'hr[E|align|noshade|size|width][]' +
1849 'blockquote[E|cite][#|Y]' +
1850 'address[E][#|S|p]' +
1852 'noframes[E][#|Y]' +
1853 'isindex[A|B|prompt][]' +
1854 'fieldset[E][#|legend|Y]' +
1855 'legend[E|accesskey|align][#|S]' +
1856 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' +
1857 'caption[E|align][#|S]' +
1859 'colgroup[ZG][col]' +
1861 'tr[ZF|bgcolor][th|td]' +
1863 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' +
1864 'noscript[E][#|Y]' +
1868 'area[E|D|shape|coords|href|nohref|alt|target][]' +
1869 'base[id|href|target][]' +
1870 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'
1873 boolAttrMap = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected,preload,autoplay,loop,controls');
1874 shortEndedElementsMap = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,source');
1875 nonEmptyElementsMap = tinymce.extend(makeMap('td,th,iframe,video,object'), shortEndedElementsMap);
1876 whiteSpaceElementsMap = makeMap('pre,script,style');
1877 selfClosingElementsMap = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
1879 tinymce.html.Schema = function(settings) {
1880 var self = this, elements = {}, children = {}, patternElements = [], validStyles;
1882 settings = settings || {};
1884 // Allow all elements and attributes if verify_html is set to false
1885 if (settings.verify_html === false)
1886 settings.valid_elements = '*[*]';
1888 // Build styles list
1889 if (settings.valid_styles) {
1892 // Convert styles into a rule list
1893 each(settings.valid_styles, function(value, key) {
1894 validStyles[key] = tinymce.explode(value);
1898 // Converts a wildcard expression string to a regexp for example *a will become /.*a/.
1899 function patternToRegExp(str) {
1900 return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
1903 // Parses the specified valid_elements string and adds to the current rules
1904 // This function is a bit hard to read since it's heavily optimized for speed
1905 function addValidElements(valid_elements) {
1906 var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
1907 prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value,
1908 elementRuleRegExp = /^([#+-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,
1909 attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
1910 hasPatternsRegExp = /[*?+]/;
1912 if (valid_elements) {
1913 // Split valid elements into an array with rules
1914 valid_elements = split(valid_elements);
1916 if (elements['@']) {
1917 globalAttributes = elements['@'].attributes;
1918 globalAttributesOrder = elements['@'].attributesOrder;
1922 for (ei = 0, el = valid_elements.length; ei < el; ei++) {
1923 // Parse element rule
1924 matches = elementRuleRegExp.exec(valid_elements[ei]);
1926 // Setup local names for matches
1927 prefix = matches[1];
1928 elementName = matches[2];
1929 outputName = matches[3];
1930 attrData = matches[4];
1932 // Create new attributes and attributesOrder
1934 attributesOrder = [];
1936 // Create the new element
1938 attributes : attributes,
1939 attributesOrder : attributesOrder
1942 // Padd empty elements prefix
1944 element.paddEmpty = true;
1946 // Remove empty elements prefix
1948 element.removeEmpty = true;
1950 // Copy attributes from global rule into current rule
1951 if (globalAttributes) {
1952 for (key in globalAttributes)
1953 attributes[key] = globalAttributes[key];
1955 attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
1958 // Attributes defined
1960 attrData = split(attrData, '|');
1961 for (ai = 0, al = attrData.length; ai < al; ai++) {
1962 matches = attrRuleRegExp.exec(attrData[ai]);
1965 attrType = matches[1];
1966 attrName = matches[2].replace(/::/g, ':');
1967 prefix = matches[3];
1971 if (attrType === '!') {
1972 element.attributesRequired = element.attributesRequired || [];
1973 element.attributesRequired.push(attrName);
1974 attr.required = true;
1977 // Denied from global
1978 if (attrType === '-') {
1979 delete attributes[attrName];
1980 attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1);
1987 if (prefix === '=') {
1988 element.attributesDefault = element.attributesDefault || [];
1989 element.attributesDefault.push({name: attrName, value: value});
1990 attr.defaultValue = value;
1994 if (prefix === ':') {
1995 element.attributesForced = element.attributesForced || [];
1996 element.attributesForced.push({name: attrName, value: value});
1997 attr.forcedValue = value;
2002 attr.validValues = makeMap(value, '?');
2005 // Check for attribute patterns
2006 if (hasPatternsRegExp.test(attrName)) {
2007 element.attributePatterns = element.attributePatterns || [];
2008 attr.pattern = patternToRegExp(attrName);
2009 element.attributePatterns.push(attr);
2011 // Add attribute to order list if it doesn't already exist
2012 if (!attributes[attrName])
2013 attributesOrder.push(attrName);
2015 attributes[attrName] = attr;
2021 // Global rule, store away these for later usage
2022 if (!globalAttributes && elementName == '@') {
2023 globalAttributes = attributes;
2024 globalAttributesOrder = attributesOrder;
2027 // Handle substitute elements such as b/strong
2029 element.outputName = elementName;
2030 elements[outputName] = element;
2033 // Add pattern or exact element
2034 if (hasPatternsRegExp.test(elementName)) {
2035 element.pattern = patternToRegExp(elementName);
2036 patternElements.push(element);
2038 elements[elementName] = element;
2044 function setValidElements(valid_elements) {
2046 patternElements = [];
2048 addValidElements(valid_elements);
2050 each(transitional, function(element, name) {
2051 children[name] = element.children;
2055 // Adds custom non HTML elements to the schema
2056 function addCustomElements(custom_elements) {
2057 var customElementRegExp = /^(~)?(.+)$/;
2059 if (custom_elements) {
2060 each(split(custom_elements), function(rule) {
2061 var matches = customElementRegExp.exec(rule),
2062 cloneName = matches[1] === '~' ? 'span' : 'div',
2065 children[name] = children[cloneName];
2067 // Add custom elements at span/div positions
2068 each(children, function(element, child) {
2069 if (element[cloneName])
2070 element[name] = element[cloneName];
2076 // Adds valid children to the schema object
2077 function addValidChildren(valid_children) {
2078 var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;
2080 if (valid_children) {
2081 each(split(valid_children), function(rule) {
2082 var matches = childRuleRegExp.exec(rule), parent, prefix;
2085 prefix = matches[1];
2087 // Add/remove items from default
2089 parent = children[matches[2]];
2091 parent = children[matches[2]] = {'#comment' : {}};
2093 parent = children[matches[2]];
2095 each(split(matches[3], '|'), function(child) {
2097 delete parent[child];
2106 if (!settings.valid_elements) {
2107 // No valid elements defined then clone the elements from the transitional spec
2108 each(transitional, function(element, name) {
2110 attributes : element.attributes,
2111 attributesOrder : element.attributesOrder
2114 children[name] = element.children;
2118 each(split('strong/b,em/i'), function(item) {
2119 item = split(item, '/');
2120 elements[item[1]].outputName = item[0];
2123 // Add default alt attribute for images
2124 elements.img.attributesDefault = [{name: 'alt', value: ''}];
2126 // Remove these if they are empty by default
2127 each(split('ol,ul,li,sub,sup,blockquote,tr,div,span,font,a,table,tbody'), function(name) {
2128 elements[name].removeEmpty = true;
2131 // Padd these by default
2132 each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) {
2133 elements[name].paddEmpty = true;
2136 setValidElements(settings.valid_elements);
2138 addCustomElements(settings.custom_elements);
2139 addValidChildren(settings.valid_children);
2140 addValidElements(settings.extended_valid_elements);
2142 // Todo: Remove this when we fix list handling to be valid
2143 addValidChildren('+ol[ul|ol],+ul[ul|ol]');
2145 // Delete invalid elements
2146 if (settings.invalid_elements) {
2147 tinymce.each(tinymce.explode(settings.invalid_elements), function(item) {
2149 delete elements[item];
2153 self.children = children;
2155 self.styles = validStyles;
2157 self.getBoolAttrs = function() {
2161 self.getBlockElements = function() {
2162 return blockElementsMap;
2165 self.getShortEndedElements = function() {
2166 return shortEndedElementsMap;
2169 self.getSelfClosingElements = function() {
2170 return selfClosingElementsMap;
2173 self.getNonEmptyElements = function() {
2174 return nonEmptyElementsMap;
2177 self.getWhiteSpaceElements = function() {
2178 return whiteSpaceElementsMap;
2181 self.isValidChild = function(name, child) {
2182 var parent = children[name];
2184 return !!(parent && parent[child]);
2187 self.getElementRule = function(name) {
2188 var element = elements[name], i;
2190 // Exact match found
2194 // No exact match then try the patterns
2195 i = patternElements.length;
2197 element = patternElements[i];
2199 if (element.pattern.test(name))
2204 self.addValidElements = addValidElements;
2206 self.setValidElements = setValidElements;
2208 self.addCustomElements = addCustomElements;
2210 self.addValidChildren = addValidChildren;
2213 // Expose boolMap and blockElementMap as static properties for usage in DOMUtils
2214 tinymce.html.Schema.boolAttrMap = boolAttrMap;
2215 tinymce.html.Schema.blockElementsMap = blockElementsMap;
2218 (function(tinymce) {
2219 tinymce.html.SaxParser = function(settings, schema) {
2220 var self = this, noop = function() {};
2222 settings = settings || {};
2223 self.schema = schema = schema || new tinymce.html.Schema();
2225 if (settings.fix_self_closing !== false)
2226 settings.fix_self_closing = true;
2228 // Add handler functions from settings and setup default handlers
2229 tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) {
2231 self[name] = settings[name] || noop;
2234 self.parse = function(html) {
2235 var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name,
2236 shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue,
2237 validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing,
2238 tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing;
2240 function processEndTag(name) {
2243 // Find position of parent of the same type
2246 if (stack[pos].name === name)
2252 // Close all the open elements
2253 for (i = stack.length - 1; i >= pos; i--) {
2257 self.end(name.name);
2260 // Remove the open elements from the stack
2265 // Precompile RegExps and map objects
2266 tokenRegExp = new RegExp('<(?:' +
2267 '(?:!--([\\w\\W]*?)-->)|' + // Comment
2268 '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA
2269 '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
2270 '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
2271 '(?:\\/([^>]+)>)|' + // End element
2272 '(?:([^\\s\\/<>]+)\\s*((?:[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*)>)' + // Start element
2275 attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g;
2277 'script' : /<\/script[^>]*>/gi,
2278 'style' : /<\/style[^>]*>/gi,
2279 'noscript' : /<\/noscript[^>]*>/gi
2282 // Setup lookup tables for empty elements and boolean attributes
2283 shortEndedElements = schema.getShortEndedElements();
2284 selfClosing = schema.getSelfClosingElements();
2285 fillAttrsMap = schema.getBoolAttrs();
2286 validate = settings.validate;
2287 fixSelfClosing = settings.fix_self_closing;
2289 while (matches = tokenRegExp.exec(html)) {
2291 if (index < matches.index)
2292 self.text(decode(html.substr(index, matches.index - index)));
2294 if (value = matches[6]) { // End element
2295 processEndTag(value.toLowerCase());
2296 } else if (value = matches[7]) { // Start element
2297 value = value.toLowerCase();
2298 isShortEnded = value in shortEndedElements;
2300 // Is self closing tag for example an <li> after an open <li>
2301 if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value)
2302 processEndTag(value);
2305 if (!validate || (elementRule = schema.getElementRule(value))) {
2306 isValidElement = true;
2308 // Grab attributes map and patters when validation is enabled
2310 validAttributesMap = elementRule.attributes;
2311 validAttributePatterns = elementRule.attributePatterns;
2315 if (attribsValue = matches[8]) {
2319 attribsValue.replace(attrRegExp, function(match, name, value, val2, val3) {
2322 name = name.toLowerCase();
2323 value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
2325 // Validate name and value
2326 if (validate && name.indexOf('data-') !== 0) {
2327 attrRule = validAttributesMap[name];
2329 // Find rule by pattern matching
2330 if (!attrRule && validAttributePatterns) {
2331 i = validAttributePatterns.length;
2333 attrRule = validAttributePatterns[i];
2334 if (attrRule.pattern.test(name))
2343 // No attribute rule found
2348 if (attrRule.validValues && !(value in attrRule.validValues))
2352 // Add attribute to list and map
2353 attrList.map[name] = value;
2364 // Process attributes if validation is enabled
2366 attributesRequired = elementRule.attributesRequired;
2367 attributesDefault = elementRule.attributesDefault;
2368 attributesForced = elementRule.attributesForced;
2370 // Handle forced attributes
2371 if (attributesForced) {
2372 i = attributesForced.length;
2374 attr = attributesForced[i];
2376 attrValue = attr.value;
2378 if (attrValue === '{$uid}')
2379 attrValue = 'mce_' + idCount++;
2381 attrList.map[name] = attrValue;
2382 attrList.push({name: name, value: attrValue});
2386 // Handle default attributes
2387 if (attributesDefault) {
2388 i = attributesDefault.length;
2390 attr = attributesDefault[i];
2393 if (!(name in attrList.map)) {
2394 attrValue = attr.value;
2396 if (attrValue === '{$uid}')
2397 attrValue = 'mce_' + idCount++;
2399 attrList.map[name] = attrValue;
2400 attrList.push({name: name, value: attrValue});
2405 // Handle required attributes
2406 if (attributesRequired) {
2407 i = attributesRequired.length;
2409 if (attributesRequired[i] in attrList.map)
2413 // None of the required attributes where found
2415 isValidElement = false;
2418 // Invalidate element if it's marked as bogus
2419 if (attrList.map['data-mce-bogus'])
2420 isValidElement = false;
2424 self.start(value, attrList, isShortEnded);
2426 isValidElement = false;
2428 // Treat script, noscript and style a bit different since they may include code that looks like elements
2429 if (endRegExp = specialElements[value]) {
2430 endRegExp.lastIndex = index = matches.index + matches[0].length;
2432 if (matches = endRegExp.exec(html)) {
2434 text = html.substr(index, matches.index - index);
2436 index = matches.index + matches[0].length;
2438 text = html.substr(index);
2439 index = html.length;
2442 if (isValidElement && text.length > 0)
2443 self.text(text, true);
2448 tokenRegExp.lastIndex = index;
2452 // Push value on to stack
2453 if (!isShortEnded) {
2454 if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1)
2455 stack.push({name: value, valid: isValidElement});
2456 else if (isValidElement)
2459 } else if (value = matches[1]) { // Comment
2460 self.comment(value);
2461 } else if (value = matches[2]) { // CDATA
2463 } else if (value = matches[3]) { // DOCTYPE
2464 self.doctype(value);
2465 } else if (value = matches[4]) { // PI
2466 self.pi(value, matches[5]);
2469 index = matches.index + matches[0].length;
2473 if (index < html.length)
2474 self.text(decode(html.substr(index)));
2476 // Close any open elements
2477 for (i = stack.length - 1; i >= 0; i--) {
2481 self.end(value.name);
2487 (function(tinymce) {
2488 var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = {
2494 '#document-fragment' : 11
2497 // Walks the tree left/right
2498 function walk(node, root_node, prev) {
2499 var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next';
2501 // Walk into nodes if it has a start
2502 if (node[startName])
2503 return node[startName];
2505 // Return the sibling if it has one
2506 if (node !== root_node) {
2507 sibling = node[siblingName];
2512 // Walk up the parents to look for siblings
2513 for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) {
2514 sibling = parent[siblingName];
2522 function Node(name, type) {
2527 this.attributes = [];
2528 this.attributes.map = {};
2532 tinymce.extend(Node.prototype, {
2533 replace : function(node) {
2539 self.insert(node, self);
2545 attr : function(name, value) {
2546 var self = this, attrs, i, undef;
2548 if (typeof name !== "string") {
2550 self.attr(i, name[i]);
2555 if (attrs = self.attributes) {
2556 if (value !== undef) {
2558 if (value === null) {
2559 if (name in attrs.map) {
2560 delete attrs.map[name];
2564 if (attrs[i].name === name) {
2565 attrs = attrs.splice(i, 1);
2575 if (name in attrs.map) {
2579 if (attrs[i].name === name) {
2580 attrs[i].value = value;
2585 attrs.push({name: name, value: value});
2587 attrs.map[name] = value;
2591 return attrs.map[name];
2596 clone : function() {
2597 var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs;
2599 // Clone element attributes
2600 if (selfAttrs = self.attributes) {
2602 cloneAttrs.map = {};
2604 for (i = 0, l = selfAttrs.length; i < l; i++) {
2605 selfAttr = selfAttrs[i];
2607 // Clone everything except id
2608 if (selfAttr.name !== 'id') {
2609 cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value};
2610 cloneAttrs.map[selfAttr.name] = selfAttr.value;
2614 clone.attributes = cloneAttrs;
2617 clone.value = self.value;
2618 clone.shortEnded = self.shortEnded;
2623 wrap : function(wrapper) {
2626 self.parent.insert(wrapper, self);
2627 wrapper.append(self);
2632 unwrap : function() {
2633 var self = this, node, next;
2635 for (node = self.firstChild; node; ) {
2637 self.insert(node, self, true);
2644 remove : function() {
2645 var self = this, parent = self.parent, next = self.next, prev = self.prev;
2648 if (parent.firstChild === self) {
2649 parent.firstChild = next;
2657 if (parent.lastChild === self) {
2658 parent.lastChild = prev;
2666 self.parent = self.next = self.prev = null;
2672 append : function(node) {
2673 var self = this, last;
2678 last = self.lastChild;
2682 self.lastChild = node;
2684 self.lastChild = self.firstChild = node;
2691 insert : function(node, ref_node, before) {
2697 parent = ref_node.parent || this;
2700 if (ref_node === parent.firstChild)
2701 parent.firstChild = node;
2703 ref_node.prev.next = node;
2705 node.prev = ref_node.prev;
2706 node.next = ref_node;
2707 ref_node.prev = node;
2709 if (ref_node === parent.lastChild)
2710 parent.lastChild = node;
2712 ref_node.next.prev = node;
2714 node.next = ref_node.next;
2715 node.prev = ref_node;
2716 ref_node.next = node;
2719 node.parent = parent;
2724 getAll : function(name) {
2725 var self = this, node, collection = [];
2727 for (node = self.firstChild; node; node = walk(node, self)) {
2728 if (node.name === name)
2729 collection.push(node);
2735 empty : function() {
2736 var self = this, nodes, i, node;
2738 // Remove all children
2739 if (self.firstChild) {
2742 // Collect the children
2743 for (node = self.firstChild; node; node = walk(node, self))
2746 // Remove the children
2750 node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
2754 self.firstChild = self.lastChild = null;
2759 isEmpty : function(elements) {
2760 var self = this, node = self.firstChild, i, name;
2764 if (node.type === 1) {
2765 // Ignore bogus elements
2766 if (node.attributes.map['data-mce-bogus'])
2769 // Keep empty elements like <img />
2770 if (elements[node.name])
2773 // Keep elements with data attributes or name attribute like <a name="1"></a>
2774 i = node.attributes.length;
2776 name = node.attributes[i].name;
2777 if (name === "name" || name.indexOf('data-') === 0)
2782 // Keep non whitespace text nodes
2783 if ((node.type === 3 && !whiteSpaceRegExp.test(node.value)))
2785 } while (node = walk(node, self));
2792 tinymce.extend(Node, {
2793 create : function(name, attrs) {
2797 node = new Node(name, typeLookup[name] || 1);
2799 // Add attributes if needed
2801 for (attrName in attrs)
2802 node.attr(attrName, attrs[attrName]);
2809 tinymce.html.Node = Node;
2812 (function(tinymce) {
2813 var Node = tinymce.html.Node;
2815 tinymce.html.DomParser = function(settings, schema) {
2816 var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};
2818 settings = settings || {};
2819 settings.validate = "validate" in settings ? settings.validate : true;
2820 settings.root_name = settings.root_name || 'body';
2821 self.schema = schema = schema || new tinymce.html.Schema();
2823 function fixInvalidChildren(nodes) {
2824 var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i,
2825 childClone, nonEmptyElements, nonSplitableElements, sibling, nextNode;
2827 nonSplitableElements = tinymce.makeMap('tr,td,th,tbody,thead,tfoot,table');
2828 nonEmptyElements = schema.getNonEmptyElements();
2830 for (ni = 0; ni < nodes.length; ni++) {
2837 // Get list of all parent nodes until we find a valid parent to stick the child into
2839 for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent)
2840 parents.push(parent);
2842 // Found a suitable parent
2843 if (parent && parents.length > 1) {
2844 // Reverse the array since it makes looping easier
2847 // Clone the related parent and insert that after the moved node
2848 newParent = currentNode = self.filterNode(parents[0].clone());
2850 // Start cloning and moving children on the left side of the target node
2851 for (i = 0; i < parents.length - 1; i++) {
2852 if (schema.isValidChild(currentNode.name, parents[i].name)) {
2853 tempNode = self.filterNode(parents[i].clone());
2854 currentNode.append(tempNode);
2856 tempNode = currentNode;
2858 for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) {
2859 nextNode = childNode.next;
2860 tempNode.append(childNode);
2861 childNode = nextNode;
2864 currentNode = tempNode;
2867 if (!newParent.isEmpty(nonEmptyElements)) {
2868 parent.insert(newParent, parents[0], true);
2869 parent.insert(node, newParent);
2871 parent.insert(node, parents[0], true);
2874 // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p>
2875 parent = parents[0];
2876 if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') {
2877 parent.empty().remove();
2879 } else if (node.parent) {
2880 // If it's an LI try to find a UL/OL for it or wrap it
2881 if (node.name === 'li') {
2882 sibling = node.prev;
2883 if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
2884 sibling.append(node);
2888 sibling = node.next;
2889 if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
2890 sibling.insert(node, sibling.firstChild, true);
2894 node.wrap(self.filterNode(new Node('ul', 1)));
2898 // Try wrapping the element in a DIV
2899 if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
2900 node.wrap(self.filterNode(new Node('div', 1)));
2902 // We failed wrapping it, then remove or unwrap it
2903 if (node.name === 'style' || node.name === 'script')
2904 node.empty().remove();
2912 self.filterNode = function(node) {
2915 // Run element filters
2916 if (name in nodeFilters) {
2917 list = matchedNodes[name];
2922 matchedNodes[name] = [node];
2925 // Run attribute filters
2926 i = attributeFilters.length;
2928 name = attributeFilters[i].name;
2930 if (name in node.attributes.map) {
2931 list = matchedAttributes[name];
2936 matchedAttributes[name] = [node];
2943 self.addNodeFilter = function(name, callback) {
2944 tinymce.each(tinymce.explode(name), function(name) {
2945 var list = nodeFilters[name];
2948 nodeFilters[name] = list = [];
2950 list.push(callback);
2954 self.addAttributeFilter = function(name, callback) {
2955 tinymce.each(tinymce.explode(name), function(name) {
2958 for (i = 0; i < attributeFilters.length; i++) {
2959 if (attributeFilters[i].name === name) {
2960 attributeFilters[i].callbacks.push(callback);
2965 attributeFilters.push({name: name, callbacks: [callback]});
2969 self.parse = function(html, args) {
2970 var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate,
2971 blockElements, startWhiteSpaceRegExp, invalidChildren = [],
2972 endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements;
2976 matchedAttributes = {};
2977 blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
2978 nonEmptyElements = schema.getNonEmptyElements();
2979 children = schema.children;
2980 validate = settings.validate;
2982 whiteSpaceElements = schema.getWhiteSpaceElements();
2983 startWhiteSpaceRegExp = /^[ \t\r\n]+/;
2984 endWhiteSpaceRegExp = /[ \t\r\n]+$/;
2985 allWhiteSpaceRegExp = /[ \t\r\n]+/g;
2987 function createNode(name, type) {
2988 var node = new Node(name, type), list;
2990 if (name in nodeFilters) {
2991 list = matchedNodes[name];
2996 matchedNodes[name] = [node];
3002 function removeWhitespaceBefore(node) {
3003 var textNode, textVal, sibling;
3005 for (textNode = node.prev; textNode && textNode.type === 3; ) {
3006 textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
3008 if (textVal.length > 0) {
3009 textNode.value = textVal;
3010 textNode = textNode.prev;
3012 sibling = textNode.prev;
3019 parser = new tinymce.html.SaxParser({
3020 validate : validate,
3021 fix_self_closing : !validate, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results
3023 cdata: function(text) {
3024 node.append(createNode('#cdata', 4)).value = text;
3027 text: function(text, raw) {
3030 // Trim all redundant whitespace on non white space elements
3031 if (!whiteSpaceElements[node.name]) {
3032 text = text.replace(allWhiteSpaceRegExp, ' ');
3034 if (node.lastChild && blockElements[node.lastChild.name])
3035 text = text.replace(startWhiteSpaceRegExp, '');
3038 // Do we need to create the node
3039 if (text.length !== 0) {
3040 textNode = createNode('#text', 3);
3041 textNode.raw = !!raw;
3042 node.append(textNode).value = text;
3046 comment: function(text) {
3047 node.append(createNode('#comment', 8)).value = text;
3050 pi: function(name, text) {
3051 node.append(createNode(name, 7)).value = text;
3052 removeWhitespaceBefore(node);
3055 doctype: function(text) {
3058 newNode = node.append(createNode('#doctype', 10));
3059 newNode.value = text;
3060 removeWhitespaceBefore(node);
3063 start: function(name, attrs, empty) {
3064 var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent;
3066 elementRule = validate ? schema.getElementRule(name) : {};
3068 newNode = createNode(elementRule.outputName || name, 1);
3069 newNode.attributes = attrs;
3070 newNode.shortEnded = empty;
3072 node.append(newNode);
3074 // Check if node is valid child of the parent node is the child is
3075 // unknown we don't collect it since it's probably a custom element
3076 parent = children[node.name];
3077 if (parent && children[newNode.name] && !parent[newNode.name])
3078 invalidChildren.push(newNode);
3080 attrFiltersLen = attributeFilters.length;
3081 while (attrFiltersLen--) {
3082 attrName = attributeFilters[attrFiltersLen].name;
3084 if (attrName in attrs.map) {
3085 list = matchedAttributes[attrName];
3090 matchedAttributes[attrName] = [newNode];
3094 // Trim whitespace before block
3095 if (blockElements[name])
3096 removeWhitespaceBefore(newNode);
3098 // Change current node if the element wasn't empty i.e not <br /> or <img />
3104 end: function(name) {
3105 var textNode, elementRule, text, sibling, tempNode;
3107 elementRule = validate ? schema.getElementRule(name) : {};
3109 if (blockElements[name]) {
3110 if (!whiteSpaceElements[node.name]) {
3111 // Trim whitespace at beginning of block
3112 for (textNode = node.firstChild; textNode && textNode.type === 3; ) {
3113 text = textNode.value.replace(startWhiteSpaceRegExp, '');
3115 if (text.length > 0) {
3116 textNode.value = text;
3117 textNode = textNode.next;
3119 sibling = textNode.next;
3125 // Trim whitespace at end of block
3126 for (textNode = node.lastChild; textNode && textNode.type === 3; ) {
3127 text = textNode.value.replace(endWhiteSpaceRegExp, '');
3129 if (text.length > 0) {
3130 textNode.value = text;
3131 textNode = textNode.prev;
3133 sibling = textNode.prev;
3140 // Trim start white space
3141 textNode = node.prev;
3142 if (textNode && textNode.type === 3) {
3143 text = textNode.value.replace(startWhiteSpaceRegExp, '');
3145 if (text.length > 0)
3146 textNode.value = text;
3152 // Handle empty nodes
3153 if (elementRule.removeEmpty || elementRule.paddEmpty) {
3154 if (node.isEmpty(nonEmptyElements)) {
3155 if (elementRule.paddEmpty)
3156 node.empty().append(new Node('#text', '3')).value = '\u00a0';
3158 // Leave nodes that have a name like <a name="name">
3159 if (!node.attributes.map.name) {
3160 tempNode = node.parent;
3161 node.empty().remove();
3174 rootNode = node = new Node(settings.root_name, 11);
3179 fixInvalidChildren(invalidChildren);
3182 for (name in matchedNodes) {
3183 list = nodeFilters[name];
3184 nodes = matchedNodes[name];
3186 // Remove already removed children
3189 if (!nodes[fi].parent)
3190 nodes.splice(fi, 1);
3193 for (i = 0, l = list.length; i < l; i++)
3194 list[i](nodes, name, args);
3197 // Run attribute filters
3198 for (i = 0, l = attributeFilters.length; i < l; i++) {
3199 list = attributeFilters[i];
3201 if (list.name in matchedAttributes) {
3202 nodes = matchedAttributes[list.name];
3204 // Remove already removed children
3207 if (!nodes[fi].parent)
3208 nodes.splice(fi, 1);
3211 for (fi = 0, fl = list.callbacks.length; fi < fl; fi++)
3212 list.callbacks[fi](nodes, list.name, args);
3219 // Remove <br> at end of block elements Gecko and WebKit injects BR elements to
3220 // make it possible to place the caret inside empty blocks. This logic tries to remove
3221 // these elements and keep br elements that where intended to be there intact
3222 if (settings.remove_trailing_brs) {
3223 self.addNodeFilter('br', function(nodes, name) {
3224 var i, l = nodes.length, node, blockElements = schema.getBlockElements(),
3225 nonEmptyElements = schema.getNonEmptyElements(), parent, prev, prevName;
3227 // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p>
3228 for (i = 0; i < l; i++) {
3230 parent = node.parent;
3232 if (blockElements[node.parent.name] && node === parent.lastChild) {
3233 // Loop all nodes to the right of the current node and check for other BR elements
3234 // excluding bookmarks since they are invisible
3237 prevName = prev.name;
3240 if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') {
3241 // Found a non BR element
3242 if (prevName !== "br")
3245 // Found another br it's a <br><br> structure then don't remove anything
3246 if (prevName === 'br') {
3258 // Is the parent to be considered empty after we removed the BR
3259 if (parent.isEmpty(nonEmptyElements)) {
3260 elementRule = schema.getElementRule(parent.name);
3262 // Remove or padd the element depending on schema rule
3263 if (elementRule.removeEmpty)
3265 else if (elementRule.paddEmpty)
3266 parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0';
3276 tinymce.html.Writer = function(settings) {
3277 var html = [], indent, indentBefore, indentAfter, encode, htmlOutput;
3279 settings = settings || {};
3280 indent = settings.indent;
3281 indentBefore = tinymce.makeMap(settings.indent_before || '');
3282 indentAfter = tinymce.makeMap(settings.indent_after || '');
3283 encode = tinymce.html.Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
3284 htmlOutput = settings.element_format == "html";
3287 start: function(name, attrs, empty) {
3288 var i, l, attr, value;
3290 if (indent && indentBefore[name] && html.length > 0) {
3291 value = html[html.length - 1];
3293 if (value.length > 0 && value !== '\n')
3297 html.push('<', name);
3300 for (i = 0, l = attrs.length; i < l; i++) {
3302 html.push(' ', attr.name, '="', encode(attr.value, true), '"');
3306 if (!empty || htmlOutput)
3307 html[html.length] = '>';
3309 html[html.length] = ' />';
3311 if (empty && indent && indentAfter[name] && html.length > 0) {
3312 value = html[html.length - 1];
3314 if (value.length > 0 && value !== '\n')
3319 end: function(name) {
3322 /*if (indent && indentBefore[name] && html.length > 0) {
3323 value = html[html.length - 1];
3325 if (value.length > 0 && value !== '\n')
3329 html.push('</', name, '>');
3331 if (indent && indentAfter[name] && html.length > 0) {
3332 value = html[html.length - 1];
3334 if (value.length > 0 && value !== '\n')
3339 text: function(text, raw) {
3340 if (text.length > 0)
3341 html[html.length] = raw ? text : encode(text);
3344 cdata: function(text) {
3345 html.push('<![CDATA[', text, ']]>');
3348 comment: function(text) {
3349 html.push('<!--', text, '-->');
3352 pi: function(name, text) {
3354 html.push('<?', name, ' ', text, '?>');
3356 html.push('<?', name, '?>');
3362 doctype: function(text) {
3363 html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
3370 getContent: function() {
3371 return html.join('').replace(/\n$/, '');
3376 (function(tinymce) {
3377 tinymce.html.Serializer = function(settings, schema) {
3378 var self = this, writer = new tinymce.html.Writer(settings);
3380 settings = settings || {};
3381 settings.validate = "validate" in settings ? settings.validate : true;
3383 self.schema = schema = schema || new tinymce.html.Schema();
3384 self.writer = writer;
3386 self.serialize = function(node) {
3387 var handlers, validate;
3389 validate = settings.validate;
3393 3: function(node, raw) {
3394 writer.text(node.value, node.raw);
3399 writer.comment(node.value);
3402 // Processing instruction
3404 writer.pi(node.name, node.value);
3408 10: function(node) {
3409 writer.doctype(node.value);
3414 writer.cdata(node.value);
3417 // Document fragment
3418 11: function(node) {
3419 if ((node = node.firstChild)) {
3422 } while (node = node.next);
3429 function walk(node) {
3430 var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
3434 isEmpty = node.shortEnded;
3435 attrs = node.attributes;
3438 if (validate && attrs && attrs.length > 1) {
3440 sortedAttrs.map = {};
3442 elementRule = schema.getElementRule(node.name);
3443 for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
3444 attrName = elementRule.attributesOrder[i];
3446 if (attrName in attrs.map) {
3447 attrValue = attrs.map[attrName];
3448 sortedAttrs.map[attrName] = attrValue;
3449 sortedAttrs.push({name: attrName, value: attrValue});
3453 for (i = 0, l = attrs.length; i < l; i++) {
3454 attrName = attrs[i].name;
3456 if (!(attrName in sortedAttrs.map)) {
3457 attrValue = attrs.map[attrName];
3458 sortedAttrs.map[attrName] = attrValue;
3459 sortedAttrs.push({name: attrName, value: attrValue});
3463 attrs = sortedAttrs;
3466 writer.start(node.name, attrs, isEmpty);
3469 if ((node = node.firstChild)) {
3472 } while (node = node.next);
3481 // Serialize element and treat all non elements as fragments
3482 if (node.type == 1 && !settings.inner)
3487 return writer.getContent();
3492 (function(tinymce) {
3494 var each = tinymce.each,
3496 isWebKit = tinymce.isWebKit,
3497 isIE = tinymce.isIE,
3498 Entities = tinymce.html.Entities,
3499 simpleSelectorRe = /^([a-z0-9],?)+$/i,
3500 blockElementsMap = tinymce.html.Schema.blockElementsMap,
3501 whiteSpaceRegExp = /^[ \t\r\n]*$/;
3503 tinymce.create('tinymce.dom.DOMUtils', {
3507 pixelStyles : /^(top|left|bottom|right|width|height|borderWidth)$/,
3510 "class" : "className",
3511 className : "className",
3512 checked : "checked",
3513 disabled : "disabled",
3514 maxlength : "maxLength",
3515 readonly : "readOnly",
3516 selected : "selected",
3523 DOMUtils : function(d, s) {
3524 var t = this, globalStyle;
3529 t.cssFlicker = false;
3531 t.stdMode = !tinymce.isIE || d.documentMode >= 8;
3532 t.boxModel = !tinymce.isIE || d.compatMode == "CSS1Compat" || t.stdMode;
3533 t.hasOuterHTML = "outerHTML" in d.createElement("a");
3535 t.settings = s = tinymce.extend({
3536 keep_values : false,
3540 t.schema = s.schema;
3541 t.styles = new tinymce.html.Styles({
3542 url_converter : s.url_converter,
3543 url_converter_scope : s.url_converter_scope
3546 // Fix IE6SP2 flicker and check it failed for pre SP2
3547 if (tinymce.isIE6) {
3549 d.execCommand('BackgroundImageCache', false, true);
3551 t.cssFlicker = true;
3556 // Add missing HTML 4/5 elements to IE
3557 ('abbr article aside audio canvas ' +
3558 'details figcaption figure footer ' +
3559 'header hgroup mark menu meter nav ' +
3560 'output progress section summary ' +
3561 'time video').replace(/\w+/g, function(name) {
3562 d.createElement(name);
3566 tinymce.addUnload(t.destroy, t);
3569 getRoot : function() {
3570 var t = this, s = t.settings;
3572 return (s && t.get(s.root_element)) || t.doc.body;
3575 getViewPort : function(w) {
3578 w = !w ? this.win : w;
3580 b = this.boxModel ? d.documentElement : d.body;
3582 // Returns viewport size excluding scrollbars
3584 x : w.pageXOffset || b.scrollLeft,
3585 y : w.pageYOffset || b.scrollTop,
3586 w : w.innerWidth || b.clientWidth,
3587 h : w.innerHeight || b.clientHeight
3591 getRect : function(e) {
3592 var p, t = this, sr;
3606 getSize : function(e) {
3610 w = t.getStyle(e, 'width');
3611 h = t.getStyle(e, 'height');
3613 // Non pixel value, then force offset/clientWidth
3614 if (w.indexOf('px') === -1)
3617 // Non pixel value, then force offset/clientWidth
3618 if (h.indexOf('px') === -1)
3622 w : parseInt(w) || e.offsetWidth || e.clientWidth,
3623 h : parseInt(h) || e.offsetHeight || e.clientHeight
3627 getParent : function(n, f, r) {
3628 return this.getParents(n, f, r, false);
3631 getParents : function(n, f, r, c) {
3632 var t = this, na, se = t.settings, o = [];
3635 c = c === undefined;
3638 r = r || t.getRoot();
3640 // Wrap node name as func
3641 if (is(f, 'string')) {
3645 f = function(n) {return n.nodeType == 1;};
3654 if (n == r || !n.nodeType || n.nodeType === 9)
3667 return c ? o : null;
3673 if (e && this.doc && typeof(e) == 'string') {
3675 e = this.doc.getElementById(e);
3677 // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick
3678 if (e && e.id !== n)
3679 return this.doc.getElementsByName(n)[1];
3685 getNext : function(node, selector) {
3686 return this._findSib(node, selector, 'nextSibling');
3689 getPrev : function(node, selector) {
3690 return this._findSib(node, selector, 'previousSibling');
3694 add : function(p, n, a, h, c) {
3697 return this.run(p, function(p) {
3700 e = is(n, 'string') ? t.doc.createElement(n) : n;
3710 return !c ? p.appendChild(e) : e;
3714 create : function(n, a, h) {
3715 return this.add(this.doc.createElement(n), n, a, h, 1);
3718 createHTML : function(n, a, h) {
3719 var o = '', t = this, k;
3724 if (a.hasOwnProperty(k))
3725 o += ' ' + k + '="' + t.encode(a[k]) + '"';
3728 // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime
3729 if (typeof(h) != "undefined")
3730 return o + '>' + h + '</' + n + '>';
3735 remove : function(node, keep_children) {
3736 return this.run(node, function(node) {
3737 var child, parent = node.parentNode;
3742 if (keep_children) {
3743 while (child = node.firstChild) {
3744 // IE 8 will crash if you don't remove completely empty text nodes
3745 if (!tinymce.isIE || child.nodeType !== 3 || child.nodeValue)
3746 parent.insertBefore(child, node);
3748 node.removeChild(child);
3752 return parent.removeChild(node);
3756 setStyle : function(n, na, v) {
3759 return t.run(n, function(e) {
3764 // Camelcase it, if needed
3765 na = na.replace(/-(\D)/g, function(a, b){
3766 return b.toUpperCase();
3769 // Default px suffix on these
3770 if (t.pixelStyles.test(na) && (tinymce.is(v, 'number') || /^[\-0-9\.]+$/.test(v)))
3775 // IE specific opacity
3777 s.filter = v === '' ? '' : "alpha(opacity=" + (v * 100) + ")";
3779 if (!n.currentStyle || !n.currentStyle.hasLayout)
3780 s.display = 'inline-block';
3783 // Fix for older browsers
3784 s[na] = s['-moz-opacity'] = s['-khtml-opacity'] = v || '';
3788 isIE ? s.styleFloat = v : s.cssFloat = v;
3795 // Force update of the style data
3796 if (t.settings.update_styles)
3797 t.setAttrib(e, 'data-mce-style');
3801 getStyle : function(n, na, c) {
3808 if (this.doc.defaultView && c) {
3810 na = na.replace(/[A-Z]/g, function(a){
3815 return this.doc.defaultView.getComputedStyle(n, null).getPropertyValue(na);
3817 // Old safari might fail
3822 // Camelcase it, if needed
3823 na = na.replace(/-(\D)/g, function(a, b){
3824 return b.toUpperCase();
3828 na = isIE ? 'styleFloat' : 'cssFloat';
3831 if (n.currentStyle && c)
3832 return n.currentStyle[na];
3834 return n.style ? n.style[na] : undefined;
3837 setStyles : function(e, o) {
3838 var t = this, s = t.settings, ol;
3840 ol = s.update_styles;
3841 s.update_styles = 0;
3843 each(o, function(v, n) {
3844 t.setStyle(e, n, v);
3847 // Update style info
3848 s.update_styles = ol;
3849 if (s.update_styles)
3850 t.setAttrib(e, s.cssText);
3853 removeAllAttribs: function(e) {
3854 return this.run(e, function(e) {
3855 var i, attrs = e.attributes;
3856 for (i = attrs.length - 1; i >= 0; i--) {
3857 e.removeAttributeNode(attrs.item(i));
3862 setAttrib : function(e, n, v) {
3870 if (t.settings.strict)
3871 n = n.toLowerCase();
3873 return this.run(e, function(e) {
3878 if (!is(v, 'string')) {
3879 each(v, function(v, n) {
3880 t.setStyle(e, n, v);
3886 // No mce_style for elements with these since they might get resized by the user
3887 if (s.keep_values) {
3888 if (v && !t._isRes(v))
3889 e.setAttribute('data-mce-style', v, 2);
3891 e.removeAttribute('data-mce-style', 2);
3894 e.style.cssText = v;
3898 e.className = v || ''; // Fix IE null bug
3903 if (s.keep_values) {
3904 if (s.url_converter)
3905 v = s.url_converter.call(s.url_converter_scope || t, v, n, e);
3907 t.setAttrib(e, 'data-mce-' + n, v, 2);
3913 e.setAttribute('data-mce-style', v);
3917 if (is(v) && v !== null && v.length !== 0)
3918 e.setAttribute(n, '' + v, 2);
3920 e.removeAttribute(n, 2);
3924 setAttribs : function(e, o) {
3927 return this.run(e, function(e) {
3928 each(o, function(v, n) {
3929 t.setAttrib(e, n, v);
3934 getAttrib : function(e, n, dv) {
3939 if (!e || e.nodeType !== 1)
3945 // Try the mce variant for these
3946 if (/^(src|href|style|coords|shape)$/.test(n)) {
3947 v = e.getAttribute("data-mce-" + n);
3953 if (isIE && t.props[n]) {
3955 v = v && v.nodeValue ? v.nodeValue : v;
3959 v = e.getAttribute(n, 2);
3961 // Check boolean attribs
3962 if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(n)) {
3963 if (e[t.props[n]] === true && v === '')
3969 // Inner input elements will override attributes on form elements
3970 if (e.nodeName === "FORM" && e.getAttributeNode(n))
3971 return e.getAttributeNode(n).nodeValue;
3973 if (n === 'style') {
3974 v = v || e.style.cssText;
3977 v = t.serializeStyle(t.parseStyle(v), e.nodeName);
3979 if (t.settings.keep_values && !t._isRes(v))
3980 e.setAttribute('data-mce-style', v);
3984 // Remove Apple and WebKit stuff
3985 if (isWebKit && n === "class" && v)
3986 v = v.replace(/(apple|webkit)\-[a-z\-]+/gi, '');
3993 // IE returns 1 as default value
4000 // IE returns +0 as default value for size
4001 if (v === '+0' || v === 20 || v === 0)
4018 // IE returns -1 as default value
4026 // IE returns default value
4027 if (v === 32768 || v === 2147483647 || v === '32768')
4042 v = v.toLowerCase();
4046 // IE has odd anonymous function for event attributes
4047 if (n.indexOf('on') === 0 && v)
4048 v = tinymce._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1', '' + v);
4052 return (v !== undefined && v !== null && v !== '') ? '' + v : dv;
4055 getPos : function(n, ro) {
4056 var t = this, x = 0, y = 0, e, d = t.doc, r;
4062 // Use getBoundingClientRect on IE, Opera has it but it's not perfect
4063 if (isIE && !t.stdMode) {
4064 n = n.getBoundingClientRect();
4065 e = t.boxModel ? d.documentElement : d.body;
4066 x = t.getStyle(t.select('html')[0], 'borderWidth'); // Remove border
4067 x = (x == 'medium' || t.boxModel && !t.isIE6) && 2 || x;
4069 return {x : n.left + e.scrollLeft - x, y : n.top + e.scrollTop - x};
4073 while (r && r != ro && r.nodeType) {
4074 x += r.offsetLeft || 0;
4075 y += r.offsetTop || 0;
4080 while (r && r != ro && r.nodeType) {
4081 x -= r.scrollLeft || 0;
4082 y -= r.scrollTop || 0;
4087 return {x : x, y : y};
4090 parseStyle : function(st) {
4091 return this.styles.parse(st);
4094 serializeStyle : function(o, name) {
4095 return this.styles.serialize(o, name);
4098 loadCSS : function(u) {
4099 var t = this, d = t.doc, head;
4104 head = t.select('head')[0];
4106 each(u.split(','), function(u) {
4113 link = t.create('link', {rel : 'stylesheet', href : tinymce._addVer(u)});
4115 // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug
4116 // This fix seems to resolve that issue by realcing the document ones a stylesheet finishes loading
4117 // It's ugly but it seems to work fine.
4118 if (isIE && d.documentMode && d.recalc) {
4119 link.onload = function() {
4127 head.appendChild(link);
4131 addClass : function(e, c) {
4132 return this.run(e, function(e) {
4138 if (this.hasClass(e, c))
4141 o = this.removeClass(e, c);
4143 return e.className = (o != '' ? (o + ' ') : '') + c;
4147 removeClass : function(e, c) {
4150 return t.run(e, function(e) {
4153 if (t.hasClass(e, c)) {
4155 re = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g");
4157 v = e.className.replace(re, ' ');
4158 v = tinymce.trim(v != ' ' ? v : '');
4164 e.removeAttribute('class');
4165 e.removeAttribute('className');
4175 hasClass : function(n, c) {
4181 return (' ' + n.className + ' ').indexOf(' ' + c + ' ') !== -1;
4184 show : function(e) {
4185 return this.setStyle(e, 'display', 'block');
4188 hide : function(e) {
4189 return this.setStyle(e, 'display', 'none');
4192 isHidden : function(e) {
4195 return !e || e.style.display == 'none' || this.getStyle(e, 'display') == 'none';
4198 uniqueId : function(p) {
4199 return (!p ? 'mce_' : p) + (this.counter++);
4202 setHTML : function(element, html) {
4205 return self.run(element, function(element) {
4207 // Remove all child nodes, IE keeps empty text nodes in DOM
4208 while (element.firstChild)
4209 element.removeChild(element.firstChild);
4212 // IE will remove comments from the beginning
4213 // unless you padd the contents with something
4214 element.innerHTML = '<br />' + html;
4215 element.removeChild(element.firstChild);
4217 // IE sometimes produces an unknown runtime error on innerHTML if it's an block element within a block element for example a div inside a p
4218 // This seems to fix this problem
4220 // Create new div with HTML contents and a BR infront to keep comments
4221 element = self.create('div');
4222 element.innerHTML = '<br />' + html;
4224 // Add all children from div to target
4225 each (element.childNodes, function(node, i) {
4228 element.appendChild(node);
4232 element.innerHTML = html;
4238 getOuterHTML : function(elm) {
4239 var doc, self = this;
4241 elm = self.get(elm);
4246 if (elm.nodeType === 1 && self.hasOuterHTML)
4247 return elm.outerHTML;
4249 doc = (elm.ownerDocument || self.doc).createElement("body");
4250 doc.appendChild(elm.cloneNode(true));
4252 return doc.innerHTML;
4255 setOuterHTML : function(e, h, d) {
4258 function setHTML(e, h, d) {
4261 tp = d.createElement("body");
4266 t.insertAfter(n.cloneNode(true), e);
4267 n = n.previousSibling;
4273 return this.run(e, function(e) {
4276 // Only set HTML on elements
4277 if (e.nodeType == 1) {
4278 d = d || e.ownerDocument || t.doc;
4282 // Try outerHTML for IE it sometimes produces an unknown runtime error
4283 if (isIE && e.nodeType == 1)
4288 // Fix for unknown runtime error
4297 decode : Entities.decode,
4299 encode : Entities.encodeAllRaw,
4301 insertAfter : function(node, reference_node) {
4302 reference_node = this.get(reference_node);
4304 return this.run(node, function(node) {
4305 var parent, nextSibling;
4307 parent = reference_node.parentNode;
4308 nextSibling = reference_node.nextSibling;
4311 parent.insertBefore(node, nextSibling);
4313 parent.appendChild(node);
4319 isBlock : function(node) {
4320 var type = node.nodeType;
4322 // If it's a node then check the type and use the nodeName
4324 return !!(type === 1 && blockElementsMap[node.nodeName]);
4326 return !!blockElementsMap[node];
4329 replace : function(n, o, k) {
4333 n = n.cloneNode(true);
4335 return t.run(o, function(o) {
4337 each(tinymce.grep(o.childNodes), function(c) {
4342 return o.parentNode.replaceChild(n, o);
4346 rename : function(elm, name) {
4347 var t = this, newElm;
4349 if (elm.nodeName != name.toUpperCase()) {
4350 // Rename block element
4351 newElm = t.create(name);
4353 // Copy attribs to new block
4354 each(t.getAttribs(elm), function(attr_node) {
4355 t.setAttrib(newElm, attr_node.nodeName, t.getAttrib(elm, attr_node.nodeName));
4359 t.replace(newElm, elm, 1);
4362 return newElm || elm;
4365 findCommonAncestor : function(a, b) {
4371 while (pe && ps != pe)
4380 if (!ps && a.ownerDocument)
4381 return a.ownerDocument.documentElement;
4386 toHex : function(s) {
4387 var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s);
4390 s = parseInt(s).toString(16);
4392 return s.length > 1 ? s : '0' + s; // 0 -> 00
4396 s = '#' + hex(c[1]) + hex(c[2]) + hex(c[3]);
4404 getClasses : function() {
4405 var t = this, cl = [], i, lo = {}, f = t.settings.class_filter, ov;
4410 function addClasses(s) {
4412 each(s.imports, function(r) {
4416 each(s.cssRules || s.rules, function(r) {
4417 // Real type or fake it on IE
4418 switch (r.type || 1) {
4421 if (r.selectorText) {
4422 each(r.selectorText.split(','), function(v) {
4423 v = v.replace(/^\s*|\s*$|^\s\./g, "");
4425 // Is internal or it doesn't contain a class
4426 if (/\.mce/.test(v) || !/\.[\w\-]+$/.test(v))
4429 // Remove everything but class name
4431 v = tinymce._replace(/.*\.([a-z0-9_\-]+).*/i, '$1', v);
4434 if (f && !(v = f(v, ov)))
4438 cl.push({'class' : v});
4447 addClasses(r.styleSheet);
4454 each(t.doc.styleSheets, addClasses);
4465 run : function(e, f, s) {
4468 if (t.doc && typeof(e) === 'string')
4475 if (!e.nodeType && (e.length || e.length === 0)) {
4478 each(e, function(e, i) {
4480 if (typeof(e) == 'string')
4481 e = t.doc.getElementById(e);
4483 o.push(f.call(s, e, i));
4490 return f.call(s, e);
4493 getAttribs : function(n) {
4504 // Object will throw exception in IE
4505 if (n.nodeName == 'OBJECT')
4506 return n.attributes;
4508 // IE doesn't keep the selected attribute if you clone option elements
4509 if (n.nodeName === 'OPTION' && this.getAttrib(n, 'selected'))
4510 o.push({specified : 1, nodeName : 'selected'});
4512 // It's crazy that this is faster in IE but it's because it returns all attributes all the time
4513 n.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi, '').replace(/[\w:\-]+/gi, function(a) {
4514 o.push({specified : 1, nodeName : a});
4520 return n.attributes;
4523 isEmpty : function(node, elements) {
4524 var self = this, i, attributes, type, walker, name;
4526 node = node.firstChild;
4528 walker = new tinymce.dom.TreeWalker(node);
4529 elements = elements || self.schema ? self.schema.getNonEmptyElements() : null;
4532 type = node.nodeType;
4535 // Ignore bogus elements
4536 if (node.getAttribute('data-mce-bogus'))
4539 // Keep empty elements like <img />
4540 if (elements && elements[node.nodeName.toLowerCase()])
4543 // Keep elements with data attributes or name attribute like <a name="1"></a>
4544 attributes = self.getAttribs(node);
4545 i = node.attributes.length;
4547 name = node.attributes[i].nodeName;
4548 if (name === "name" || name.indexOf('data-') === 0)
4553 // Keep non whitespace text nodes
4554 if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue)))
4556 } while (node = walker.next());
4562 destroy : function(s) {
4568 t.win = t.doc = t.root = t.events = null;
4570 // Manual destroy then remove unload handler
4572 tinymce.removeUnload(t.destroy);
4575 createRng : function() {
4578 return d.createRange ? d.createRange() : new tinymce.dom.Range(this);
4581 nodeIndex : function(node, normalized) {
4582 var idx = 0, lastNodeType, lastNode, nodeType, nodeValueExists;
4585 for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) {
4586 nodeType = node.nodeType;
4588 // Normalize text nodes
4589 if (normalized && nodeType == 3) {
4590 // ensure that text nodes that have been removed are handled correctly in Internet Explorer.
4591 // (the nodeValue attribute will not exist, and will error here).
4592 nodeValueExists = false;
4593 try {nodeValueExists = node.nodeValue.length} catch (c) {}
4594 if (nodeType == lastNodeType || !nodeValueExists)
4598 lastNodeType = nodeType;
4605 split : function(pe, e, re) {
4606 var t = this, r = t.createRng(), bef, aft, pa;
4608 // W3C valid browsers tend to leave empty nodes to the left/right side of the contents, this makes sense
4609 // but we don't want that in our code since it serves no purpose for the end user
4610 // For example if this is chopped:
4611 // <p>text 1<span><b>CHOP</b></span>text 2</p>
4613 // <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p>
4614 // this function will then trim of empty edges and produce:
4615 // <p>text 1</p><b>CHOP</b><p>text 2</p>
4616 function trim(node) {
4617 var i, children = node.childNodes, type = node.nodeType;
4619 if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark')
4622 for (i = children.length - 1; i >= 0; i--)
4626 // Keep non whitespace text nodes
4627 if (type == 3 && node.nodeValue.length > 0) {
4628 // If parent element isn't a block or there isn't any useful contents for example "<p> </p>"
4629 if (!t.isBlock(node.parentNode) || tinymce.trim(node.nodeValue).length > 0)
4631 } else if (type == 1) {
4632 // If the only child is a bookmark then move it up
4633 children = node.childNodes;
4634 if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark')
4635 node.parentNode.insertBefore(children[0], node);
4637 // Keep non empty elements or img, hr etc
4638 if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName))
4650 r.setStart(pe.parentNode, t.nodeIndex(pe));
4651 r.setEnd(e.parentNode, t.nodeIndex(e));
4652 bef = r.extractContents();
4656 r.setStart(e.parentNode, t.nodeIndex(e) + 1);
4657 r.setEnd(pe.parentNode, t.nodeIndex(pe) + 1);
4658 aft = r.extractContents();
4660 // Insert before chunk
4662 pa.insertBefore(trim(bef), pe);
4664 // Insert middle chunk
4666 pa.replaceChild(re, e);
4668 pa.insertBefore(e, pe);
4670 // Insert after chunk
4671 pa.insertBefore(trim(aft), pe);
4678 bind : function(target, name, func, scope) {
4682 t.events = new tinymce.dom.EventUtils();
4684 return t.events.add(target, name, func, scope || this);
4687 unbind : function(target, name, func) {
4691 t.events = new tinymce.dom.EventUtils();
4693 return t.events.remove(target, name, func);
4697 _findSib : function(node, selector, name) {
4698 var t = this, f = selector;
4701 // If expression make a function of it using is
4702 if (is(f, 'string')) {
4703 f = function(node) {
4704 return t.is(node, selector);
4708 // Loop all siblings
4709 for (node = node[name]; node; node = node[name]) {
4718 _isRes : function(c) {
4719 // Is live resizble element
4720 return /^(top|left|bottom|right|width|height)/i.test(c) || /;\s*(top|left|bottom|right|width|height)/i.test(c);
4724 walk : function(n, f, s) {
4725 var d = this.doc, w;
4727 if (d.createTreeWalker) {
4728 w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false);
4730 while ((n = w.nextNode()) != null)
4731 f.call(s || this, n);
4733 tinymce.walk(n, f, 'childNodes', s);
4738 toRGB : function(s) {
4739 var c = /^\s*?#([0-9A-F]{2})([0-9A-F]{1,2})([0-9A-F]{2})?\s*?$/.exec(s);
4746 return "rgb(" + parseInt(c[1], 16) + "," + parseInt(c[2], 16) + "," + parseInt(c[3], 16) + ")";
4754 tinymce.DOM = new tinymce.dom.DOMUtils(document, {process_html : 0});
4758 // Range constructor
4759 function Range(dom) {
4767 START_OFFSET = 'startOffset',
4768 START_CONTAINER = 'startContainer',
4769 END_CONTAINER = 'endContainer',
4770 END_OFFSET = 'endOffset',
4771 extend = tinymce.extend,
4772 nodeIndex = dom.nodeIndex;
4776 startContainer : doc,
4781 commonAncestorContainer : doc,
4790 setStart : setStart,
4792 setStartBefore : setStartBefore,
4793 setStartAfter : setStartAfter,
4794 setEndBefore : setEndBefore,
4795 setEndAfter : setEndAfter,
4796 collapse : collapse,
4797 selectNode : selectNode,
4798 selectNodeContents : selectNodeContents,
4799 compareBoundaryPoints : compareBoundaryPoints,
4800 deleteContents : deleteContents,
4801 extractContents : extractContents,
4802 cloneContents : cloneContents,
4803 insertNode : insertNode,
4804 surroundContents : surroundContents,
4805 cloneRange : cloneRange
4808 function setStart(n, o) {
4809 _setEndPoint(TRUE, n, o);
4812 function setEnd(n, o) {
4813 _setEndPoint(FALSE, n, o);
4816 function setStartBefore(n) {
4817 setStart(n.parentNode, nodeIndex(n));
4820 function setStartAfter(n) {
4821 setStart(n.parentNode, nodeIndex(n) + 1);
4824 function setEndBefore(n) {
4825 setEnd(n.parentNode, nodeIndex(n));
4828 function setEndAfter(n) {
4829 setEnd(n.parentNode, nodeIndex(n) + 1);
4832 function collapse(ts) {
4834 t[END_CONTAINER] = t[START_CONTAINER];
4835 t[END_OFFSET] = t[START_OFFSET];
4837 t[START_CONTAINER] = t[END_CONTAINER];
4838 t[START_OFFSET] = t[END_OFFSET];
4844 function selectNode(n) {
4849 function selectNodeContents(n) {
4851 setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length);
4854 function compareBoundaryPoints(h, r) {
4855 var sc = t[START_CONTAINER], so = t[START_OFFSET], ec = t[END_CONTAINER], eo = t[END_OFFSET],
4856 rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset;
4858 // Check START_TO_START
4860 return _compareBoundaryPoints(sc, so, rsc, rso);
4862 // Check START_TO_END
4864 return _compareBoundaryPoints(ec, eo, rsc, rso);
4868 return _compareBoundaryPoints(ec, eo, rec, reo);
4870 // Check END_TO_START
4872 return _compareBoundaryPoints(sc, so, rec, reo);
4875 function deleteContents() {
4879 function extractContents() {
4880 return _traverse(EXTRACT);
4883 function cloneContents() {
4884 return _traverse(CLONE);
4887 function insertNode(n) {
4888 var startContainer = this[START_CONTAINER],
4889 startOffset = this[START_OFFSET], nn, o;
4891 // Node is TEXT_NODE or CDATA
4892 if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) {
4894 // At the start of text
4895 startContainer.parentNode.insertBefore(n, startContainer);
4896 } else if (startOffset >= startContainer.nodeValue.length) {
4897 // At the end of text
4898 dom.insertAfter(n, startContainer);
4900 // Middle, need to split
4901 nn = startContainer.splitText(startOffset);
4902 startContainer.parentNode.insertBefore(n, nn);
4905 // Insert element node
4906 if (startContainer.childNodes.length > 0)
4907 o = startContainer.childNodes[startOffset];
4910 startContainer.insertBefore(n, o);
4912 startContainer.appendChild(n);
4916 function surroundContents(n) {
4917 var f = t.extractContents();
4924 function cloneRange() {
4925 return extend(new Range(dom), {
4926 startContainer : t[START_CONTAINER],
4927 startOffset : t[START_OFFSET],
4928 endContainer : t[END_CONTAINER],
4929 endOffset : t[END_OFFSET],
4930 collapsed : t.collapsed,
4931 commonAncestorContainer : t.commonAncestorContainer
4937 function _getSelectedNode(container, offset) {
4940 if (container.nodeType == 3 /* TEXT_NODE */)
4946 child = container.firstChild;
4947 while (child && offset > 0) {
4949 child = child.nextSibling;
4958 function _isCollapsed() {
4959 return (t[START_CONTAINER] == t[END_CONTAINER] && t[START_OFFSET] == t[END_OFFSET]);
4962 function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) {
4963 var c, offsetC, n, cmnRoot, childA, childB;
4965 // In the first case the boundary-points have the same container. A is before B
4966 // if its offset is less than the offset of B, A is equal to B if its offset is
4967 // equal to the offset of B, and A is after B if its offset is greater than the
4969 if (containerA == containerB) {
4970 if (offsetA == offsetB)
4973 if (offsetA < offsetB)
4974 return -1; // before
4979 // In the second case a child node C of the container of A is an ancestor
4980 // container of B. In this case, A is before B if the offset of A is less than or
4981 // equal to the index of the child node C and A is after B otherwise.
4983 while (c && c.parentNode != containerA)
4988 n = containerA.firstChild;
4990 while (n != c && offsetC < offsetA) {
4995 if (offsetA <= offsetC)
4996 return -1; // before
5001 // In the third case a child node C of the container of B is an ancestor container
5002 // of A. In this case, A is before B if the index of the child node C is less than
5003 // the offset of B and A is after B otherwise.
5005 while (c && c.parentNode != containerB) {
5011 n = containerB.firstChild;
5013 while (n != c && offsetC < offsetB) {
5018 if (offsetC < offsetB)
5019 return -1; // before
5024 // In the fourth case, none of three other cases hold: the containers of A and B
5025 // are siblings or descendants of sibling nodes. In this case, A is before B if
5026 // the container of A is before the container of B in a pre-order traversal of the
5027 // Ranges' context tree and A is after B otherwise.
5028 cmnRoot = dom.findCommonAncestor(containerA, containerB);
5029 childA = containerA;
5031 while (childA && childA.parentNode != cmnRoot)
5032 childA = childA.parentNode;
5037 childB = containerB;
5038 while (childB && childB.parentNode != cmnRoot)
5039 childB = childB.parentNode;
5044 if (childA == childB)
5047 n = cmnRoot.firstChild;
5050 return -1; // before
5059 function _setEndPoint(st, n, o) {
5063 t[START_CONTAINER] = n;
5064 t[START_OFFSET] = o;
5066 t[END_CONTAINER] = n;
5070 // If one boundary-point of a Range is set to have a root container
5071 // other than the current one for the Range, the Range is collapsed to
5072 // the new position. This enforces the restriction that both boundary-
5073 // points of a Range must have the same root container.
5074 ec = t[END_CONTAINER];
5075 while (ec.parentNode)
5078 sc = t[START_CONTAINER];
5079 while (sc.parentNode)
5083 // The start position of a Range is guaranteed to never be after the
5084 // end position. To enforce this restriction, if the start is set to
5085 // be at a position after the end, the Range is collapsed to that
5087 if (_compareBoundaryPoints(t[START_CONTAINER], t[START_OFFSET], t[END_CONTAINER], t[END_OFFSET]) > 0)
5092 t.collapsed = _isCollapsed();
5093 t.commonAncestorContainer = dom.findCommonAncestor(t[START_CONTAINER], t[END_CONTAINER]);
5096 function _traverse(how) {
5097 var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep;
5099 if (t[START_CONTAINER] == t[END_CONTAINER])
5100 return _traverseSameContainer(how);
5102 for (c = t[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
5103 if (p == t[START_CONTAINER])
5104 return _traverseCommonStartContainer(c, how);
5106 ++endContainerDepth;
5109 for (c = t[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
5110 if (p == t[END_CONTAINER])
5111 return _traverseCommonEndContainer(c, how);
5113 ++startContainerDepth;
5116 depthDiff = startContainerDepth - endContainerDepth;
5118 startNode = t[START_CONTAINER];
5119 while (depthDiff > 0) {
5120 startNode = startNode.parentNode;
5124 endNode = t[END_CONTAINER];
5125 while (depthDiff < 0) {
5126 endNode = endNode.parentNode;
5130 // ascend the ancestor hierarchy until we have a common parent.
5131 for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) {
5136 return _traverseCommonAncestors(startNode, endNode, how);
5139 function _traverseSameContainer(how) {
5140 var frag, s, sub, n, cnt, sibling, xferNode;
5143 frag = doc.createDocumentFragment();
5145 // If selection is empty, just return the fragment
5146 if (t[START_OFFSET] == t[END_OFFSET])
5149 // Text node needs special case handling
5150 if (t[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) {
5151 // get the substring
5152 s = t[START_CONTAINER].nodeValue;
5153 sub = s.substring(t[START_OFFSET], t[END_OFFSET]);
5155 // set the original text node to its new value
5157 t[START_CONTAINER].deleteData(t[START_OFFSET], t[END_OFFSET] - t[START_OFFSET]);
5159 // Nothing is partially selected, so collapse to start point
5166 frag.appendChild(doc.createTextNode(sub));
5170 // Copy nodes between the start/end offsets.
5171 n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]);
5172 cnt = t[END_OFFSET] - t[START_OFFSET];
5175 sibling = n.nextSibling;
5176 xferNode = _traverseFullySelected(n, how);
5179 frag.appendChild( xferNode );
5185 // Nothing is partially selected, so collapse to start point
5192 function _traverseCommonStartContainer(endAncestor, how) {
5193 var frag, n, endIdx, cnt, sibling, xferNode;
5196 frag = doc.createDocumentFragment();
5198 n = _traverseRightBoundary(endAncestor, how);
5201 frag.appendChild(n);
5203 endIdx = nodeIndex(endAncestor);
5204 cnt = endIdx - t[START_OFFSET];
5207 // Collapse to just before the endAncestor, which
5208 // is partially selected.
5210 t.setEndBefore(endAncestor);
5217 n = endAncestor.previousSibling;
5219 sibling = n.previousSibling;
5220 xferNode = _traverseFullySelected(n, how);
5223 frag.insertBefore(xferNode, frag.firstChild);
5229 // Collapse to just before the endAncestor, which
5230 // is partially selected.
5232 t.setEndBefore(endAncestor);
5239 function _traverseCommonEndContainer(startAncestor, how) {
5240 var frag, startIdx, n, cnt, sibling, xferNode;
5243 frag = doc.createDocumentFragment();
5245 n = _traverseLeftBoundary(startAncestor, how);
5247 frag.appendChild(n);
5249 startIdx = nodeIndex(startAncestor);
5250 ++startIdx; // Because we already traversed it
5252 cnt = t[END_OFFSET] - startIdx;
5253 n = startAncestor.nextSibling;
5255 sibling = n.nextSibling;
5256 xferNode = _traverseFullySelected(n, how);
5259 frag.appendChild(xferNode);
5266 t.setStartAfter(startAncestor);
5273 function _traverseCommonAncestors(startAncestor, endAncestor, how) {
5274 var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling;
5277 frag = doc.createDocumentFragment();
5279 n = _traverseLeftBoundary(startAncestor, how);
5281 frag.appendChild(n);
5283 commonParent = startAncestor.parentNode;
5284 startOffset = nodeIndex(startAncestor);
5285 endOffset = nodeIndex(endAncestor);
5288 cnt = endOffset - startOffset;
5289 sibling = startAncestor.nextSibling;
5292 nextSibling = sibling.nextSibling;
5293 n = _traverseFullySelected(sibling, how);
5296 frag.appendChild(n);
5298 sibling = nextSibling;
5302 n = _traverseRightBoundary(endAncestor, how);
5305 frag.appendChild(n);
5308 t.setStartAfter(startAncestor);
5315 function _traverseRightBoundary(root, how) {
5316 var next = _getSelectedNode(t[END_CONTAINER], t[END_OFFSET] - 1), parent, clonedParent, prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != t[END_CONTAINER];
5319 return _traverseNode(next, isFullySelected, FALSE, how);
5321 parent = next.parentNode;
5322 clonedParent = _traverseNode(parent, FALSE, FALSE, how);
5326 prevSibling = next.previousSibling;
5327 clonedChild = _traverseNode(next, isFullySelected, FALSE, how);
5330 clonedParent.insertBefore(clonedChild, clonedParent.firstChild);
5332 isFullySelected = TRUE;
5337 return clonedParent;
5339 next = parent.previousSibling;
5340 parent = parent.parentNode;
5342 clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how);
5345 clonedGrandParent.appendChild(clonedParent);
5347 clonedParent = clonedGrandParent;
5351 function _traverseLeftBoundary(root, how) {
5352 var next = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]), isFullySelected = next != t[START_CONTAINER], parent, clonedParent, nextSibling, clonedChild, clonedGrandParent;
5355 return _traverseNode(next, isFullySelected, TRUE, how);
5357 parent = next.parentNode;
5358 clonedParent = _traverseNode(parent, FALSE, TRUE, how);
5362 nextSibling = next.nextSibling;
5363 clonedChild = _traverseNode(next, isFullySelected, TRUE, how);
5366 clonedParent.appendChild(clonedChild);
5368 isFullySelected = TRUE;
5373 return clonedParent;
5375 next = parent.nextSibling;
5376 parent = parent.parentNode;
5378 clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how);
5381 clonedGrandParent.appendChild(clonedParent);
5383 clonedParent = clonedGrandParent;
5387 function _traverseNode(n, isFullySelected, isLeft, how) {
5388 var txtValue, newNodeValue, oldNodeValue, offset, newNode;
5390 if (isFullySelected)
5391 return _traverseFullySelected(n, how);
5393 if (n.nodeType == 3 /* TEXT_NODE */) {
5394 txtValue = n.nodeValue;
5397 offset = t[START_OFFSET];
5398 newNodeValue = txtValue.substring(offset);
5399 oldNodeValue = txtValue.substring(0, offset);
5401 offset = t[END_OFFSET];
5402 newNodeValue = txtValue.substring(0, offset);
5403 oldNodeValue = txtValue.substring(offset);
5407 n.nodeValue = oldNodeValue;
5412 newNode = n.cloneNode(FALSE);
5413 newNode.nodeValue = newNodeValue;
5421 return n.cloneNode(FALSE);
5424 function _traverseFullySelected(n, how) {
5426 return how == CLONE ? n.cloneNode(TRUE) : n;
5428 n.parentNode.removeChild(n);
5436 function Selection(selection) {
5437 var t = this, invisibleChar = '\uFEFF', range, lastIERng, dom = selection.dom, TRUE = true, FALSE = false;
5439 // Returns a W3C DOM compatible range object by using the IE Range API
5440 function getRange() {
5441 var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed;
5443 // If selection is outside the current document just return an empty range
5444 element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
5445 if (element.ownerDocument != dom.doc)
5448 collapsed = selection.isCollapsed();
5450 // Handle control selection or text selection of a image
5451 if (ieRange.item || !element.hasChildNodes()) {
5453 domRange.setStart(element, 0);
5454 domRange.setEnd(element, 0);
5456 domRange.setStart(element.parentNode, dom.nodeIndex(element));
5457 domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
5463 function findEndPoint(start) {
5464 var marker, container, offset, nodes, startIndex = 0, endIndex, index, parent, checkRng, position;
5466 // Setup temp range and collapse it
5467 checkRng = ieRange.duplicate();
5468 checkRng.collapse(start);
5470 // Create marker and insert it at the end of the endpoints parent
5471 marker = dom.create('a');
5472 parent = checkRng.parentElement();
5474 // If parent doesn't have any children then set the container to that parent and the index to 0
5475 if (!parent.hasChildNodes()) {
5476 domRange[start ? 'setStart' : 'setEnd'](parent, 0);
5480 parent.appendChild(marker);
5481 checkRng.moveToElementText(marker);
5482 position = ieRange.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', checkRng);
5484 // The position is after the end of the parent element.
5485 // This is the case where IE puts the caret to the left edge of a table.
5486 domRange[start ? 'setStartAfter' : 'setEndAfter'](parent);
5491 // Setup node list and endIndex
5492 nodes = tinymce.grep(parent.childNodes);
5493 endIndex = nodes.length - 1;
5494 // Perform a binary search for the position
5495 while (startIndex <= endIndex) {
5496 index = Math.floor((startIndex + endIndex) / 2);
5498 // Insert marker and check it's position relative to the selection
5499 parent.insertBefore(marker, nodes[index]);
5500 checkRng.moveToElementText(marker);
5501 position = ieRange.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', checkRng);
5503 // Marker is to the right
5504 startIndex = index + 1;
5505 } else if (position < 0) {
5506 // Marker is to the left
5507 endIndex = index - 1;
5509 // Maker is where we are
5516 container = position > 0 || index == 0 ? marker.nextSibling : marker.previousSibling;
5518 // Handle element selection
5519 if (container.nodeType == 1) {
5522 // Find offset and container
5523 offset = dom.nodeIndex(container);
5524 container = container.parentNode;
5526 // Move the offset if we are setting the end or the position is after an element
5527 if (!start || index > 0)
5530 // Calculate offset within text node
5531 if (position > 0 || index == 0) {
5532 checkRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', ieRange);
5533 offset = checkRng.text.length;
5535 checkRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', ieRange);
5536 offset = container.nodeValue.length - checkRng.text.length;
5542 domRange[start ? 'setStart' : 'setEnd'](container, offset);
5548 // Find end point if needed
5555 this.addRange = function(rng) {
5556 var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body;
5558 function setEndPoint(start) {
5559 var container, offset, marker, tmpRng, nodes;
5561 marker = dom.create('a');
5562 container = start ? startContainer : endContainer;
5563 offset = start ? startOffset : endOffset;
5564 tmpRng = ieRng.duplicate();
5566 if (container == doc || container == doc.documentElement) {
5571 if (container.nodeType == 3) {
5572 container.parentNode.insertBefore(marker, container);
5573 tmpRng.moveToElementText(marker);
5574 tmpRng.moveStart('character', offset);
5576 ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
5578 nodes = container.childNodes;
5581 if (offset >= nodes.length) {
5582 dom.insertAfter(marker, nodes[nodes.length - 1]);
5584 container.insertBefore(marker, nodes[offset]);
5587 tmpRng.moveToElementText(marker);
5589 // Empty node selection for example <div>|</div>
5590 marker = doc.createTextNode(invisibleChar);
5591 container.appendChild(marker);
5592 tmpRng.moveToElementText(marker.parentNode);
5593 tmpRng.collapse(TRUE);
5596 ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
5601 // Destroy cached range
5604 // Setup some shorter versions
5605 startContainer = rng.startContainer;
5606 startOffset = rng.startOffset;
5607 endContainer = rng.endContainer;
5608 endOffset = rng.endOffset;
5609 ieRng = body.createTextRange();
5611 // If single element selection then try making a control selection out of it
5612 if (startContainer == endContainer && startContainer.nodeType == 1 && startOffset == endOffset - 1) {
5613 if (startOffset == endOffset - 1) {
5615 ctrlRng = body.createControlRange();
5616 ctrlRng.addElement(startContainer.childNodes[startOffset]);
5625 // Set start/end point of selection
5629 // Select the new range and scroll it into view
5633 this.getRangeAt = function() {
5634 // Setup new range if the cache is empty
5635 if (!range || !tinymce.dom.RangeUtils.compareRanges(lastIERng, selection.getRng())) {
5638 // Store away text range for next call
5639 lastIERng = selection.getRng();
5642 // IE will say that the range is equal then produce an invalid argument exception
5643 // if you perform specific operations in a keyup event. For example Ctrl+Del.
5644 // This hack will invalidate the range cache if the exception occurs
5646 range.startContainer.nextSibling;
5652 // Return cached range
5656 this.destroy = function() {
5657 // Destroy cached range and last IE range to avoid memory leaks
5658 lastIERng = range = null;
5662 // Expose the selection object
5663 tinymce.dom.TridentSelection = Selection;
5667 (function(tinymce) {
5669 var each = tinymce.each, DOM = tinymce.DOM, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, Event;
5671 tinymce.create('tinymce.dom.EventUtils', {
5672 EventUtils : function() {
5677 add : function(o, n, f, s) {
5678 var cb, t = this, el = t.events, r;
5680 if (n instanceof Array) {
5683 each(n, function(n) {
5684 r.push(t.add(o, n, f, s));
5691 if (o && o.hasOwnProperty && o instanceof Array) {
5694 each(o, function(o) {
5696 r.push(t.add(o, n, f, s));
5707 // Setup event callback
5709 // Is all events disabled
5713 e = e || window.event;
5715 // Patch in target, preventDefault and stopPropagation in IE it's W3C valid
5718 e.target = e.srcElement;
5720 // Patch in preventDefault, stopPropagation methods for W3C compatibility
5721 tinymce.extend(e, t._stoppers);
5727 return f.call(s, e);
5730 if (n == 'unload') {
5731 tinymce.unloads.unshift({func : cb});
5744 // Store away listener reference
5758 remove : function(o, n, f) {
5759 var t = this, a = t.events, s = false, r;
5762 if (o && o.hasOwnProperty && o instanceof Array) {
5765 each(o, function(o) {
5767 r.push(t.remove(o, n, f));
5775 each(a, function(e, i) {
5776 if (e.obj == o && e.name == n && (!f || (e.func == f || e.cfunc == f))) {
5778 t._remove(o, n, e.cfunc);
5787 clear : function(o) {
5788 var t = this, a = t.events, i, e;
5793 for (i = a.length - 1; i >= 0; i--) {
5797 t._remove(e.obj, e.name, e.cfunc);
5798 e.obj = e.cfunc = null;
5805 cancel : function(e) {
5811 return this.prevent(e);
5814 stop : function(e) {
5815 if (e.stopPropagation)
5816 e.stopPropagation();
5818 e.cancelBubble = true;
5823 prevent : function(e) {
5824 if (e.preventDefault)
5827 e.returnValue = false;
5832 destroy : function() {
5835 each(t.events, function(e, i) {
5836 t._remove(e.obj, e.name, e.cfunc);
5837 e.obj = e.cfunc = null;
5844 _add : function(o, n, f) {
5846 o.attachEvent('on' + n, f);
5847 else if (o.addEventListener)
5848 o.addEventListener(n, f, false);
5853 _remove : function(o, n, f) {
5857 o.detachEvent('on' + n, f);
5858 else if (o.removeEventListener)
5859 o.removeEventListener(n, f, false);
5863 // Might fail with permission denined on IE so we just ignore that
5868 _pageInit : function(win) {
5871 // Keep it from running more than once
5877 each(t.inits, function(c) {
5884 _wait : function(win) {
5885 var t = this, doc = win.document;
5887 // No need since the document is already loaded
5888 if (win.tinyMCE_GZ && tinyMCE_GZ.loaded) {
5894 if (doc.attachEvent) {
5895 doc.attachEvent("onreadystatechange", function() {
5896 if (doc.readyState === "complete") {
5897 doc.detachEvent("onreadystatechange", arguments.callee);
5902 if (doc.documentElement.doScroll && win == win.top) {
5908 // If IE is used, use the trick by Diego Perini
5909 // http://javascript.nwbox.com/IEContentLoaded/
5910 doc.documentElement.doScroll("left");
5912 setTimeout(arguments.callee, 0);
5919 } else if (doc.addEventListener) {
5920 t._add(win, 'DOMContentLoaded', function() {
5925 t._add(win, 'load', function() {
5931 preventDefault : function() {
5932 this.returnValue = false;
5935 stopPropagation : function() {
5936 this.cancelBubble = true;
5941 Event = tinymce.dom.Event = new tinymce.dom.EventUtils();
5943 // Dispatch DOM content loaded event for IE and Safari
5944 Event._wait(window);
5946 tinymce.addUnload(function() {
5951 (function(tinymce) {
5952 tinymce.dom.Element = function(id, settings) {
5953 var t = this, dom, el;
5955 t.settings = settings = settings || {};
5957 t.dom = dom = settings.dom || tinymce.DOM;
5959 // Only IE leaks DOM references, this is a lot faster
5964 ('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' +
5965 'setAttrib,setAttribs,getAttrib,addClass,removeClass,' +
5966 'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' +
5967 'isHidden,setHTML,get').split(/,/)
5972 for (i = 0; i < arguments.length; i++)
5973 a.push(arguments[i]);
5975 a = dom[k].apply(dom, a);
5983 on : function(n, f, s) {
5984 return tinymce.dom.Event.add(t.id, n, f, s);
5987 getXY : function() {
5989 x : parseInt(t.getStyle('left')),
5990 y : parseInt(t.getStyle('top'))
5994 getSize : function() {
5995 var n = dom.get(t.id);
5998 w : parseInt(t.getStyle('width') || n.clientWidth),
5999 h : parseInt(t.getStyle('height') || n.clientHeight)
6003 moveTo : function(x, y) {
6004 t.setStyles({left : x, top : y});
6007 moveBy : function(x, y) {
6010 t.moveTo(p.x + x, p.y + y);
6013 resizeTo : function(w, h) {
6014 t.setStyles({width : w, height : h});
6017 resizeBy : function(w, h) {
6018 var s = t.getSize();
6020 t.resizeTo(s.w + w, s.h + h);
6023 update : function(k) {
6026 if (tinymce.isIE6 && settings.blocker) {
6030 if (k.indexOf('get') === 0 || k.indexOf('has') === 0 || k.indexOf('is') === 0)
6033 // Remove blocker on remove
6034 if (k == 'remove') {
6035 dom.remove(t.blocker);
6040 t.blocker = dom.uniqueId();
6041 b = dom.add(settings.container || dom.getRoot(), 'iframe', {id : t.blocker, style : 'position:absolute;', frameBorder : 0, src : 'javascript:""'});
6042 dom.setStyle(b, 'opacity', 0);
6044 b = dom.get(t.blocker);
6047 left : t.getStyle('left', 1),
6048 top : t.getStyle('top', 1),
6049 width : t.getStyle('width', 1),
6050 height : t.getStyle('height', 1),
6051 display : t.getStyle('display', 1),
6052 zIndex : parseInt(t.getStyle('zIndex', 1) || 0) - 1
6060 (function(tinymce) {
6061 function trimNl(s) {
6062 return s.replace(/[\n\r]+/g, '');
6066 var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each;
6068 tinymce.create('tinymce.dom.Selection', {
6069 Selection : function(dom, win, serializer) {
6074 t.serializer = serializer;
6078 'onBeforeSetContent',
6080 'onBeforeGetContent',
6086 t[e] = new tinymce.util.Dispatcher(t);
6089 // No W3C Range support
6090 if (!t.win.getSelection)
6091 t.tridentSel = new tinymce.dom.TridentSelection(t);
6093 if (tinymce.isIE && dom.boxModel)
6094 this._fixIESelection();
6097 tinymce.addUnload(t.destroy, t);
6100 getContent : function(s) {
6101 var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n;
6106 s.format = s.format || 'html';
6107 t.onBeforeGetContent.dispatch(t, s);
6109 if (s.format == 'text')
6110 return t.isCollapsed() ? '' : (r.text || (se.toString ? se.toString() : ''));
6112 if (r.cloneContents) {
6113 n = r.cloneContents();
6117 } else if (is(r.item) || is(r.htmlText))
6118 e.innerHTML = r.item ? r.item(0).outerHTML : r.htmlText;
6120 e.innerHTML = r.toString();
6122 // Keep whitespace before and after
6123 if (/^\s/.test(e.innerHTML))
6126 if (/\s+$/.test(e.innerHTML))
6131 s.content = t.isCollapsed() ? '' : wb + t.serializer.serialize(e, s) + wa;
6132 t.onGetContent.dispatch(t, s);
6137 setContent : function(content, args) {
6138 var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp;
6140 args = args || {format : 'html'};
6142 content = args.content = content;
6144 // Dispatch before set content event
6145 if (!args.no_events)
6146 self.onBeforeSetContent.dispatch(self, args);
6148 content = args.content;
6150 if (rng.insertNode) {
6151 // Make caret marker since insertNode places the caret in the beginning of text after insert
6152 content += '<span id="__caret">_</span>';
6154 // Delete and insert new node
6155 if (rng.startContainer == doc && rng.endContainer == doc) {
6156 // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents
6157 doc.body.innerHTML = content;
6159 rng.deleteContents();
6161 if (doc.body.childNodes.length == 0) {
6162 doc.body.innerHTML = content;
6164 // createContextualFragment doesn't exists in IE 9 DOMRanges
6165 if (rng.createContextualFragment) {
6166 rng.insertNode(rng.createContextualFragment(content));
6168 // Fake createContextualFragment call in IE 9
6169 frag = doc.createDocumentFragment();
6170 temp = doc.createElement('div');
6172 frag.appendChild(temp);
6173 temp.outerHTML = content;
6175 rng.insertNode(frag);
6180 // Move to caret marker
6181 caretNode = self.dom.get('__caret');
6183 // Make sure we wrap it compleatly, Opera fails with a simple select call
6184 rng = doc.createRange();
6185 rng.setStartBefore(caretNode);
6186 rng.setEndBefore(caretNode);
6189 // Remove the caret position
6190 self.dom.remove('__caret');
6194 // Delete content and get caret text selection
6195 doc.execCommand('Delete', false, null);
6196 rng = self.getRng();
6199 rng.pasteHTML(content);
6202 // Dispatch set content event
6203 if (!args.no_events)
6204 self.onSetContent.dispatch(self, args);
6207 getStart : function() {
6208 var rng = this.getRng(), startElement, parentElement, checkRng, node;
6210 if (rng.duplicate || rng.item) {
6211 // Control selection, return first item
6215 // Get start element
6216 checkRng = rng.duplicate();
6217 checkRng.collapse(1);
6218 startElement = checkRng.parentElement();
6220 // Check if range parent is inside the start element, then return the inner parent element
6221 // This will fix issues when a single element is selected, IE would otherwise return the wrong start element
6222 parentElement = node = rng.parentElement();
6223 while (node = node.parentNode) {
6224 if (node == startElement) {
6225 startElement = parentElement;
6230 return startElement;
6232 startElement = rng.startContainer;
6234 if (startElement.nodeType == 1 && startElement.hasChildNodes())
6235 startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)];
6237 if (startElement && startElement.nodeType == 3)
6238 return startElement.parentNode;
6240 return startElement;
6244 getEnd : function() {
6245 var t = this, r = t.getRng(), e, eo;
6247 if (r.duplicate || r.item) {
6253 e = r.parentElement();
6255 if (e && e.nodeName == 'BODY')
6256 return e.lastChild || e;
6263 if (e.nodeType == 1 && e.hasChildNodes())
6264 e = e.childNodes[eo > 0 ? eo - 1 : eo];
6266 if (e && e.nodeType == 3)
6267 return e.parentNode;
6273 getBookmark : function(type, normalized) {
6274 var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, index, chr = '\uFEFF', styles;
6276 function findIndex(name, element) {
6279 each(dom.select(name), function(node, i) {
6280 if (node == element)
6288 function getLocation() {
6289 var rng = t.getRng(true), root = dom.getRoot(), bookmark = {};
6291 function getPoint(rng, start) {
6292 var container = rng[start ? 'startContainer' : 'endContainer'],
6293 offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
6295 if (container.nodeType == 3) {
6297 for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling)
6298 offset += node.nodeValue.length;
6303 childNodes = container.childNodes;
6305 if (offset >= childNodes.length && childNodes.length) {
6307 offset = Math.max(0, childNodes.length - 1);
6310 point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after);
6313 for (; container && container != root; container = container.parentNode)
6314 point.push(t.dom.nodeIndex(container, normalized));
6319 bookmark.start = getPoint(rng, true);
6321 if (!t.isCollapsed())
6322 bookmark.end = getPoint(rng);
6327 return getLocation();
6330 // Handle simple range
6332 return {rng : t.getRng()};
6335 id = dom.uniqueId();
6336 collapsed = tinyMCE.activeEditor.selection.isCollapsed();
6337 styles = 'overflow:hidden;line-height:0px';
6340 if (rng.duplicate || rng.item) {
6343 rng2 = rng.duplicate();
6346 // Insert start marker
6348 rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>');
6350 // Insert end marker
6352 rng2.collapse(false);
6354 // Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p>
6355 rng.moveToElementText(rng2.parentElement());
6356 if (rng.compareEndPoints('StartToEnd', rng2) == 0)
6357 rng2.move('character', -1);
6359 rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');
6362 // IE might throw unspecified error so lets ignore it
6366 // Control selection
6367 element = rng.item(0);
6368 name = element.nodeName;
6370 return {name : name, index : findIndex(name, element)};
6373 element = t.getNode();
6374 name = element.nodeName;
6376 return {name : name, index : findIndex(name, element)};
6379 rng2 = rng.cloneRange();
6381 // Insert end marker
6383 rng2.collapse(false);
6384 rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr));
6388 rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr));
6391 t.moveToBookmark({id : id, keep : 1});
6396 moveToBookmark : function(bookmark) {
6397 var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset;
6399 // Clear selection cache
6401 t.tridentSel.destroy();
6404 if (bookmark.start) {
6405 rng = dom.createRng();
6406 root = dom.getRoot();
6408 function setEndPoint(start) {
6409 var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;
6414 // Find container node
6415 for (node = root, i = point.length - 1; i >= 1; i--) {
6416 children = node.childNodes;
6418 if (point[i] > children.length - 1)
6421 node = children[point[i]];
6424 // Move text offset to best suitable location
6425 if (node.nodeType === 3)
6426 offset = Math.min(point[0], node.nodeValue.length);
6428 // Move element offset to best suitable location
6429 if (node.nodeType === 1)
6430 offset = Math.min(point[0], node.childNodes.length);
6432 // Set offset within container node
6434 rng.setStart(node, offset);
6436 rng.setEnd(node, offset);
6442 if (setEndPoint(true) && setEndPoint()) {
6445 } else if (bookmark.id) {
6446 function restoreEndPoint(suffix) {
6447 var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;
6450 node = marker.parentNode;
6452 if (suffix == 'start') {
6454 idx = dom.nodeIndex(marker);
6456 node = marker.firstChild;
6460 startContainer = endContainer = node;
6461 startOffset = endOffset = idx;
6464 idx = dom.nodeIndex(marker);
6466 node = marker.firstChild;
6470 endContainer = node;
6475 prev = marker.previousSibling;
6476 next = marker.nextSibling;
6478 // Remove all marker text nodes
6479 each(tinymce.grep(marker.childNodes), function(node) {
6480 if (node.nodeType == 3)
6481 node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
6484 // Remove marker but keep children if for example contents where inserted into the marker
6485 // Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature
6486 while (marker = dom.get(bookmark.id + '_' + suffix))
6487 dom.remove(marker, 1);
6489 // If siblings are text nodes then merge them unless it's Opera since it some how removes the node
6490 // and we are sniffing since adding a lot of detection code for a browser with 3% of the market isn't worth the effort. Sorry, Opera but it's just a fact
6491 if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) {
6492 idx = prev.nodeValue.length;
6493 prev.appendData(next.nodeValue);
6496 if (suffix == 'start') {
6497 startContainer = endContainer = prev;
6498 startOffset = endOffset = idx;
6500 endContainer = prev;
6508 function addBogus(node) {
6509 // Adds a bogus BR element for empty block elements or just a space on IE since it renders BR elements incorrectly
6510 if (dom.isBlock(node) && !node.innerHTML)
6511 node.innerHTML = !isIE ? '<br data-mce-bogus="1" />' : ' ';
6516 // Restore start/end points
6517 restoreEndPoint('start');
6518 restoreEndPoint('end');
6520 if (startContainer) {
6521 rng = dom.createRng();
6522 rng.setStart(addBogus(startContainer), startOffset);
6523 rng.setEnd(addBogus(endContainer), endOffset);
6526 } else if (bookmark.name) {
6527 t.select(dom.select(bookmark.name)[bookmark.index]);
6528 } else if (bookmark.rng)
6529 t.setRng(bookmark.rng);
6533 select : function(node, content) {
6534 var t = this, dom = t.dom, rng = dom.createRng(), idx;
6537 idx = dom.nodeIndex(node);
6538 rng.setStart(node.parentNode, idx);
6539 rng.setEnd(node.parentNode, idx + 1);
6541 // Find first/last text node or BR element
6543 function setPoint(node, start) {
6544 var walker = new tinymce.dom.TreeWalker(node, node);
6548 if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) {
6550 rng.setStart(node, 0);
6552 rng.setEnd(node, node.nodeValue.length);
6558 if (node.nodeName == 'BR') {
6560 rng.setStartBefore(node);
6562 rng.setEndBefore(node);
6566 } while (node = (start ? walker.next() : walker.prev()));
6579 isCollapsed : function() {
6580 var t = this, r = t.getRng(), s = t.getSel();
6585 if (r.compareEndPoints)
6586 return r.compareEndPoints('StartToEnd', r) === 0;
6588 return !s || r.collapsed;
6591 collapse : function(to_start) {
6592 var self = this, rng = self.getRng(), node;
6594 // Control range on IE
6597 rng = self.win.document.body.createTextRange();
6598 rng.moveToElementText(node);
6601 rng.collapse(!!to_start);
6605 getSel : function() {
6606 var t = this, w = this.win;
6608 return w.getSelection ? w.getSelection() : w.document.selection;
6611 getRng : function(w3c) {
6612 var t = this, s, r, elm, doc = t.win.document;
6614 // Found tridentSel object then we need to use that one
6615 if (w3c && t.tridentSel)
6616 return t.tridentSel.getRangeAt(0);
6620 r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange());
6622 // IE throws unspecified error here if TinyMCE is placed in a frame/iframe
6625 // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet
6626 if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) {
6627 elm = doc.selection.createRange().item(0);
6628 r = doc.createRange();
6629 r.setStartBefore(elm);
6633 // No range found then create an empty one
6634 // This can occur when the editor is placed in a hidden container element on Gecko
6635 // Or on IE when there was an exception
6637 r = doc.createRange ? doc.createRange() : doc.body.createTextRange();
6639 if (t.selectedRange && t.explicitRange) {
6640 if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) {
6641 // Safari, Opera and Chrome only ever select text which causes the range to change.
6642 // This lets us use the originally set range if the selection hasn't been changed by the user.
6643 r = t.explicitRange;
6645 t.selectedRange = null;
6646 t.explicitRange = null;
6653 setRng : function(r) {
6656 if (!t.tridentSel) {
6660 t.explicitRange = r;
6663 s.removeAllRanges();
6665 // IE9 might throw errors here don't know why
6669 t.selectedRange = s.getRangeAt(0);
6674 t.tridentSel.addRange(r);
6678 // Is IE specific range
6682 // Needed for some odd IE bug #1843306
6687 setNode : function(n) {
6690 t.setContent(t.dom.getOuterHTML(n));
6695 getNode : function() {
6696 var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer;
6698 // Range maybe lost after the editor is made visible again
6700 return t.dom.getRoot();
6703 elm = rng.commonAncestorContainer;
6705 // Handle selection a image or other control like element such as anchors
6706 if (!rng.collapsed) {
6707 if (rng.startContainer == rng.endContainer) {
6708 if (rng.endOffset - rng.startOffset < 2) {
6709 if (rng.startContainer.hasChildNodes())
6710 elm = rng.startContainer.childNodes[rng.startOffset];
6714 // If the anchor node is a element instead of a text node then return this element
6715 //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1)
6716 // return sel.anchorNode.childNodes[sel.anchorOffset];
6718 // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.
6719 // This happens when you double click an underlined word in FireFox.
6720 if (start.nodeType === 3 && end.nodeType === 3) {
6721 function skipEmptyTextNodes(n, forwards) {
6723 while (n && n.nodeType === 3 && n.length === 0) {
6724 n = forwards ? n.nextSibling : n.previousSibling;
6728 if (start.length === rng.startOffset) {
6729 start = skipEmptyTextNodes(start.nextSibling, true);
6731 start = start.parentNode;
6733 if (rng.endOffset === 0) {
6734 end = skipEmptyTextNodes(end.previousSibling, false);
6736 end = end.parentNode;
6739 if (start && start === end)
6744 if (elm && elm.nodeType == 3)
6745 return elm.parentNode;
6750 return rng.item ? rng.item(0) : rng.parentElement();
6753 getSelectedBlocks : function(st, en) {
6754 var t = this, dom = t.dom, sb, eb, n, bl = [];
6756 sb = dom.getParent(st || t.getStart(), dom.isBlock);
6757 eb = dom.getParent(en || t.getEnd(), dom.isBlock);
6762 if (sb && eb && sb != eb) {
6765 while ((n = n.nextSibling) && n != eb) {
6777 destroy : function(s) {
6783 t.tridentSel.destroy();
6785 // Manual destroy then remove unload handler
6787 tinymce.removeUnload(t.destroy);
6790 // IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode
6791 _fixIESelection : function() {
6792 var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm;
6794 // Make HTML element unselectable since we are going to handle selection by hand
6795 doc.documentElement.unselectable = true;
6797 // Return range from point or null if it failed
6798 function rngFromPoint(x, y) {
6799 var rng = body.createTextRange();
6802 rng.moveToPoint(x, y);
6804 // IE sometimes throws and exception, so lets just ignore it
6811 // Fires while the selection is changing
6812 function selectionChange(e) {
6815 // Check if the button is down or not
6817 // Create range from mouse position
6818 pointRng = rngFromPoint(e.x, e.y);
6821 // Check if pointRange is before/after selection then change the endPoint
6822 if (pointRng.compareEndPoints('StartToStart', startRng) > 0)
6823 pointRng.setEndPoint('StartToStart', startRng);
6825 pointRng.setEndPoint('EndToEnd', startRng);
6833 // Removes listeners
6834 function endSelection() {
6835 var rng = doc.selection.createRange();
6837 // If the range is collapsed then use the last start range
6838 if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0)
6841 dom.unbind(doc, 'mouseup', endSelection);
6842 dom.unbind(doc, 'mousemove', selectionChange);
6843 startRng = started = 0;
6846 // Detect when user selects outside BODY
6847 dom.bind(doc, ['mousedown', 'contextmenu'], function(e) {
6848 if (e.target.nodeName === 'HTML') {
6852 // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML
6853 htmlElm = doc.documentElement;
6854 if (htmlElm.scrollHeight > htmlElm.clientHeight)
6858 // Setup start position
6859 startRng = rngFromPoint(e.x, e.y);
6861 // Listen for selection change events
6862 dom.bind(doc, 'mouseup', endSelection);
6863 dom.bind(doc, 'mousemove', selectionChange);
6874 (function(tinymce) {
6875 tinymce.dom.Serializer = function(settings, dom, schema) {
6876 var onPreProcess, onPostProcess, isIE = tinymce.isIE, each = tinymce.each, htmlParser;
6878 // Support the old apply_source_formatting option
6879 if (!settings.apply_source_formatting)
6880 settings.indent = false;
6882 settings.remove_trailing_brs = true;
6884 // Default DOM and Schema if they are undefined
6885 dom = dom || tinymce.DOM;
6886 schema = schema || new tinymce.html.Schema(settings);
6887 settings.entity_encoding = settings.entity_encoding || 'named';
6889 onPreProcess = new tinymce.util.Dispatcher(self);
6891 onPostProcess = new tinymce.util.Dispatcher(self);
6893 htmlParser = new tinymce.html.DomParser(settings, schema);
6895 // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed
6896 htmlParser.addAttributeFilter('src,href,style', function(nodes, name) {
6897 var i = nodes.length, node, value, internalName = 'data-mce-' + name, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef;
6902 value = node.attributes.map[internalName];
6903 if (value !== undef) {
6904 // Set external name to internal value and remove internal
6905 node.attr(name, value.length > 0 ? value : null);
6906 node.attr(internalName, null);
6908 // No internal attribute found then convert the value we have in the DOM
6909 value = node.attributes.map[name];
6911 if (name === "style")
6912 value = dom.serializeStyle(dom.parseStyle(value), node.name);
6913 else if (urlConverter)
6914 value = urlConverter.call(urlConverterScope, value, name, node.name);
6916 node.attr(name, value.length > 0 ? value : null);
6921 // Remove internal classes mceItem<..>
6922 htmlParser.addAttributeFilter('class', function(nodes, name) {
6923 var i = nodes.length, node, value;
6927 value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, '');
6928 node.attr('class', value.length > 0 ? value : null);
6932 // Remove bookmark elements
6933 htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) {
6934 var i = nodes.length, node;
6939 if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup)
6944 // Force script into CDATA sections and remove the mce- prefix also add comments around styles
6945 htmlParser.addNodeFilter('script,style', function(nodes, name) {
6946 var i = nodes.length, node, value;
6948 function trim(value) {
6949 return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')
6950 .replace(/^[\r\n]*|[\r\n]*$/g, '')
6951 .replace(/^\s*(\/\/\s*<!--|\/\/\s*<!\[CDATA\[|<!--|<!\[CDATA\[)[\r\n]*/g, '')
6952 .replace(/\s*(\/\/\s*\]\]>|\/\/\s*-->|\]\]>|-->|\]\]-->)\s*$/g, '');
6957 value = node.firstChild ? node.firstChild.value : '';
6959 if (name === "script") {
6960 // Remove mce- prefix from script elements
6961 node.attr('type', (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''));
6963 if (value.length > 0)
6964 node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
6966 if (value.length > 0)
6967 node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
6972 // Convert comments to cdata and handle protected comments
6973 htmlParser.addNodeFilter('#comment', function(nodes, name) {
6974 var i = nodes.length, node;
6979 if (node.value.indexOf('[CDATA[') === 0) {
6980 node.name = '#cdata';
6982 node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');
6983 } else if (node.value.indexOf('mce:protected ') === 0) {
6984 node.name = "#text";
6987 node.value = unescape(node.value).substr(14);
6992 htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) {
6993 var i = nodes.length, node;
6997 if (node.type === 7)
6999 else if (node.type === 1) {
7000 if (name === "input" && !("type" in node.attributes.map))
7001 node.attr('type', 'text');
7006 // Fix list elements, TODO: Replace this later
7007 if (settings.fix_list_elements) {
7008 htmlParser.addNodeFilter('ul,ol', function(nodes, name) {
7009 var i = nodes.length, node, parentNode;
7013 parentNode = node.parent;
7015 if (parentNode.name === 'ul' || parentNode.name === 'ol') {
7016 if (node.prev && node.prev.name === 'li') {
7017 node.prev.append(node);
7024 // Remove internal data attributes
7025 htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style', function(nodes, name) {
7026 var i = nodes.length;
7029 nodes[i].attr(name, null);
7033 // Return public methods
7037 addNodeFilter : htmlParser.addNodeFilter,
7039 addAttributeFilter : htmlParser.addAttributeFilter,
7041 onPreProcess : onPreProcess,
7043 onPostProcess : onPostProcess,
7045 serialize : function(node, args) {
7046 var impl, doc, oldDoc, htmlSerializer, content;
7048 // Explorer won't clone contents of script and style and the
7049 // selected index of select elements are cleared on a clone operation.
7050 if (isIE && dom.select('script,style,select').length > 0) {
7051 content = node.innerHTML;
7052 node = node.cloneNode(false);
7053 dom.setHTML(node, content);
7055 node = node.cloneNode(true);
7057 // Nodes needs to be attached to something in WebKit/Opera
7058 // Older builds of Opera crashes if you attach the node to an document created dynamically
7059 // and since we can't feature detect a crash we need to sniff the acutal build number
7060 // This fix will make DOM ranges and make Sizzle happy!
7061 impl = node.ownerDocument.implementation;
7062 if (impl.createHTMLDocument) {
7063 // Create an empty HTML document
7064 doc = impl.createHTMLDocument("");
7066 // Add the element or it's children if it's a body element to the new document
7067 each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) {
7068 doc.body.appendChild(doc.importNode(node, true));
7071 // Grab first child or body element for serialization
7072 if (node.nodeName != 'BODY')
7073 node = doc.body.firstChild;
7077 // set the new document in DOMUtils so createElement etc works
7083 args.format = args.format || 'html';
7086 if (!args.no_events) {
7088 onPreProcess.dispatch(self, args);
7092 htmlSerializer = new tinymce.html.Serializer(settings, schema);
7094 // Parse and serialize HTML
7095 args.content = htmlSerializer.serialize(
7096 htmlParser.parse(args.getInner ? node.innerHTML : tinymce.trim(dom.getOuterHTML(node), args), args)
7099 // Replace all BOM characters for now until we can find a better solution
7101 args.content = args.content.replace(/\uFEFF/g, '');
7104 if (!args.no_events)
7105 onPostProcess.dispatch(self, args);
7107 // Restore the old document if it was changed
7113 return args.content;
7116 addRules : function(rules) {
7117 schema.addValidElements(rules);
7120 setRules : function(rules) {
7121 schema.setValidElements(rules);
7126 (function(tinymce) {
7127 tinymce.dom.ScriptLoader = function(settings) {
7133 scriptLoadedCallbacks = {},
7134 queueLoadedCallbacks = [],
7138 function loadScript(url, callback) {
7139 var t = this, dom = tinymce.DOM, elm, uri, loc, id;
7141 // Execute callback when script is loaded
7146 elm.onreadystatechange = elm.onload = elm = null;
7152 // Report the error so it's easier for people to spot loading errors
7153 if (typeof(console) !== "undefined" && console.log)
7154 console.log("Failed to load: " + url);
7156 // We can't mark it as done if there is a load error since
7157 // A) We don't want to produce 404 errors on the server and
7158 // B) the onerror event won't fire on all browsers.
7162 id = dom.uniqueId();
7164 if (tinymce.isIE6) {
7165 uri = new tinymce.util.URI(url);
7168 // If script is from same domain and we
7169 // use IE 6 then use XHR since it's more reliable
7170 if (uri.host == loc.hostname && uri.port == loc.port && (uri.protocol + ':') == loc.protocol && uri.protocol.toLowerCase() != 'file') {
7171 tinymce.util.XHR.send({
7172 url : tinymce._addVer(uri.getURI()),
7173 success : function(content) {
7174 // Create new temp script element
7175 var script = dom.create('script', {
7176 type : 'text/javascript'
7179 // Evaluate script in global scope
7180 script.text = content;
7181 document.getElementsByTagName('head')[0].appendChild(script);
7194 // Create new script element
7195 elm = dom.create('script', {
7197 type : 'text/javascript',
7198 src : tinymce._addVer(url)
7201 // Add onload listener for non IE browsers since IE9
7202 // fires onload event before the script is parsed and executed
7206 // Add onerror event will get fired on some browsers but not all of them
7207 elm.onerror = error;
7209 // Opera 9.60 doesn't seem to fire the onreadystate event at correctly
7210 if (!tinymce.isOpera) {
7211 elm.onreadystatechange = function() {
7212 var state = elm.readyState;
7214 // Loaded state is passed on IE 6 however there
7215 // are known issues with this method but we can't use
7216 // XHR in a cross domain loading
7217 if (state == 'complete' || state == 'loaded')
7222 // Most browsers support this feature so we report errors
7223 // for those at least to help users track their missing plugins etc
7224 // todo: Removed since it produced error if the document is unloaded by navigating away, re-add it as an option
7225 /*elm.onerror = function() {
7226 alert('Failed to load: ' + url);
7229 // Add script to document
7230 (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
7233 this.isDone = function(url) {
7234 return states[url] == LOADED;
7237 this.markDone = function(url) {
7238 states[url] = LOADED;
7241 this.add = this.load = function(url, callback, scope) {
7242 var item, state = states[url];
7244 // Add url to load queue
7245 if (state == undefined) {
7247 states[url] = QUEUED;
7251 // Store away callback for later execution
7252 if (!scriptLoadedCallbacks[url])
7253 scriptLoadedCallbacks[url] = [];
7255 scriptLoadedCallbacks[url].push({
7257 scope : scope || this
7262 this.loadQueue = function(callback, scope) {
7263 this.loadScripts(queue, callback, scope);
7266 this.loadScripts = function(scripts, callback, scope) {
7269 function execScriptLoadedCallbacks(url) {
7270 // Execute URL callback functions
7271 tinymce.each(scriptLoadedCallbacks[url], function(callback) {
7272 callback.func.call(callback.scope);
7275 scriptLoadedCallbacks[url] = undefined;
7278 queueLoadedCallbacks.push({
7280 scope : scope || this
7283 loadScripts = function() {
7284 var loadingScripts = tinymce.grep(scripts);
7286 // Current scripts has been handled
7289 // Load scripts that needs to be loaded
7290 tinymce.each(loadingScripts, function(url) {
7291 // Script is already loaded then execute script callbacks directly
7292 if (states[url] == LOADED) {
7293 execScriptLoadedCallbacks(url);
7297 // Is script not loading then start loading it
7298 if (states[url] != LOADING) {
7299 states[url] = LOADING;
7302 loadScript(url, function() {
7303 states[url] = LOADED;
7306 execScriptLoadedCallbacks(url);
7308 // Load more scripts if they where added by the recently loaded script
7314 // No scripts are currently loading then execute all pending queue loaded callbacks
7316 tinymce.each(queueLoadedCallbacks, function(callback) {
7317 callback.func.call(callback.scope);
7320 queueLoadedCallbacks.length = 0;
7328 // Global script loader
7329 tinymce.ScriptLoader = new tinymce.dom.ScriptLoader();
7332 tinymce.dom.TreeWalker = function(start_node, root_node) {
7333 var node = start_node;
7335 function findSibling(node, start_name, sibling_name, shallow) {
7336 var sibling, parent;
7339 // Walk into nodes if it has a start
7340 if (!shallow && node[start_name])
7341 return node[start_name];
7343 // Return the sibling if it has one
7344 if (node != root_node) {
7345 sibling = node[sibling_name];
7349 // Walk up the parents to look for siblings
7350 for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
7351 sibling = parent[sibling_name];
7359 this.current = function() {
7363 this.next = function(shallow) {
7364 return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));
7367 this.prev = function(shallow) {
7368 return (node = findSibling(node, 'lastChild', 'previousSibling', shallow));
7372 (function(tinymce) {
7373 tinymce.dom.RangeUtils = function(dom) {
7374 var INVISIBLE_CHAR = '\uFEFF';
7376 this.walk = function(rng, callback) {
7377 var startContainer = rng.startContainer,
7378 startOffset = rng.startOffset,
7379 endContainer = rng.endContainer,
7380 endOffset = rng.endOffset,
7381 ancestor, startPoint,
7382 endPoint, node, parent, siblings, nodes;
7384 // Handle table cell selection the table plugin enables
7385 // you to fake select table cells and perform formatting actions on them
7386 nodes = dom.select('td.mceSelected,th.mceSelected');
7387 if (nodes.length > 0) {
7388 tinymce.each(nodes, function(node) {
7395 function collectSiblings(node, name, end_node) {
7398 for (; node && node != end_node; node = node[name])
7399 siblings.push(node);
7404 function findEndPoint(node, root) {
7406 if (node.parentNode == root)
7409 node = node.parentNode;
7413 function walkBoundary(start_node, end_node, next) {
7414 var siblingName = next ? 'nextSibling' : 'previousSibling';
7416 for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) {
7417 parent = node.parentNode;
7418 siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName);
7420 if (siblings.length) {
7429 // If index based start position then resolve it
7430 if (startContainer.nodeType == 1 && startContainer.hasChildNodes())
7431 startContainer = startContainer.childNodes[startOffset];
7433 // If index based end position then resolve it
7434 if (endContainer.nodeType == 1 && endContainer.hasChildNodes())
7435 endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)];
7437 // Find common ancestor and end points
7438 ancestor = dom.findCommonAncestor(startContainer, endContainer);
7441 if (startContainer == endContainer)
7442 return callback([startContainer]);
7444 // Process left side
7445 for (node = startContainer; node; node = node.parentNode) {
7446 if (node == endContainer)
7447 return walkBoundary(startContainer, ancestor, true);
7449 if (node == ancestor)
7453 // Process right side
7454 for (node = endContainer; node; node = node.parentNode) {
7455 if (node == startContainer)
7456 return walkBoundary(endContainer, ancestor);
7458 if (node == ancestor)
7462 // Find start/end point
7463 startPoint = findEndPoint(startContainer, ancestor) || startContainer;
7464 endPoint = findEndPoint(endContainer, ancestor) || endContainer;
7467 walkBoundary(startContainer, startPoint, true);
7469 // Walk the middle from start to end point
7470 siblings = collectSiblings(
7471 startPoint == startContainer ? startPoint : startPoint.nextSibling,
7473 endPoint == endContainer ? endPoint.nextSibling : endPoint
7476 if (siblings.length)
7480 walkBoundary(endContainer, endPoint);
7483 /* this.split = function(rng) {
7484 var startContainer = rng.startContainer,
7485 startOffset = rng.startOffset,
7486 endContainer = rng.endContainer,
7487 endOffset = rng.endOffset;
7489 function splitText(node, offset) {
7490 if (offset == node.nodeValue.length)
7491 node.appendData(INVISIBLE_CHAR);
7493 node = node.splitText(offset);
7495 if (node.nodeValue === INVISIBLE_CHAR)
7496 node.nodeValue = '';
7501 // Handle single text node
7502 if (startContainer == endContainer) {
7503 if (startContainer.nodeType == 3) {
7504 if (startOffset != 0)
7505 startContainer = endContainer = splitText(startContainer, startOffset);
7507 if (endOffset - startOffset != startContainer.nodeValue.length)
7508 splitText(startContainer, endOffset - startOffset);
7511 // Split startContainer text node if needed
7512 if (startContainer.nodeType == 3 && startOffset != 0) {
7513 startContainer = splitText(startContainer, startOffset);
7517 // Split endContainer text node if needed
7518 if (endContainer.nodeType == 3 && endOffset != endContainer.nodeValue.length) {
7519 endContainer = splitText(endContainer, endOffset).previousSibling;
7520 endOffset = endContainer.nodeValue.length;
7525 startContainer : startContainer,
7526 startOffset : startOffset,
7527 endContainer : endContainer,
7528 endOffset : endOffset
7534 tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) {
7536 // Compare native IE ranges
7537 if (rng1.item || rng1.duplicate) {
7538 // Both are control ranges and the selected element matches
7539 if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0))
7542 // Both are text ranges and the range matches
7543 if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1))
7546 // Compare w3c ranges
7547 return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset;
7555 (function(tinymce) {
7556 var Event = tinymce.dom.Event, each = tinymce.each;
7558 tinymce.create('tinymce.ui.KeyboardNavigation', {
7559 KeyboardNavigation: function(settings, dom) {
7560 var t = this, root = settings.root, items = settings.items,
7561 enableUpDown = settings.enableUpDown, enableLeftRight = settings.enableLeftRight || !settings.enableUpDown,
7562 excludeFromTabOrder = settings.excludeFromTabOrder,
7563 itemFocussed, itemBlurred, rootKeydown, rootFocussed, focussedId;
7565 dom = dom || tinymce.DOM;
7567 itemFocussed = function(evt) {
7568 focussedId = evt.target.id;
7571 itemBlurred = function(evt) {
7572 dom.setAttrib(evt.target.id, 'tabindex', '-1');
7575 rootFocussed = function(evt) {
7576 var item = dom.get(focussedId);
7577 dom.setAttrib(item, 'tabindex', '0');
7581 t.focus = function() {
7582 dom.get(focussedId).focus();
7585 t.destroy = function() {
7586 each(items, function(item) {
7587 dom.unbind(dom.get(item.id), 'focus', itemFocussed);
7588 dom.unbind(dom.get(item.id), 'blur', itemBlurred);
7591 dom.unbind(dom.get(root), 'focus', rootFocussed);
7592 dom.unbind(dom.get(root), 'keydown', rootKeydown);
7594 items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null;
7595 t.destroy = function() {};
7598 t.moveFocus = function(dir, evt) {
7599 var idx = -1, controls = t.controls, newFocus;
7604 each(items, function(item, index) {
7605 if (item.id === focussedId) {
7613 idx = items.length - 1;
7614 } else if (idx >= items.length) {
7618 newFocus = items[idx];
7619 dom.setAttrib(focussedId, 'tabindex', '-1');
7620 dom.setAttrib(newFocus.id, 'tabindex', '0');
7621 dom.get(newFocus.id).focus();
7623 if (settings.actOnFocus) {
7624 settings.onAction(newFocus.id);
7631 rootKeydown = function(evt) {
7632 var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40, DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32;
7634 switch (evt.keyCode) {
7636 if (enableLeftRight) t.moveFocus(-1);
7640 if (enableLeftRight) t.moveFocus(1);
7644 if (enableUpDown) t.moveFocus(-1);
7648 if (enableUpDown) t.moveFocus(1);
7652 if (settings.onCancel) {
7653 settings.onCancel();
7661 if (settings.onAction) {
7662 settings.onAction(focussedId);
7669 // Set up state and listeners for each item.
7670 each(items, function(item, idx) {
7674 item.id = dom.uniqueId('_mce_item_');
7677 if (excludeFromTabOrder) {
7678 dom.bind(item.id, 'blur', itemBlurred);
7681 tabindex = (idx === 0 ? '0' : '-1');
7684 dom.setAttrib(item.id, 'tabindex', tabindex);
7685 dom.bind(dom.get(item.id), 'focus', itemFocussed);
7688 // Setup initial state for root element.
7690 focussedId = items[0].id;
7693 dom.setAttrib(root, 'tabindex', '-1');
7695 // Setup listeners for root element.
7696 dom.bind(dom.get(root), 'focus', rootFocussed);
7697 dom.bind(dom.get(root), 'keydown', rootKeydown);
7701 (function(tinymce) {
7702 // Shorten class names
7703 var DOM = tinymce.DOM, is = tinymce.is;
7705 tinymce.create('tinymce.ui.Control', {
7706 Control : function(id, s, editor) {
7708 this.settings = s = s || {};
7709 this.rendered = false;
7710 this.onRender = new tinymce.util.Dispatcher(this);
7711 this.classPrefix = '';
7712 this.scope = s.scope || this;
7715 this.editor = editor;
7718 setAriaProperty : function(property, value) {
7719 var element = DOM.get(this.id + '_aria') || DOM.get(this.id);
7721 DOM.setAttrib(element, 'aria-' + property, !!value);
7725 focus : function() {
7726 DOM.get(this.id).focus();
7729 setDisabled : function(s) {
7730 if (s != this.disabled) {
7731 this.setAriaProperty('disabled', s);
7733 this.setState('Disabled', s);
7734 this.setState('Enabled', !s);
7739 isDisabled : function() {
7740 return this.disabled;
7743 setActive : function(s) {
7744 if (s != this.active) {
7745 this.setState('Active', s);
7747 this.setAriaProperty('pressed', s);
7751 isActive : function() {
7755 setState : function(c, s) {
7756 var n = DOM.get(this.id);
7758 c = this.classPrefix + c;
7763 DOM.removeClass(n, c);
7766 isRendered : function() {
7767 return this.rendered;
7770 renderHTML : function() {
7773 renderTo : function(n) {
7774 DOM.setHTML(n, this.renderHTML());
7777 postRender : function() {
7780 // Set pending states
7781 if (is(t.disabled)) {
7794 remove : function() {
7795 DOM.remove(this.id);
7799 destroy : function() {
7800 tinymce.dom.Event.clear(this.id);
7804 tinymce.create('tinymce.ui.Container:tinymce.ui.Control', {
7805 Container : function(id, s, editor) {
7806 this.parent(id, s, editor);
7814 this.lookup[c.id] = c;
7815 this.controls.push(c);
7821 return this.lookup[n];
7826 tinymce.create('tinymce.ui.Separator:tinymce.ui.Control', {
7827 Separator : function(id, s) {
7829 this.classPrefix = 'mceSeparator';
7830 this.setDisabled(true);
7833 renderHTML : function() {
7834 return tinymce.DOM.createHTML('span', {'class' : this.classPrefix, role : 'separator', 'aria-orientation' : 'vertical', tabindex : '-1'});
7838 (function(tinymce) {
7839 var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;
7841 tinymce.create('tinymce.ui.MenuItem:tinymce.ui.Control', {
7842 MenuItem : function(id, s) {
7844 this.classPrefix = 'mceMenuItem';
7847 setSelected : function(s) {
7848 this.setState('Selected', s);
7849 this.setAriaProperty('checked', !!s);
7853 isSelected : function() {
7854 return this.selected;
7857 postRender : function() {
7862 // Set pending state
7864 t.setSelected(t.selected);
7869 (function(tinymce) {
7870 var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;
7872 tinymce.create('tinymce.ui.Menu:tinymce.ui.MenuItem', {
7873 Menu : function(id, s) {
7878 t.collapsed = false;
7880 t.onAddItem = new tinymce.util.Dispatcher(this);
7883 expand : function(d) {
7887 walk(t, function(o) {
7893 t.collapsed = false;
7896 collapse : function(d) {
7900 walk(t, function(o) {
7909 isCollapsed : function() {
7910 return this.collapsed;
7915 o = new tinymce.ui.MenuItem(o.id || DOM.uniqueId(), o);
7917 this.onAddItem.dispatch(this, o);
7919 return this.items[o.id] = o;
7922 addSeparator : function() {
7923 return this.add({separator : true});
7926 addMenu : function(o) {
7928 o = this.createMenu(o);
7935 hasMenus : function() {
7936 return this.menuCount !== 0;
7939 remove : function(o) {
7940 delete this.items[o.id];
7943 removeAll : function() {
7946 walk(t, function(o) {
7958 createMenu : function(o) {
7959 var m = new tinymce.ui.Menu(o.id || DOM.uniqueId(), o);
7961 m.onAddItem.add(this.onAddItem.dispatch, this.onAddItem);
7967 (function(tinymce) {
7968 var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event, Element = tinymce.dom.Element;
7970 tinymce.create('tinymce.ui.DropMenu:tinymce.ui.Menu', {
7971 DropMenu : function(id, s) {
7973 s.container = s.container || DOM.doc.body;
7974 s.offset_x = s.offset_x || 0;
7975 s.offset_y = s.offset_y || 0;
7976 s.vp_offset_x = s.vp_offset_x || 0;
7977 s.vp_offset_y = s.vp_offset_y || 0;
7979 if (is(s.icons) && !s.icons)
7980 s['class'] += ' mceNoIcons';
7983 this.onShowMenu = new tinymce.util.Dispatcher(this);
7984 this.onHideMenu = new tinymce.util.Dispatcher(this);
7985 this.classPrefix = 'mceMenu';
7988 createMenu : function(s) {
7989 var t = this, cs = t.settings, m;
7991 s.container = s.container || cs.container;
7993 s.constrain = s.constrain || cs.constrain;
7994 s['class'] = s['class'] || cs['class'];
7995 s.vp_offset_x = s.vp_offset_x || cs.vp_offset_x;
7996 s.vp_offset_y = s.vp_offset_y || cs.vp_offset_y;
7997 s.keyboard_focus = cs.keyboard_focus;
7998 m = new tinymce.ui.DropMenu(s.id || DOM.uniqueId(), s);
8000 m.onAddItem.add(t.onAddItem.dispatch, t.onAddItem);
8005 focus : function() {
8007 if (t.keyboardNav) {
8008 t.keyboardNav.focus();
8012 update : function() {
8013 var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th;
8015 tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth;
8016 th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight;
8019 t.element.setStyles({width : tw + 2, height : th + 2});
8021 t.element.setStyles({width : tw, height : th});
8024 DOM.setStyle(co, 'width', tw);
8027 DOM.setStyle(co, 'height', th);
8029 if (tb.clientHeight < s.max_height)
8030 DOM.setStyle(co, 'overflow', 'hidden');
8034 showMenu : function(x, y, px) {
8035 var t = this, s = t.settings, co, vp = DOM.getViewPort(), w, h, mx, my, ot = 2, dm, tb, cp = t.classPrefix;
8039 if (t.isMenuVisible)
8043 co = DOM.add(t.settings.container, t.renderNode());
8045 each(t.items, function(o) {
8049 t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});
8051 co = DOM.get('menu_' + t.id);
8053 // Move layer out of sight unless it's Opera since it scrolls to top of page due to an bug
8054 if (!tinymce.isOpera)
8055 DOM.setStyles(co, {left : -0xFFFF , top : -0xFFFF});
8060 x += s.offset_x || 0;
8061 y += s.offset_y || 0;
8065 // Move inside viewport if not submenu
8067 w = co.clientWidth - ot;
8068 h = co.clientHeight - ot;
8072 if ((x + s.vp_offset_x + w) > mx)
8073 x = px ? px - w : Math.max(0, (mx - s.vp_offset_x) - w);
8075 if ((y + s.vp_offset_y + h) > my)
8076 y = Math.max(0, (my - s.vp_offset_y) - h);
8079 DOM.setStyles(co, {left : x , top : y});
8082 t.isMenuVisible = 1;
8083 t.mouseClickFunc = Event.add(co, 'click', function(e) {
8088 if (e && (e = DOM.getParent(e, 'tr')) && !DOM.hasClass(e, cp + 'ItemSub')) {
8100 dm = dm.settings.parent;
8103 if (m.settings.onclick)
8104 m.settings.onclick(e);
8106 return Event.cancel(e); // Cancel to fix onbeforeunload problem
8111 t.mouseOverFunc = Event.add(co, 'mouseover', function(e) {
8115 if (e && (e = DOM.getParent(e, 'tr'))) {
8119 t.lastMenu.collapse(1);
8124 if (e && DOM.hasClass(e, cp + 'ItemSub')) {
8125 //p = DOM.getPos(s.container);
8127 m.showMenu((r.x + r.w - ot), r.y - ot, r.x);
8129 DOM.addClass(DOM.get(m.id).firstChild, cp + 'ItemActive');
8135 Event.add(co, 'keydown', t._keyHandler, t);
8137 t.onShowMenu.dispatch(t);
8139 if (s.keyboard_focus) {
8140 t._setupKeyboardNav();
8144 hideMenu : function(c) {
8145 var t = this, co = DOM.get('menu_' + t.id), e;
8147 if (!t.isMenuVisible)
8150 if (t.keyboardNav) t.keyboardNav.destroy();
8151 Event.remove(co, 'mouseover', t.mouseOverFunc);
8152 Event.remove(co, 'click', t.mouseClickFunc);
8153 Event.remove(co, 'keydown', t._keyHandler);
8155 t.isMenuVisible = 0;
8163 if (e = DOM.get(t.id))
8164 DOM.removeClass(e.firstChild, t.classPrefix + 'ItemActive');
8166 t.onHideMenu.dispatch(t);
8174 if (t.isRendered && (co = DOM.get('menu_' + t.id)))
8175 t._add(DOM.select('tbody', co)[0], o);
8180 collapse : function(d) {
8185 remove : function(o) {
8189 return this.parent(o);
8192 destroy : function() {
8193 var t = this, co = DOM.get('menu_' + t.id);
8195 if (t.keyboardNav) t.keyboardNav.destroy();
8196 Event.remove(co, 'mouseover', t.mouseOverFunc);
8197 Event.remove(DOM.select('a', co), 'focus', t.mouseOverFunc);
8198 Event.remove(co, 'click', t.mouseClickFunc);
8199 Event.remove(co, 'keydown', t._keyHandler);
8207 renderNode : function() {
8208 var t = this, s = t.settings, n, tb, co, w;
8210 w = DOM.create('div', {role: 'listbox', id : 'menu_' + t.id, 'class' : s['class'], 'style' : 'position:absolute;left:0;top:0;z-index:200000;outline:0'});
8211 if (t.settings.parent) {
8212 DOM.setAttrib(w, 'aria-parent', 'menu_' + t.settings.parent.id);
8214 co = DOM.add(w, 'div', {role: 'presentation', id : 'menu_' + t.id + '_co', 'class' : t.classPrefix + (s['class'] ? ' ' + s['class'] : '')});
8215 t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});
8218 DOM.add(co, 'span', {'class' : t.classPrefix + 'Line'});
8220 // n = DOM.add(co, 'div', {id : 'menu_' + t.id + '_co', 'class' : 'mceMenuContainer'});
8221 n = DOM.add(co, 'table', {role: 'presentation', id : 'menu_' + t.id + '_tbl', border : 0, cellPadding : 0, cellSpacing : 0});
8222 tb = DOM.add(n, 'tbody');
8224 each(t.items, function(o) {
8233 // Internal functions
8234 _setupKeyboardNav : function(){
8235 var contextMenu, menuItems, t=this;
8236 contextMenu = DOM.select('#menu_' + t.id)[0];
8237 menuItems = DOM.select('a[role=option]', 'menu_' + t.id);
8238 menuItems.splice(0,0,contextMenu);
8239 t.keyboardNav = new tinymce.ui.KeyboardNavigation({
8240 root: 'menu_' + t.id,
8242 onCancel: function() {
8247 contextMenu.focus();
8250 _keyHandler : function(evt) {
8252 switch (evt.keyCode) {
8254 if (t.settings.parent) {
8256 t.settings.parent.focus();
8261 if (t.mouseOverFunc)
8262 t.mouseOverFunc(evt);
8267 _add : function(tb, o) {
8268 var n, s = o.settings, a, ro, it, cp = this.classPrefix, ic;
8271 ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'ItemSeparator'});
8272 DOM.add(ro, 'td', {'class' : cp + 'ItemSeparator'});
8274 if (n = ro.previousSibling)
8275 DOM.addClass(n, 'mceLast');
8280 n = ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'Item ' + cp + 'ItemEnabled'});
8281 n = it = DOM.add(n, s.titleItem ? 'th' : 'td');
8282 n = a = DOM.add(n, 'a', {id: o.id + '_aria', role: s.titleItem ? 'presentation' : 'option', href : 'javascript:;', onclick : "return false;", onmousedown : 'return false;'});
8285 DOM.setAttrib(a, 'aria-haspopup', 'true');
8286 DOM.setAttrib(a, 'aria-owns', 'menu_' + o.id);
8289 DOM.addClass(it, s['class']);
8290 // n = DOM.add(n, 'span', {'class' : 'item'});
8292 ic = DOM.add(n, 'span', {'class' : 'mceIcon' + (s.icon ? ' mce_' + s.icon : '')});
8295 DOM.add(ic, 'img', {src : s.icon_src});
8297 n = DOM.add(n, s.element || 'span', {'class' : 'mceText', title : o.settings.title}, o.settings.title);
8299 if (o.settings.style)
8300 DOM.setAttrib(n, 'style', o.settings.style);
8302 if (tb.childNodes.length == 1)
8303 DOM.addClass(ro, 'mceFirst');
8305 if ((n = ro.previousSibling) && DOM.hasClass(n, cp + 'ItemSeparator'))
8306 DOM.addClass(ro, 'mceFirst');
8309 DOM.addClass(ro, cp + 'ItemSub');
8311 if (n = ro.previousSibling)
8312 DOM.removeClass(n, 'mceLast');
8314 DOM.addClass(ro, 'mceLast');
8318 (function(tinymce) {
8319 var DOM = tinymce.DOM;
8321 tinymce.create('tinymce.ui.Button:tinymce.ui.Control', {
8322 Button : function(id, s, ed) {
8323 this.parent(id, s, ed);
8324 this.classPrefix = 'mceButton';
8327 renderHTML : function() {
8328 var cp = this.classPrefix, s = this.settings, h, l;
8330 l = DOM.encode(s.label || '');
8331 h = '<a role="button" id="' + this.id + '" href="javascript:;" class="' + cp + ' ' + cp + 'Enabled ' + s['class'] + (l ? ' ' + cp + 'Labeled' : '') +'" onmousedown="return false;" onclick="return false;" aria-labelledby="' + this.id + '_voice" title="' + DOM.encode(s.title) + '">';
8334 h += '<img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" />' + l;
8336 h += '<span class="mceIcon ' + s['class'] + '"></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : '');
8338 h += '<span class="mceVoiceLabel mceIconOnly" style="display: none;" id="' + this.id + '_voice">' + s.title + '</span>';
8343 postRender : function() {
8344 var t = this, s = t.settings;
8346 tinymce.dom.Event.add(t.id, 'click', function(e) {
8347 if (!t.isDisabled())
8348 return s.onclick.call(s.scope, e);
8354 (function(tinymce) {
8355 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;
8357 tinymce.create('tinymce.ui.ListBox:tinymce.ui.Control', {
8358 ListBox : function(id, s, ed) {
8361 t.parent(id, s, ed);
8365 t.onChange = new Dispatcher(t);
8367 t.onPostRender = new Dispatcher(t);
8369 t.onAdd = new Dispatcher(t);
8371 t.onRenderMenu = new tinymce.util.Dispatcher(this);
8373 t.classPrefix = 'mceListBox';
8376 select : function(va) {
8377 var t = this, fv, f;
8379 if (va == undefined)
8380 return t.selectByIndex(-1);
8382 // Is string or number make function selector
8391 // Do we need to do something?
8392 if (va != t.selectedValue) {
8394 each(t.items, function(o, i) {
8403 t.selectByIndex(-1);
8407 selectByIndex : function(idx) {
8410 if (idx != t.selectedIndex) {
8411 e = DOM.get(t.id + '_text');
8415 t.selectedValue = o.value;
8416 t.selectedIndex = idx;
8417 DOM.setHTML(e, DOM.encode(o.title));
8418 DOM.removeClass(e, 'mceTitle');
8419 DOM.setAttrib(t.id, 'aria-valuenow', o.title);
8421 DOM.setHTML(e, DOM.encode(t.settings.title));
8422 DOM.addClass(e, 'mceTitle');
8423 t.selectedValue = t.selectedIndex = null;
8424 DOM.setAttrib(t.id, 'aria-valuenow', t.settings.title);
8430 add : function(n, v, o) {
8434 o = tinymce.extend(o, {
8440 t.onAdd.dispatch(t, o);
8443 getLength : function() {
8444 return this.items.length;
8447 renderHTML : function() {
8448 var h = '', t = this, s = t.settings, cp = t.classPrefix;
8450 h = '<span role="button" aria-haspopup="true" aria-labelledby="' + t.id +'_text" aria-describedby="' + t.id + '_voiceDesc"><table role="presentation" tabindex="0" id="' + t.id + '" cellpadding="0" cellspacing="0" class="' + cp + ' ' + cp + 'Enabled' + (s['class'] ? (' ' + s['class']) : '') + '"><tbody><tr>';
8451 h += '<td>' + DOM.createHTML('span', {id: t.id + '_voiceDesc', 'class': 'voiceLabel', style:'display:none;'}, t.settings.title);
8452 h += DOM.createHTML('a', {id : t.id + '_text', tabindex : -1, href : 'javascript:;', 'class' : 'mceText', onclick : "return false;", onmousedown : 'return false;'}, DOM.encode(t.settings.title)) + '</td>';
8453 h += '<td>' + DOM.createHTML('a', {id : t.id + '_open', tabindex : -1, href : 'javascript:;', 'class' : 'mceOpen', onclick : "return false;", onmousedown : 'return false;'}, '<span><span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span></span>') + '</td>';
8454 h += '</tr></tbody></table></span>';
8459 showMenu : function() {
8460 var t = this, p1, p2, e = DOM.get(this.id), m;
8462 if (t.isDisabled() || t.items.length == 0)
8465 if (t.menu && t.menu.isMenuVisible)
8466 return t.hideMenu();
8468 if (!t.isMenuRendered) {
8470 t.isMenuRendered = true;
8473 p1 = DOM.getPos(this.settings.menu_container);
8477 m.settings.offset_x = p2.x;
8478 m.settings.offset_y = p2.y;
8479 m.settings.keyboard_focus = !tinymce.isOpera; // Opera is buggy when it comes to auto focus
8483 m.items[t.oldID].setSelected(0);
8485 each(t.items, function(o) {
8486 if (o.value === t.selectedValue) {
8487 m.items[o.id].setSelected(1);
8492 m.showMenu(0, e.clientHeight);
8494 Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
8495 DOM.addClass(t.id, t.classPrefix + 'Selected');
8497 //DOM.get(t.id + '_text').focus();
8500 hideMenu : function(e) {
8503 if (t.menu && t.menu.isMenuVisible) {
8504 DOM.removeClass(t.id, t.classPrefix + 'Selected');
8506 // Prevent double toogles by canceling the mouse click event to the button
8507 if (e && e.type == "mousedown" && (e.target.id == t.id + '_text' || e.target.id == t.id + '_open'))
8510 if (!e || !DOM.getParent(e.target, '.mceMenu')) {
8511 DOM.removeClass(t.id, t.classPrefix + 'Selected');
8512 Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
8518 renderMenu : function() {
8521 m = t.settings.control_manager.createDropMenu(t.id + '_menu', {
8523 'class' : t.classPrefix + 'Menu mceNoIcons',
8528 m.onHideMenu.add(function() {
8534 title : t.settings.title,
8535 'class' : 'mceMenuItemTitle',
8536 onclick : function() {
8537 if (t.settings.onselect('') !== false)
8538 t.select(''); // Must be runned after
8542 each(t.items, function(o) {
8543 // No value then treat it as a title
8544 if (o.value === undefined) {
8547 'class' : 'mceMenuItemTitle',
8548 onclick : function() {
8549 if (t.settings.onselect('') !== false)
8550 t.select(''); // Must be runned after
8554 o.id = DOM.uniqueId();
8555 o.onclick = function() {
8556 if (t.settings.onselect(o.value) !== false)
8557 t.select(o.value); // Must be runned after
8564 t.onRenderMenu.dispatch(t, m);
8568 postRender : function() {
8569 var t = this, cp = t.classPrefix;
8571 Event.add(t.id, 'click', t.showMenu, t);
8572 Event.add(t.id, 'keydown', function(evt) {
8573 if (evt.keyCode == 32) { // Space
8578 Event.add(t.id, 'focus', function() {
8580 t.keyDownHandler = Event.add(t.id, 'keydown', function(e) {
8581 if (e.keyCode == 40) {
8586 t.keyPressHandler = Event.add(t.id, 'keypress', function(e) {
8588 if (e.keyCode == 13) {
8589 // Fake select on enter
8590 v = t.selectedValue;
8591 t.selectedValue = null; // Needs to be null to fake change
8593 t.settings.onselect(v);
8600 Event.add(t.id, 'blur', function() {
8601 Event.remove(t.id, 'keydown', t.keyDownHandler);
8602 Event.remove(t.id, 'keypress', t.keyPressHandler);
8606 // Old IE doesn't have hover on all elements
8607 if (tinymce.isIE6 || !DOM.boxModel) {
8608 Event.add(t.id, 'mouseover', function() {
8609 if (!DOM.hasClass(t.id, cp + 'Disabled'))
8610 DOM.addClass(t.id, cp + 'Hover');
8613 Event.add(t.id, 'mouseout', function() {
8614 if (!DOM.hasClass(t.id, cp + 'Disabled'))
8615 DOM.removeClass(t.id, cp + 'Hover');
8619 t.onPostRender.dispatch(t, DOM.get(t.id));
8622 destroy : function() {
8625 Event.clear(this.id + '_text');
8626 Event.clear(this.id + '_open');
8630 (function(tinymce) {
8631 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;
8633 tinymce.create('tinymce.ui.NativeListBox:tinymce.ui.ListBox', {
8634 NativeListBox : function(id, s) {
8636 this.classPrefix = 'mceNativeListBox';
8639 setDisabled : function(s) {
8640 DOM.get(this.id).disabled = s;
8641 this.setAriaProperty('disabled', s);
8644 isDisabled : function() {
8645 return DOM.get(this.id).disabled;
8648 select : function(va) {
8649 var t = this, fv, f;
8651 if (va == undefined)
8652 return t.selectByIndex(-1);
8654 // Is string or number make function selector
8663 // Do we need to do something?
8664 if (va != t.selectedValue) {
8666 each(t.items, function(o, i) {
8675 t.selectByIndex(-1);
8679 selectByIndex : function(idx) {
8680 DOM.get(this.id).selectedIndex = idx + 1;
8681 this.selectedValue = this.items[idx] ? this.items[idx].value : null;
8684 add : function(n, v, a) {
8691 DOM.add(DOM.get(this.id), 'option', a, n);
8700 t.onAdd.dispatch(t, o);
8703 getLength : function() {
8704 return this.items.length;
8707 renderHTML : function() {
8710 h = DOM.createHTML('option', {value : ''}, '-- ' + t.settings.title + ' --');
8712 each(t.items, function(it) {
8713 h += DOM.createHTML('option', {value : it.value}, it.title);
8716 h = DOM.createHTML('select', {id : t.id, 'class' : 'mceNativeListBox', 'aria-labelledby': t.id + '_aria'}, h);
8717 h += DOM.createHTML('span', {id : t.id + '_aria', 'style': 'display: none'}, t.settings.title);
8721 postRender : function() {
8722 var t = this, ch, changeListenerAdded = true;
8726 function onChange(e) {
8727 var v = t.items[e.target.selectedIndex - 1];
8729 if (v && (v = v.value)) {
8730 t.onChange.dispatch(t, v);
8732 if (t.settings.onselect)
8733 t.settings.onselect(v);
8737 Event.add(t.id, 'change', onChange);
8739 // Accessibility keyhandler
8740 Event.add(t.id, 'keydown', function(e) {
8743 Event.remove(t.id, 'change', ch);
8744 changeListenerAdded = false;
8746 bf = Event.add(t.id, 'blur', function() {
8747 if (changeListenerAdded) return;
8748 changeListenerAdded = true;
8749 Event.add(t.id, 'change', onChange);
8750 Event.remove(t.id, 'blur', bf);
8753 if (e.keyCode == 13 || e.keyCode == 32) {
8755 return Event.cancel(e);
8759 t.onPostRender.dispatch(t, DOM.get(t.id));
8763 (function(tinymce) {
8764 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;
8766 tinymce.create('tinymce.ui.MenuButton:tinymce.ui.Button', {
8767 MenuButton : function(id, s, ed) {
8768 this.parent(id, s, ed);
8770 this.onRenderMenu = new tinymce.util.Dispatcher(this);
8772 s.menu_container = s.menu_container || DOM.doc.body;
8775 showMenu : function() {
8776 var t = this, p1, p2, e = DOM.get(t.id), m;
8781 if (!t.isMenuRendered) {
8783 t.isMenuRendered = true;
8786 if (t.isMenuVisible)
8787 return t.hideMenu();
8789 p1 = DOM.getPos(t.settings.menu_container);
8793 m.settings.offset_x = p2.x;
8794 m.settings.offset_y = p2.y;
8795 m.settings.vp_offset_x = p2.x;
8796 m.settings.vp_offset_y = p2.y;
8797 m.settings.keyboard_focus = t._focused;
8798 m.showMenu(0, e.clientHeight);
8800 Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
8801 t.setState('Selected', 1);
8803 t.isMenuVisible = 1;
8806 renderMenu : function() {
8809 m = t.settings.control_manager.createDropMenu(t.id + '_menu', {
8811 'class' : this.classPrefix + 'Menu',
8812 icons : t.settings.icons
8815 m.onHideMenu.add(function() {
8820 t.onRenderMenu.dispatch(t, m);
8824 hideMenu : function(e) {
8827 // Prevent double toogles by canceling the mouse click event to the button
8828 if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id || e.id === t.id + '_open';}))
8831 if (!e || !DOM.getParent(e.target, '.mceMenu')) {
8832 t.setState('Selected', 0);
8833 Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
8838 t.isMenuVisible = 0;
8841 postRender : function() {
8842 var t = this, s = t.settings;
8844 Event.add(t.id, 'click', function() {
8845 if (!t.isDisabled()) {
8856 (function(tinymce) {
8857 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;
8859 tinymce.create('tinymce.ui.SplitButton:tinymce.ui.MenuButton', {
8860 SplitButton : function(id, s, ed) {
8861 this.parent(id, s, ed);
8862 this.classPrefix = 'mceSplitButton';
8865 renderHTML : function() {
8866 var h, t = this, s = t.settings, h1;
8871 h1 = DOM.createHTML('img ', {src : s.image, role: 'presentation', 'class' : 'mceAction ' + s['class']});
8873 h1 = DOM.createHTML('span', {'class' : 'mceAction ' + s['class']}, '');
8875 h1 += DOM.createHTML('span', {'class': 'mceVoiceLabel mceIconOnly', id: t.id + '_voice', style: 'display:none;'}, s.title);
8876 h += '<td >' + DOM.createHTML('a', {role: 'button', id : t.id + '_action', tabindex: '-1', href : 'javascript:;', 'class' : 'mceAction ' + s['class'], onclick : "return false;", onmousedown : 'return false;', title : s.title}, h1) + '</td>';
8878 h1 = DOM.createHTML('span', {'class' : 'mceOpen ' + s['class']}, '<span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span>');
8879 h += '<td >' + DOM.createHTML('a', {role: 'button', id : t.id + '_open', tabindex: '-1', href : 'javascript:;', 'class' : 'mceOpen ' + s['class'], onclick : "return false;", onmousedown : 'return false;', title : s.title}, h1) + '</td>';
8881 h += '</tr></tbody>';
8882 h = DOM.createHTML('table', {id : t.id, role: 'presentation', tabindex: '0', 'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h);
8883 return DOM.createHTML('span', {role: 'button', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h);
8886 postRender : function() {
8887 var t = this, s = t.settings, activate;
8890 activate = function(evt) {
8891 if (!t.isDisabled()) {
8896 Event.add(t.id + '_action', 'click', activate);
8897 Event.add(t.id, ['click', 'keydown'], function(evt) {
8898 var DOM_VK_SPACE = 32, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_UP = 38, DOM_VK_DOWN = 40;
8899 if ((evt.keyCode === 32 || evt.keyCode === 13 || evt.keyCode === 14) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) {
8902 } else if (evt.type === 'click' || evt.keyCode === DOM_VK_DOWN) {
8909 Event.add(t.id + '_open', 'click', function (evt) {
8913 Event.add([t.id, t.id + '_open'], 'focus', function() {t._focused = 1;});
8914 Event.add([t.id, t.id + '_open'], 'blur', function() {t._focused = 0;});
8916 // Old IE doesn't have hover on all elements
8917 if (tinymce.isIE6 || !DOM.boxModel) {
8918 Event.add(t.id, 'mouseover', function() {
8919 if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled'))
8920 DOM.addClass(t.id, 'mceSplitButtonHover');
8923 Event.add(t.id, 'mouseout', function() {
8924 if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled'))
8925 DOM.removeClass(t.id, 'mceSplitButtonHover');
8930 destroy : function() {
8933 Event.clear(this.id + '_action');
8934 Event.clear(this.id + '_open');
8935 Event.clear(this.id);
8940 (function(tinymce) {
8941 var DOM = tinymce.DOM, Event = tinymce.dom.Event, is = tinymce.is, each = tinymce.each;
8943 tinymce.create('tinymce.ui.ColorSplitButton:tinymce.ui.SplitButton', {
8944 ColorSplitButton : function(id, s, ed) {
8947 t.parent(id, s, ed);
8949 t.settings = s = tinymce.extend({
8950 colors : '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,008000,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF',
8952 default_color : '#888888'
8955 t.onShowMenu = new tinymce.util.Dispatcher(t);
8957 t.onHideMenu = new tinymce.util.Dispatcher(t);
8959 t.value = s.default_color;
8962 showMenu : function() {
8963 var t = this, r, p, e, p2;
8968 if (!t.isMenuRendered) {
8970 t.isMenuRendered = true;
8973 if (t.isMenuVisible)
8974 return t.hideMenu();
8977 DOM.show(t.id + '_menu');
8978 DOM.addClass(e, 'mceSplitButtonSelected');
8980 DOM.setStyles(t.id + '_menu', {
8982 top : p2.y + e.clientHeight,
8987 Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
8988 t.onShowMenu.dispatch(t);
8991 t._keyHandler = Event.add(t.id + '_menu', 'keydown', function(e) {
8992 if (e.keyCode == 27)
8996 DOM.select('a', t.id + '_menu')[0].focus(); // Select first link
8999 t.isMenuVisible = 1;
9002 hideMenu : function(e) {
9005 if (t.isMenuVisible) {
9006 // Prevent double toogles by canceling the mouse click event to the button
9007 if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';}))
9010 if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) {
9011 DOM.removeClass(t.id, 'mceSplitButtonSelected');
9012 Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
9013 Event.remove(t.id + '_menu', 'keydown', t._keyHandler);
9014 DOM.hide(t.id + '_menu');
9017 t.isMenuVisible = 0;
9021 renderMenu : function() {
9022 var t = this, m, i = 0, s = t.settings, n, tb, tr, w, context;
9024 w = DOM.add(s.menu_container, 'div', {role: 'listbox', id : t.id + '_menu', 'class' : s['menu_class'] + ' ' + s['class'], style : 'position:absolute;left:0;top:-1000px;'});
9025 m = DOM.add(w, 'div', {'class' : s['class'] + ' mceSplitButtonMenu'});
9026 DOM.add(m, 'span', {'class' : 'mceMenuLine'});
9028 n = DOM.add(m, 'table', {role: 'presentation', 'class' : 'mceColorSplitMenu'});
9029 tb = DOM.add(n, 'tbody');
9031 // Generate color grid
9033 each(is(s.colors, 'array') ? s.colors : s.colors.split(','), function(c) {
9034 c = c.replace(/^#/, '');
9037 tr = DOM.add(tb, 'tr');
9038 i = s.grid_width - 1;
9041 n = DOM.add(tr, 'td');
9042 n = DOM.add(n, 'a', {
9044 href : 'javascript:;',
9046 backgroundColor : '#' + c
9048 'title': t.editor.getLang('colors.' + c, c),
9049 'data-mce-color' : '#' + c
9052 if (t.editor.forcedHighContrastMode) {
9053 n = DOM.add(n, 'canvas', { width: 16, height: 16, 'aria-hidden': 'true' });
9054 if (n.getContext && (context = n.getContext("2d"))) {
9055 context.fillStyle = '#' + c;
9056 context.fillRect(0, 0, 16, 16);
9058 // No point leaving a canvas element around if it's not supported for drawing on anyway.
9064 if (s.more_colors_func) {
9065 n = DOM.add(tb, 'tr');
9066 n = DOM.add(n, 'td', {colspan : s.grid_width, 'class' : 'mceMoreColors'});
9067 n = DOM.add(n, 'a', {role: 'option', id : t.id + '_more', href : 'javascript:;', onclick : 'return false;', 'class' : 'mceMoreColors'}, s.more_colors_title);
9069 Event.add(n, 'click', function(e) {
9070 s.more_colors_func.call(s.more_colors_scope || this);
9071 return Event.cancel(e); // Cancel to fix onbeforeunload problem
9075 DOM.addClass(m, 'mceColorSplitMenu');
9077 new tinymce.ui.KeyboardNavigation({
9078 root: t.id + '_menu',
9079 items: DOM.select('a', t.id + '_menu'),
9080 onCancel: function() {
9086 // Prevent IE from scrolling and hindering click to occur #4019
9087 Event.add(t.id + '_menu', 'mousedown', function(e) {return Event.cancel(e);});
9089 Event.add(t.id + '_menu', 'click', function(e) {
9092 e = DOM.getParent(e.target, 'a', tb);
9094 if (e && e.nodeName.toLowerCase() == 'a' && (c = e.getAttribute('data-mce-color')))
9097 return Event.cancel(e); // Prevent IE auto save warning
9103 setColor : function(c) {
9104 this.displayColor(c);
9106 this.settings.onselect(c);
9109 displayColor : function(c) {
9112 DOM.setStyle(t.id + '_preview', 'backgroundColor', c);
9117 postRender : function() {
9118 var t = this, id = t.id;
9121 DOM.add(id + '_action', 'div', {id : id + '_preview', 'class' : 'mceColorPreview'});
9122 DOM.setStyle(t.id + '_preview', 'backgroundColor', t.value);
9125 destroy : function() {
9128 Event.clear(this.id + '_menu');
9129 Event.clear(this.id + '_more');
9130 DOM.remove(this.id + '_menu');
9135 (function(tinymce) {
9136 // Shorten class names
9137 var dom = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event;
9138 tinymce.create('tinymce.ui.ToolbarGroup:tinymce.ui.Container', {
9139 renderHTML : function() {
9140 var t = this, h = [], controls = t.controls, each = tinymce.each, settings = t.settings;
9142 h.push('<div id="' + t.id + '" role="group" aria-labelledby="' + t.id + '_voice">');
9143 //TODO: ACC test this out - adding a role = application for getting the landmarks working well.
9144 h.push("<span role='application'>");
9145 h.push('<span id="' + t.id + '_voice" class="mceVoiceLabel" style="display:none;">' + dom.encode(settings.name) + '</span>');
9146 each(controls, function(toolbar) {
9147 h.push(toolbar.renderHTML());
9155 focus : function() {
9156 this.keyNav.focus();
9159 postRender : function() {
9160 var t = this, items = [];
9162 each(t.controls, function(toolbar) {
9163 each (toolbar.controls, function(control) {
9165 items.push(control);
9170 t.keyNav = new tinymce.ui.KeyboardNavigation({
9173 onCancel: function() {
9176 excludeFromTabOrder: !t.settings.tab_focus_toolbar
9180 destroy : function() {
9184 self.keyNav.destroy();
9185 Event.clear(self.id);
9190 (function(tinymce) {
9191 // Shorten class names
9192 var dom = tinymce.DOM, each = tinymce.each;
9193 tinymce.create('tinymce.ui.Toolbar:tinymce.ui.Container', {
9194 renderHTML : function() {
9195 var t = this, h = '', c, co, s = t.settings, i, pr, nx, cl;
9198 for (i=0; i<cl.length; i++) {
9199 // Get current control, prev control, next control and if the control is a list box or not
9204 // Add toolbar start
9206 c = 'mceToolbarStart';
9209 c += ' mceToolbarStartButton';
9210 else if (co.SplitButton)
9211 c += ' mceToolbarStartSplitButton';
9212 else if (co.ListBox)
9213 c += ' mceToolbarStartListBox';
9215 h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->'));
9218 // Add toolbar end before list box and after the previous button
9219 // This is to fix the o2k7 editor skins
9220 if (pr && co.ListBox) {
9221 if (pr.Button || pr.SplitButton)
9222 h += dom.createHTML('td', {'class' : 'mceToolbarEnd'}, dom.createHTML('span', null, '<!-- IE -->'));
9225 // Render control HTML
9227 // IE 8 quick fix, needed to propertly generate a hit area for anchors
9229 h += '<td style="position: relative">' + co.renderHTML() + '</td>';
9231 h += '<td>' + co.renderHTML() + '</td>';
9233 // Add toolbar start after list box and before the next button
9234 // This is to fix the o2k7 editor skins
9235 if (nx && co.ListBox) {
9236 if (nx.Button || nx.SplitButton)
9237 h += dom.createHTML('td', {'class' : 'mceToolbarStart'}, dom.createHTML('span', null, '<!-- IE -->'));
9241 c = 'mceToolbarEnd';
9244 c += ' mceToolbarEndButton';
9245 else if (co.SplitButton)
9246 c += ' mceToolbarEndSplitButton';
9247 else if (co.ListBox)
9248 c += ' mceToolbarEndListBox';
9250 h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->'));
9252 return dom.createHTML('table', {id : t.id, 'class' : 'mceToolbar' + (s['class'] ? ' ' + s['class'] : ''), cellpadding : '0', cellspacing : '0', align : t.settings.align || '', role: 'presentation', tabindex: '-1'}, '<tbody><tr>' + h + '</tr></tbody>');
9257 (function(tinymce) {
9258 var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each;
9260 tinymce.create('tinymce.AddOnManager', {
9261 AddOnManager : function() {
9267 self.onAdd = new Dispatcher(self);
9271 return this.lookup[n];
9274 requireLangPack : function(n) {
9275 var s = tinymce.settings;
9277 if (s && s.language && s.language_load !== false)
9278 tinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js');
9281 add : function(id, o) {
9283 this.lookup[id] = o;
9284 this.onAdd.dispatch(this, id, o);
9289 load : function(n, u, cb, s) {
9295 if (u.indexOf('/') != 0 && u.indexOf('://') == -1)
9296 u = tinymce.baseURL + '/' + u;
9298 t.urls[n] = u.substring(0, u.lastIndexOf('/'));
9301 tinymce.ScriptLoader.add(u, cb, s);
9305 // Create plugin and theme managers
9306 tinymce.PluginManager = new tinymce.AddOnManager();
9307 tinymce.ThemeManager = new tinymce.AddOnManager();
9310 (function(tinymce) {
9312 var each = tinymce.each, extend = tinymce.extend,
9313 DOM = tinymce.DOM, Event = tinymce.dom.Event,
9314 ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
9315 explode = tinymce.explode,
9316 Dispatcher = tinymce.util.Dispatcher, undefined, instanceCounter = 0;
9318 // Setup some URLs where the editor API is located and where the document is
9319 tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
9320 if (!/[\/\\]$/.test(tinymce.documentBaseURL))
9321 tinymce.documentBaseURL += '/';
9323 tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL);
9325 tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL);
9327 // Add before unload listener
9328 // This was required since IE was leaking memory if you added and removed beforeunload listeners
9329 // with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event
9330 tinymce.onBeforeUnload = new Dispatcher(tinymce);
9332 // Must be on window or IE will leak if the editor is placed in frame or iframe
9333 Event.add(window, 'beforeunload', function(e) {
9334 tinymce.onBeforeUnload.dispatch(tinymce, e);
9337 tinymce.onAddEditor = new Dispatcher(tinymce);
9339 tinymce.onRemoveEditor = new Dispatcher(tinymce);
9341 tinymce.EditorManager = extend(tinymce, {
9346 activeEditor : null,
9348 init : function(s) {
9349 var t = this, pl, sl = tinymce.ScriptLoader, e, el = [], ed;
9351 function execCallback(se, n, s) {
9357 if (tinymce.is(f, 'string')) {
9358 s = f.replace(/\.\w+$/, '');
9359 s = s ? tinymce.resolve(s) : 0;
9360 f = tinymce.resolve(f);
9363 return f.apply(s || this, Array.prototype.slice.call(arguments, 2));
9374 Event.add(document, 'init', function() {
9377 execCallback(s, 'onpageload');
9381 l = s.elements || '';
9384 each(explode(l), function(v) {
9386 ed = new tinymce.Editor(v, s);
9390 each(document.forms, function(f) {
9391 each(f.elements, function(e) {
9393 v = 'mce_editor_' + instanceCounter++;
9394 DOM.setAttrib(e, 'id', v);
9396 ed = new tinymce.Editor(v, s);
9408 case "specific_textareas":
9409 function hasClass(n, c) {
9410 return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
9413 each(DOM.select('textarea'), function(v) {
9414 if (s.editor_deselector && hasClass(v, s.editor_deselector))
9417 if (!s.editor_selector || hasClass(v, s.editor_selector)) {
9418 // Can we use the name
9419 e = DOM.get(v.name);
9423 // Generate unique name if missing or already exists
9424 if (!v.id || t.get(v.id))
9425 v.id = DOM.uniqueId();
9427 ed = new tinymce.Editor(v.id, s);
9435 // Call onInit when all editors are initialized
9439 each(el, function(ed) {
9442 if (!ed.initialized) {
9444 ed.onInit.add(function() {
9449 execCallback(s, 'oninit');
9456 execCallback(s, 'oninit');
9462 get : function(id) {
9463 if (id === undefined)
9464 return this.editors;
9466 return this.editors[id];
9469 getInstanceById : function(id) {
9470 return this.get(id);
9473 add : function(editor) {
9474 var self = this, editors = self.editors;
9476 // Add named and index editor instance
9477 editors[editor.id] = editor;
9478 editors.push(editor);
9480 self._setActive(editor);
9481 self.onAddEditor.dispatch(self, editor);
9484 // Patch the tinymce.Editor instance with jQuery adapter logic
9485 if (tinymce.adapter)
9486 tinymce.adapter.patchEditor(editor);
9492 remove : function(editor) {
9493 var t = this, i, editors = t.editors;
9495 // Not in the collection
9496 if (!editors[editor.id])
9499 delete editors[editor.id];
9501 for (i = 0; i < editors.length; i++) {
9502 if (editors[i] == editor) {
9503 editors.splice(i, 1);
9508 // Select another editor since the active one was removed
9509 if (t.activeEditor == editor)
9510 t._setActive(editors[0]);
9513 t.onRemoveEditor.dispatch(t, editor);
9518 execCommand : function(c, u, v) {
9519 var t = this, ed = t.get(v), w;
9527 case "mceAddEditor":
9528 case "mceAddControl":
9530 new tinymce.Editor(v, t.settings).render();
9534 case "mceAddFrameControl":
9537 // Add tinyMCE global instance and tinymce namespace to specified window
9538 w.tinyMCE = tinyMCE;
9539 w.tinymce = tinymce;
9541 tinymce.DOM.doc = w.document;
9542 tinymce.DOM.win = w;
9544 ed = new tinymce.Editor(v.element_id, v);
9547 // Fix IE memory leaks
9551 w.detachEvent('onunload', clr);
9552 w = w.tinyMCE = w.tinymce = null; // IE leak
9555 w.attachEvent('onunload', clr);
9558 v.page_window = null;
9562 case "mceRemoveEditor":
9563 case "mceRemoveControl":
9569 case 'mceToggleEditor':
9571 t.execCommand('mceAddControl', 0, v);
9583 // Run command on active editor
9585 return t.activeEditor.execCommand(c, u, v);
9590 execInstanceCommand : function(id, c, u, v) {
9591 var ed = this.get(id);
9594 return ed.execCommand(c, u, v);
9599 triggerSave : function() {
9600 each(this.editors, function(e) {
9605 addI18n : function(p, o) {
9606 var lo, i18n = this.i18n;
9608 if (!tinymce.is(p, 'string')) {
9609 each(p, function(o, lc) {
9610 each(o, function(o, g) {
9611 each(o, function(o, k) {
9613 i18n[lc + '.' + k] = o;
9615 i18n[lc + '.' + g + '.' + k] = o;
9620 each(o, function(o, k) {
9621 i18n[p + '.' + k] = o;
9628 _setActive : function(editor) {
9629 this.selectedInstance = this.activeEditor = editor;
9634 (function(tinymce) {
9635 // Shorten these names
9636 var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend,
9637 Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isGecko = tinymce.isGecko,
9638 isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, is = tinymce.is,
9639 ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
9640 inArray = tinymce.inArray, grep = tinymce.grep, explode = tinymce.explode;
9642 tinymce.create('tinymce.Editor', {
9643 Editor : function(id, s) {
9646 t.id = t.editorId = id;
9648 t.execCommands = {};
9649 t.queryStateCommands = {};
9650 t.queryValueCommands = {};
9652 t.isNotDirty = false;
9656 // Add events to the editor
9700 'onBeforeSetContent',
9702 'onBeforeGetContent',
9716 'onBeforeExecCommand',
9726 'onSetProgressState'
9728 t[e] = new Dispatcher(t);
9731 t.settings = s = extend({
9734 docs_language : 'en',
9741 document_base_url : tinymce.documentBaseURL,
9742 add_form_submit_trigger : 1,
9744 add_unload_trigger : 1,
9747 remove_script_host : 1,
9748 table_inline_editing : 0,
9749 object_resizing : 1,
9751 accessibility_focus : 1,
9752 custom_shortcuts : 1,
9753 custom_undo_redo_keyboard_shortcuts : 1,
9754 custom_undo_redo_restore_selection : 1,
9755 custom_undo_redo : 1,
9756 doctype : tinymce.isIE6 ? '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' : '<!DOCTYPE>', // Use old doctype on IE 6 to avoid horizontal scroll
9757 visual_table_class : 'mceItemTable',
9759 font_size_style_values : 'xx-small,x-small,small,medium,large,x-large,xx-large',
9760 apply_source_formatting : 1,
9761 directionality : 'ltr',
9762 forced_root_block : 'p',
9764 padd_empty_editor : 1,
9767 force_p_newlines : 1,
9768 indentation : '30px',
9770 fix_table_elements : 1,
9772 convert_fonts_to_spans : true,
9774 indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',
9775 indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',
9777 entity_encoding : 'named',
9778 url_converter : t.convertURL,
9779 url_converter_scope : t,
9783 t.documentBaseURI = new tinymce.util.URI(s.document_base_url || tinymce.documentBaseURL, {
9784 base_uri : tinyMCE.baseURI
9787 t.baseURI = tinymce.baseURI;
9792 t.execCallback('setup', t);
9795 render : function(nst) {
9796 var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader;
9798 // Page is not loaded yet, wait for it
9799 if (!Event.domLoaded) {
9800 Event.add(document, 'init', function() {
9806 tinyMCE.settings = s;
9808 // Element not found, then skip initialization
9809 if (!t.getElement())
9812 // Is a iPad/iPhone, then skip initialization. We need to sniff here since the
9813 // browser says it has contentEditable support but there is no visible caret
9814 // We will remove this check ones Apple implements full contentEditable support
9815 if (tinymce.isIDevice)
9818 // Add hidden input for non input elements inside form elements
9819 if (!/TEXTAREA|INPUT/i.test(t.getElement().nodeName) && s.hidden_input && DOM.getParent(id, 'form'))
9820 DOM.insertAfter(DOM.create('input', {type : 'hidden', name : id}), id);
9822 if (tinymce.WindowManager)
9823 t.windowManager = new tinymce.WindowManager(t);
9825 if (s.encoding == 'xml') {
9826 t.onGetContent.add(function(ed, o) {
9828 o.content = DOM.encode(o.content);
9832 if (s.add_form_submit_trigger) {
9833 t.onSubmit.addToTop(function() {
9834 if (t.initialized) {
9841 if (s.add_unload_trigger) {
9842 t._beforeUnload = tinyMCE.onBeforeUnload.add(function() {
9843 if (t.initialized && !t.destroyed && !t.isHidden())
9844 t.save({format : 'raw', no_events : true});
9848 tinymce.addUnload(t.destroy, t);
9850 if (s.submit_patch) {
9851 t.onBeforeRenderUI.add(function() {
9852 var n = t.getElement().form;
9858 if (n._mceOldSubmit)
9861 // Check page uses id="submit" or name="submit" for it's submit button
9862 if (!n.submit.nodeType && !n.submit.length) {
9864 n._mceOldSubmit = n.submit;
9865 n.submit = function() {
9866 // Save all instances
9867 tinymce.triggerSave();
9870 return t.formElement._mceOldSubmit(t.formElement);
9879 function loadScripts() {
9880 if (s.language && s.language_load !== false)
9881 sl.add(tinymce.baseURL + '/langs/' + s.language + '.js');
9883 if (s.theme && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme])
9884 ThemeManager.load(s.theme, 'themes/' + s.theme + '/editor_template' + tinymce.suffix + '.js');
9886 each(explode(s.plugins), function(p) {
9887 if (p && p.charAt(0) != '-' && !PluginManager.urls[p]) {
9888 // Skip safari plugin, since it is removed as of 3.3b1
9892 PluginManager.load(p, 'plugins/' + p + '/editor_plugin' + tinymce.suffix + '.js');
9896 // Init when que is loaded
9897 sl.loadQueue(function() {
9907 var n, t = this, s = t.settings, w, h, e = t.getElement(), o, ti, u, bi, bc, re, i;
9911 s.aria_label = s.aria_label || DOM.getAttrib(e, 'aria-label', t.getLang('aria.rich_text_area'));
9914 s.theme = s.theme.replace(/-/, '');
9915 o = ThemeManager.get(s.theme);
9918 if (t.theme.init && s.init_theme)
9919 t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, ''));
9922 // Create all plugins
9923 each(explode(s.plugins.replace(/\-/g, '')), function(p) {
9924 var c = PluginManager.get(p), u = PluginManager.urls[p] || tinymce.documentBaseURL.replace(/\/$/, ''), po;
9936 // Setup popup CSS path(s)
9937 if (s.popup_css !== false) {
9939 s.popup_css = t.documentBaseURI.toAbsolute(s.popup_css);
9941 s.popup_css = t.baseURI.toAbsolute("themes/" + s.theme + "/skins/" + s.skin + "/dialog.css");
9944 if (s.popup_css_add)
9945 s.popup_css += ',' + t.documentBaseURI.toAbsolute(s.popup_css_add);
9947 t.controlManager = new tinymce.ControlManager(t);
9949 if (s.custom_undo_redo) {
9950 t.onBeforeExecCommand.add(function(ed, cmd, ui, val, a) {
9951 if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))
9952 t.undoManager.beforeChange();
9955 t.onExecCommand.add(function(ed, cmd, ui, val, a) {
9956 if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))
9957 t.undoManager.add();
9961 t.onExecCommand.add(function(ed, c) {
9962 // Don't refresh the select lists until caret move
9963 if (!/^(FontName|FontSize)$/.test(c))
9967 // Remove ghost selections on images and tables in Gecko
9969 function repaint(a, o) {
9970 if (!o || !o.initial)
9971 t.execCommand('mceRepaint');
9974 t.onUndo.add(repaint);
9975 t.onRedo.add(repaint);
9976 t.onSetContent.add(repaint);
9979 // Enables users to override the control factory
9980 t.onBeforeRenderUI.dispatch(t, t.controlManager);
9984 w = s.width || e.style.width || e.offsetWidth;
9985 h = s.height || e.style.height || e.offsetHeight;
9986 t.orgDisplay = e.style.display;
9987 re = /^[0-9\.]+(|px)$/i;
9989 if (re.test('' + w))
9990 w = Math.max(parseInt(w) + (o.deltaWidth || 0), 100);
9992 if (re.test('' + h))
9993 h = Math.max(parseInt(h) + (o.deltaHeight || 0), 100);
9996 o = t.theme.renderUI({
10000 deltaWidth : s.delta_width,
10001 deltaHeight : s.delta_height
10004 t.editorContainer = o.editorContainer;
10008 // User specified a document.domain value
10009 if (document.domain && location.hostname != document.domain)
10010 tinymce.relaxedDomain = document.domain;
10013 DOM.setStyles(o.sizeContainer || o.editorContainer, {
10018 // Load specified content CSS last
10019 if (s.content_css) {
10020 tinymce.each(explode(s.content_css), function(u) {
10021 t.contentCSS.push(t.documentBaseURI.toAbsolute(u));
10025 h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : '');
10029 t.iframeHTML = s.doctype + '<html><head xmlns="http://www.w3.org/1999/xhtml">';
10031 // We only need to override paths if we have to
10032 // IE has a bug where it remove site absolute urls to relative ones if this is specified
10033 if (s.document_base_url != tinymce.documentBaseURL)
10034 t.iframeHTML += '<base href="' + t.documentBaseURI.getURI() + '" />';
10036 // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode.
10038 t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />';
10040 t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=edge" />';
10042 t.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
10044 // Firefox 2 doesn't load stylesheets correctly this way
10045 if (!isGecko || !/Firefox\/2/.test(navigator.userAgent)) {
10046 for (i = 0; i < t.contentCSS.length; i++)
10047 t.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + t.contentCSS[i] + '" />';
10052 bi = s.body_id || 'tinymce';
10053 if (bi.indexOf('=') != -1) {
10054 bi = t.getParam('body_id', '', 'hash');
10055 bi = bi[t.id] || bi;
10058 bc = s.body_class || '';
10059 if (bc.indexOf('=') != -1) {
10060 bc = t.getParam('body_class', '', 'hash');
10061 bc = bc[t.id] || '';
10064 t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '"></body></html>';
10066 // Domain relaxing enabled, then set document domain
10067 if (tinymce.relaxedDomain && (isIE || (tinymce.isOpera && parseFloat(opera.version()) < 11))) {
10068 // We need to write the contents here in IE since multiple writes messes up refresh button and back button
10069 u = 'javascript:(function(){document.open();document.domain="' + document.domain + '";var ed = window.parent.tinyMCE.get("' + t.id + '");document.write(ed.iframeHTML);document.close();ed.setupIframe();})()';
10073 // TODO: ACC add the appropriate description on this.
10074 n = DOM.add(o.iframeContainer, 'iframe', {
10075 id : t.id + "_ifr",
10076 src : u || 'javascript:""', // Workaround for HTTPS warning in IE6/7
10078 title : s.aria_label,
10085 t.contentAreaContainer = o.iframeContainer;
10086 DOM.get(o.editorContainer).style.display = t.orgDisplay;
10087 DOM.get(t.id).style.display = 'none';
10088 DOM.setAttrib(t.id, 'aria-hidden', true);
10090 if (!tinymce.relaxedDomain || !u)
10093 e = n = o = null; // Cleanup
10096 setupIframe : function() {
10097 var t = this, s = t.settings, e = DOM.get(t.id), d = t.getDoc(), h, b;
10099 // Setup iframe body
10100 if (!isIE || !tinymce.relaxedDomain) {
10102 d.write(t.iframeHTML);
10105 if (tinymce.relaxedDomain)
10106 d.domain = tinymce.relaxedDomain;
10109 // Design mode needs to be added here Ctrl+A will fail otherwise
10113 d.designMode = 'On';
10115 // Will fail on Gecko if the editor is placed in an hidden container element
10116 // The design mode will be set ones the editor is focused
10120 // IE needs to use contentEditable or it will display non secure items for HTTPS
10122 // It will not steal focus if we hide it while setting contentEditable
10127 b.contentEditable = true;
10132 t.schema = new tinymce.html.Schema(s);
10134 t.dom = new tinymce.dom.DOMUtils(t.getDoc(), {
10135 keep_values : true,
10136 url_converter : t.convertURL,
10137 url_converter_scope : t,
10138 hex_colors : s.force_hex_style_colors,
10139 class_filter : s.class_filter,
10141 fix_ie_paragraphs : 1,
10145 t.parser = new tinymce.html.DomParser(s, t.schema);
10147 // Force anchor names closed
10148 t.parser.addAttributeFilter('name', function(nodes, name) {
10149 var i = nodes.length, sibling, prevSibling, parent, node;
10153 if (node.name === 'a' && node.firstChild) {
10154 parent = node.parent;
10156 // Move children after current node
10157 sibling = node.lastChild;
10159 prevSibling = sibling.prev;
10160 parent.insert(sibling, node);
10161 sibling = prevSibling;
10167 // Convert src and href into data-mce-src, data-mce-href and data-mce-style
10168 t.parser.addAttributeFilter('src,href,style', function(nodes, name) {
10169 var i = nodes.length, node, dom = t.dom, value;
10173 value = node.attr(name);
10175 if (name === "style")
10176 node.attr('data-mce-style', dom.serializeStyle(dom.parseStyle(value), node.name));
10178 node.attr('data-mce-' + name, t.convertURL(value, name, node.name));
10182 // Keep scripts from executing
10183 t.parser.addNodeFilter('script', function(nodes, name) {
10184 var i = nodes.length;
10187 nodes[i].attr('type', 'mce-text/javascript');
10190 t.parser.addNodeFilter('#cdata', function(nodes, name) {
10191 var i = nodes.length, node;
10196 node.name = '#comment';
10197 node.value = '[CDATA[' + node.value + ']]';
10201 t.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) {
10202 var i = nodes.length, node, nonEmptyElements = t.schema.getNonEmptyElements();
10207 if (node.isEmpty(nonEmptyElements))
10208 node.empty().append(new tinymce.html.Node('br', 1)).shortEnded = true;
10212 t.serializer = new tinymce.dom.Serializer(s, t.dom, t.schema);
10214 t.selection = new tinymce.dom.Selection(t.dom, t.getWin(), t.serializer);
10216 t.formatter = new tinymce.Formatter(this);
10218 // Register default formats
10219 t.formatter.register({
10221 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}},
10222 {selector : 'img,table', collapsed : false, styles : {'float' : 'left'}}
10226 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}},
10227 {selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}},
10228 {selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}}
10232 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}},
10233 {selector : 'img,table', collapsed : false, styles : {'float' : 'right'}}
10237 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}}
10241 {inline : 'strong', remove : 'all'},
10242 {inline : 'span', styles : {fontWeight : 'bold'}},
10243 {inline : 'b', remove : 'all'}
10247 {inline : 'em', remove : 'all'},
10248 {inline : 'span', styles : {fontStyle : 'italic'}},
10249 {inline : 'i', remove : 'all'}
10253 {inline : 'span', styles : {textDecoration : 'underline'}, exact : true},
10254 {inline : 'u', remove : 'all'}
10258 {inline : 'span', styles : {textDecoration : 'line-through'}, exact : true},
10259 {inline : 'strike', remove : 'all'}
10262 forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false},
10263 hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false},
10264 fontname : {inline : 'span', styles : {fontFamily : '%value'}},
10265 fontsize : {inline : 'span', styles : {fontSize : '%value'}},
10266 fontsize_class : {inline : 'span', attributes : {'class' : '%value'}},
10267 blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'},
10268 subscript : {inline : 'sub'},
10269 superscript : {inline : 'sup'},
10272 {selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true},
10273 {selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},
10274 {selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}
10278 // Register default block formats
10279 each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) {
10280 t.formatter.register(name, {block : name, remove : 'all'});
10283 // Register user defined formats
10284 t.formatter.register(t.settings.formats);
10286 t.undoManager = new tinymce.UndoManager(t);
10289 t.undoManager.onAdd.add(function(um, l) {
10291 return t.onChange.dispatch(t, l, um);
10294 t.undoManager.onUndo.add(function(um, l) {
10295 return t.onUndo.dispatch(t, l, um);
10298 t.undoManager.onRedo.add(function(um, l) {
10299 return t.onRedo.dispatch(t, l, um);
10302 t.forceBlocks = new tinymce.ForceBlocks(t, {
10303 forced_root_block : s.forced_root_block
10306 t.editorCommands = new tinymce.EditorCommands(t);
10309 t.serializer.onPreProcess.add(function(se, o) {
10310 return t.onPreProcess.dispatch(t, o, se);
10313 t.serializer.onPostProcess.add(function(se, o) {
10314 return t.onPostProcess.dispatch(t, o, se);
10317 t.onPreInit.dispatch(t);
10319 if (!s.gecko_spellcheck)
10320 t.getBody().spellcheck = 0;
10325 t.controlManager.onPostRender.dispatch(t, t.controlManager);
10326 t.onPostRender.dispatch(t);
10328 if (s.directionality)
10329 t.getBody().dir = s.directionality;
10332 t.getBody().style.whiteSpace = "nowrap";
10334 if (s.handle_node_change_callback) {
10335 t.onNodeChange.add(function(ed, cm, n) {
10336 t.execCallback('handle_node_change_callback', t.id, n, -1, -1, true, t.selection.isCollapsed());
10340 if (s.save_callback) {
10341 t.onSaveContent.add(function(ed, o) {
10342 var h = t.execCallback('save_callback', t.id, o.content, t.getBody());
10349 if (s.onchange_callback) {
10350 t.onChange.add(function(ed, l) {
10351 t.execCallback('onchange_callback', t, l);
10356 t.onBeforeSetContent.add(function(ed, o) {
10358 each(s.protect, function(pattern) {
10359 o.content = o.content.replace(pattern, function(str) {
10360 return '<!--mce:protected ' + escape(str) + '-->';
10367 if (s.convert_newlines_to_brs) {
10368 t.onBeforeSetContent.add(function(ed, o) {
10370 o.content = o.content.replace(/\r?\n/g, '<br />');
10374 if (s.preformatted) {
10375 t.onPostProcess.add(function(ed, o) {
10376 o.content = o.content.replace(/^\s*<pre.*?>/, '');
10377 o.content = o.content.replace(/<\/pre>\s*$/, '');
10380 o.content = '<pre class="mceItemHidden">' + o.content + '</pre>';
10384 if (s.verify_css_classes) {
10385 t.serializer.attribValueFilter = function(n, v) {
10388 if (n == 'class') {
10389 // Build regexp for classes
10390 if (!t.classesRE) {
10391 cl = t.dom.getClasses();
10393 if (cl.length > 0) {
10396 each (cl, function(o) {
10397 s += (s ? '|' : '') + o['class'];
10400 t.classesRE = new RegExp('(' + s + ')', 'gi');
10404 return !t.classesRE || /(\bmceItem\w+\b|\bmceTemp\w+\b)/g.test(v) || t.classesRE.test(v) ? v : '';
10411 if (s.cleanup_callback) {
10412 t.onBeforeSetContent.add(function(ed, o) {
10413 o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
10416 t.onPreProcess.add(function(ed, o) {
10418 t.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o);
10421 t.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o);
10424 t.onPostProcess.add(function(ed, o) {
10426 o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
10429 o.content = t.execCallback('cleanup_callback', 'get_from_editor', o.content, o);
10433 if (s.save_callback) {
10434 t.onGetContent.add(function(ed, o) {
10436 o.content = t.execCallback('save_callback', t.id, o.content, t.getBody());
10440 if (s.handle_event_callback) {
10441 t.onEvent.add(function(ed, e, o) {
10442 if (t.execCallback('handle_event_callback', e, ed, o) === false)
10447 // Add visual aids when new contents is added
10448 t.onSetContent.add(function() {
10449 t.addVisual(t.getBody());
10452 // Remove empty contents
10453 if (s.padd_empty_editor) {
10454 t.onPostProcess.add(function(ed, o) {
10455 o.content = o.content.replace(/^(<p[^>]*>( | |\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, '');
10460 // Fix gecko link bug, when a link is placed at the end of block elements there is
10461 // no way to move the caret behind the link. This fix adds a bogus br element after the link
10462 function fixLinks(ed, o) {
10463 each(ed.dom.select('a'), function(n) {
10464 var pn = n.parentNode;
10466 if (ed.dom.isBlock(pn) && pn.lastChild === n)
10467 ed.dom.add(pn, 'br', {'data-mce-bogus' : 1});
10471 t.onExecCommand.add(function(ed, cmd) {
10472 if (cmd === 'CreateLink')
10476 t.onSetContent.add(t.selection.onSetContent.add(fixLinks));
10480 // Design mode must be set here once again to fix a bug where
10481 // Ctrl+A/Delete/Backspace didn't work if the editor was added using mceAddControl then removed then added again
10482 d.designMode = 'Off';
10483 d.designMode = 'On';
10485 // Will fail on Gecko if the editor is placed in an hidden container element
10486 // The design mode will be set ones the editor is focused
10491 // A small timeout was needed since firefox will remove. Bug: #1838304
10492 setTimeout(function () {
10496 t.load({initial : true, format : 'html'});
10497 t.startContent = t.getContent({format : 'raw'});
10498 t.undoManager.add();
10499 t.initialized = true;
10501 t.onInit.dispatch(t);
10502 t.execCallback('setupcontent_callback', t.id, t.getBody(), t.getDoc());
10503 t.execCallback('init_instance_callback', t);
10505 t.nodeChanged({initial : 1});
10507 // Load specified content CSS last
10508 each(t.contentCSS, function(u) {
10512 // Handle auto focus
10513 if (s.auto_focus) {
10514 setTimeout(function () {
10515 var ed = tinymce.get(s.auto_focus);
10517 ed.selection.select(ed.getBody(), 1);
10518 ed.selection.collapse(1);
10519 ed.getWin().focus();
10528 focus : function(sf) {
10529 var oed, t = this, ce = t.settings.content_editable, ieRng, controlElm, doc = t.getDoc();
10532 // Get selected control element
10533 ieRng = t.selection.getRng();
10535 controlElm = ieRng.item(0);
10538 // Is not content editable
10540 t.getWin().focus();
10542 // Restore selected control element
10543 // This is needed when for example an image is selected within a
10544 // layer a call to focus will then remove the control selection
10545 if (controlElm && controlElm.ownerDocument == doc) {
10546 ieRng = doc.body.createControlRange();
10547 ieRng.addElement(controlElm);
10553 if (tinymce.activeEditor != t) {
10554 if ((oed = tinymce.activeEditor) != null)
10555 oed.onDeactivate.dispatch(oed, t);
10557 t.onActivate.dispatch(t, oed);
10560 tinymce._setActive(t);
10563 execCallback : function(n) {
10564 var t = this, f = t.settings[n], s;
10569 // Look through lookup
10570 if (t.callbackLookup && (s = t.callbackLookup[n])) {
10575 if (is(f, 'string')) {
10576 s = f.replace(/\.\w+$/, '');
10577 s = s ? tinymce.resolve(s) : 0;
10578 f = tinymce.resolve(f);
10579 t.callbackLookup = t.callbackLookup || {};
10580 t.callbackLookup[n] = {func : f, scope : s};
10583 return f.apply(s || t, Array.prototype.slice.call(arguments, 1));
10586 translate : function(s) {
10587 var c = this.settings.language || 'en', i18n = tinymce.i18n;
10592 return i18n[c + '.' + s] || s.replace(/{\#([^}]+)\}/g, function(a, b) {
10593 return i18n[c + '.' + b] || '{#' + b + '}';
10597 getLang : function(n, dv) {
10598 return tinymce.i18n[(this.settings.language || 'en') + '.' + n] || (is(dv) ? dv : '{#' + n + '}');
10601 getParam : function(n, dv, ty) {
10602 var tr = tinymce.trim, v = is(this.settings[n]) ? this.settings[n] : dv, o;
10604 if (ty === 'hash') {
10607 if (is(v, 'string')) {
10608 each(v.indexOf('=') > 0 ? v.split(/[;,](?![^=;,]*(?:[;,]|$))/) : v.split(','), function(v) {
10612 o[tr(v[0])] = tr(v[1]);
10614 o[tr(v[0])] = tr(v);
10625 nodeChanged : function(o) {
10626 var t = this, s = t.selection, n = s.getStart() || t.getBody();
10628 // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
10629 if (t.initialized) {
10631 n = isIE && n.ownerDocument != t.getDoc() ? t.getBody() : n; // Fix for IE initial state
10633 // Get parents and add them to object
10635 t.dom.getParent(n, function(node) {
10636 if (node.nodeName == 'BODY')
10639 o.parents.push(node);
10642 t.onNodeChange.dispatch(
10644 o ? o.controlManager || t.controlManager : t.controlManager,
10652 addButton : function(n, s) {
10655 t.buttons = t.buttons || {};
10659 addCommand : function(name, callback, scope) {
10660 this.execCommands[name] = {func : callback, scope : scope || this};
10663 addQueryStateHandler : function(name, callback, scope) {
10664 this.queryStateCommands[name] = {func : callback, scope : scope || this};
10667 addQueryValueHandler : function(name, callback, scope) {
10668 this.queryValueCommands[name] = {func : callback, scope : scope || this};
10671 addShortcut : function(pa, desc, cmd_func, sc) {
10674 if (!t.settings.custom_shortcuts)
10677 t.shortcuts = t.shortcuts || {};
10679 if (is(cmd_func, 'string')) {
10682 cmd_func = function() {
10683 t.execCommand(c, false, null);
10687 if (is(cmd_func, 'object')) {
10690 cmd_func = function() {
10691 t.execCommand(c[0], c[1], c[2]);
10695 each(explode(pa), function(pa) {
10698 scope : sc || this,
10705 each(explode(pa, '+'), function(v) {
10714 o.charCode = v.charCodeAt(0);
10715 o.keyCode = v.toUpperCase().charCodeAt(0);
10719 t.shortcuts[(o.ctrl ? 'ctrl' : '') + ',' + (o.alt ? 'alt' : '') + ',' + (o.shift ? 'shift' : '') + ',' + o.keyCode] = o;
10725 execCommand : function(cmd, ui, val, a) {
10726 var t = this, s = 0, o, st;
10728 if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(cmd) && (!a || !a.skip_focus))
10732 t.onBeforeExecCommand.dispatch(t, cmd, ui, val, o);
10736 // Command callback
10737 if (t.execCallback('execcommand_callback', t.id, t.selection.getNode(), cmd, ui, val)) {
10738 t.onExecCommand.dispatch(t, cmd, ui, val, a);
10742 // Registred commands
10743 if (o = t.execCommands[cmd]) {
10744 st = o.func.call(o.scope, ui, val);
10746 // Fall through on true
10748 t.onExecCommand.dispatch(t, cmd, ui, val, a);
10754 each(t.plugins, function(p) {
10755 if (p.execCommand && p.execCommand(cmd, ui, val)) {
10756 t.onExecCommand.dispatch(t, cmd, ui, val, a);
10766 if (t.theme && t.theme.execCommand && t.theme.execCommand(cmd, ui, val)) {
10767 t.onExecCommand.dispatch(t, cmd, ui, val, a);
10772 if (t.editorCommands.execCommand(cmd, ui, val)) {
10773 t.onExecCommand.dispatch(t, cmd, ui, val, a);
10777 // Browser commands
10778 t.getDoc().execCommand(cmd, ui, val);
10779 t.onExecCommand.dispatch(t, cmd, ui, val, a);
10782 queryCommandState : function(cmd) {
10783 var t = this, o, s;
10785 // Is hidden then return undefined
10789 // Registred commands
10790 if (o = t.queryStateCommands[cmd]) {
10791 s = o.func.call(o.scope);
10793 // Fall though on true
10798 // Registred commands
10799 o = t.editorCommands.queryCommandState(cmd);
10803 // Browser commands
10805 return this.getDoc().queryCommandState(cmd);
10807 // Fails sometimes see bug: 1896577
10811 queryCommandValue : function(c) {
10812 var t = this, o, s;
10814 // Is hidden then return undefined
10818 // Registred commands
10819 if (o = t.queryValueCommands[c]) {
10820 s = o.func.call(o.scope);
10822 // Fall though on true
10827 // Registred commands
10828 o = t.editorCommands.queryCommandValue(c);
10832 // Browser commands
10834 return this.getDoc().queryCommandValue(c);
10836 // Fails sometimes see bug: 1896577
10840 show : function() {
10843 DOM.show(t.getContainer());
10848 hide : function() {
10849 var t = this, d = t.getDoc();
10851 // Fixed bug where IE has a blinking cursor left from the editor
10853 d.execCommand('SelectAll');
10855 // We must save before we hide so Safari doesn't crash
10857 DOM.hide(t.getContainer());
10858 DOM.setStyle(t.id, 'display', t.orgDisplay);
10861 isHidden : function() {
10862 return !DOM.isHidden(this.id);
10865 setProgressState : function(b, ti, o) {
10866 this.onSetProgressState.dispatch(this, b, ti, o);
10871 load : function(o) {
10872 var t = this, e = t.getElement(), h;
10878 // Double encode existing entities in the value
10879 h = t.setContent(is(e.value) ? e.value : e.innerHTML, o);
10883 t.onLoadContent.dispatch(t, o);
10885 o.element = e = null;
10891 save : function(o) {
10892 var t = this, e = t.getElement(), h, f;
10894 if (!e || !t.initialized)
10900 // Add undo level will trigger onchange event
10901 if (!o.no_events) {
10902 t.undoManager.typing = false;
10903 t.undoManager.add();
10907 h = o.content = t.getContent(o);
10910 t.onSaveContent.dispatch(t, o);
10914 if (!/TEXTAREA|INPUT/i.test(e.nodeName)) {
10917 // Update hidden form element
10918 if (f = DOM.getParent(t.id, 'form')) {
10919 each(f.elements, function(e) {
10920 if (e.name == t.id) {
10929 o.element = e = null;
10934 setContent : function(content, args) {
10935 var self = this, rootNode, body = self.getBody();
10937 // Setup args object
10939 args.format = args.format || 'html';
10941 args.content = content;
10943 // Do preprocessing
10944 if (!args.no_events)
10945 self.onBeforeSetContent.dispatch(self, args);
10947 content = args.content;
10949 // Padd empty content in Gecko and Safari. Commands will otherwise fail on the content
10950 // It will also be impossible to place the caret in the editor unless there is a BR element present
10951 if (!tinymce.isIE && (content.length === 0 || /^\s+$/.test(content))) {
10952 body.innerHTML = '<br data-mce-bogus="1" />';
10956 // Parse and serialize the html
10957 if (args.format !== 'raw') {
10958 content = new tinymce.html.Serializer({}, self.schema).serialize(
10959 self.parser.parse(content)
10963 // Set the new cleaned contents to the editor
10964 args.content = tinymce.trim(content);
10965 self.dom.setHTML(body, args.content);
10967 // Do post processing
10968 if (!args.no_events)
10969 self.onSetContent.dispatch(self, args);
10971 return args.content;
10974 getContent : function(args) {
10975 var self = this, content;
10977 // Setup args object
10979 args.format = args.format || 'html';
10982 // Do preprocessing
10983 if (!args.no_events)
10984 self.onBeforeGetContent.dispatch(self, args);
10986 // Get raw contents or by default the cleaned contents
10987 if (args.format == 'raw')
10988 content = self.getBody().innerHTML;
10990 content = self.serializer.serialize(self.getBody(), args);
10992 args.content = tinymce.trim(content);
10994 // Do post processing
10995 if (!args.no_events)
10996 self.onGetContent.dispatch(self, args);
10998 return args.content;
11001 isDirty : function() {
11004 return tinymce.trim(self.startContent) != tinymce.trim(self.getContent({format : 'raw', no_events : 1})) && !self.isNotDirty;
11007 getContainer : function() {
11011 t.container = DOM.get(t.editorContainer || t.id + '_parent');
11013 return t.container;
11016 getContentAreaContainer : function() {
11017 return this.contentAreaContainer;
11020 getElement : function() {
11021 return DOM.get(this.settings.content_element || this.id);
11024 getWin : function() {
11027 if (!t.contentWindow) {
11028 e = DOM.get(t.id + "_ifr");
11031 t.contentWindow = e.contentWindow;
11034 return t.contentWindow;
11037 getDoc : function() {
11040 if (!t.contentDocument) {
11044 t.contentDocument = w.document;
11047 return t.contentDocument;
11050 getBody : function() {
11051 return this.bodyElement || this.getDoc().body;
11054 convertURL : function(u, n, e) {
11055 var t = this, s = t.settings;
11057 // Use callback instead
11058 if (s.urlconverter_callback)
11059 return t.execCallback('urlconverter_callback', u, e, true, n);
11061 // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
11062 if (!s.convert_urls || (e && e.nodeName == 'LINK') || u.indexOf('file:') === 0)
11065 // Convert to relative
11066 if (s.relative_urls)
11067 return t.documentBaseURI.toRelative(u);
11069 // Convert to absolute
11070 u = t.documentBaseURI.toAbsolute(u, s.remove_script_host);
11075 addVisual : function(e) {
11076 var t = this, s = t.settings;
11078 e = e || t.getBody();
11080 if (!is(t.hasVisual))
11081 t.hasVisual = s.visual;
11083 each(t.dom.select('table,a', e), function(e) {
11086 switch (e.nodeName) {
11088 v = t.dom.getAttrib(e, 'border');
11090 if (!v || v == '0') {
11092 t.dom.addClass(e, s.visual_table_class);
11094 t.dom.removeClass(e, s.visual_table_class);
11100 v = t.dom.getAttrib(e, 'name');
11104 t.dom.addClass(e, 'mceItemAnchor');
11106 t.dom.removeClass(e, 'mceItemAnchor');
11113 t.onVisualAid.dispatch(t, e, t.hasVisual);
11116 remove : function() {
11117 var t = this, e = t.getContainer();
11119 t.removed = 1; // Cancels post remove event execution
11122 t.execCallback('remove_instance_callback', t);
11123 t.onRemove.dispatch(t);
11125 // Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command
11126 t.onExecCommand.listeners = [];
11132 destroy : function(s) {
11135 // One time is enough
11140 tinymce.removeUnload(t.destroy);
11141 tinyMCE.onBeforeUnload.remove(t._beforeUnload);
11144 if (t.theme && t.theme.destroy)
11147 // Destroy controls, selection and dom
11148 t.controlManager.destroy();
11149 t.selection.destroy();
11152 // Remove all events
11154 // Don't clear the window or document if content editable
11155 // is enabled since other instances might still be present
11156 if (!t.settings.content_editable) {
11157 Event.clear(t.getWin());
11158 Event.clear(t.getDoc());
11161 Event.clear(t.getBody());
11162 Event.clear(t.formElement);
11165 if (t.formElement) {
11166 t.formElement.submit = t.formElement._mceOldSubmit;
11167 t.formElement._mceOldSubmit = null;
11170 t.contentAreaContainer = t.formElement = t.container = t.settings.content_element = t.bodyElement = t.contentDocument = t.contentWindow = null;
11173 t.selection = t.selection.win = t.selection.dom = t.selection.dom.doc = null;
11178 // Internal functions
11180 _addEvents : function() {
11181 // 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset
11182 var t = this, i, s = t.settings, dom = t.dom, lo = {
11183 mouseup : 'onMouseUp',
11184 mousedown : 'onMouseDown',
11187 keydown : 'onKeyDown',
11188 keypress : 'onKeyPress',
11189 submit : 'onSubmit',
11191 contextmenu : 'onContextMenu',
11192 dblclick : 'onDblClick',
11193 paste : 'onPaste' // Doesn't work in all browsers yet
11196 function eventHandler(e, o) {
11199 // Don't fire events when it's removed
11203 // Generic event handler
11204 if (t.onEvent.dispatch(t, e, o) !== false) {
11205 // Specific event handler
11206 t[lo[e.fakeType || e.type]].dispatch(t, e, o);
11211 each(lo, function(v, k) {
11213 case 'contextmenu':
11214 dom.bind(t.getDoc(), k, eventHandler);
11218 dom.bind(t.getBody(), k, function(e) {
11225 dom.bind(t.getElement().form || DOM.getParent(t.id, 'form'), k, eventHandler);
11229 dom.bind(s.content_editable ? t.getBody() : t.getDoc(), k, eventHandler);
11233 dom.bind(s.content_editable ? t.getBody() : (isGecko ? t.getDoc() : t.getWin()), 'focus', function(e) {
11238 // Fixes bug where a specified document_base_uri could result in broken images
11239 // This will also fix drag drop of images in Gecko
11240 if (tinymce.isGecko) {
11241 dom.bind(t.getDoc(), 'DOMNodeInserted', function(e) {
11246 if (e.nodeType === 1 && e.nodeName === 'IMG' && (v = e.getAttribute('data-mce-src')))
11247 e.src = t.documentBaseURI.toAbsolute(v);
11251 // Set various midas options in Gecko
11253 function setOpts() {
11254 var t = this, d = t.getDoc(), s = t.settings;
11256 if (isGecko && !s.readonly) {
11257 if (t._isHidden()) {
11259 if (!s.content_editable)
11260 d.designMode = 'On';
11262 // Fails if it's hidden
11267 // Try new Gecko method
11268 d.execCommand("styleWithCSS", 0, false);
11271 if (!t._isHidden())
11272 try {d.execCommand("useCSS", 0, true);} catch (ex) {}
11275 if (!s.table_inline_editing)
11276 try {d.execCommand('enableInlineTableEditing', false, false);} catch (ex) {}
11278 if (!s.object_resizing)
11279 try {d.execCommand('enableObjectResizing', false, false);} catch (ex) {}
11283 t.onBeforeExecCommand.add(setOpts);
11284 t.onMouseDown.add(setOpts);
11287 // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
11288 // WebKit can't even do simple things like selecting an image
11289 // This also fixes so it's possible to select mceItemAnchors
11290 if (tinymce.isWebKit) {
11291 t.onClick.add(function(ed, e) {
11294 // Needs tobe the setBaseAndExtend or it will fail to select floated images
11295 if (e.nodeName == 'IMG' || (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor'))) {
11296 t.selection.getSel().setBaseAndExtent(e, 0, e, 1);
11302 // Add node change handlers
11303 t.onMouseUp.add(t.nodeChanged);
11304 //t.onClick.add(t.nodeChanged);
11305 t.onKeyUp.add(function(ed, e) {
11308 if ((c >= 33 && c <= 36) || (c >= 37 && c <= 40) || c == 13 || c == 45 || c == 46 || c == 8 || (tinymce.isMac && (c == 91 || c == 93)) || e.ctrlKey)
11312 // Add reset handler
11313 t.onReset.add(function() {
11314 t.setContent(t.startContent, {format : 'raw'});
11318 if (s.custom_shortcuts) {
11319 if (s.custom_undo_redo_keyboard_shortcuts) {
11320 t.addShortcut('ctrl+z', t.getLang('undo_desc'), 'Undo');
11321 t.addShortcut('ctrl+y', t.getLang('redo_desc'), 'Redo');
11324 // Add default shortcuts for gecko
11325 t.addShortcut('ctrl+b', t.getLang('bold_desc'), 'Bold');
11326 t.addShortcut('ctrl+i', t.getLang('italic_desc'), 'Italic');
11327 t.addShortcut('ctrl+u', t.getLang('underline_desc'), 'Underline');
11329 // BlockFormat shortcuts keys
11330 for (i=1; i<=6; i++)
11331 t.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
11333 t.addShortcut('ctrl+7', '', ['FormatBlock', false, '<p>']);
11334 t.addShortcut('ctrl+8', '', ['FormatBlock', false, '<div>']);
11335 t.addShortcut('ctrl+9', '', ['FormatBlock', false, '<address>']);
11340 if (!e.altKey && !e.ctrlKey && !e.metaKey)
11343 each(t.shortcuts, function(o) {
11344 if (tinymce.isMac && o.ctrl != e.metaKey)
11346 else if (!tinymce.isMac && o.ctrl != e.ctrlKey)
11349 if (o.alt != e.altKey)
11352 if (o.shift != e.shiftKey)
11355 if (e.keyCode == o.keyCode || (e.charCode && e.charCode == o.charCode)) {
11364 t.onKeyUp.add(function(ed, e) {
11368 return Event.cancel(e);
11371 t.onKeyPress.add(function(ed, e) {
11375 return Event.cancel(e);
11378 t.onKeyDown.add(function(ed, e) {
11382 o.func.call(o.scope);
11383 return Event.cancel(e);
11388 if (tinymce.isIE) {
11389 // Fix so resize will only update the width and height attributes not the styles of an image
11390 // It will also block mceItemNoResize items
11391 dom.bind(t.getDoc(), 'controlselect', function(e) {
11392 var re = t.resizeInfo, cb;
11396 // Don't do this action for non image elements
11397 if (e.nodeName !== 'IMG')
11401 dom.unbind(re.node, re.ev, re.cb);
11403 if (!dom.hasClass(e, 'mceItemNoResize')) {
11405 cb = dom.bind(e, ev, function(e) {
11410 if (v = dom.getStyle(e, 'width')) {
11411 dom.setAttrib(e, 'width', v.replace(/[^0-9%]+/g, ''));
11412 dom.setStyle(e, 'width', '');
11415 if (v = dom.getStyle(e, 'height')) {
11416 dom.setAttrib(e, 'height', v.replace(/[^0-9%]+/g, ''));
11417 dom.setStyle(e, 'height', '');
11421 ev = 'resizestart';
11422 cb = dom.bind(e, 'resizestart', Event.cancel, Event);
11425 re = t.resizeInfo = {
11432 t.onKeyDown.add(function(ed, e) {
11435 switch (e.keyCode) {
11437 sel = t.getDoc().selection;
11439 // Fix IE control + backspace browser bug
11440 if (sel.createRange && sel.createRange().item) {
11441 ed.dom.remove(sel.createRange().item(0));
11442 return Event.cancel(e);
11448 if (tinymce.isOpera) {
11449 t.onClick.add(function(ed, e) {
11454 // Add custom undo/redo handlers
11455 if (s.custom_undo_redo) {
11456 function addUndo() {
11457 t.undoManager.typing = false;
11458 t.undoManager.add();
11461 dom.bind(t.getDoc(), 'focusout', function(e) {
11462 if (!t.removed && t.undoManager.typing)
11466 // Add undo level when contents is drag/dropped within the editor
11467 t.dom.bind(t.dom.getRoot(), 'dragend', function(e) {
11471 t.onKeyUp.add(function(ed, e) {
11472 var rng, parent, bookmark;
11474 // Fix for bug #3168, to remove odd ".." nodes from the DOM we need to get/set the HTML of the parent node.
11475 if (isIE && e.keyCode == 8) {
11476 rng = t.selection.getRng();
11477 if (rng.parentElement) {
11478 parent = rng.parentElement();
11479 bookmark = t.selection.getBookmark();
11480 parent.innerHTML = parent.innerHTML;
11481 t.selection.moveToBookmark(bookmark);
11485 if ((e.keyCode >= 33 && e.keyCode <= 36) || (e.keyCode >= 37 && e.keyCode <= 40) || e.keyCode == 13 || e.keyCode == 45 || e.ctrlKey)
11489 t.onKeyDown.add(function(ed, e) {
11490 var rng, parent, bookmark, keyCode = e.keyCode;
11492 // IE has a really odd bug where the DOM might include an node that doesn't have
11493 // a proper structure. If you try to access nodeValue it would throw an illegal value exception.
11494 // This seems to only happen when you delete contents and it seems to be avoidable if you refresh the element
11495 // after you delete contents from it. See: #3008923
11496 if (isIE && keyCode == 46) {
11497 rng = t.selection.getRng();
11499 if (rng.parentElement) {
11500 parent = rng.parentElement();
11502 if (!t.undoManager.typing) {
11503 t.undoManager.beforeChange();
11504 t.undoManager.typing = true;
11505 t.undoManager.add();
11508 // Select next word when ctrl key is used in combo with delete
11510 rng.moveEnd('word', 1);
11515 t.selection.getSel().clear();
11517 // Check if we are within the same parent
11518 if (rng.parentElement() == parent) {
11519 bookmark = t.selection.getBookmark();
11522 // Update the HTML and hopefully it will remove the artifacts
11523 parent.innerHTML = parent.innerHTML;
11525 // And since it's IE it can sometimes produce an unknown runtime error
11528 // Restore the caret position
11529 t.selection.moveToBookmark(bookmark);
11532 // Block the default delete behavior since it might be broken
11533 e.preventDefault();
11538 // Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter
11539 if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45) {
11540 // Add position before enter key is pressed, used by IE since it still uses the default browser behavior
11541 // Todo: Remove this once we normalize enter behavior on IE
11542 if (tinymce.isIE && keyCode == 13)
11543 t.undoManager.beforeChange();
11545 if (t.undoManager.typing)
11551 // If key isn't shift,ctrl,alt,capslock,metakey
11552 if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !t.undoManager.typing) {
11553 t.undoManager.beforeChange();
11554 t.undoManager.add();
11555 t.undoManager.typing = true;
11559 t.onMouseDown.add(function() {
11560 if (t.undoManager.typing)
11565 // Bug fix for FireFox keeping styles from end of selection instead of start.
11566 if (tinymce.isGecko) {
11567 function getAttributeApplyFunction() {
11568 var template = t.dom.getAttribs(t.selection.getStart().cloneNode(false));
11570 return function() {
11571 var target = t.selection.getStart();
11572 t.dom.removeAllAttribs(target);
11573 each(template, function(attr) {
11574 target.setAttributeNode(attr.cloneNode(true));
11579 function isSelectionAcrossElements() {
11580 var s = t.selection;
11582 return !s.isCollapsed() && s.getStart() != s.getEnd();
11585 t.onKeyPress.add(function(ed, e) {
11586 var applyAttributes;
11588 if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {
11589 applyAttributes = getAttributeApplyFunction();
11590 t.getDoc().execCommand('delete', false, null);
11593 return Event.cancel(e);
11597 t.dom.bind(t.getDoc(), 'cut', function(e) {
11598 var applyAttributes;
11600 if (isSelectionAcrossElements()) {
11601 applyAttributes = getAttributeApplyFunction();
11602 t.onKeyUp.addToTop(Event.cancel, Event);
11604 setTimeout(function() {
11606 t.onKeyUp.remove(Event.cancel, Event);
11613 _isHidden : function() {
11619 // Weird, wheres that cursor selection?
11620 s = this.selection.getSel();
11621 return (!s || !s.rangeCount || s.rangeCount == 0);
11626 (function(tinymce) {
11627 // Added for compression purposes
11628 var each = tinymce.each, undefined, TRUE = true, FALSE = false;
11630 tinymce.EditorCommands = function(editor) {
11631 var dom = editor.dom,
11632 selection = editor.selection,
11633 commands = {state: {}, exec : {}, value : {}},
11634 settings = editor.settings,
11637 function execCommand(command, ui, value) {
11640 command = command.toLowerCase();
11641 if (func = commands.exec[command]) {
11642 func(command, ui, value);
11649 function queryCommandState(command) {
11652 command = command.toLowerCase();
11653 if (func = commands.state[command])
11654 return func(command);
11659 function queryCommandValue(command) {
11662 command = command.toLowerCase();
11663 if (func = commands.value[command])
11664 return func(command);
11669 function addCommands(command_list, type) {
11670 type = type || 'exec';
11672 each(command_list, function(callback, command) {
11673 each(command.toLowerCase().split(','), function(command) {
11674 commands[type][command] = callback;
11679 // Expose public methods
11680 tinymce.extend(this, {
11681 execCommand : execCommand,
11682 queryCommandState : queryCommandState,
11683 queryCommandValue : queryCommandValue,
11684 addCommands : addCommands
11689 function execNativeCommand(command, ui, value) {
11690 if (ui === undefined)
11693 if (value === undefined)
11696 return editor.getDoc().execCommand(command, ui, value);
11699 function isFormatMatch(name) {
11700 return editor.formatter.match(name);
11703 function toggleFormat(name, value) {
11704 editor.formatter.toggle(name, value ? {value : value} : undefined);
11707 function storeSelection(type) {
11708 bookmark = selection.getBookmark(type);
11711 function restoreSelection() {
11712 selection.moveToBookmark(bookmark);
11715 // Add execCommand overrides
11717 // Ignore these, added for compatibility
11718 'mceResetDesignMode,mceBeginUndoLevel' : function() {},
11720 // Add undo manager logic
11721 'mceEndUndoLevel,mceAddUndoLevel' : function() {
11722 editor.undoManager.add();
11725 'Cut,Copy,Paste' : function(command) {
11726 var doc = editor.getDoc(), failed;
11728 // Try executing the native command
11730 execNativeCommand(command);
11736 // Present alert message about clipboard access not being available
11737 if (failed || !doc.queryCommandSupported(command)) {
11738 if (tinymce.isGecko) {
11739 editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) {
11741 open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank');
11744 editor.windowManager.alert(editor.getLang('clipboard_no_support'));
11748 // Override unlink command
11749 unlink : function(command) {
11750 if (selection.isCollapsed())
11751 selection.select(selection.getNode());
11753 execNativeCommand(command);
11754 selection.collapse(FALSE);
11757 // Override justify commands to use the text formatter engine
11758 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {
11759 var align = command.substring(7);
11761 // Remove all other alignments first
11762 each('left,center,right,full'.split(','), function(name) {
11764 editor.formatter.remove('align' + name);
11767 toggleFormat('align' + align);
11768 execCommand('mceRepaint');
11771 // Override list commands to fix WebKit bug
11772 'InsertUnorderedList,InsertOrderedList' : function(command) {
11773 var listElm, listParent;
11775 execNativeCommand(command);
11777 // WebKit produces lists within block elements so we need to split them
11778 // we will replace the native list creation logic to custom logic later on
11779 // TODO: Remove this when the list creation logic is removed
11780 listElm = dom.getParent(selection.getNode(), 'ol,ul');
11782 listParent = listElm.parentNode;
11784 // If list is within a text block then split that block
11785 if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
11787 dom.split(listParent, listElm);
11788 restoreSelection();
11793 // Override commands to use the text formatter engine
11794 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {
11795 toggleFormat(command);
11798 // Override commands to use the text formatter engine
11799 'ForeColor,HiliteColor,FontName' : function(command, ui, value) {
11800 toggleFormat(command, value);
11803 FontSize : function(command, ui, value) {
11804 var fontClasses, fontSizes;
11806 // Convert font size 1-7 to styles
11807 if (value >= 1 && value <= 7) {
11808 fontSizes = tinymce.explode(settings.font_size_style_values);
11809 fontClasses = tinymce.explode(settings.font_size_classes);
11812 value = fontClasses[value - 1] || value;
11814 value = fontSizes[value - 1] || value;
11817 toggleFormat(command, value);
11820 RemoveFormat : function(command) {
11821 editor.formatter.remove(command);
11824 mceBlockQuote : function(command) {
11825 toggleFormat('blockquote');
11828 FormatBlock : function(command, ui, value) {
11829 return toggleFormat(value || 'p');
11832 mceCleanup : function() {
11833 var bookmark = selection.getBookmark();
11835 editor.setContent(editor.getContent({cleanup : TRUE}), {cleanup : TRUE});
11837 selection.moveToBookmark(bookmark);
11840 mceRemoveNode : function(command, ui, value) {
11841 var node = value || selection.getNode();
11843 // Make sure that the body node isn't removed
11844 if (node != editor.getBody()) {
11846 editor.dom.remove(node, TRUE);
11847 restoreSelection();
11851 mceSelectNodeDepth : function(command, ui, value) {
11854 dom.getParent(selection.getNode(), function(node) {
11855 if (node.nodeType == 1 && counter++ == value) {
11856 selection.select(node);
11859 }, editor.getBody());
11862 mceSelectNode : function(command, ui, value) {
11863 selection.select(value);
11866 mceInsertContent : function(command, ui, value) {
11867 var caretNode, rng, rootNode, parent, node, rng, nodeRect, viewPortRect, args;
11869 function findSuitableCaretNode(node, root_node, next) {
11870 var walker = new tinymce.dom.TreeWalker(next ? node.nextSibling : node.previousSibling, root_node);
11872 while ((node = walker.current())) {
11873 if ((node.nodeType == 3 && tinymce.trim(node.nodeValue).length) || node.nodeName == 'BR' || node.nodeName == 'IMG')
11883 args = {content: value, format: 'html'};
11884 selection.onBeforeSetContent.dispatch(selection, args);
11885 value = args.content;
11887 // Add caret at end of contents if it's missing
11888 if (value.indexOf('{$caret}') == -1)
11889 value += '{$caret}';
11891 // Set the content at selection to a span and replace it's contents with the value
11892 selection.setContent('<span id="__mce">\uFEFF</span>', {no_events : false});
11893 dom.setOuterHTML('__mce', value.replace(/\{\$caret\}/, '<span data-mce-type="bookmark" id="__mce">\uFEFF</span>'));
11895 caretNode = dom.select('#__mce')[0];
11896 rootNode = dom.getRoot();
11898 // Move the caret into the last suitable location within the previous sibling if it's a block since the block might be split
11899 if (caretNode.previousSibling && dom.isBlock(caretNode.previousSibling) || caretNode.parentNode == rootNode) {
11900 node = findSuitableCaretNode(caretNode, rootNode);
11902 if (node.nodeName == 'BR')
11903 node.parentNode.insertBefore(caretNode, node);
11905 dom.insertAfter(caretNode, node);
11909 // Find caret root parent and clean it up using the serializer to avoid nesting
11910 while (caretNode) {
11911 if (caretNode === rootNode) {
11912 // Clean up the parent element by parsing and serializing it
11913 // This will remove invalid elements/attributes and fix nesting issues
11914 dom.setOuterHTML(parent,
11915 new tinymce.html.Serializer({}, editor.schema).serialize(
11916 editor.parser.parse(dom.getOuterHTML(parent))
11923 parent = caretNode;
11924 caretNode = caretNode.parentNode;
11927 // Find caret after cleanup and move selection to that location
11928 caretNode = dom.select('#__mce')[0];
11930 node = findSuitableCaretNode(caretNode, rootNode) || findSuitableCaretNode(caretNode, rootNode, true);
11931 dom.remove(caretNode);
11934 rng = dom.createRng();
11936 if (node.nodeType == 3) {
11937 rng.setStart(node, node.length);
11938 rng.setEnd(node, node.length);
11940 if (node.nodeName == 'BR') {
11941 rng.setStartBefore(node);
11942 rng.setEndBefore(node);
11944 rng.setStartAfter(node);
11945 rng.setEndAfter(node);
11949 selection.setRng(rng);
11951 // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well
11952 if (!tinymce.isIE) {
11953 node = dom.create('span', null, '\u00a0');
11954 rng.insertNode(node);
11955 nodeRect = dom.getRect(node);
11956 viewPortRect = dom.getViewPort(editor.getWin());
11958 // Check if node is out side the viewport if it is then scroll to it
11959 if ((nodeRect.y > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) ||
11960 (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) {
11961 editor.getBody().scrollLeft = nodeRect.x;
11962 editor.getBody().scrollTop = nodeRect.y;
11968 // Make sure that the selection is collapsed after we removed the node fixes a WebKit bug
11969 // where WebKit would place the endContainer/endOffset at a different location than the startContainer/startOffset
11970 selection.collapse(true);
11974 selection.onSetContent.dispatch(selection, args);
11975 editor.addVisual();
11978 mceInsertRawHTML : function(command, ui, value) {
11979 selection.setContent('tiny_mce_marker');
11980 editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value }));
11983 mceSetContent : function(command, ui, value) {
11984 editor.setContent(value);
11987 'Indent,Outdent' : function(command) {
11988 var intentValue, indentUnit, value;
11990 // Setup indent level
11991 intentValue = settings.indentation;
11992 indentUnit = /[a-z%]+$/i.exec(intentValue);
11993 intentValue = parseInt(intentValue);
11995 if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {
11996 each(selection.getSelectedBlocks(), function(element) {
11997 if (command == 'outdent') {
11998 value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue);
11999 dom.setStyle(element, 'paddingLeft', value ? value + indentUnit : '');
12001 dom.setStyle(element, 'paddingLeft', (parseInt(element.style.paddingLeft || 0) + intentValue) + indentUnit);
12004 execNativeCommand(command);
12007 mceRepaint : function() {
12010 if (tinymce.isGecko) {
12012 storeSelection(TRUE);
12014 if (selection.getSel())
12015 selection.getSel().selectAllChildren(editor.getBody());
12017 selection.collapse(TRUE);
12018 restoreSelection();
12025 mceToggleFormat : function(command, ui, value) {
12026 editor.formatter.toggle(value);
12029 InsertHorizontalRule : function() {
12030 editor.execCommand('mceInsertContent', false, '<hr />');
12033 mceToggleVisualAid : function() {
12034 editor.hasVisual = !editor.hasVisual;
12035 editor.addVisual();
12038 mceReplaceContent : function(command, ui, value) {
12039 editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'})));
12042 mceInsertLink : function(command, ui, value) {
12043 var link = dom.getParent(selection.getNode(), 'a'), img, floatVal;
12045 if (tinymce.is(value, 'string'))
12046 value = {href : value};
12048 // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
12049 value.href = value.href.replace(' ', '%20');
12052 // WebKit can't create links on float images for some odd reason so just remove it and restore it later
12053 if (tinymce.isWebKit) {
12054 img = dom.getParent(selection.getNode(), 'img');
12057 floatVal = img.style.cssFloat;
12058 img.style.cssFloat = null;
12062 execNativeCommand('CreateLink', FALSE, 'javascript:mctmp(0);');
12064 // Restore float value
12066 img.style.cssFloat = floatVal;
12068 each(dom.select("a[href='javascript:mctmp(0);']"), function(link) {
12069 dom.setAttribs(link, value);
12073 dom.setAttribs(link, value);
12075 editor.dom.remove(link, TRUE);
12079 selectAll : function() {
12080 var root = dom.getRoot(), rng = dom.createRng();
12082 rng.setStart(root, 0);
12083 rng.setEnd(root, root.childNodes.length);
12085 editor.selection.setRng(rng);
12089 // Add queryCommandState overrides
12091 // Override justify commands
12092 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {
12093 return isFormatMatch('align' + command.substring(7));
12096 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {
12097 return isFormatMatch(command);
12100 mceBlockQuote : function() {
12101 return isFormatMatch('blockquote');
12104 Outdent : function() {
12107 if (settings.inline_styles) {
12108 if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0)
12111 if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0)
12115 return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE'));
12118 'InsertUnorderedList,InsertOrderedList' : function(command) {
12119 return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL');
12123 // Add queryCommandValue overrides
12125 'FontSize,FontName' : function(command) {
12126 var value = 0, parent;
12128 if (parent = dom.getParent(selection.getNode(), 'span')) {
12129 if (command == 'fontsize')
12130 value = parent.style.fontSize;
12132 value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase();
12139 // Add undo manager logic
12140 if (settings.custom_undo_redo) {
12142 Undo : function() {
12143 editor.undoManager.undo();
12146 Redo : function() {
12147 editor.undoManager.redo();
12154 (function(tinymce) {
12155 var Dispatcher = tinymce.util.Dispatcher;
12157 tinymce.UndoManager = function(editor) {
12158 var self, index = 0, data = [];
12160 function getContent() {
12161 return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}));
12167 onAdd : new Dispatcher(self),
12169 onUndo : new Dispatcher(self),
12171 onRedo : new Dispatcher(self),
12173 beforeChange : function() {
12174 // Set before bookmark on previous level
12176 data[index].beforeBookmark = editor.selection.getBookmark(2, true);
12179 add : function(level) {
12180 var i, settings = editor.settings, lastLevel;
12182 level = level || {};
12183 level.content = getContent();
12185 // Add undo level if needed
12186 lastLevel = data[index];
12187 if (lastLevel && lastLevel.content == level.content)
12190 // Time to compress
12191 if (settings.custom_undo_redo_levels) {
12192 if (data.length > settings.custom_undo_redo_levels) {
12193 for (i = 0; i < data.length - 1; i++)
12194 data[i] = data[i + 1];
12197 index = data.length;
12201 // Get a non intrusive normalized bookmark
12202 level.bookmark = editor.selection.getBookmark(2, true);
12204 // Crop array if needed
12205 if (index < data.length - 1)
12206 data.length = index + 1;
12209 index = data.length - 1;
12211 self.onAdd.dispatch(self, level);
12212 editor.isNotDirty = 0;
12217 undo : function() {
12222 self.typing = false;
12226 level = data[--index];
12228 editor.setContent(level.content, {format : 'raw'});
12229 editor.selection.moveToBookmark(level.beforeBookmark);
12231 self.onUndo.dispatch(self, level);
12237 redo : function() {
12240 if (index < data.length - 1) {
12241 level = data[++index];
12243 editor.setContent(level.content, {format : 'raw'});
12244 editor.selection.moveToBookmark(level.bookmark);
12246 self.onRedo.dispatch(self, level);
12252 clear : function() {
12255 self.typing = false;
12258 hasUndo : function() {
12259 return index > 0 || this.typing;
12262 hasRedo : function() {
12263 return index < data.length - 1 && !this.typing;
12269 (function(tinymce) {
12271 var Event = tinymce.dom.Event,
12272 isIE = tinymce.isIE,
12273 isGecko = tinymce.isGecko,
12274 isOpera = tinymce.isOpera,
12275 each = tinymce.each,
12276 extend = tinymce.extend,
12280 function cloneFormats(node) {
12281 var clone, temp, inner;
12284 if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {
12286 temp = node.cloneNode(false);
12287 temp.appendChild(clone);
12290 clone = inner = node.cloneNode(false);
12293 clone.removeAttribute('id');
12295 } while (node = node.parentNode);
12298 return {wrapper : clone, inner : inner};
12301 // Checks if the selection/caret is at the end of the specified block element
12302 function isAtEnd(rng, par) {
12303 var rng2 = par.ownerDocument.createRange();
12305 rng2.setStart(rng.endContainer, rng.endOffset);
12306 rng2.setEndAfter(par);
12308 // Get number of characters to the right of the cursor if it's zero then we are at the end and need to merge the next block element
12309 return rng2.cloneContents().textContent.length == 0;
12312 function splitList(selection, dom, li) {
12313 var listBlock, block;
12315 if (dom.isEmpty(li)) {
12316 listBlock = dom.getParent(li, 'ul,ol');
12318 if (!dom.getParent(listBlock.parentNode, 'ul,ol')) {
12319 dom.split(listBlock, li);
12320 block = dom.create('p', 0, '<br data-mce-bogus="1" />');
12321 dom.replace(block, li);
12322 selection.select(block, 1);
12331 tinymce.create('tinymce.ForceBlocks', {
12332 ForceBlocks : function(ed) {
12333 var t = this, s = ed.settings, elm;
12337 elm = (s.forced_root_block || 'p').toLowerCase();
12338 s.element = elm.toUpperCase();
12340 ed.onPreInit.add(t.setup, t);
12342 if (s.forced_root_block) {
12343 ed.onInit.add(t.forceRoots, t);
12344 ed.onSetContent.add(t.forceRoots, t);
12345 ed.onBeforeGetContent.add(t.forceRoots, t);
12346 ed.onExecCommand.add(function(ed, cmd) {
12347 if (cmd == 'mceInsertContent') {
12355 setup : function() {
12356 var t = this, ed = t.editor, s = ed.settings, dom = ed.dom, selection = ed.selection;
12358 // Force root blocks when typing and when getting output
12359 if (s.forced_root_block) {
12360 ed.onBeforeExecCommand.add(t.forceRoots, t);
12361 ed.onKeyUp.add(t.forceRoots, t);
12362 ed.onPreProcess.add(t.forceRoots, t);
12365 if (s.force_br_newlines) {
12366 // Force IE to produce BRs on enter
12368 ed.onKeyPress.add(function(ed, e) {
12371 if (e.keyCode == 13 && selection.getNode().nodeName != 'LI') {
12372 selection.setContent('<br id="__" /> ', {format : 'raw'});
12374 n.removeAttribute('id');
12375 selection.select(n);
12376 selection.collapse();
12377 return Event.cancel(e);
12383 if (s.force_p_newlines) {
12385 ed.onKeyPress.add(function(ed, e) {
12386 if (e.keyCode == 13 && !e.shiftKey && !t.insertPara(e))
12390 // Ungly hack to for IE to preserve the formatting when you press
12391 // enter at the end of a block element with formatted contents
12392 // This logic overrides the browsers default logic with
12393 // custom logic that enables us to control the output
12394 tinymce.addUnload(function() {
12395 t._previousFormats = 0; // Fix IE leak
12398 ed.onKeyPress.add(function(ed, e) {
12399 t._previousFormats = 0;
12401 // Clone the current formats, this will later be applied to the new block contents
12402 if (e.keyCode == 13 && !e.shiftKey && ed.selection.isCollapsed() && s.keep_styles)
12403 t._previousFormats = cloneFormats(ed.selection.getStart());
12406 ed.onKeyUp.add(function(ed, e) {
12407 // Let IE break the element and the wrap the new caret location in the previous formats
12408 if (e.keyCode == 13 && !e.shiftKey) {
12409 var parent = ed.selection.getStart(), fmt = t._previousFormats;
12411 // Parent is an empty block
12412 if (!parent.hasChildNodes() && fmt) {
12413 parent = dom.getParent(parent, dom.isBlock);
12415 if (parent && parent.nodeName != 'LI') {
12416 parent.innerHTML = '';
12418 if (t._previousFormats) {
12419 parent.appendChild(fmt.wrapper);
12420 fmt.inner.innerHTML = '\uFEFF';
12422 parent.innerHTML = '\uFEFF';
12424 selection.select(parent, 1);
12425 selection.collapse(true);
12426 ed.getDoc().execCommand('Delete', false, null);
12427 t._previousFormats = 0;
12435 ed.onKeyDown.add(function(ed, e) {
12436 if ((e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey)
12437 t.backspaceDelete(e, e.keyCode == 8);
12442 // Workaround for missing shift+enter support, http://bugs.webkit.org/show_bug.cgi?id=16973
12443 if (tinymce.isWebKit) {
12444 function insertBr(ed) {
12445 var rng = selection.getRng(), br, div = dom.create('div', null, ' '), divYPos, vpHeight = dom.getViewPort(ed.getWin()).h;
12447 // Insert BR element
12448 rng.insertNode(br = dom.create('br'));
12450 // Place caret after BR
12451 rng.setStartAfter(br);
12452 rng.setEndAfter(br);
12453 selection.setRng(rng);
12455 // Could not place caret after BR then insert an nbsp entity and move the caret
12456 if (selection.getSel().focusNode == br.previousSibling) {
12457 selection.select(dom.insertAfter(dom.doc.createTextNode('\u00a0'), br));
12458 selection.collapse(TRUE);
12461 // Create a temporary DIV after the BR and get the position as it
12462 // seems like getPos() returns 0 for text nodes and BR elements.
12463 dom.insertAfter(div, br);
12464 divYPos = dom.getPos(div).y;
12467 // Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117
12468 if (divYPos > vpHeight) // It is not necessary to scroll if the DIV is inside the view port.
12469 ed.getWin().scrollTo(0, divYPos);
12472 ed.onKeyPress.add(function(ed, e) {
12473 if (e.keyCode == 13 && (e.shiftKey || (s.force_br_newlines && !dom.getParent(selection.getNode(), 'h1,h2,h3,h4,h5,h6,ol,ul')))) {
12480 // IE specific fixes
12482 // Replaces IE:s auto generated paragraphs with the specified element name
12483 if (s.element != 'P') {
12484 ed.onKeyPress.add(function(ed, e) {
12485 t.lastElm = selection.getNode().nodeName;
12488 ed.onKeyUp.add(function(ed, e) {
12489 var bl, n = selection.getNode(), b = ed.getBody();
12491 if (b.childNodes.length === 1 && n.nodeName == 'P') {
12492 n = dom.rename(n, s.element);
12493 selection.select(n);
12494 selection.collapse();
12496 } else if (e.keyCode == 13 && !e.shiftKey && t.lastElm != 'P') {
12497 bl = dom.getParent(n, 'p');
12500 dom.rename(bl, s.element);
12509 find : function(n, t, s) {
12510 var ed = this.editor, w = ed.getDoc().createTreeWalker(n, 4, null, FALSE), c = -1;
12512 while (n = w.nextNode()) {
12516 if (t == 0 && n == s)
12520 if (t == 1 && c == s)
12527 forceRoots : function(ed, e) {
12528 var t = this, ed = t.editor, b = ed.getBody(), d = ed.getDoc(), se = ed.selection, s = se.getSel(), r = se.getRng(), si = -2, ei, so, eo, tr, c = -0xFFFFFF;
12529 var nx, bl, bp, sp, le, nl = b.childNodes, i, n, eid;
12531 // Fix for bug #1863847
12532 //if (e && e.keyCode == 13)
12535 // Wrap non blocks into blocks
12536 for (i = nl.length - 1; i >= 0; i--) {
12539 // Ignore internal elements
12540 if (nx.nodeType === 1 && nx.getAttribute('data-mce-type')) {
12545 // Is text or non block element
12546 if (nx.nodeType === 3 || (!t.dom.isBlock(nx) && nx.nodeType !== 8 && !/^(script|mce:script|style|mce:style)$/i.test(nx.nodeName))) {
12548 // Create new block but ignore whitespace
12549 if (nx.nodeType != 3 || /[^\s]/g.test(nx.nodeValue)) {
12551 if (si == -2 && r) {
12552 if (!isIE || r.setStart) {
12553 // If selection is element then mark it
12554 if (r.startContainer.nodeType == 1 && (n = r.startContainer.childNodes[r.startOffset]) && n.nodeType == 1) {
12555 // Save the id of the selected element
12556 eid = n.getAttribute("id");
12557 n.setAttribute("id", "__mce");
12559 // If element is inside body, might not be the case in contentEdiable mode
12560 if (ed.dom.getParent(r.startContainer, function(e) {return e === b;})) {
12561 so = r.startOffset;
12563 si = t.find(b, 0, r.startContainer);
12564 ei = t.find(b, 0, r.endContainer);
12568 // Force control range into text range
12570 tr = d.body.createTextRange();
12571 tr.moveToElementText(r.item(0));
12575 tr = d.body.createTextRange();
12576 tr.moveToElementText(b);
12578 bp = tr.move('character', c) * -1;
12580 tr = r.duplicate();
12582 sp = tr.move('character', c) * -1;
12584 tr = r.duplicate();
12586 le = (tr.move('character', c) * -1) - sp;
12593 // Uses replaceChild instead of cloneNode since it removes selected attribute from option elements on IE
12594 // See: http://support.microsoft.com/kb/829907
12595 bl = ed.dom.create(ed.settings.forced_root_block);
12596 nx.parentNode.replaceChild(bl, nx);
12597 bl.appendChild(nx);
12600 if (bl.hasChildNodes())
12601 bl.insertBefore(nx, bl.firstChild);
12603 bl.appendChild(nx);
12606 bl = null; // Time to create new block
12609 // Restore selection
12611 if (!isIE || r.setStart) {
12612 bl = b.getElementsByTagName(ed.settings.element)[0];
12613 r = d.createRange();
12615 // Select last location or generated block
12617 r.setStart(t.find(b, 1, si), so);
12621 // Select last location or generated block
12623 r.setEnd(t.find(b, 1, ei), eo);
12628 s.removeAllRanges();
12633 r = s.createRange();
12634 r.moveToElementText(b);
12636 r.moveStart('character', si);
12637 r.moveEnd('character', ei);
12643 } else if ((!isIE || r.setStart) && (n = ed.dom.get('__mce'))) {
12644 // Restore the id of the selected element
12646 n.setAttribute('id', eid);
12648 n.removeAttribute('id');
12650 // Move caret before selected element
12651 r = d.createRange();
12652 r.setStartBefore(n);
12658 getParentBlock : function(n) {
12661 return d.getParent(n, d.isBlock);
12664 insertPara : function(e) {
12665 var t = this, ed = t.editor, dom = ed.dom, d = ed.getDoc(), se = ed.settings, s = ed.selection.getSel(), r = s.getRangeAt(0), b = d.body;
12666 var rb, ra, dir, sn, so, en, eo, sb, eb, bn, bef, aft, sc, ec, n, vp = dom.getViewPort(ed.getWin()), y, ch, car;
12668 ed.undoManager.beforeChange();
12670 // If root blocks are forced then use Operas default behavior since it's really good
12671 // Removed due to bug: #1853816
12672 // if (se.forced_root_block && isOpera)
12675 // Setup before range
12676 rb = d.createRange();
12678 // If is before the first block element and in body, then move it into first block element
12679 rb.setStart(s.anchorNode, s.anchorOffset);
12682 // Setup after range
12683 ra = d.createRange();
12685 // If is before the first block element and in body, then move it into first block element
12686 ra.setStart(s.focusNode, s.focusOffset);
12689 // Setup start/end points
12690 dir = rb.compareBoundaryPoints(rb.START_TO_END, ra) < 0;
12691 sn = dir ? s.anchorNode : s.focusNode;
12692 so = dir ? s.anchorOffset : s.focusOffset;
12693 en = dir ? s.focusNode : s.anchorNode;
12694 eo = dir ? s.focusOffset : s.anchorOffset;
12696 // If selection is in empty table cell
12697 if (sn === en && /^(TD|TH)$/.test(sn.nodeName)) {
12698 if (sn.firstChild.nodeName == 'BR')
12699 dom.remove(sn.firstChild); // Remove BR
12701 // Create two new block elements
12702 if (sn.childNodes.length == 0) {
12703 ed.dom.add(sn, se.element, null, '<br />');
12704 aft = ed.dom.add(sn, se.element, null, '<br />');
12708 ed.dom.add(sn, se.element, null, n);
12709 aft = ed.dom.add(sn, se.element, null, '<br />');
12712 // Move caret into the last one
12713 r = d.createRange();
12714 r.selectNodeContents(aft);
12716 ed.selection.setRng(r);
12721 // If the caret is in an invalid location in FF we need to move it into the first block
12722 if (sn == b && en == b && b.firstChild && ed.dom.isBlock(b.firstChild)) {
12723 sn = en = sn.firstChild;
12725 rb = d.createRange();
12726 rb.setStart(sn, 0);
12727 ra = d.createRange();
12728 ra.setStart(en, 0);
12731 // Never use body as start or end node
12732 sn = sn.nodeName == "HTML" ? d.body : sn; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
12733 sn = sn.nodeName == "BODY" ? sn.firstChild : sn;
12734 en = en.nodeName == "HTML" ? d.body : en; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
12735 en = en.nodeName == "BODY" ? en.firstChild : en;
12737 // Get start and end blocks
12738 sb = t.getParentBlock(sn);
12739 eb = t.getParentBlock(en);
12740 bn = sb ? sb.nodeName : se.element; // Get block name to create
12742 // Return inside list use default browser behavior
12743 if (n = t.dom.getParent(sb, 'li,pre')) {
12744 if (n.nodeName == 'LI')
12745 return splitList(ed.selection, t.dom, n);
12750 // If caption or absolute layers then always generate new blocks within
12751 if (sb && (sb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
12756 // If caption or absolute layers then always generate new blocks within
12757 if (eb && (eb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
12763 if (/(TD|TABLE|TH|CAPTION)/.test(bn) || (sb && bn == "DIV" && /left|right/gi.test(dom.getStyle(sb, 'float', 1)))) {
12768 // Setup new before and after blocks
12769 bef = (sb && sb.nodeName == bn) ? sb.cloneNode(0) : ed.dom.create(bn);
12770 aft = (eb && eb.nodeName == bn) ? eb.cloneNode(0) : ed.dom.create(bn);
12772 // Remove id from after clone
12773 aft.removeAttribute('id');
12775 // Is header and cursor is at the end, then force paragraph under
12776 if (/^(H[1-6])$/.test(bn) && isAtEnd(r, sb))
12777 aft = ed.dom.create(se.element);
12779 // Find start chop node
12782 if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
12786 } while ((n = n.previousSibling ? n.previousSibling : n.parentNode));
12788 // Find end chop node
12791 if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
12795 } while ((n = n.nextSibling ? n.nextSibling : n.parentNode));
12797 // Place first chop part into before block element
12798 if (sc.nodeName == bn)
12799 rb.setStart(sc, 0);
12801 rb.setStartBefore(sc);
12804 bef.appendChild(rb.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari
12806 // Place secnd chop part within new block element
12808 ra.setEndAfter(ec);
12810 //console.debug(s.focusNode, s.focusOffset);
12813 ra.setStart(en, eo);
12814 aft.appendChild(ra.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari
12816 // Create range around everything
12817 r = d.createRange();
12818 if (!sc.previousSibling && sc.parentNode.nodeName == bn) {
12819 r.setStartBefore(sc.parentNode);
12821 if (rb.startContainer.nodeName == bn && rb.startOffset == 0)
12822 r.setStartBefore(rb.startContainer);
12824 r.setStart(rb.startContainer, rb.startOffset);
12827 if (!ec.nextSibling && ec.parentNode.nodeName == bn)
12828 r.setEndAfter(ec.parentNode);
12830 r.setEnd(ra.endContainer, ra.endOffset);
12832 // Delete and replace it with new block elements
12833 r.deleteContents();
12836 ed.getWin().scrollTo(0, vp.y);
12838 // Never wrap blocks in blocks
12839 if (bef.firstChild && bef.firstChild.nodeName == bn)
12840 bef.innerHTML = bef.firstChild.innerHTML;
12842 if (aft.firstChild && aft.firstChild.nodeName == bn)
12843 aft.innerHTML = aft.firstChild.innerHTML;
12845 // Padd empty blocks
12846 if (dom.isEmpty(bef))
12847 bef.innerHTML = '<br />';
12849 function appendStyles(e, en) {
12850 var nl = [], nn, n, i;
12854 // Make clones of style elements
12855 if (se.keep_styles) {
12858 // We only want style specific elements
12859 if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(n.nodeName)) {
12860 nn = n.cloneNode(FALSE);
12861 dom.setAttrib(nn, 'id', ''); // Remove ID since it needs to be unique
12864 } while (n = n.parentNode);
12867 // Append style elements to aft
12868 if (nl.length > 0) {
12869 for (i = nl.length - 1, nn = e; i >= 0; i--)
12870 nn = nn.appendChild(nl[i]);
12872 // Padd most inner style element
12873 nl[0].innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there
12874 return nl[0]; // Move caret to most inner element
12876 e.innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there
12879 // Fill empty afterblook with current style
12880 if (dom.isEmpty(aft))
12881 car = appendStyles(aft, en);
12883 // Opera needs this one backwards for older versions
12884 if (isOpera && parseFloat(opera.version()) < 9.5) {
12896 function first(n) {
12897 return d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE).nextNode() || n;
12900 // Move cursor and scroll into view
12901 r = d.createRange();
12902 r.selectNodeContents(isGecko ? first(car || aft) : car || aft);
12904 s.removeAllRanges();
12907 // scrollIntoView seems to scroll the parent window in most browsers now including FF 3.0b4 so it's time to stop using it and do it our selfs
12908 y = ed.dom.getPos(aft).y;
12909 //ch = aft.clientHeight;
12911 // Is element within viewport
12912 if (y < vp.y || y + 25 > vp.y + vp.h) {
12913 ed.getWin().scrollTo(0, y < vp.y ? y : y - vp.h + 25); // Needs to be hardcoded to roughly one line of text if a huge text block is broken into two blocks
12916 'Element: y=' + y + ', h=' + ch + ', ' +
12917 'Viewport: y=' + vp.y + ", h=" + vp.h + ', bottom=' + (vp.y + vp.h)
12921 ed.undoManager.add();
12926 backspaceDelete : function(e, bs) {
12927 var t = this, ed = t.editor, b = ed.getBody(), dom = ed.dom, n, se = ed.selection, r = se.getRng(), sc = r.startContainer, n, w, tn, walker;
12929 // Delete when caret is behind a element doesn't work correctly on Gecko see #3011651
12930 if (!bs && r.collapsed && sc.nodeType == 1 && r.startOffset == sc.childNodes.length) {
12931 walker = new tinymce.dom.TreeWalker(sc.lastChild, sc);
12933 // Walk the dom backwards until we find a text node
12934 for (n = sc.lastChild; n; n = walker.prev()) {
12935 if (n.nodeType == 3) {
12936 r.setStart(n, n.nodeValue.length);
12944 // The caret sometimes gets stuck in Gecko if you delete empty paragraphs
12945 // This workaround removes the element by hand and moves the caret to the previous element
12946 if (sc && ed.dom.isBlock(sc) && !/^(TD|TH)$/.test(sc.nodeName) && bs) {
12947 if (sc.childNodes.length == 0 || (sc.childNodes.length == 1 && sc.firstChild.nodeName == 'BR')) {
12948 // Find previous block element
12950 while ((n = n.previousSibling) && !ed.dom.isBlock(n)) ;
12953 if (sc != b.firstChild) {
12954 // Find last text node
12955 w = ed.dom.doc.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE);
12956 while (tn = w.nextNode())
12959 // Place caret at the end of last text node
12960 r = ed.getDoc().createRange();
12961 r.setStart(n, n.nodeValue ? n.nodeValue.length : 0);
12962 r.setEnd(n, n.nodeValue ? n.nodeValue.length : 0);
12965 // Remove the target container
12969 return Event.cancel(e);
12977 (function(tinymce) {
12979 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, extend = tinymce.extend;
12981 tinymce.create('tinymce.ControlManager', {
12982 ControlManager : function(ed, s) {
12988 t.onAdd = new tinymce.util.Dispatcher(t);
12989 t.onPostRender = new tinymce.util.Dispatcher(t);
12990 t.prefix = s.prefix || ed.id + '_';
12993 t.onPostRender.add(function() {
12994 each(t.controls, function(c) {
13000 get : function(id) {
13001 return this.controls[this.prefix + id] || this.controls[id];
13004 setActive : function(id, s) {
13007 if (c = this.get(id))
13013 setDisabled : function(id, s) {
13016 if (c = this.get(id))
13022 add : function(c) {
13026 t.controls[c.id] = c;
13027 t.onAdd.dispatch(c, t);
13033 createControl : function(n) {
13034 var c, t = this, ed = t.editor;
13036 each(ed.plugins, function(p) {
13037 if (p.createControl) {
13038 c = p.createControl(n, t);
13048 return t.createSeparator();
13051 if (!c && ed.buttons && (c = ed.buttons[n]))
13052 return t.createButton(n, c);
13057 createDropMenu : function(id, s, cc) {
13058 var t = this, ed = t.editor, c, bm, v, cls;
13061 'class' : 'mceDropDown',
13062 constrain : ed.settings.constrain_menus
13065 s['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin';
13066 if (v = ed.getParam('skin_variant'))
13067 s['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1);
13069 id = t.prefix + id;
13070 cls = cc || t._cls.dropmenu || tinymce.ui.DropMenu;
13071 c = t.controls[id] = new cls(id, s);
13072 c.onAddItem.add(function(c, o) {
13073 var s = o.settings;
13075 s.title = ed.getLang(s.title, s.title);
13078 s.onclick = function(v) {
13080 ed.execCommand(s.cmd, s.ui || false, s.value);
13085 ed.onRemove.add(function() {
13089 // Fix for bug #1897785, #1898007
13090 if (tinymce.isIE) {
13091 c.onShowMenu.add(function() {
13092 // IE 8 needs focus in order to store away a range with the current collapsed caret location
13095 bm = ed.selection.getBookmark(1);
13098 c.onHideMenu.add(function() {
13100 ed.selection.moveToBookmark(bm);
13109 createListBox : function(id, s, cc) {
13110 var t = this, ed = t.editor, cmd, c, cls;
13115 s.title = ed.translate(s.title);
13116 s.scope = s.scope || ed;
13119 s.onselect = function(v) {
13120 ed.execCommand(s.cmd, s.ui || false, v || s.value);
13126 'class' : 'mce_' + id,
13128 control_manager : t
13131 id = t.prefix + id;
13133 if (ed.settings.use_native_selects)
13134 c = new tinymce.ui.NativeListBox(id, s);
13136 cls = cc || t._cls.listbox || tinymce.ui.ListBox;
13137 c = new cls(id, s, ed);
13140 t.controls[id] = c;
13142 // Fix focus problem in Safari
13143 if (tinymce.isWebKit) {
13144 c.onPostRender.add(function(c, n) {
13145 // Store bookmark on mousedown
13146 Event.add(n, 'mousedown', function() {
13147 ed.bookmark = ed.selection.getBookmark(1);
13150 // Restore on focus, since it might be lost
13151 Event.add(n, 'focus', function() {
13152 ed.selection.moveToBookmark(ed.bookmark);
13153 ed.bookmark = null;
13159 ed.onMouseDown.add(c.hideMenu, c);
13164 createButton : function(id, s, cc) {
13165 var t = this, ed = t.editor, o, c, cls;
13170 s.title = ed.translate(s.title);
13171 s.label = ed.translate(s.label);
13172 s.scope = s.scope || ed;
13174 if (!s.onclick && !s.menu_button) {
13175 s.onclick = function() {
13176 ed.execCommand(s.cmd, s.ui || false, s.value);
13182 'class' : 'mce_' + id,
13183 unavailable_prefix : ed.getLang('unavailable', ''),
13185 control_manager : t
13188 id = t.prefix + id;
13190 if (s.menu_button) {
13191 cls = cc || t._cls.menubutton || tinymce.ui.MenuButton;
13192 c = new cls(id, s, ed);
13193 ed.onMouseDown.add(c.hideMenu, c);
13195 cls = t._cls.button || tinymce.ui.Button;
13196 c = new cls(id, s);
13202 createMenuButton : function(id, s, cc) {
13206 return this.createButton(id, s, cc);
13209 createSplitButton : function(id, s, cc) {
13210 var t = this, ed = t.editor, cmd, c, cls;
13215 s.title = ed.translate(s.title);
13216 s.scope = s.scope || ed;
13219 s.onclick = function(v) {
13220 ed.execCommand(s.cmd, s.ui || false, v || s.value);
13225 s.onselect = function(v) {
13226 ed.execCommand(s.cmd, s.ui || false, v || s.value);
13232 'class' : 'mce_' + id,
13234 control_manager : t
13237 id = t.prefix + id;
13238 cls = cc || t._cls.splitbutton || tinymce.ui.SplitButton;
13239 c = t.add(new cls(id, s, ed));
13240 ed.onMouseDown.add(c.hideMenu, c);
13245 createColorSplitButton : function(id, s, cc) {
13246 var t = this, ed = t.editor, cmd, c, cls, bm;
13251 s.title = ed.translate(s.title);
13252 s.scope = s.scope || ed;
13255 s.onclick = function(v) {
13257 bm = ed.selection.getBookmark(1);
13259 ed.execCommand(s.cmd, s.ui || false, v || s.value);
13264 s.onselect = function(v) {
13265 ed.execCommand(s.cmd, s.ui || false, v || s.value);
13271 'class' : 'mce_' + id,
13272 'menu_class' : ed.getParam('skin') + 'Skin',
13274 more_colors_title : ed.getLang('more_colors')
13277 id = t.prefix + id;
13278 cls = cc || t._cls.colorsplitbutton || tinymce.ui.ColorSplitButton;
13279 c = new cls(id, s, ed);
13280 ed.onMouseDown.add(c.hideMenu, c);
13282 // Remove the menu element when the editor is removed
13283 ed.onRemove.add(function() {
13287 // Fix for bug #1897785, #1898007
13288 if (tinymce.isIE) {
13289 c.onShowMenu.add(function() {
13290 // IE 8 needs focus in order to store away a range with the current collapsed caret location
13292 bm = ed.selection.getBookmark(1);
13295 c.onHideMenu.add(function() {
13297 ed.selection.moveToBookmark(bm);
13306 createToolbar : function(id, s, cc) {
13307 var c, t = this, cls;
13309 id = t.prefix + id;
13310 cls = cc || t._cls.toolbar || tinymce.ui.Toolbar;
13311 c = new cls(id, s, t.editor);
13319 createToolbarGroup : function(id, s, cc) {
13320 var c, t = this, cls;
13321 id = t.prefix + id;
13322 cls = cc || this._cls.toolbarGroup || tinymce.ui.ToolbarGroup;
13323 c = new cls(id, s, t.editor);
13331 createSeparator : function(cc) {
13332 var cls = cc || this._cls.separator || tinymce.ui.Separator;
13337 setControlType : function(n, c) {
13338 return this._cls[n.toLowerCase()] = c;
13341 destroy : function() {
13342 each(this.controls, function(c) {
13346 this.controls = null;
13351 (function(tinymce) {
13352 var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isIE = tinymce.isIE, isOpera = tinymce.isOpera;
13354 tinymce.create('tinymce.WindowManager', {
13355 WindowManager : function(ed) {
13359 t.onOpen = new Dispatcher(t);
13360 t.onClose = new Dispatcher(t);
13365 open : function(s, p) {
13366 var t = this, f = '', x, y, mo = t.editor.settings.dialog_type == 'modal', w, sw, sh, vp = tinymce.DOM.getViewPort(), u;
13368 // Default some options
13371 sw = isOpera ? vp.w : screen.width; // Opera uses windows inside the Opera window
13372 sh = isOpera ? vp.h : screen.height;
13373 s.name = s.name || 'mc_' + new Date().getTime();
13374 s.width = parseInt(s.width || 320);
13375 s.height = parseInt(s.height || 240);
13376 s.resizable = true;
13377 s.left = s.left || parseInt(sw / 2.0) - (s.width / 2.0);
13378 s.top = s.top || parseInt(sh / 2.0) - (s.height / 2.0);
13380 p.mce_width = s.width;
13381 p.mce_height = s.height;
13382 p.mce_auto_focus = s.auto_focus;
13388 s.dialogWidth = s.width + 'px';
13389 s.dialogHeight = s.height + 'px';
13390 s.scroll = s.scrollbars || false;
13394 // Build features string
13395 each(s, function(v, k) {
13396 if (tinymce.is(v, 'boolean'))
13397 v = v ? 'yes' : 'no';
13399 if (!/^(name|url)$/.test(k)) {
13401 f += (f ? ';' : '') + k + ':' + v;
13403 f += (f ? ',' : '') + k + '=' + v;
13409 t.onOpen.dispatch(t, s, p);
13411 u = s.url || s.file;
13412 u = tinymce._addVer(u);
13417 window.showModalDialog(u, window, f);
13419 w = window.open(u, s.name, f);
13425 alert(t.editor.getLang('popup_blocked'));
13428 close : function(w) {
13430 this.onClose.dispatch(this);
13433 createInstance : function(cl, a, b, c, d, e) {
13434 var f = tinymce.resolve(cl);
13436 return new f(a, b, c, d, e);
13439 confirm : function(t, cb, s, w) {
13442 cb.call(s || this, w.confirm(this._decode(this.editor.getLang(t, t))));
13445 alert : function(tx, cb, s, w) {
13449 w.alert(t._decode(t.editor.getLang(tx, tx)));
13455 resizeBy : function(dw, dh, win) {
13456 win.resizeBy(dw, dh);
13459 // Internal functions
13461 _decode : function(s) {
13462 return tinymce.DOM.decode(s).replace(/\\n/g, '\n');
13466 (function(tinymce) {
13467 tinymce.Formatter = function(ed) {
13469 each = tinymce.each,
13471 selection = ed.selection,
13472 TreeWalker = tinymce.dom.TreeWalker,
13473 rangeUtils = new tinymce.dom.RangeUtils(dom),
13474 isValid = ed.schema.isValidChild,
13475 isBlock = dom.isBlock,
13476 forcedRootBlock = ed.settings.forced_root_block,
13477 nodeIndex = dom.nodeIndex,
13478 INVISIBLE_CHAR = '\uFEFF',
13479 MCE_ATTR_RE = /^(src|href|style)$/,
13483 pendingFormats = {apply : [], remove : []};
13485 function isArray(obj) {
13486 return obj instanceof Array;
13489 function getParents(node, selector) {
13490 return dom.getParents(node, selector, dom.getRoot());
13493 function isCaretNode(node) {
13494 return node.nodeType === 1 && (node.face === 'mceinline' || node.style.fontFamily === 'mceinline');
13497 // Public functions
13499 function get(name) {
13500 return name ? formats[name] : formats;
13503 function register(name, format) {
13505 if (typeof(name) !== 'string') {
13506 each(name, function(format, name) {
13507 register(name, format);
13510 // Force format into array and add it to internal collection
13511 format = format.length ? format : [format];
13513 each(format, function(format) {
13514 // Set deep to false by default on selector formats this to avoid removing
13515 // alignment on images inside paragraphs when alignment is changed on paragraphs
13516 if (format.deep === undefined)
13517 format.deep = !format.selector;
13520 if (format.split === undefined)
13521 format.split = !format.selector || format.inline;
13524 if (format.remove === undefined && format.selector && !format.inline)
13525 format.remove = 'none';
13527 // Mark format as a mixed format inline + block level
13528 if (format.selector && format.inline) {
13529 format.mixed = true;
13530 format.block_expand = true;
13533 // Split classes if needed
13534 if (typeof(format.classes) === 'string')
13535 format.classes = format.classes.split(/\s+/);
13538 formats[name] = format;
13543 var getTextDecoration = function(node) {
13546 ed.dom.getParent(node, function(n) {
13547 decoration = ed.dom.getStyle(n, 'text-decoration');
13548 return decoration && decoration !== 'none';
13554 var processUnderlineAndColor = function(node) {
13555 var textDecoration;
13556 if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {
13557 textDecoration = getTextDecoration(node.parentNode);
13558 if (ed.dom.getStyle(node, 'color') && textDecoration) {
13559 ed.dom.setStyle(node, 'text-decoration', textDecoration);
13560 } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) {
13561 ed.dom.setStyle(node, 'text-decoration', null);
13566 function apply(name, vars, node) {
13567 var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed();
13569 function moveStart(rng) {
13570 var container = rng.startContainer,
13571 offset = rng.startOffset,
13574 // Move startContainer/startOffset in to a suitable node
13575 if (container.nodeType == 1 || container.nodeValue === "") {
13576 container = container.nodeType == 1 ? container.childNodes[offset] : container;
13578 // Might fail if the offset is behind the last element in it's container
13580 walker = new TreeWalker(container, container.parentNode);
13581 for (node = walker.current(); node; node = walker.next()) {
13582 if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
13583 rng.setStart(node, 0);
13593 function setElementFormat(elm, fmt) {
13594 fmt = fmt || format;
13597 each(fmt.styles, function(value, name) {
13598 dom.setStyle(elm, name, replaceVars(value, vars));
13601 each(fmt.attributes, function(value, name) {
13602 dom.setAttrib(elm, name, replaceVars(value, vars));
13605 each(fmt.classes, function(value) {
13606 value = replaceVars(value, vars);
13608 if (!dom.hasClass(elm, value))
13609 dom.addClass(elm, value);
13614 function applyRngStyle(rng) {
13615 var newWrappers = [], wrapName, wrapElm;
13617 // Setup wrapper element
13618 wrapName = format.inline || format.block;
13619 wrapElm = dom.create(wrapName);
13620 setElementFormat(wrapElm);
13622 rangeUtils.walk(rng, function(nodes) {
13623 var currentWrapElm;
13625 function process(node) {
13626 var nodeName = node.nodeName.toLowerCase(), parentName = node.parentNode.nodeName.toLowerCase(), found;
13628 // Stop wrapping on br elements
13629 if (isEq(nodeName, 'br')) {
13630 currentWrapElm = 0;
13632 // Remove any br elements when we wrap things
13639 // If node is wrapper type
13640 if (format.wrapper && matchNode(node, name, vars)) {
13641 currentWrapElm = 0;
13645 // Can we rename the block
13646 if (format.block && !format.wrapper && isTextBlock(nodeName)) {
13647 node = dom.rename(node, wrapName);
13648 setElementFormat(node);
13649 newWrappers.push(node);
13650 currentWrapElm = 0;
13654 // Handle selector patterns
13655 if (format.selector) {
13656 // Look for matching formats
13657 each(formatList, function(format) {
13658 // Check collapsed state if it exists
13659 if ('collapsed' in format && format.collapsed !== isCollapsed) {
13663 if (dom.is(node, format.selector) && !isCaretNode(node)) {
13664 setElementFormat(node, format);
13669 // Continue processing if a selector match wasn't found and a inline element is defined
13670 if (!format.inline || found) {
13671 currentWrapElm = 0;
13676 // Is it valid to wrap this item
13677 if (isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
13678 !(node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279)) {
13680 if (!currentWrapElm) {
13682 currentWrapElm = wrapElm.cloneNode(FALSE);
13683 node.parentNode.insertBefore(currentWrapElm, node);
13684 newWrappers.push(currentWrapElm);
13687 currentWrapElm.appendChild(node);
13689 // Start a new wrapper for possible children
13690 currentWrapElm = 0;
13692 each(tinymce.grep(node.childNodes), process);
13694 // End the last wrapper
13695 currentWrapElm = 0;
13699 // Process siblings from range
13700 each(nodes, process);
13703 // Wrap links inside as well, for example color inside a link when the wrapper is around the link
13704 if (format.wrap_links === false) {
13705 each(newWrappers, function(node) {
13706 function process(node) {
13707 var i, currentWrapElm, children;
13709 if (node.nodeName === 'A') {
13710 currentWrapElm = wrapElm.cloneNode(FALSE);
13711 newWrappers.push(currentWrapElm);
13713 children = tinymce.grep(node.childNodes);
13714 for (i = 0; i < children.length; i++)
13715 currentWrapElm.appendChild(children[i]);
13717 node.appendChild(currentWrapElm);
13720 each(tinymce.grep(node.childNodes), process);
13728 each(newWrappers, function(node) {
13731 function getChildCount(node) {
13734 each(node.childNodes, function(node) {
13735 if (!isWhiteSpaceNode(node) && !isBookmarkNode(node))
13742 function mergeStyles(node) {
13745 each(node.childNodes, function(node) {
13746 if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) {
13748 return FALSE; // break loop
13752 // If child was found and of the same type as the current node
13753 if (child && matchName(child, format)) {
13754 clone = child.cloneNode(FALSE);
13755 setElementFormat(clone);
13757 dom.replace(clone, node, TRUE);
13758 dom.remove(child, 1);
13761 return clone || node;
13764 childCount = getChildCount(node);
13766 // Remove empty nodes but only if there is multiple wrappers and they are not block
13767 // elements so never remove single <h1></h1> since that would remove the currrent empty block element where the caret is at
13768 if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) {
13769 dom.remove(node, 1);
13773 if (format.inline || format.wrapper) {
13774 // Merges the current node with it's children of similar type to reduce the number of elements
13775 if (!format.exact && childCount === 1)
13776 node = mergeStyles(node);
13778 // Remove/merge children
13779 each(formatList, function(format) {
13780 // Merge all children of similar type will move styles from child to parent
13781 // this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span>
13782 // will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span>
13783 each(dom.select(format.inline, node), function(child) {
13786 // When wrap_links is set to false we don't want
13787 // to remove the format on children within links
13788 if (format.wrap_links === false) {
13789 parent = child.parentNode;
13792 if (parent.nodeName === 'A')
13794 } while (parent = parent.parentNode);
13797 removeFormat(format, vars, child, format.exact ? child : null);
13801 // Remove child if direct parent is of same type
13802 if (matchNode(node.parentNode, name, vars)) {
13803 dom.remove(node, 1);
13808 // Look for parent with similar style format
13809 if (format.merge_with_parents) {
13810 dom.getParent(node.parentNode, function(parent) {
13811 if (matchNode(parent, name, vars)) {
13812 dom.remove(node, 1);
13819 // Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b>
13821 node = mergeSiblings(getNonWhiteSpaceSibling(node), node);
13822 node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));
13830 rng = dom.createRng();
13832 rng.setStartBefore(node);
13833 rng.setEndAfter(node);
13835 applyRngStyle(expandRng(rng, formatList));
13837 if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
13838 // Obtain selection node before selection is unselected by applyRngStyle()
13839 var curSelNode = ed.selection.getNode();
13841 // Apply formatting to selection
13842 bookmark = selection.getBookmark();
13843 applyRngStyle(expandRng(selection.getRng(TRUE), formatList));
13845 // Colored nodes should be underlined so that the color of the underline matches the text color.
13846 if (format.styles && (format.styles.color || format.styles.textDecoration)) {
13847 tinymce.walk(curSelNode, processUnderlineAndColor, 'childNodes');
13848 processUnderlineAndColor(curSelNode);
13851 selection.moveToBookmark(bookmark);
13852 selection.setRng(moveStart(selection.getRng(TRUE)));
13855 performCaretAction('apply', name, vars);
13860 function remove(name, vars, node) {
13861 var formatList = get(name), format = formatList[0], bookmark, i, rng;
13863 function moveStart(rng) {
13864 var container = rng.startContainer,
13865 offset = rng.startOffset,
13866 walker, node, nodes, tmpNode;
13868 // Convert text node into index if possible
13869 if (container.nodeType == 3 && offset >= container.nodeValue.length - 1) {
13870 container = container.parentNode;
13871 offset = nodeIndex(container) + 1;
13874 // Move startContainer/startOffset in to a suitable node
13875 if (container.nodeType == 1) {
13876 nodes = container.childNodes;
13877 container = nodes[Math.min(offset, nodes.length - 1)];
13878 walker = new TreeWalker(container);
13880 // If offset is at end of the parent node walk to the next one
13881 if (offset > nodes.length - 1)
13884 for (node = walker.current(); node; node = walker.next()) {
13885 if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
13886 // IE has a "neat" feature where it moves the start node into the closest element
13887 // we can avoid this by inserting an element before it and then remove it after we set the selection
13888 tmpNode = dom.create('a', null, INVISIBLE_CHAR);
13889 node.parentNode.insertBefore(tmpNode, node);
13891 // Set selection and remove tmpNode
13892 rng.setStart(node, 0);
13893 selection.setRng(rng);
13894 dom.remove(tmpNode);
13902 // Merges the styles for each node
13903 function process(node) {
13904 var children, i, l;
13906 // Grab the children first since the nodelist might be changed
13907 children = tinymce.grep(node.childNodes);
13909 // Process current node
13910 for (i = 0, l = formatList.length; i < l; i++) {
13911 if (removeFormat(formatList[i], vars, node, node))
13915 // Process the children
13917 for (i = 0, l = children.length; i < l; i++)
13918 process(children[i]);
13922 function findFormatRoot(container) {
13925 // Find format root
13926 each(getParents(container.parentNode).reverse(), function(parent) {
13929 // Find format root element
13930 if (!formatRoot && parent.id != '_start' && parent.id != '_end') {
13931 // Is the node matching the format we are looking for
13932 format = matchNode(parent, name, vars);
13933 if (format && format.split !== false)
13934 formatRoot = parent;
13941 function wrapAndSplit(format_root, container, target, split) {
13942 var parent, clone, lastClone, firstClone, i, formatRootParent;
13944 // Format root found then clone formats and split it
13946 formatRootParent = format_root.parentNode;
13948 for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {
13949 clone = parent.cloneNode(FALSE);
13951 for (i = 0; i < formatList.length; i++) {
13952 if (removeFormat(formatList[i], vars, clone, clone)) {
13958 // Build wrapper node
13961 clone.appendChild(lastClone);
13964 firstClone = clone;
13970 // Never split block elements if the format is mixed
13971 if (split && (!format.mixed || !isBlock(format_root)))
13972 container = dom.split(format_root, container);
13974 // Wrap container in cloned formats
13976 target.parentNode.insertBefore(lastClone, target);
13977 firstClone.appendChild(target);
13984 function splitToFormatRoot(container) {
13985 return wrapAndSplit(findFormatRoot(container), container, container, true);
13988 function unwrap(start) {
13989 var node = dom.get(start ? '_start' : '_end'),
13990 out = node[start ? 'firstChild' : 'lastChild'];
13992 // If the end is placed within the start the result will be removed
13993 // So this checks if the out node is a bookmark node if it is it
13994 // checks for another more suitable node
13995 if (isBookmarkNode(out))
13996 out = out[start ? 'firstChild' : 'lastChild'];
13998 dom.remove(node, true);
14003 function removeRngStyle(rng) {
14004 var startContainer, endContainer;
14006 rng = expandRng(rng, formatList, TRUE);
14008 if (format.split) {
14009 startContainer = getContainer(rng, TRUE);
14010 endContainer = getContainer(rng);
14012 if (startContainer != endContainer) {
14013 // Wrap start/end nodes in span element since these might be cloned/moved
14014 startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'});
14015 endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'});
14018 splitToFormatRoot(startContainer);
14019 splitToFormatRoot(endContainer);
14021 // Unwrap start/end to get real elements again
14022 startContainer = unwrap(TRUE);
14023 endContainer = unwrap();
14025 startContainer = endContainer = splitToFormatRoot(startContainer);
14027 // Update range positions since they might have changed after the split operations
14028 rng.startContainer = startContainer.parentNode;
14029 rng.startOffset = nodeIndex(startContainer);
14030 rng.endContainer = endContainer.parentNode;
14031 rng.endOffset = nodeIndex(endContainer) + 1;
14034 // Remove items between start/end
14035 rangeUtils.walk(rng, function(nodes) {
14036 each(nodes, function(node) {
14039 // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined.
14040 if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && getTextDecoration(node.parentNode) === 'underline') {
14041 removeFormat({'deep': false, 'exact': true, 'inline': 'span', 'styles': {'textDecoration' : 'underline'}}, null, node);
14049 rng = dom.createRng();
14050 rng.setStartBefore(node);
14051 rng.setEndAfter(node);
14052 removeRngStyle(rng);
14056 if (!selection.isCollapsed() || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
14057 bookmark = selection.getBookmark();
14058 removeRngStyle(selection.getRng(TRUE));
14059 selection.moveToBookmark(bookmark);
14061 // Check if start element still has formatting then we are at: "<b>text|</b>text" and need to move the start into the next text node
14062 if (match(name, vars, selection.getStart())) {
14063 moveStart(selection.getRng(true));
14068 performCaretAction('remove', name, vars);
14071 function toggle(name, vars, node) {
14072 var fmt = get(name);
14074 if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0]['toggle']))
14075 remove(name, vars, node);
14077 apply(name, vars, node);
14080 function matchNode(node, name, vars, similar) {
14081 var formatList = get(name), format, i, classes;
14083 function matchItems(node, format, item_name) {
14084 var key, value, items = format[item_name], i;
14088 // Non indexed object
14089 if (items.length === undefined) {
14090 for (key in items) {
14091 if (items.hasOwnProperty(key)) {
14092 if (item_name === 'attributes')
14093 value = dom.getAttrib(node, key);
14095 value = getStyle(node, key);
14097 if (similar && !value && !format.exact)
14100 if ((!similar || format.exact) && !isEq(value, replaceVars(items[key], vars)))
14105 // Only one match needed for indexed arrays
14106 for (i = 0; i < items.length; i++) {
14107 if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i]))
14116 if (formatList && node) {
14117 // Check each format in list
14118 for (i = 0; i < formatList.length; i++) {
14119 format = formatList[i];
14121 // Name name, attributes, styles and classes
14122 if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) {
14124 if (classes = format.classes) {
14125 for (i = 0; i < classes.length; i++) {
14126 if (!dom.hasClass(node, classes[i]))
14137 function match(name, vars, node) {
14140 function matchParents(node) {
14141 // Find first node with similar format settings
14142 node = dom.getParent(node, function(node) {
14143 return !!matchNode(node, name, vars, true);
14146 // Do an exact check on the similar format element
14147 return matchNode(node, name, vars);
14150 // Check specified node
14152 return matchParents(node);
14154 // Check pending formats
14155 if (selection.isCollapsed()) {
14156 for (i = pendingFormats.apply.length - 1; i >= 0; i--) {
14157 if (pendingFormats.apply[i].name == name)
14161 for (i = pendingFormats.remove.length - 1; i >= 0; i--) {
14162 if (pendingFormats.remove[i].name == name)
14166 return matchParents(selection.getNode());
14169 // Check selected node
14170 node = selection.getNode();
14171 if (matchParents(node))
14174 // Check start node if it's different
14175 startNode = selection.getStart();
14176 if (startNode != node) {
14177 if (matchParents(startNode))
14184 function matchAll(names, vars) {
14185 var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name;
14187 // If the selection is collapsed then check pending formats
14188 if (selection.isCollapsed()) {
14189 for (ni = 0; ni < names.length; ni++) {
14190 // If the name is to be removed, then stop it from being added
14191 for (i = pendingFormats.remove.length - 1; i >= 0; i--) {
14194 if (pendingFormats.remove[i].name == name) {
14195 checkedMap[name] = true;
14201 // If the format is to be applied
14202 for (i = pendingFormats.apply.length - 1; i >= 0; i--) {
14203 for (ni = 0; ni < names.length; ni++) {
14206 if (!checkedMap[name] && pendingFormats.apply[i].name == name) {
14207 checkedMap[name] = true;
14208 matchedFormatNames.push(name);
14214 // Check start of selection for formats
14215 startElement = selection.getStart();
14216 dom.getParent(startElement, function(node) {
14219 for (i = 0; i < names.length; i++) {
14222 if (!checkedMap[name] && matchNode(node, name, vars)) {
14223 checkedMap[name] = true;
14224 matchedFormatNames.push(name);
14229 return matchedFormatNames;
14232 function canApply(name) {
14233 var formatList = get(name), startNode, parents, i, x, selector;
14236 startNode = selection.getStart();
14237 parents = getParents(startNode);
14239 for (x = formatList.length - 1; x >= 0; x--) {
14240 selector = formatList[x].selector;
14242 // Format is not selector based, then always return TRUE
14246 for (i = parents.length - 1; i >= 0; i--) {
14247 if (dom.is(parents[i], selector))
14256 // Expose to public
14257 tinymce.extend(this, {
14259 register : register,
14264 matchAll : matchAll,
14265 matchNode : matchNode,
14266 canApply : canApply
14269 // Private functions
14271 function matchName(node, format) {
14272 // Check for inline match
14273 if (isEq(node, format.inline))
14276 // Check for block match
14277 if (isEq(node, format.block))
14280 // Check for selector match
14281 if (format.selector)
14282 return dom.is(node, format.selector);
14285 function isEq(str1, str2) {
14289 str1 = '' + (str1.nodeName || str1);
14290 str2 = '' + (str2.nodeName || str2);
14292 return str1.toLowerCase() == str2.toLowerCase();
14295 function getStyle(node, name) {
14296 var styleVal = dom.getStyle(node, name);
14298 // Force the format to hex
14299 if (name == 'color' || name == 'backgroundColor')
14300 styleVal = dom.toHex(styleVal);
14302 // Opera will return bold as 700
14303 if (name == 'fontWeight' && styleVal == 700)
14306 return '' + styleVal;
14309 function replaceVars(value, vars) {
14310 if (typeof(value) != "string")
14311 value = value(vars);
14313 value = value.replace(/%(\w+)/g, function(str, name) {
14314 return vars[name] || str;
14321 function isWhiteSpaceNode(node) {
14322 return node && node.nodeType === 3 && /^([\s\r\n]+|)$/.test(node.nodeValue);
14325 function wrap(node, name, attrs) {
14326 var wrapper = dom.create(name, attrs);
14328 node.parentNode.insertBefore(wrapper, node);
14329 wrapper.appendChild(node);
14334 function expandRng(rng, format, remove) {
14335 var startContainer = rng.startContainer,
14336 startOffset = rng.startOffset,
14337 endContainer = rng.endContainer,
14338 endOffset = rng.endOffset, sibling, lastIdx, leaf;
14340 // This function walks up the tree if there is no siblings before/after the node
14341 function findParentContainer(container, child_name, sibling_name, root) {
14344 root = root || dom.getRoot();
14347 // Check if we can move up are we at root level or body level
14348 parent = container.parentNode;
14350 // Stop expanding on block elements or root depending on format
14351 if (parent == root || (!format[0].block_expand && isBlock(parent)))
14354 for (sibling = parent[child_name]; sibling && sibling != container; sibling = sibling[sibling_name]) {
14355 if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
14358 if (sibling.nodeType == 3 && !isWhiteSpaceNode(sibling))
14362 container = container.parentNode;
14368 // This function walks down the tree to find the leaf at the selection.
14369 // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node.
14370 function findLeaf(node, offset) {
14371 if (offset === undefined)
14372 offset = node.nodeType === 3 ? node.length : node.childNodes.length;
14373 while (node && node.hasChildNodes()) {
14374 node = node.childNodes[offset];
14376 offset = node.nodeType === 3 ? node.length : node.childNodes.length;
14378 return { node: node, offset: offset };
14381 // If index based start position then resolve it
14382 if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) {
14383 lastIdx = startContainer.childNodes.length - 1;
14384 startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset];
14386 if (startContainer.nodeType == 3)
14390 // If index based end position then resolve it
14391 if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) {
14392 lastIdx = endContainer.childNodes.length - 1;
14393 endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1];
14395 if (endContainer.nodeType == 3)
14396 endOffset = endContainer.nodeValue.length;
14399 // Exclude bookmark nodes if possible
14400 if (isBookmarkNode(startContainer.parentNode))
14401 startContainer = startContainer.parentNode;
14403 if (isBookmarkNode(startContainer))
14404 startContainer = startContainer.nextSibling || startContainer;
14406 if (isBookmarkNode(endContainer.parentNode)) {
14407 endOffset = dom.nodeIndex(endContainer);
14408 endContainer = endContainer.parentNode;
14411 if (isBookmarkNode(endContainer) && endContainer.previousSibling) {
14412 endContainer = endContainer.previousSibling;
14413 endOffset = endContainer.length;
14416 if (format[0].inline) {
14417 // Avoid applying formatting to a trailing space.
14418 leaf = findLeaf(endContainer, endOffset);
14420 while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling)
14421 leaf = findLeaf(leaf.node.previousSibling);
14423 if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 &&
14424 leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') {
14426 if (leaf.offset > 1) {
14427 endContainer = leaf.node;
14428 endContainer.splitText(leaf.offset - 1);
14429 } else if (leaf.node.previousSibling) {
14430 endContainer = leaf.node.previousSibling;
14436 // Move start/end point up the tree if the leaves are sharp and if we are in different containers
14437 // Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!
14438 // This will reduce the number of wrapper elements that needs to be created
14439 // Move start point up the tree
14440 if (format[0].inline || format[0].block_expand) {
14441 startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');
14442 endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');
14445 // Expand start/end container to matching selector
14446 if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) {
14447 function findSelectorEndPoint(container, sibling_name) {
14448 var parents, i, y, curFormat;
14450 if (container.nodeType == 3 && container.nodeValue.length == 0 && container[sibling_name])
14451 container = container[sibling_name];
14453 parents = getParents(container);
14454 for (i = 0; i < parents.length; i++) {
14455 for (y = 0; y < format.length; y++) {
14456 curFormat = format[y];
14458 // If collapsed state is set then skip formats that doesn't match that
14459 if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed)
14462 if (dom.is(parents[i], curFormat.selector))
14470 // Find new startContainer/endContainer if there is better one
14471 startContainer = findSelectorEndPoint(startContainer, 'previousSibling');
14472 endContainer = findSelectorEndPoint(endContainer, 'nextSibling');
14475 // Expand start/end container to matching block element or text node
14476 if (format[0].block || format[0].selector) {
14477 function findBlockEndPoint(container, sibling_name, sibling_name2) {
14480 // Expand to block of similar type
14481 if (!format[0].wrapper)
14482 node = dom.getParent(container, format[0].block);
14484 // Expand to first wrappable block element or any block element
14486 node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock);
14488 // Exclude inner lists from wrapping
14489 if (node && format[0].wrapper)
14490 node = getParents(node, 'ul,ol').reverse()[0] || node;
14492 // Didn't find a block element look for first/last wrappable element
14496 while (node[sibling_name] && !isBlock(node[sibling_name])) {
14497 node = node[sibling_name];
14499 // Break on BR but include it will be removed later on
14500 // we can't remove it now since we need to check if it can be wrapped
14501 if (isEq(node, 'br'))
14506 return node || container;
14509 // Find new startContainer/endContainer if there is better one
14510 startContainer = findBlockEndPoint(startContainer, 'previousSibling');
14511 endContainer = findBlockEndPoint(endContainer, 'nextSibling');
14513 // Non block element then try to expand up the leaf
14514 if (format[0].block) {
14515 if (!isBlock(startContainer))
14516 startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');
14518 if (!isBlock(endContainer))
14519 endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');
14523 // Setup index for startContainer
14524 if (startContainer.nodeType == 1) {
14525 startOffset = nodeIndex(startContainer);
14526 startContainer = startContainer.parentNode;
14529 // Setup index for endContainer
14530 if (endContainer.nodeType == 1) {
14531 endOffset = nodeIndex(endContainer) + 1;
14532 endContainer = endContainer.parentNode;
14535 // Return new range like object
14537 startContainer : startContainer,
14538 startOffset : startOffset,
14539 endContainer : endContainer,
14540 endOffset : endOffset
14544 function removeFormat(format, vars, node, compare_node) {
14545 var i, attrs, stylesModified;
14547 // Check if node matches format
14548 if (!matchName(node, format))
14551 // Should we compare with format attribs and styles
14552 if (format.remove != 'all') {
14554 each(format.styles, function(value, name) {
14555 value = replaceVars(value, vars);
14558 if (typeof(name) === 'number') {
14563 if (!compare_node || isEq(getStyle(compare_node, name), value))
14564 dom.setStyle(node, name, '');
14566 stylesModified = 1;
14569 // Remove style attribute if it's empty
14570 if (stylesModified && dom.getAttrib(node, 'style') == '') {
14571 node.removeAttribute('style');
14572 node.removeAttribute('data-mce-style');
14575 // Remove attributes
14576 each(format.attributes, function(value, name) {
14579 value = replaceVars(value, vars);
14582 if (typeof(name) === 'number') {
14587 if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) {
14588 // Keep internal classes
14589 if (name == 'class') {
14590 value = dom.getAttrib(node, name);
14592 // Build new class value where everything is removed except the internal prefixed classes
14594 each(value.split(/\s+/), function(cls) {
14595 if (/mce\w+/.test(cls))
14596 valueOut += (valueOut ? ' ' : '') + cls;
14599 // We got some internal classes left
14601 dom.setAttrib(node, name, valueOut);
14607 // IE6 has a bug where the attribute doesn't get removed correctly
14608 if (name == "class")
14609 node.removeAttribute('className');
14611 // Remove mce prefixed attributes
14612 if (MCE_ATTR_RE.test(name))
14613 node.removeAttribute('data-mce-' + name);
14615 node.removeAttribute(name);
14620 each(format.classes, function(value) {
14621 value = replaceVars(value, vars);
14623 if (!compare_node || dom.hasClass(compare_node, value))
14624 dom.removeClass(node, value);
14627 // Check for non internal attributes
14628 attrs = dom.getAttribs(node);
14629 for (i = 0; i < attrs.length; i++) {
14630 if (attrs[i].nodeName.indexOf('_') !== 0)
14635 // Remove the inline child if it's empty for example <b> or <span>
14636 if (format.remove != 'none') {
14637 removeNode(node, format);
14642 function removeNode(node, format) {
14643 var parentNode = node.parentNode, rootBlockElm;
14645 if (format.block) {
14646 if (!forcedRootBlock) {
14647 function find(node, next, inc) {
14648 node = getNonWhiteSpaceSibling(node, next, inc);
14650 return !node || (node.nodeName == 'BR' || isBlock(node));
14653 // Append BR elements if needed before we remove the block
14654 if (isBlock(node) && !isBlock(parentNode)) {
14655 if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1))
14656 node.insertBefore(dom.create('br'), node.firstChild);
14658 if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1))
14659 node.appendChild(dom.create('br'));
14662 // Wrap the block in a forcedRootBlock if we are at the root of document
14663 if (parentNode == dom.getRoot()) {
14664 if (!format.list_block || !isEq(node, format.list_block)) {
14665 each(tinymce.grep(node.childNodes), function(node) {
14666 if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) {
14668 rootBlockElm = wrap(node, forcedRootBlock);
14670 rootBlockElm.appendChild(node);
14679 // Never remove nodes that isn't the specified inline element if a selector is specified too
14680 if (format.selector && format.inline && !isEq(format.inline, node))
14683 dom.remove(node, 1);
14686 function getNonWhiteSpaceSibling(node, next, inc) {
14688 next = next ? 'nextSibling' : 'previousSibling';
14690 for (node = inc ? node : node[next]; node; node = node[next]) {
14691 if (node.nodeType == 1 || !isWhiteSpaceNode(node))
14697 function isBookmarkNode(node) {
14698 return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark';
14701 function mergeSiblings(prev, next) {
14702 var marker, sibling, tmpSibling;
14704 function compareElements(node1, node2) {
14705 // Not the same name
14706 if (node1.nodeName != node2.nodeName)
14709 function getAttribs(node) {
14712 each(dom.getAttribs(node), function(attr) {
14713 var name = attr.nodeName.toLowerCase();
14715 // Don't compare internal attributes or style
14716 if (name.indexOf('_') !== 0 && name !== 'style')
14717 attribs[name] = dom.getAttrib(node, name);
14723 function compareObjects(obj1, obj2) {
14726 for (name in obj1) {
14727 // Obj1 has item obj2 doesn't have
14728 if (obj1.hasOwnProperty(name)) {
14729 value = obj2[name];
14731 // Obj2 doesn't have obj1 item
14732 if (value === undefined)
14735 // Obj2 item has a different value
14736 if (obj1[name] != value)
14739 // Delete similar value
14744 // Check if obj 2 has something obj 1 doesn't have
14745 for (name in obj2) {
14746 // Obj2 has item obj1 doesn't have
14747 if (obj2.hasOwnProperty(name))
14754 // Attribs are not the same
14755 if (!compareObjects(getAttribs(node1), getAttribs(node2)))
14758 // Styles are not the same
14759 if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style'))))
14765 // Check if next/prev exists and that they are elements
14766 if (prev && next) {
14767 function findElementSibling(node, sibling_name) {
14768 for (sibling = node; sibling; sibling = sibling[sibling_name]) {
14769 if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0)
14772 if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
14779 // If previous sibling is empty then jump over it
14780 prev = findElementSibling(prev, 'previousSibling');
14781 next = findElementSibling(next, 'nextSibling');
14783 // Compare next and previous nodes
14784 if (compareElements(prev, next)) {
14785 // Append nodes between
14786 for (sibling = prev.nextSibling; sibling && sibling != next;) {
14787 tmpSibling = sibling;
14788 sibling = sibling.nextSibling;
14789 prev.appendChild(tmpSibling);
14792 // Remove next node
14795 // Move children into prev node
14796 each(tinymce.grep(next.childNodes), function(node) {
14797 prev.appendChild(node);
14807 function isTextBlock(name) {
14808 return /^(h[1-6]|p|div|pre|address|dl|dt|dd)$/.test(name);
14811 function getContainer(rng, start) {
14812 var container, offset, lastIdx;
14814 container = rng[start ? 'startContainer' : 'endContainer'];
14815 offset = rng[start ? 'startOffset' : 'endOffset'];
14817 if (container.nodeType == 1) {
14818 lastIdx = container.childNodes.length - 1;
14820 if (!start && offset)
14823 container = container.childNodes[offset > lastIdx ? lastIdx : offset];
14829 function performCaretAction(type, name, vars) {
14830 var i, currentPendingFormats = pendingFormats[type],
14831 otherPendingFormats = pendingFormats[type == 'apply' ? 'remove' : 'apply'];
14833 function hasPending() {
14834 return pendingFormats.apply.length || pendingFormats.remove.length;
14837 function resetPending() {
14838 pendingFormats.apply = [];
14839 pendingFormats.remove = [];
14842 function perform(caret_node) {
14843 // Apply pending formats
14844 each(pendingFormats.apply.reverse(), function(item) {
14845 apply(item.name, item.vars, caret_node);
14847 // Colored nodes should be underlined so that the color of the underline matches the text color.
14848 if (item.name === 'forecolor' && item.vars.value)
14849 processUnderlineAndColor(caret_node.parentNode);
14852 // Remove pending formats
14853 each(pendingFormats.remove.reverse(), function(item) {
14854 remove(item.name, item.vars, caret_node);
14857 dom.remove(caret_node, 1);
14861 // Check if it already exists then ignore it
14862 for (i = currentPendingFormats.length - 1; i >= 0; i--) {
14863 if (currentPendingFormats[i].name == name)
14867 currentPendingFormats.push({name : name, vars : vars});
14869 // Check if it's in the other type, then remove it
14870 for (i = otherPendingFormats.length - 1; i >= 0; i--) {
14871 if (otherPendingFormats[i].name == name)
14872 otherPendingFormats.splice(i, 1);
14875 // Pending apply or remove formats
14876 if (hasPending()) {
14877 ed.getDoc().execCommand('FontName', false, 'mceinline');
14878 pendingFormats.lastRng = selection.getRng();
14880 // IE will convert the current word
14881 each(dom.select('font,span'), function(node) {
14884 if (isCaretNode(node)) {
14885 bookmark = selection.getBookmark();
14887 selection.moveToBookmark(bookmark);
14892 // Only register listeners once if we need to
14893 if (!pendingFormats.isListening && hasPending()) {
14894 pendingFormats.isListening = true;
14896 each('onKeyDown,onKeyUp,onKeyPress,onMouseUp'.split(','), function(event) {
14897 ed[event].addToTop(function(ed, e) {
14898 // Do we have pending formats and is the selection moved has moved
14899 if (hasPending() && !tinymce.dom.RangeUtils.compareRanges(pendingFormats.lastRng, selection.getRng())) {
14900 each(dom.select('font,span'), function(node) {
14904 if (isCaretNode(node)) {
14905 textNode = node.firstChild;
14910 rng = dom.createRng();
14911 rng.setStart(textNode, textNode.nodeValue.length);
14912 rng.setEnd(textNode, textNode.nodeValue.length);
14913 selection.setRng(rng);
14920 // Always unbind and clear pending styles on keyup
14921 if (e.type == 'keyup' || e.type == 'mouseup')
14932 tinymce.onAddEditor.add(function(tinymce, ed) {
14933 var filters, fontSizes, dom, settings = ed.settings;
14935 if (settings.inline_styles) {
14936 fontSizes = tinymce.explode(settings.font_size_style_values);
14938 function replaceWithSpan(node, styles) {
14939 tinymce.each(styles, function(value, name) {
14941 dom.setStyle(node, name, value);
14944 dom.rename(node, 'span');
14948 font : function(dom, node) {
14949 replaceWithSpan(node, {
14950 backgroundColor : node.style.backgroundColor,
14951 color : node.color,
14952 fontFamily : node.face,
14953 fontSize : fontSizes[parseInt(node.size) - 1]
14957 u : function(dom, node) {
14958 replaceWithSpan(node, {
14959 textDecoration : 'underline'
14963 strike : function(dom, node) {
14964 replaceWithSpan(node, {
14965 textDecoration : 'line-through'
14970 function convert(editor, params) {
14973 if (settings.convert_fonts_to_spans) {
14974 tinymce.each(dom.select('font,u,strike', params.node), function(node) {
14975 filters[node.nodeName.toLowerCase()](ed.dom, node);
14980 ed.onPreProcess.add(convert);
14981 ed.onSetContent.add(convert);
14983 ed.onInit.add(function() {
14984 ed.selection.onSetContent.add(convert);