2 var whiteSpaceRe = /^\s*|\s*$/g,
3 undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
10 releaseDate : '2011-08-04',
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.isIE7 = t.isIE && /MSIE [7]/.test(ua);
25 t.isIE8 = t.isIE && /MSIE [8]/.test(ua);
27 t.isIE9 = t.isIE && /MSIE [9]/.test(ua);
29 t.isGecko = !t.isWebKit && /Gecko/.test(ua);
31 t.isMac = ua.indexOf('Mac') != -1;
33 t.isAir = /adobeair/i.test(ua);
35 t.isIDevice = /(iPad|iPhone)/.test(ua);
37 t.isIOS5 = t.isIDevice && ua.match(/AppleWebKit\/(\d*)/)[1]>=534;
39 // TinyMCE .NET webcontrol might be setting the values for TinyMCE
40 if (win.tinyMCEPreInit) {
41 t.suffix = tinyMCEPreInit.suffix;
42 t.baseURL = tinyMCEPreInit.base;
43 t.query = tinyMCEPreInit.query;
47 // Get suffix and base
50 // If base element found, add that infront of baseURL
51 nl = d.getElementsByTagName('base');
52 for (i=0; i<nl.length; i++) {
54 // Host only value like http://site.com or http://site.com:8008
55 if (/^https?:\/\/[^\/]+$/.test(v))
58 base = v ? v.match(/.*\//)[0] : ''; // Get only directory
63 if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) {
64 if (/_(src|dev)\.js/g.test(n.src))
67 if ((p = n.src.indexOf('?')) != -1)
68 t.query = n.src.substring(p + 1);
70 t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));
72 // If path to script is relative and a base href was found add that one infront
73 // the src property will always be an absolute one on non IE browsers and IE 8
74 // so this logic will basically only be executed on older IE versions
75 if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0)
76 t.baseURL = base + t.baseURL;
85 nl = d.getElementsByTagName('script');
86 for (i=0; i<nl.length; i++) {
92 n = d.getElementsByTagName('head')[0];
94 nl = n.getElementsByTagName('script');
95 for (i=0; i<nl.length; i++) {
104 is : function(o, t) {
106 return o !== undefined;
108 if (t == 'array' && (o.hasOwnProperty && o instanceof Array))
111 return typeof(o) == t;
114 makeMap : function(items, delim, map) {
118 delim = delim || ',';
120 if (typeof(items) == "string")
121 items = items.split(delim);
132 each : function(o, cb, s) {
140 if (o.length !== undefined) {
141 // Indexed arrays, needed for Safari
142 for (n=0, l = o.length; n < l; n++) {
143 if (cb.call(s, o[n], n, o) === false)
149 if (o.hasOwnProperty(n)) {
150 if (cb.call(s, o[n], n, o) === false)
160 map : function(a, f) {
163 tinymce.each(a, function(v) {
170 grep : function(a, f) {
173 tinymce.each(a, function(v) {
181 inArray : function(a, v) {
185 for (i = 0, l = a.length; i < l; i++) {
194 extend : function(o, e) {
195 var i, l, a = arguments;
197 for (i = 1, l = a.length; i < l; i++) {
200 tinymce.each(e, function(v, n) {
211 return (s ? '' + s : '').replace(whiteSpaceRe, '');
214 create : function(s, p, root) {
215 var t = this, sp, ns, cn, scn, c, de = 0;
217 // Parse : <prefix> <class>:<super class>
218 s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
219 cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
221 // Create namespace for new class
222 ns = t.createNS(s[3].replace(/\.\w+$/, ''), root);
224 // Class already exists
228 // Make pure static class
229 if (s[2] == 'static') {
233 this.onCreate(s[2], s[3], ns[cn]);
238 // Create default constructor
240 p[cn] = function() {};
244 // Add constructor and methods
246 t.extend(ns[cn].prototype, p);
250 sp = t.resolve(s[5]).prototype;
251 scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
253 // Extend constructor
256 // Add passthrough constructor
257 ns[cn] = function() {
258 return sp[scn].apply(this, arguments);
261 // Add inherit constructor
262 ns[cn] = function() {
263 this.parent = sp[scn];
264 return c.apply(this, arguments);
267 ns[cn].prototype[cn] = ns[cn];
270 t.each(sp, function(f, n) {
271 ns[cn].prototype[n] = sp[n];
274 // Add overridden methods
275 t.each(p, function(f, n) {
276 // Extend methods if needed
278 ns[cn].prototype[n] = function() {
280 return f.apply(this, arguments);
284 ns[cn].prototype[n] = f;
289 // Add static methods
290 t.each(p['static'], function(f, n) {
295 this.onCreate(s[2], s[3], ns[cn].prototype);
298 walk : function(o, f, n, s) {
305 tinymce.each(o, function(o, i) {
306 if (f.call(s, o, i, n) === false)
309 tinymce.walk(o, f, n, s);
314 createNS : function(n, o) {
320 for (i=0; i<n.length; i++) {
332 resolve : function(n, o) {
338 for (i = 0, l = n.length; i < l; i++) {
348 addUnload : function(f, s) {
351 f = {func : f, scope : s || this};
355 var li = t.unloads, o, n;
358 // Call unload handlers
363 o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
366 // Detach unload function
367 if (win.detachEvent) {
368 win.detachEvent('onbeforeunload', fakeUnload);
369 win.detachEvent('onunload', unload);
370 } else if (win.removeEventListener)
371 win.removeEventListener('unload', unload, false);
373 // Destroy references
374 t.unloads = o = li = w = unload = 0;
376 // Run garbarge collector on IE
377 if (win.CollectGarbage)
382 function fakeUnload() {
385 // Is there things still loading, then do some magic
386 if (d.readyState == 'interactive') {
388 // Prevent memory leak
389 d.detachEvent('onstop', stop);
391 // Call unload handler
398 // Fire unload when the currently loading page is stopped
400 d.attachEvent('onstop', stop);
402 // Remove onstop listener after a while to prevent the unload function
403 // to execute if the user presses cancel in an onbeforeunload
404 // confirm dialog and then presses the browser stop button
405 win.setTimeout(function() {
407 d.detachEvent('onstop', stop);
412 // Attach unload handler
413 if (win.attachEvent) {
414 win.attachEvent('onunload', unload);
415 win.attachEvent('onbeforeunload', fakeUnload);
416 } else if (win.addEventListener)
417 win.addEventListener('unload', unload, false);
419 // Setup initial unload handler array
427 removeUnload : function(f) {
428 var u = this.unloads, r = null;
430 tinymce.each(u, function(o, i) {
431 if (o && o.func == f) {
441 explode : function(s, d) {
442 return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;
445 _addVer : function(u) {
451 v = (u.indexOf('?') == -1 ? '?' : '&') + this.query;
453 if (u.indexOf('#') == -1)
456 return u.replace('#', v + '#');
459 // Fix function for IE 9 where regexps isn't working correctly
460 // Todo: remove me once MS fixes the bug
461 _replace : function(find, replace, str) {
462 // On IE9 we have to fake $x replacement
463 if (isRegExpBroken) {
464 return str.replace(find, function() {
465 var val = replace, args = arguments, i;
467 for (i = 0; i < args.length - 2; i++) {
468 if (args[i] === undefined) {
469 val = val.replace(new RegExp('\\$' + i, 'g'), '');
471 val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);
479 return str.replace(find, replace);
484 // Initialize the API
487 // Expose tinymce namespace to the global namespace (window)
488 win.tinymce = win.tinyMCE = tinymce;
490 // Describe the different namespaces
496 tinymce.create('tinymce.util.Dispatcher', {
500 Dispatcher : function(s) {
501 this.scope = s || this;
505 add : function(cb, s) {
506 this.listeners.push({cb : cb, scope : s || this.scope});
511 addToTop : function(cb, s) {
512 this.listeners.unshift({cb : cb, scope : s || this.scope});
517 remove : function(cb) {
518 var l = this.listeners, o = null;
520 tinymce.each(l, function(c, i) {
531 dispatch : function() {
532 var s, a = arguments, i, li = this.listeners, c;
534 // Needs to be a real loop since the listener count might change while looping
535 // And this is also more efficient
536 for (i = 0; i<li.length; i++) {
538 s = c.cb.apply(c.scope, a);
550 var each = tinymce.each;
552 tinymce.create('tinymce.util.URI', {
553 URI : function(u, s) {
554 var t = this, o, a, b, base_url;
560 s = t.settings = s || {};
562 // Strange app protocol or local anchor
563 if (/^(mailto|tel|news|javascript|about|data):/i.test(u) || /^\s*#/.test(u)) {
568 // Absolute path with no host, fake host and protocol
569 if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)
570 u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;
572 // Relative path http:// or protocol relative //path
573 if (!/^[\w-]*:?\/\//.test(u)) {
574 base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory;
575 u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u);
578 // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
579 u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
580 u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
581 each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
584 // Zope 3 workaround, they use @@something
586 s = s.replace(/\(mce_at\)/g, '@@');
591 if (b = s.base_uri) {
593 t.protocol = b.protocol;
596 t.userInfo = b.userInfo;
598 if (!t.port && t.host == 'mce_host')
601 if (!t.host || t.host == 'mce_host')
607 //t.path = t.path || '/';
610 setPath : function(p) {
613 p = /^(.*?)\/?(\w+)?$/.exec(p);
625 toRelative : function(u) {
631 u = new tinymce.util.URI(u, {base_uri : t});
633 // Not on same domain/port or protocol
634 if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
637 o = t.toRelPath(t.path, u.path);
650 toAbsolute : function(u, nh) {
651 var u = new tinymce.util.URI(u, {base_uri : this});
653 return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
656 toRelPath : function(base, path) {
657 var items, bp = 0, out = '', i, l;
660 base = base.substring(0, base.lastIndexOf('/'));
661 base = base.split('/');
662 items = path.split('/');
664 if (base.length >= items.length) {
665 for (i = 0, l = base.length; i < l; i++) {
666 if (i >= items.length || base[i] != items[i]) {
673 if (base.length < items.length) {
674 for (i = 0, l = items.length; i < l; i++) {
675 if (i >= base.length || base[i] != items[i]) {
685 for (i = 0, l = base.length - (bp - 1); i < l; i++)
688 for (i = bp - 1, l = items.length; i < l; i++) {
690 out += "/" + items[i];
698 toAbsPath : function(base, path) {
699 var i, nb = 0, o = [], tr, outPath;
702 tr = /\/$/.test(path) ? '/' : '';
703 base = base.split('/');
704 path = path.split('/');
706 // Remove empty chunks
707 each(base, function(k) {
714 // Merge relURLParts chunks
715 for (i = path.length - 1, o = []; i >= 0; i--) {
717 if (path[i].length == 0 || path[i] == ".")
721 if (path[i] == '..') {
735 i = base.length - nb;
739 outPath = o.reverse().join('/');
741 outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
743 // Add front / if it's needed
744 if (outPath.indexOf('/') !== 0)
745 outPath = '/' + outPath;
747 // Add traling / if it's needed
748 if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)
754 getURI : function(nh) {
758 if (!t.source || nh) {
763 s += t.protocol + '://';
766 s += t.userInfo + '@';
793 var each = tinymce.each;
795 tinymce.create('static tinymce.util.Cookie', {
796 getHash : function(n) {
797 var v = this.get(n), h;
800 each(v.split('&'), function(v) {
803 h[unescape(v[0])] = unescape(v[1]);
810 setHash : function(n, v, e, p, d, s) {
813 each(v, function(v, k) {
814 o += (!o ? '' : '&') + escape(k) + '=' + escape(v);
817 this.set(n, o, e, p, d, s);
821 var c = document.cookie, e, p = n + "=", b;
827 b = c.indexOf("; " + p);
837 e = c.indexOf(";", b);
842 return unescape(c.substring(b + p.length, e));
845 set : function(n, v, e, p, d, s) {
846 document.cookie = n + "=" + escape(v) +
847 ((e) ? "; expires=" + e.toGMTString() : "") +
848 ((p) ? "; path=" + escape(p) : "") +
849 ((d) ? "; domain=" + d : "") +
850 ((s) ? "; secure" : "");
853 remove : function(n, p) {
856 d.setTime(d.getTime() - 1000);
858 this.set(n, '', d, p, d);
864 function serialize(o, quote) {
867 quote = quote || '"';
875 v = '\bb\tt\nn\ff\rr\""\'\'\\\\';
877 return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {
878 // Make sure single quotes never get encoded inside double quotes for JSON compatibility
879 if (quote === '"' && a === "'")
885 return '\\' + v.charAt(i + 1);
887 a = b.charCodeAt().toString(16);
889 return '\\u' + '0000'.substring(a.length) + a;
894 if (o.hasOwnProperty && o instanceof Array) {
895 for (i=0, v = '['; i<o.length; i++)
896 v += (i > 0 ? ',' : '') + serialize(o[i], quote);
904 v += typeof o[i] != 'function' ? (v.length > 1 ? ',' + quote : quote) + i + quote +':' + serialize(o[i], quote) : '';
912 tinymce.util.JSON = {
913 serialize: serialize,
917 return eval('(' + s + ')');
925 tinymce.create('static tinymce.util.XHR', {
927 var x, t, w = window, c = 0;
930 o.scope = o.scope || this;
931 o.success_scope = o.success_scope || o.scope;
932 o.error_scope = o.error_scope || o.scope;
933 o.async = o.async === false ? false : true;
934 o.data = o.data || '';
940 x = new ActiveXObject(s);
947 x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP');
950 if (x.overrideMimeType)
951 x.overrideMimeType(o.content_type);
953 x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async);
956 x.setRequestHeader('Content-Type', o.content_type);
958 x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
963 if (!o.async || x.readyState == 4 || c++ > 10000) {
964 if (o.success && c < 10000 && x.status == 200)
965 o.success.call(o.success_scope, '' + x.responseText, x, o);
967 o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);
971 w.setTimeout(ready, 10);
974 // Syncronous request
978 // Wait for response, onReadyStateChange can not be used since it leaks memory in IE
979 t = w.setTimeout(ready, 10);
985 var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR;
987 tinymce.create('tinymce.util.JSONRequest', {
988 JSONRequest : function(s) {
989 this.settings = extend({
995 var ecb = o.error, scb = o.success;
997 o = extend(this.settings, o);
999 o.success = function(c, x) {
1002 if (typeof(c) == 'undefined') {
1004 error : 'JSON Parse error.'
1009 ecb.call(o.error_scope || o.scope, c.error, x);
1011 scb.call(o.success_scope || o.scope, c.result);
1014 o.error = function(ty, x) {
1016 ecb.call(o.error_scope || o.scope, ty, x);
1019 o.data = JSON.serialize({
1020 id : o.id || 'c' + (this.count++),
1025 // JSON content type for Ruby on rails. Bug: #1883287
1026 o.content_type = 'application/json';
1032 sendRPC : function(o) {
1033 return new tinymce.util.JSONRequest().send(o);
1047 (function(tinymce) {
1048 function cleanupStylesWhenDeleting(ed) {
1049 var dom = ed.dom, selection = ed.selection, VK= tinymce.VK;
1050 ed.onKeyUp.add(function(ed, e) {
1051 if (e.keyCode == VK.DELETE ||e.keyCode == VK.BACKSPACE) {
1052 var startContainer = selection.getRng().startContainer;
1053 var blockElement = startContainer;
1054 while (!dom.isBlock(blockElement)) {
1055 blockElement = blockElement.parentNode;
1057 var spans = dom.select("span.Apple-style-span", blockElement);
1058 dom.remove(spans, true);
1063 tinymce.create('tinymce.util.Quirks', {
1064 Quirks: function(ed) {
1065 if (tinymce.isWebKit) {
1066 cleanupStylesWhenDeleting(ed);
1073 (function(tinymce) {
1074 var namedEntities, baseEntities, reverseEntities,
1075 attrsCharsRegExp = /[&<>\"\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1076 textCharsRegExp = /[<>&\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
1077 rawCharsRegExp = /[<>&\"\']/g,
1078 entityRegExp = /&(#x|#)?([\w]+);/g,
1080 128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020",
1081 135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152",
1082 142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022",
1083 150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A",
1084 156 : "\u0153", 158 : "\u017E", 159 : "\u0178"
1089 '\"' : '"', // Needs to be escaped since the YUI compressor would otherwise break the code
1096 // Reverse lookup table for raw entities
1105 // Decodes text by using the browser
1106 function nativeDecode(text) {
1109 elm = document.createElement("div");
1110 elm.innerHTML = text;
1112 return elm.textContent || elm.innerText || text;
1115 // Build a two way lookup table for the entities
1116 function buildEntitiesLookup(items, radix) {
1117 var i, chr, entity, lookup = {};
1120 items = items.split(',');
1121 radix = radix || 10;
1123 // Build entities lookup table
1124 for (i = 0; i < items.length; i += 2) {
1125 chr = String.fromCharCode(parseInt(items[i], radix));
1127 // Only add non base entities
1128 if (!baseEntities[chr]) {
1129 entity = '&' + items[i + 1] + ';';
1130 lookup[chr] = entity;
1131 lookup[entity] = chr;
1139 // Unpack entities lookup where the numbers are in radix 32 to reduce the size
1140 namedEntities = buildEntitiesLookup(
1141 '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +
1142 '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +
1143 '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +
1144 '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +
1145 '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +
1146 '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +
1147 '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +
1148 '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +
1149 '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +
1150 '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +
1151 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +
1152 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +
1153 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +
1154 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +
1155 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +
1156 '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +
1157 '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +
1158 '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +
1159 '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +
1160 '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +
1161 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +
1162 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
1163 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
1164 '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
1165 '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro'
1168 tinymce.html = tinymce.html || {};
1170 tinymce.html.Entities = {
1171 encodeRaw : function(text, attr) {
1172 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1173 return baseEntities[chr] || chr;
1177 encodeAllRaw : function(text) {
1178 return ('' + text).replace(rawCharsRegExp, function(chr) {
1179 return baseEntities[chr] || chr;
1183 encodeNumeric : function(text, attr) {
1184 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1185 // Multi byte sequence convert it to a single entity
1187 return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';';
1189 return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
1193 encodeNamed : function(text, attr, entities) {
1194 entities = entities || namedEntities;
1196 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1197 return baseEntities[chr] || entities[chr] || chr;
1201 getEncodeFunc : function(name, entities) {
1202 var Entities = tinymce.html.Entities;
1204 entities = buildEntitiesLookup(entities) || namedEntities;
1206 function encodeNamedAndNumeric(text, attr) {
1207 return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
1208 return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
1212 function encodeCustomNamed(text, attr) {
1213 return Entities.encodeNamed(text, attr, entities);
1216 // Replace + with , to be compatible with previous TinyMCE versions
1217 name = tinymce.makeMap(name.replace(/\+/g, ','));
1219 // Named and numeric encoder
1220 if (name.named && name.numeric)
1221 return encodeNamedAndNumeric;
1227 return encodeCustomNamed;
1229 return Entities.encodeNamed;
1234 return Entities.encodeNumeric;
1237 return Entities.encodeRaw;
1240 decode : function(text) {
1241 return text.replace(entityRegExp, function(all, numeric, value) {
1243 value = parseInt(value, numeric.length === 2 ? 16 : 10);
1245 // Support upper UTF
1246 if (value > 0xFFFF) {
1249 return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF));
1251 return asciiMap[value] || String.fromCharCode(value);
1254 return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
1260 tinymce.html.Styles = function(settings, schema) {
1261 var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,
1262 urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,
1263 styleRegExp = /\s*([^:]+):\s*([^;]+);?/g,
1264 trimRightRegExp = /\s+$/,
1265 urlColorRegExp = /rgb/,
1266 undef, i, encodingLookup = {}, encodingItems;
1268 settings = settings || {};
1270 encodingItems = '\\" \\\' \\; \\: ; : \uFEFF'.split(' ');
1271 for (i = 0; i < encodingItems.length; i++) {
1272 encodingLookup[encodingItems[i]] = '\uFEFF' + i;
1273 encodingLookup['\uFEFF' + i] = encodingItems[i];
1276 function toHex(match, r, g, b) {
1278 val = parseInt(val).toString(16);
1280 return val.length > 1 ? val : '0' + val; // 0 -> 00
1283 return '#' + hex(r) + hex(g) + hex(b);
1287 toHex : function(color) {
1288 return color.replace(rgbRegExp, toHex);
1291 parse : function(css) {
1292 var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this;
1294 function compress(prefix, suffix) {
1295 var top, right, bottom, left;
1297 // Get values and check it it needs compressing
1298 top = styles[prefix + '-top' + suffix];
1302 right = styles[prefix + '-right' + suffix];
1306 bottom = styles[prefix + '-bottom' + suffix];
1307 if (right != bottom)
1310 left = styles[prefix + '-left' + suffix];
1315 styles[prefix + suffix] = left;
1316 delete styles[prefix + '-top' + suffix];
1317 delete styles[prefix + '-right' + suffix];
1318 delete styles[prefix + '-bottom' + suffix];
1319 delete styles[prefix + '-left' + suffix];
1322 function canCompress(key) {
1323 var value = styles[key], i;
1325 if (!value || value.indexOf(' ') < 0)
1328 value = value.split(' ');
1331 if (value[i] !== value[0])
1335 styles[key] = value[0];
1340 function compress2(target, a, b, c) {
1341 if (!canCompress(a))
1344 if (!canCompress(b))
1347 if (!canCompress(c))
1351 styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
1357 // Encodes the specified string by replacing all \" \' ; : with _<num>
1358 function encode(str) {
1361 return encodingLookup[str];
1364 // Decodes the specified string by replacing all _<num> with it's original value \" \' etc
1365 // It will also decode the \" \' if keep_slashes is set to fale or omitted
1366 function decode(str, keep_slashes) {
1368 str = str.replace(/\uFEFF[0-9]/g, function(str) {
1369 return encodingLookup[str];
1374 str = str.replace(/\\([\'\";:])/g, "$1");
1380 // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing
1381 css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
1382 return str.replace(/[;:]/g, encode);
1386 while (matches = styleRegExp.exec(css)) {
1387 name = matches[1].replace(trimRightRegExp, '').toLowerCase();
1388 value = matches[2].replace(trimRightRegExp, '');
1390 if (name && value.length > 0) {
1391 // Opera will produce 700 instead of bold in their style values
1392 if (name === 'font-weight' && value === '700')
1394 else if (name === 'color' || name === 'background-color') // Lowercase colors like RED
1395 value = value.toLowerCase();
1397 // Convert RGB colors to HEX
1398 value = value.replace(rgbRegExp, toHex);
1400 // Convert URLs and force them into url('value') format
1401 value = value.replace(urlOrStrRegExp, function(match, url, url2, url3, str, str2) {
1407 // Force strings into single quote format
1408 return "'" + str.replace(/\'/g, "\\'") + "'";
1411 url = decode(url || url2 || url3);
1413 // Convert the URL to relative/absolute depending on config
1415 url = urlConverter.call(urlConverterScope, url, 'style');
1417 // Output new URL format
1418 return "url('" + url.replace(/\'/g, "\\'") + "')";
1421 styles[name] = isEncoded ? decode(value, true) : value;
1424 styleRegExp.lastIndex = matches.index + matches[0].length;
1427 // Compress the styles to reduce it's size for example IE will expand styles
1428 compress("border", "");
1429 compress("border", "-width");
1430 compress("border", "-color");
1431 compress("border", "-style");
1432 compress("padding", "");
1433 compress("margin", "");
1434 compress2('border', 'border-width', 'border-style', 'border-color');
1436 // Remove pointless border, IE produces these
1437 if (styles.border === 'medium none')
1438 delete styles.border;
1444 serialize : function(styles, element_name) {
1445 var css = '', name, value;
1447 function serializeStyles(name) {
1448 var styleList, i, l, value;
1450 styleList = schema.styles[name];
1452 for (i = 0, l = styleList.length; i < l; i++) {
1453 name = styleList[i];
1454 value = styles[name];
1456 if (value !== undef && value.length > 0)
1457 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1462 // Serialize styles according to schema
1463 if (element_name && schema && schema.styles) {
1464 // Serialize global styles and element specific styles
1465 serializeStyles('*');
1466 serializeStyles(element_name);
1468 // Output the styles in the order they are inside the object
1469 for (name in styles) {
1470 value = styles[name];
1472 if (value !== undef && value.length > 0)
1473 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
1482 (function(tinymce) {
1483 var transitional = {}, boolAttrMap, blockElementsMap, shortEndedElementsMap, nonEmptyElementsMap, customElementsMap = {},
1484 whiteSpaceElementsMap, selfClosingElementsMap, makeMap = tinymce.makeMap, each = tinymce.each;
1486 function split(str, delim) {
1487 return str.split(delim || ',');
1490 function unpack(lookup, data) {
1491 var key, elements = {};
1493 function replace(value) {
1494 return value.replace(/[A-Z]+/g, function(key) {
1495 return replace(lookup[key]);
1500 for (key in lookup) {
1501 if (lookup.hasOwnProperty(key))
1502 lookup[key] = replace(lookup[key]);
1505 // Unpack and parse data into object map
1506 replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) {
1507 attributes = split(attributes, '|');
1510 attributes : makeMap(attributes),
1511 attributesOrder : attributes,
1512 children : makeMap(children, '|', {'#comment' : {}})
1519 // Build a lookup table for block elements both lowercase and uppercase
1520 blockElementsMap = 'h1,h2,h3,h4,h5,h6,hr,p,div,address,pre,form,table,tbody,thead,tfoot,' +
1521 'th,tr,td,li,ol,ul,caption,blockquote,center,dl,dt,dd,dir,fieldset,' +
1522 'noscript,menu,isindex,samp,header,footer,article,section,hgroup';
1523 blockElementsMap = makeMap(blockElementsMap, ',', makeMap(blockElementsMap.toUpperCase()));
1525 // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size
1526 transitional = unpack({
1529 ZG : 'E|span|width|align|char|charoff|valign',
1530 X : 'p|T|div|U|W|isindex|fieldset|table',
1531 ZF : 'E|align|char|charoff|valign',
1532 W : 'pre|hr|blockquote|address|center|noframes',
1533 ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',
1535 U : 'ul|ol|dl|menu|dir',
1536 ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',
1537 T : 'h1|h2|h3|h4|h5|h6',
1543 P : 'ins|del|script',
1544 O : 'input|select|textarea|label|button',
1546 M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',
1549 J : 'tt|i|b|u|s|strike',
1550 I : 'big|small|font|basefont',
1553 F : 'object|applet|img|map|iframe',
1555 D : 'accesskey|tabindex|onfocus|onblur',
1556 C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
1557 B : 'lang|xml:lang|dir',
1558 A : 'id|class|style|title'
1559 }, 'script[id|charset|type|language|src|defer|xml:space][]' +
1560 'style[B|id|type|media|title|xml:space][]' +
1561 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' +
1562 'param[id|name|value|valuetype|type][]' +
1564 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' +
1568 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' +
1569 'h1[E|align][#|S]' +
1570 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' +
1571 'map[B|C|A|name][X|form|Q|area]' +
1572 'h2[E|align][#|S]' +
1573 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' +
1574 'h3[E|align][#|S]' +
1583 'font[A|B|size|color|face][#|S]' +
1584 'basefont[id|size|color|face][]' +
1598 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' +
1599 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' +
1600 'optgroup[E|disabled|label][option]' +
1601 'option[E|selected|disabled|label|value][]' +
1602 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' +
1603 'label[E|for|accesskey|onfocus|onblur][#|S]' +
1604 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' +
1605 'h4[E|align][#|S]' +
1606 'ins[E|cite|datetime][#|Y]' +
1607 'h5[E|align][#|S]' +
1608 'del[E|cite|datetime][#|Y]' +
1609 'h6[E|align][#|S]' +
1610 'div[E|align][#|Y]' +
1611 'ul[E|type|compact][li]' +
1612 'li[E|type|value][#|Y]' +
1613 'ol[E|type|compact|start][li]' +
1614 'dl[E|compact][dt|dd]' +
1617 'menu[E|compact][li]' +
1618 'dir[E|compact][li]' +
1619 'pre[E|width|xml:space][#|ZA]' +
1620 'hr[E|align|noshade|size|width][]' +
1621 'blockquote[E|cite][#|Y]' +
1622 'address[E][#|S|p]' +
1624 'noframes[E][#|Y]' +
1625 'isindex[A|B|prompt][]' +
1626 'fieldset[E][#|legend|Y]' +
1627 'legend[E|accesskey|align][#|S]' +
1628 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' +
1629 'caption[E|align][#|S]' +
1631 'colgroup[ZG][col]' +
1633 'tr[ZF|bgcolor][th|td]' +
1635 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' +
1636 'noscript[E][#|Y]' +
1640 'area[E|D|shape|coords|href|nohref|alt|target][]' +
1641 'base[id|href|target][]' +
1642 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'
1645 boolAttrMap = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected,autoplay,loop,controls');
1646 shortEndedElementsMap = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,source');
1647 nonEmptyElementsMap = tinymce.extend(makeMap('td,th,iframe,video,audio,object'), shortEndedElementsMap);
1648 whiteSpaceElementsMap = makeMap('pre,script,style,textarea');
1649 selfClosingElementsMap = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
1651 tinymce.html.Schema = function(settings) {
1652 var self = this, elements = {}, children = {}, patternElements = [], validStyles;
1654 settings = settings || {};
1656 // Allow all elements and attributes if verify_html is set to false
1657 if (settings.verify_html === false)
1658 settings.valid_elements = '*[*]';
1660 // Build styles list
1661 if (settings.valid_styles) {
1664 // Convert styles into a rule list
1665 each(settings.valid_styles, function(value, key) {
1666 validStyles[key] = tinymce.explode(value);
1670 // Converts a wildcard expression string to a regexp for example *a will become /.*a/.
1671 function patternToRegExp(str) {
1672 return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
1675 // Parses the specified valid_elements string and adds to the current rules
1676 // This function is a bit hard to read since it's heavily optimized for speed
1677 function addValidElements(valid_elements) {
1678 var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
1679 prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value,
1680 elementRuleRegExp = /^([#+-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,
1681 attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
1682 hasPatternsRegExp = /[*?+]/;
1684 if (valid_elements) {
1685 // Split valid elements into an array with rules
1686 valid_elements = split(valid_elements);
1688 if (elements['@']) {
1689 globalAttributes = elements['@'].attributes;
1690 globalAttributesOrder = elements['@'].attributesOrder;
1694 for (ei = 0, el = valid_elements.length; ei < el; ei++) {
1695 // Parse element rule
1696 matches = elementRuleRegExp.exec(valid_elements[ei]);
1698 // Setup local names for matches
1699 prefix = matches[1];
1700 elementName = matches[2];
1701 outputName = matches[3];
1702 attrData = matches[4];
1704 // Create new attributes and attributesOrder
1706 attributesOrder = [];
1708 // Create the new element
1710 attributes : attributes,
1711 attributesOrder : attributesOrder
1714 // Padd empty elements prefix
1716 element.paddEmpty = true;
1718 // Remove empty elements prefix
1720 element.removeEmpty = true;
1722 // Copy attributes from global rule into current rule
1723 if (globalAttributes) {
1724 for (key in globalAttributes)
1725 attributes[key] = globalAttributes[key];
1727 attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
1730 // Attributes defined
1732 attrData = split(attrData, '|');
1733 for (ai = 0, al = attrData.length; ai < al; ai++) {
1734 matches = attrRuleRegExp.exec(attrData[ai]);
1737 attrType = matches[1];
1738 attrName = matches[2].replace(/::/g, ':');
1739 prefix = matches[3];
1743 if (attrType === '!') {
1744 element.attributesRequired = element.attributesRequired || [];
1745 element.attributesRequired.push(attrName);
1746 attr.required = true;
1749 // Denied from global
1750 if (attrType === '-') {
1751 delete attributes[attrName];
1752 attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1);
1759 if (prefix === '=') {
1760 element.attributesDefault = element.attributesDefault || [];
1761 element.attributesDefault.push({name: attrName, value: value});
1762 attr.defaultValue = value;
1766 if (prefix === ':') {
1767 element.attributesForced = element.attributesForced || [];
1768 element.attributesForced.push({name: attrName, value: value});
1769 attr.forcedValue = value;
1774 attr.validValues = makeMap(value, '?');
1777 // Check for attribute patterns
1778 if (hasPatternsRegExp.test(attrName)) {
1779 element.attributePatterns = element.attributePatterns || [];
1780 attr.pattern = patternToRegExp(attrName);
1781 element.attributePatterns.push(attr);
1783 // Add attribute to order list if it doesn't already exist
1784 if (!attributes[attrName])
1785 attributesOrder.push(attrName);
1787 attributes[attrName] = attr;
1793 // Global rule, store away these for later usage
1794 if (!globalAttributes && elementName == '@') {
1795 globalAttributes = attributes;
1796 globalAttributesOrder = attributesOrder;
1799 // Handle substitute elements such as b/strong
1801 element.outputName = elementName;
1802 elements[outputName] = element;
1805 // Add pattern or exact element
1806 if (hasPatternsRegExp.test(elementName)) {
1807 element.pattern = patternToRegExp(elementName);
1808 patternElements.push(element);
1810 elements[elementName] = element;
1816 function setValidElements(valid_elements) {
1818 patternElements = [];
1820 addValidElements(valid_elements);
1822 each(transitional, function(element, name) {
1823 children[name] = element.children;
1827 // Adds custom non HTML elements to the schema
1828 function addCustomElements(custom_elements) {
1829 var customElementRegExp = /^(~)?(.+)$/;
1831 if (custom_elements) {
1832 each(split(custom_elements), function(rule) {
1833 var matches = customElementRegExp.exec(rule),
1834 inline = matches[1] === '~',
1835 cloneName = inline ? 'span' : 'div',
1838 children[name] = children[cloneName];
1839 customElementsMap[name] = cloneName;
1841 // If it's not marked as inline then add it to valid block elements
1843 blockElementsMap[name] = {};
1845 // Add custom elements at span/div positions
1846 each(children, function(element, child) {
1847 if (element[cloneName])
1848 element[name] = element[cloneName];
1854 // Adds valid children to the schema object
1855 function addValidChildren(valid_children) {
1856 var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;
1858 if (valid_children) {
1859 each(split(valid_children), function(rule) {
1860 var matches = childRuleRegExp.exec(rule), parent, prefix;
1863 prefix = matches[1];
1865 // Add/remove items from default
1867 parent = children[matches[2]];
1869 parent = children[matches[2]] = {'#comment' : {}};
1871 parent = children[matches[2]];
1873 each(split(matches[3], '|'), function(child) {
1875 delete parent[child];
1884 function getElementRule(name) {
1885 var element = elements[name], i;
1887 // Exact match found
1891 // No exact match then try the patterns
1892 i = patternElements.length;
1894 element = patternElements[i];
1896 if (element.pattern.test(name))
1901 if (!settings.valid_elements) {
1902 // No valid elements defined then clone the elements from the transitional spec
1903 each(transitional, function(element, name) {
1905 attributes : element.attributes,
1906 attributesOrder : element.attributesOrder
1909 children[name] = element.children;
1913 each(split('strong/b,em/i'), function(item) {
1914 item = split(item, '/');
1915 elements[item[1]].outputName = item[0];
1918 // Add default alt attribute for images
1919 elements.img.attributesDefault = [{name: 'alt', value: ''}];
1921 // Remove these if they are empty by default
1922 each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr'), function(name) {
1923 elements[name].removeEmpty = true;
1926 // Padd these by default
1927 each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) {
1928 elements[name].paddEmpty = true;
1931 setValidElements(settings.valid_elements);
1933 addCustomElements(settings.custom_elements);
1934 addValidChildren(settings.valid_children);
1935 addValidElements(settings.extended_valid_elements);
1937 // Todo: Remove this when we fix list handling to be valid
1938 addValidChildren('+ol[ul|ol],+ul[ul|ol]');
1940 // If the user didn't allow span only allow internal spans
1941 if (!getElementRule('span'))
1942 addValidElements('span[!data-mce-type|*]');
1944 // Delete invalid elements
1945 if (settings.invalid_elements) {
1946 tinymce.each(tinymce.explode(settings.invalid_elements), function(item) {
1948 delete elements[item];
1952 self.children = children;
1954 self.styles = validStyles;
1956 self.getBoolAttrs = function() {
1960 self.getBlockElements = function() {
1961 return blockElementsMap;
1964 self.getShortEndedElements = function() {
1965 return shortEndedElementsMap;
1968 self.getSelfClosingElements = function() {
1969 return selfClosingElementsMap;
1972 self.getNonEmptyElements = function() {
1973 return nonEmptyElementsMap;
1976 self.getWhiteSpaceElements = function() {
1977 return whiteSpaceElementsMap;
1980 self.isValidChild = function(name, child) {
1981 var parent = children[name];
1983 return !!(parent && parent[child]);
1986 self.getElementRule = getElementRule;
1988 self.getCustomElements = function() {
1989 return customElementsMap;
1992 self.addValidElements = addValidElements;
1994 self.setValidElements = setValidElements;
1996 self.addCustomElements = addCustomElements;
1998 self.addValidChildren = addValidChildren;
2001 // Expose boolMap and blockElementMap as static properties for usage in DOMUtils
2002 tinymce.html.Schema.boolAttrMap = boolAttrMap;
2003 tinymce.html.Schema.blockElementsMap = blockElementsMap;
2006 (function(tinymce) {
2007 tinymce.html.SaxParser = function(settings, schema) {
2008 var self = this, noop = function() {};
2010 settings = settings || {};
2011 self.schema = schema = schema || new tinymce.html.Schema();
2013 if (settings.fix_self_closing !== false)
2014 settings.fix_self_closing = true;
2016 // Add handler functions from settings and setup default handlers
2017 tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) {
2019 self[name] = settings[name] || noop;
2022 self.parse = function(html) {
2023 var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name, isInternalElement, removeInternalElements,
2024 shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue,
2025 validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing,
2026 tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing;
2028 function processEndTag(name) {
2031 // Find position of parent of the same type
2034 if (stack[pos].name === name)
2040 // Close all the open elements
2041 for (i = stack.length - 1; i >= pos; i--) {
2045 self.end(name.name);
2048 // Remove the open elements from the stack
2053 // Precompile RegExps and map objects
2054 tokenRegExp = new RegExp('<(?:' +
2055 '(?:!--([\\w\\W]*?)-->)|' + // Comment
2056 '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA
2057 '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
2058 '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
2059 '(?:\\/([^>]+)>)|' + // End element
2060 '(?:([^\\s\\/<>]+)\\s*((?:[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*)>)' + // Start element
2063 attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g;
2065 'script' : /<\/script[^>]*>/gi,
2066 'style' : /<\/style[^>]*>/gi,
2067 'noscript' : /<\/noscript[^>]*>/gi
2070 // Setup lookup tables for empty elements and boolean attributes
2071 shortEndedElements = schema.getShortEndedElements();
2072 selfClosing = schema.getSelfClosingElements();
2073 fillAttrsMap = schema.getBoolAttrs();
2074 validate = settings.validate;
2075 removeInternalElements = settings.remove_internals;
2076 fixSelfClosing = settings.fix_self_closing;
2078 while (matches = tokenRegExp.exec(html)) {
2080 if (index < matches.index)
2081 self.text(decode(html.substr(index, matches.index - index)));
2083 if (value = matches[6]) { // End element
2084 processEndTag(value.toLowerCase());
2085 } else if (value = matches[7]) { // Start element
2086 value = value.toLowerCase();
2087 isShortEnded = value in shortEndedElements;
2089 // Is self closing tag for example an <li> after an open <li>
2090 if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value)
2091 processEndTag(value);
2094 if (!validate || (elementRule = schema.getElementRule(value))) {
2095 isValidElement = true;
2097 // Grab attributes map and patters when validation is enabled
2099 validAttributesMap = elementRule.attributes;
2100 validAttributePatterns = elementRule.attributePatterns;
2104 if (attribsValue = matches[8]) {
2105 isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element
2107 // If the element has internal attributes then remove it if we are told to do so
2108 if (isInternalElement && removeInternalElements)
2109 isValidElement = false;
2114 attribsValue.replace(attrRegExp, function(match, name, value, val2, val3) {
2117 name = name.toLowerCase();
2118 value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
2120 // Validate name and value
2121 if (validate && !isInternalElement && name.indexOf('data-') !== 0) {
2122 attrRule = validAttributesMap[name];
2124 // Find rule by pattern matching
2125 if (!attrRule && validAttributePatterns) {
2126 i = validAttributePatterns.length;
2128 attrRule = validAttributePatterns[i];
2129 if (attrRule.pattern.test(name))
2138 // No attribute rule found
2143 if (attrRule.validValues && !(value in attrRule.validValues))
2147 // Add attribute to list and map
2148 attrList.map[name] = value;
2159 // Process attributes if validation is enabled
2160 if (validate && !isInternalElement) {
2161 attributesRequired = elementRule.attributesRequired;
2162 attributesDefault = elementRule.attributesDefault;
2163 attributesForced = elementRule.attributesForced;
2165 // Handle forced attributes
2166 if (attributesForced) {
2167 i = attributesForced.length;
2169 attr = attributesForced[i];
2171 attrValue = attr.value;
2173 if (attrValue === '{$uid}')
2174 attrValue = 'mce_' + idCount++;
2176 attrList.map[name] = attrValue;
2177 attrList.push({name: name, value: attrValue});
2181 // Handle default attributes
2182 if (attributesDefault) {
2183 i = attributesDefault.length;
2185 attr = attributesDefault[i];
2188 if (!(name in attrList.map)) {
2189 attrValue = attr.value;
2191 if (attrValue === '{$uid}')
2192 attrValue = 'mce_' + idCount++;
2194 attrList.map[name] = attrValue;
2195 attrList.push({name: name, value: attrValue});
2200 // Handle required attributes
2201 if (attributesRequired) {
2202 i = attributesRequired.length;
2204 if (attributesRequired[i] in attrList.map)
2208 // None of the required attributes where found
2210 isValidElement = false;
2213 // Invalidate element if it's marked as bogus
2214 if (attrList.map['data-mce-bogus'])
2215 isValidElement = false;
2219 self.start(value, attrList, isShortEnded);
2221 isValidElement = false;
2223 // Treat script, noscript and style a bit different since they may include code that looks like elements
2224 if (endRegExp = specialElements[value]) {
2225 endRegExp.lastIndex = index = matches.index + matches[0].length;
2227 if (matches = endRegExp.exec(html)) {
2229 text = html.substr(index, matches.index - index);
2231 index = matches.index + matches[0].length;
2233 text = html.substr(index);
2234 index = html.length;
2237 if (isValidElement && text.length > 0)
2238 self.text(text, true);
2243 tokenRegExp.lastIndex = index;
2247 // Push value on to stack
2248 if (!isShortEnded) {
2249 if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1)
2250 stack.push({name: value, valid: isValidElement});
2251 else if (isValidElement)
2254 } else if (value = matches[1]) { // Comment
2255 self.comment(value);
2256 } else if (value = matches[2]) { // CDATA
2258 } else if (value = matches[3]) { // DOCTYPE
2259 self.doctype(value);
2260 } else if (value = matches[4]) { // PI
2261 self.pi(value, matches[5]);
2264 index = matches.index + matches[0].length;
2268 if (index < html.length)
2269 self.text(decode(html.substr(index)));
2271 // Close any open elements
2272 for (i = stack.length - 1; i >= 0; i--) {
2276 self.end(value.name);
2282 (function(tinymce) {
2283 var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = {
2289 '#document-fragment' : 11
2292 // Walks the tree left/right
2293 function walk(node, root_node, prev) {
2294 var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next';
2296 // Walk into nodes if it has a start
2297 if (node[startName])
2298 return node[startName];
2300 // Return the sibling if it has one
2301 if (node !== root_node) {
2302 sibling = node[siblingName];
2307 // Walk up the parents to look for siblings
2308 for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) {
2309 sibling = parent[siblingName];
2317 function Node(name, type) {
2322 this.attributes = [];
2323 this.attributes.map = {};
2327 tinymce.extend(Node.prototype, {
2328 replace : function(node) {
2334 self.insert(node, self);
2340 attr : function(name, value) {
2341 var self = this, attrs, i, undef;
2343 if (typeof name !== "string") {
2345 self.attr(i, name[i]);
2350 if (attrs = self.attributes) {
2351 if (value !== undef) {
2353 if (value === null) {
2354 if (name in attrs.map) {
2355 delete attrs.map[name];
2359 if (attrs[i].name === name) {
2360 attrs = attrs.splice(i, 1);
2370 if (name in attrs.map) {
2374 if (attrs[i].name === name) {
2375 attrs[i].value = value;
2380 attrs.push({name: name, value: value});
2382 attrs.map[name] = value;
2386 return attrs.map[name];
2391 clone : function() {
2392 var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs;
2394 // Clone element attributes
2395 if (selfAttrs = self.attributes) {
2397 cloneAttrs.map = {};
2399 for (i = 0, l = selfAttrs.length; i < l; i++) {
2400 selfAttr = selfAttrs[i];
2402 // Clone everything except id
2403 if (selfAttr.name !== 'id') {
2404 cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value};
2405 cloneAttrs.map[selfAttr.name] = selfAttr.value;
2409 clone.attributes = cloneAttrs;
2412 clone.value = self.value;
2413 clone.shortEnded = self.shortEnded;
2418 wrap : function(wrapper) {
2421 self.parent.insert(wrapper, self);
2422 wrapper.append(self);
2427 unwrap : function() {
2428 var self = this, node, next;
2430 for (node = self.firstChild; node; ) {
2432 self.insert(node, self, true);
2439 remove : function() {
2440 var self = this, parent = self.parent, next = self.next, prev = self.prev;
2443 if (parent.firstChild === self) {
2444 parent.firstChild = next;
2452 if (parent.lastChild === self) {
2453 parent.lastChild = prev;
2461 self.parent = self.next = self.prev = null;
2467 append : function(node) {
2468 var self = this, last;
2473 last = self.lastChild;
2477 self.lastChild = node;
2479 self.lastChild = self.firstChild = node;
2486 insert : function(node, ref_node, before) {
2492 parent = ref_node.parent || this;
2495 if (ref_node === parent.firstChild)
2496 parent.firstChild = node;
2498 ref_node.prev.next = node;
2500 node.prev = ref_node.prev;
2501 node.next = ref_node;
2502 ref_node.prev = node;
2504 if (ref_node === parent.lastChild)
2505 parent.lastChild = node;
2507 ref_node.next.prev = node;
2509 node.next = ref_node.next;
2510 node.prev = ref_node;
2511 ref_node.next = node;
2514 node.parent = parent;
2519 getAll : function(name) {
2520 var self = this, node, collection = [];
2522 for (node = self.firstChild; node; node = walk(node, self)) {
2523 if (node.name === name)
2524 collection.push(node);
2530 empty : function() {
2531 var self = this, nodes, i, node;
2533 // Remove all children
2534 if (self.firstChild) {
2537 // Collect the children
2538 for (node = self.firstChild; node; node = walk(node, self))
2541 // Remove the children
2545 node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
2549 self.firstChild = self.lastChild = null;
2554 isEmpty : function(elements) {
2555 var self = this, node = self.firstChild, i, name;
2559 if (node.type === 1) {
2560 // Ignore bogus elements
2561 if (node.attributes.map['data-mce-bogus'])
2564 // Keep empty elements like <img />
2565 if (elements[node.name])
2568 // Keep elements with data attributes or name attribute like <a name="1"></a>
2569 i = node.attributes.length;
2571 name = node.attributes[i].name;
2572 if (name === "name" || name.indexOf('data-') === 0)
2577 // Keep non whitespace text nodes
2578 if ((node.type === 3 && !whiteSpaceRegExp.test(node.value)))
2580 } while (node = walk(node, self));
2586 walk : function(prev) {
2587 return walk(this, null, prev);
2591 tinymce.extend(Node, {
2592 create : function(name, attrs) {
2596 node = new Node(name, typeLookup[name] || 1);
2598 // Add attributes if needed
2600 for (attrName in attrs)
2601 node.attr(attrName, attrs[attrName]);
2608 tinymce.html.Node = Node;
2611 (function(tinymce) {
2612 var Node = tinymce.html.Node;
2614 tinymce.html.DomParser = function(settings, schema) {
2615 var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};
2617 settings = settings || {};
2618 settings.validate = "validate" in settings ? settings.validate : true;
2619 settings.root_name = settings.root_name || 'body';
2620 self.schema = schema = schema || new tinymce.html.Schema();
2622 function fixInvalidChildren(nodes) {
2623 var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i,
2624 childClone, nonEmptyElements, nonSplitableElements, sibling, nextNode;
2626 nonSplitableElements = tinymce.makeMap('tr,td,th,tbody,thead,tfoot,table');
2627 nonEmptyElements = schema.getNonEmptyElements();
2629 for (ni = 0; ni < nodes.length; ni++) {
2636 // Get list of all parent nodes until we find a valid parent to stick the child into
2638 for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent)
2639 parents.push(parent);
2641 // Found a suitable parent
2642 if (parent && parents.length > 1) {
2643 // Reverse the array since it makes looping easier
2646 // Clone the related parent and insert that after the moved node
2647 newParent = currentNode = self.filterNode(parents[0].clone());
2649 // Start cloning and moving children on the left side of the target node
2650 for (i = 0; i < parents.length - 1; i++) {
2651 if (schema.isValidChild(currentNode.name, parents[i].name)) {
2652 tempNode = self.filterNode(parents[i].clone());
2653 currentNode.append(tempNode);
2655 tempNode = currentNode;
2657 for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) {
2658 nextNode = childNode.next;
2659 tempNode.append(childNode);
2660 childNode = nextNode;
2663 currentNode = tempNode;
2666 if (!newParent.isEmpty(nonEmptyElements)) {
2667 parent.insert(newParent, parents[0], true);
2668 parent.insert(node, newParent);
2670 parent.insert(node, parents[0], true);
2673 // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p>
2674 parent = parents[0];
2675 if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') {
2676 parent.empty().remove();
2678 } else if (node.parent) {
2679 // If it's an LI try to find a UL/OL for it or wrap it
2680 if (node.name === 'li') {
2681 sibling = node.prev;
2682 if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
2683 sibling.append(node);
2687 sibling = node.next;
2688 if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
2689 sibling.insert(node, sibling.firstChild, true);
2693 node.wrap(self.filterNode(new Node('ul', 1)));
2697 // Try wrapping the element in a DIV
2698 if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
2699 node.wrap(self.filterNode(new Node('div', 1)));
2701 // We failed wrapping it, then remove or unwrap it
2702 if (node.name === 'style' || node.name === 'script')
2703 node.empty().remove();
2711 self.filterNode = function(node) {
2714 // Run element filters
2715 if (name in nodeFilters) {
2716 list = matchedNodes[name];
2721 matchedNodes[name] = [node];
2724 // Run attribute filters
2725 i = attributeFilters.length;
2727 name = attributeFilters[i].name;
2729 if (name in node.attributes.map) {
2730 list = matchedAttributes[name];
2735 matchedAttributes[name] = [node];
2742 self.addNodeFilter = function(name, callback) {
2743 tinymce.each(tinymce.explode(name), function(name) {
2744 var list = nodeFilters[name];
2747 nodeFilters[name] = list = [];
2749 list.push(callback);
2753 self.addAttributeFilter = function(name, callback) {
2754 tinymce.each(tinymce.explode(name), function(name) {
2757 for (i = 0; i < attributeFilters.length; i++) {
2758 if (attributeFilters[i].name === name) {
2759 attributeFilters[i].callbacks.push(callback);
2764 attributeFilters.push({name: name, callbacks: [callback]});
2768 self.parse = function(html, args) {
2769 var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate,
2770 blockElements, startWhiteSpaceRegExp, invalidChildren = [],
2771 endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements, rootBlockName;
2775 matchedAttributes = {};
2776 blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
2777 nonEmptyElements = schema.getNonEmptyElements();
2778 children = schema.children;
2779 validate = settings.validate;
2780 rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
2782 whiteSpaceElements = schema.getWhiteSpaceElements();
2783 startWhiteSpaceRegExp = /^[ \t\r\n]+/;
2784 endWhiteSpaceRegExp = /[ \t\r\n]+$/;
2785 allWhiteSpaceRegExp = /[ \t\r\n]+/g;
2787 function addRootBlocks() {
2788 var node = rootNode.firstChild, next, rootBlockNode;
2793 if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) {
2794 if (!rootBlockNode) {
2795 // Create a new root block element
2796 rootBlockNode = createNode(rootBlockName, 1);
2797 rootNode.insert(rootBlockNode, node);
2798 rootBlockNode.append(node);
2800 rootBlockNode.append(node);
2802 rootBlockNode = null;
2809 function createNode(name, type) {
2810 var node = new Node(name, type), list;
2812 if (name in nodeFilters) {
2813 list = matchedNodes[name];
2818 matchedNodes[name] = [node];
2824 function removeWhitespaceBefore(node) {
2825 var textNode, textVal, sibling;
2827 for (textNode = node.prev; textNode && textNode.type === 3; ) {
2828 textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
2830 if (textVal.length > 0) {
2831 textNode.value = textVal;
2832 textNode = textNode.prev;
2834 sibling = textNode.prev;
2841 parser = new tinymce.html.SaxParser({
2842 validate : validate,
2843 fix_self_closing : !validate, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results
2845 cdata: function(text) {
2846 node.append(createNode('#cdata', 4)).value = text;
2849 text: function(text, raw) {
2852 // Trim all redundant whitespace on non white space elements
2853 if (!whiteSpaceElements[node.name]) {
2854 text = text.replace(allWhiteSpaceRegExp, ' ');
2856 if (node.lastChild && blockElements[node.lastChild.name])
2857 text = text.replace(startWhiteSpaceRegExp, '');
2860 // Do we need to create the node
2861 if (text.length !== 0) {
2862 textNode = createNode('#text', 3);
2863 textNode.raw = !!raw;
2864 node.append(textNode).value = text;
2868 comment: function(text) {
2869 node.append(createNode('#comment', 8)).value = text;
2872 pi: function(name, text) {
2873 node.append(createNode(name, 7)).value = text;
2874 removeWhitespaceBefore(node);
2877 doctype: function(text) {
2880 newNode = node.append(createNode('#doctype', 10));
2881 newNode.value = text;
2882 removeWhitespaceBefore(node);
2885 start: function(name, attrs, empty) {
2886 var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent;
2888 elementRule = validate ? schema.getElementRule(name) : {};
2890 newNode = createNode(elementRule.outputName || name, 1);
2891 newNode.attributes = attrs;
2892 newNode.shortEnded = empty;
2894 node.append(newNode);
2896 // Check if node is valid child of the parent node is the child is
2897 // unknown we don't collect it since it's probably a custom element
2898 parent = children[node.name];
2899 if (parent && children[newNode.name] && !parent[newNode.name])
2900 invalidChildren.push(newNode);
2902 attrFiltersLen = attributeFilters.length;
2903 while (attrFiltersLen--) {
2904 attrName = attributeFilters[attrFiltersLen].name;
2906 if (attrName in attrs.map) {
2907 list = matchedAttributes[attrName];
2912 matchedAttributes[attrName] = [newNode];
2916 // Trim whitespace before block
2917 if (blockElements[name])
2918 removeWhitespaceBefore(newNode);
2920 // Change current node if the element wasn't empty i.e not <br /> or <img />
2926 end: function(name) {
2927 var textNode, elementRule, text, sibling, tempNode;
2929 elementRule = validate ? schema.getElementRule(name) : {};
2931 if (blockElements[name]) {
2932 if (!whiteSpaceElements[node.name]) {
2933 // Trim whitespace at beginning of block
2934 for (textNode = node.firstChild; textNode && textNode.type === 3; ) {
2935 text = textNode.value.replace(startWhiteSpaceRegExp, '');
2937 if (text.length > 0) {
2938 textNode.value = text;
2939 textNode = textNode.next;
2941 sibling = textNode.next;
2947 // Trim whitespace at end of block
2948 for (textNode = node.lastChild; textNode && textNode.type === 3; ) {
2949 text = textNode.value.replace(endWhiteSpaceRegExp, '');
2951 if (text.length > 0) {
2952 textNode.value = text;
2953 textNode = textNode.prev;
2955 sibling = textNode.prev;
2962 // Trim start white space
2963 textNode = node.prev;
2964 if (textNode && textNode.type === 3) {
2965 text = textNode.value.replace(startWhiteSpaceRegExp, '');
2967 if (text.length > 0)
2968 textNode.value = text;
2974 // Handle empty nodes
2975 if (elementRule.removeEmpty || elementRule.paddEmpty) {
2976 if (node.isEmpty(nonEmptyElements)) {
2977 if (elementRule.paddEmpty)
2978 node.empty().append(new Node('#text', '3')).value = '\u00a0';
2980 // Leave nodes that have a name like <a name="name">
2981 if (!node.attributes.map.name) {
2982 tempNode = node.parent;
2983 node.empty().remove();
2996 rootNode = node = new Node(args.context || settings.root_name, 11);
3000 // Fix invalid children or report invalid children in a contextual parsing
3001 if (validate && invalidChildren.length) {
3003 fixInvalidChildren(invalidChildren);
3005 args.invalid = true;
3008 // Wrap nodes in the root into block elements if the root is body
3009 if (rootBlockName && rootNode.name == 'body')
3012 // Run filters only when the contents is valid
3013 if (!args.invalid) {
3015 for (name in matchedNodes) {
3016 list = nodeFilters[name];
3017 nodes = matchedNodes[name];
3019 // Remove already removed children
3022 if (!nodes[fi].parent)
3023 nodes.splice(fi, 1);
3026 for (i = 0, l = list.length; i < l; i++)
3027 list[i](nodes, name, args);
3030 // Run attribute filters
3031 for (i = 0, l = attributeFilters.length; i < l; i++) {
3032 list = attributeFilters[i];
3034 if (list.name in matchedAttributes) {
3035 nodes = matchedAttributes[list.name];
3037 // Remove already removed children
3040 if (!nodes[fi].parent)
3041 nodes.splice(fi, 1);
3044 for (fi = 0, fl = list.callbacks.length; fi < fl; fi++)
3045 list.callbacks[fi](nodes, list.name, args);
3053 // Remove <br> at end of block elements Gecko and WebKit injects BR elements to
3054 // make it possible to place the caret inside empty blocks. This logic tries to remove
3055 // these elements and keep br elements that where intended to be there intact
3056 if (settings.remove_trailing_brs) {
3057 self.addNodeFilter('br', function(nodes, name) {
3058 var i, l = nodes.length, node, blockElements = schema.getBlockElements(),
3059 nonEmptyElements = schema.getNonEmptyElements(), parent, prev, prevName;
3061 // Remove brs from body element as well
3062 blockElements.body = 1;
3064 // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p>
3065 for (i = 0; i < l; i++) {
3067 parent = node.parent;
3069 if (blockElements[node.parent.name] && node === parent.lastChild) {
3070 // Loop all nodes to the right of the current node and check for other BR elements
3071 // excluding bookmarks since they are invisible
3074 prevName = prev.name;
3077 if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') {
3078 // Found a non BR element
3079 if (prevName !== "br")
3082 // Found another br it's a <br><br> structure then don't remove anything
3083 if (prevName === 'br') {
3095 // Is the parent to be considered empty after we removed the BR
3096 if (parent.isEmpty(nonEmptyElements)) {
3097 elementRule = schema.getElementRule(parent.name);
3099 // Remove or padd the element depending on schema rule
3100 if (elementRule.removeEmpty)
3102 else if (elementRule.paddEmpty)
3103 parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0';
3113 tinymce.html.Writer = function(settings) {
3114 var html = [], indent, indentBefore, indentAfter, encode, htmlOutput;
3116 settings = settings || {};
3117 indent = settings.indent;
3118 indentBefore = tinymce.makeMap(settings.indent_before || '');
3119 indentAfter = tinymce.makeMap(settings.indent_after || '');
3120 encode = tinymce.html.Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
3121 htmlOutput = settings.element_format == "html";
3124 start: function(name, attrs, empty) {
3125 var i, l, attr, value;
3127 if (indent && indentBefore[name] && html.length > 0) {
3128 value = html[html.length - 1];
3130 if (value.length > 0 && value !== '\n')
3134 html.push('<', name);
3137 for (i = 0, l = attrs.length; i < l; i++) {
3139 html.push(' ', attr.name, '="', encode(attr.value, true), '"');
3143 if (!empty || htmlOutput)
3144 html[html.length] = '>';
3146 html[html.length] = ' />';
3148 if (empty && indent && indentAfter[name] && html.length > 0) {
3149 value = html[html.length - 1];
3151 if (value.length > 0 && value !== '\n')
3156 end: function(name) {
3159 /*if (indent && indentBefore[name] && html.length > 0) {
3160 value = html[html.length - 1];
3162 if (value.length > 0 && value !== '\n')
3166 html.push('</', name, '>');
3168 if (indent && indentAfter[name] && html.length > 0) {
3169 value = html[html.length - 1];
3171 if (value.length > 0 && value !== '\n')
3176 text: function(text, raw) {
3177 if (text.length > 0)
3178 html[html.length] = raw ? text : encode(text);
3181 cdata: function(text) {
3182 html.push('<![CDATA[', text, ']]>');
3185 comment: function(text) {
3186 html.push('<!--', text, '-->');
3189 pi: function(name, text) {
3191 html.push('<?', name, ' ', text, '?>');
3193 html.push('<?', name, '?>');
3199 doctype: function(text) {
3200 html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
3207 getContent: function() {
3208 return html.join('').replace(/\n$/, '');
3213 (function(tinymce) {
3214 tinymce.html.Serializer = function(settings, schema) {
3215 var self = this, writer = new tinymce.html.Writer(settings);
3217 settings = settings || {};
3218 settings.validate = "validate" in settings ? settings.validate : true;
3220 self.schema = schema = schema || new tinymce.html.Schema();
3221 self.writer = writer;
3223 self.serialize = function(node) {
3224 var handlers, validate;
3226 validate = settings.validate;
3230 3: function(node, raw) {
3231 writer.text(node.value, node.raw);
3236 writer.comment(node.value);
3239 // Processing instruction
3241 writer.pi(node.name, node.value);
3245 10: function(node) {
3246 writer.doctype(node.value);
3251 writer.cdata(node.value);
3254 // Document fragment
3255 11: function(node) {
3256 if ((node = node.firstChild)) {
3259 } while (node = node.next);
3266 function walk(node) {
3267 var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
3271 isEmpty = node.shortEnded;
3272 attrs = node.attributes;
3275 if (validate && attrs && attrs.length > 1) {
3277 sortedAttrs.map = {};
3279 elementRule = schema.getElementRule(node.name);
3280 for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
3281 attrName = elementRule.attributesOrder[i];
3283 if (attrName in attrs.map) {
3284 attrValue = attrs.map[attrName];
3285 sortedAttrs.map[attrName] = attrValue;
3286 sortedAttrs.push({name: attrName, value: attrValue});
3290 for (i = 0, l = attrs.length; i < l; i++) {
3291 attrName = attrs[i].name;
3293 if (!(attrName in sortedAttrs.map)) {
3294 attrValue = attrs.map[attrName];
3295 sortedAttrs.map[attrName] = attrValue;
3296 sortedAttrs.push({name: attrName, value: attrValue});
3300 attrs = sortedAttrs;
3303 writer.start(node.name, attrs, isEmpty);
3306 if ((node = node.firstChild)) {
3309 } while (node = node.next);
3318 // Serialize element and treat all non elements as fragments
3319 if (node.type == 1 && !settings.inner)
3324 return writer.getContent();
3329 (function(tinymce) {
3331 var each = tinymce.each,
3333 isWebKit = tinymce.isWebKit,
3334 isIE = tinymce.isIE,
3335 Entities = tinymce.html.Entities,
3336 simpleSelectorRe = /^([a-z0-9],?)+$/i,
3337 blockElementsMap = tinymce.html.Schema.blockElementsMap,
3338 whiteSpaceRegExp = /^[ \t\r\n]*$/;
3340 tinymce.create('tinymce.dom.DOMUtils', {
3344 pixelStyles : /^(top|left|bottom|right|width|height|borderWidth)$/,
3347 "class" : "className",
3348 className : "className",
3349 checked : "checked",
3350 disabled : "disabled",
3351 maxlength : "maxLength",
3352 readonly : "readOnly",
3353 selected : "selected",
3360 DOMUtils : function(d, s) {
3361 var t = this, globalStyle, name;
3366 t.cssFlicker = false;
3368 t.stdMode = !tinymce.isIE || d.documentMode >= 8;
3369 t.boxModel = !tinymce.isIE || d.compatMode == "CSS1Compat" || t.stdMode;
3370 t.hasOuterHTML = "outerHTML" in d.createElement("a");
3372 t.settings = s = tinymce.extend({
3373 keep_values : false,
3377 t.schema = s.schema;
3378 t.styles = new tinymce.html.Styles({
3379 url_converter : s.url_converter,
3380 url_converter_scope : s.url_converter_scope
3383 // Fix IE6SP2 flicker and check it failed for pre SP2
3384 if (tinymce.isIE6) {
3386 d.execCommand('BackgroundImageCache', false, true);
3388 t.cssFlicker = true;
3392 if (isIE && s.schema) {
3393 // Add missing HTML 4/5 elements to IE
3394 ('abbr article aside audio canvas ' +
3395 'details figcaption figure footer ' +
3396 'header hgroup mark menu meter nav ' +
3397 'output progress section summary ' +
3398 'time video').replace(/\w+/g, function(name) {
3399 d.createElement(name);
3402 // Create all custom elements
3403 for (name in s.schema.getCustomElements()) {
3404 d.createElement(name);
3408 tinymce.addUnload(t.destroy, t);
3411 getRoot : function() {
3412 var t = this, s = t.settings;
3414 return (s && t.get(s.root_element)) || t.doc.body;
3417 getViewPort : function(w) {
3420 w = !w ? this.win : w;
3422 b = this.boxModel ? d.documentElement : d.body;
3424 // Returns viewport size excluding scrollbars
3426 x : w.pageXOffset || b.scrollLeft,
3427 y : w.pageYOffset || b.scrollTop,
3428 w : w.innerWidth || b.clientWidth,
3429 h : w.innerHeight || b.clientHeight
3433 getRect : function(e) {
3434 var p, t = this, sr;
3448 getSize : function(e) {
3452 w = t.getStyle(e, 'width');
3453 h = t.getStyle(e, 'height');
3455 // Non pixel value, then force offset/clientWidth
3456 if (w.indexOf('px') === -1)
3459 // Non pixel value, then force offset/clientWidth
3460 if (h.indexOf('px') === -1)
3464 w : parseInt(w) || e.offsetWidth || e.clientWidth,
3465 h : parseInt(h) || e.offsetHeight || e.clientHeight
3469 getParent : function(n, f, r) {
3470 return this.getParents(n, f, r, false);
3473 getParents : function(n, f, r, c) {
3474 var t = this, na, se = t.settings, o = [];
3477 c = c === undefined;
3480 r = r || t.getRoot();
3482 // Wrap node name as func
3483 if (is(f, 'string')) {
3487 f = function(n) {return n.nodeType == 1;};
3496 if (n == r || !n.nodeType || n.nodeType === 9)
3509 return c ? o : null;
3515 if (e && this.doc && typeof(e) == 'string') {
3517 e = this.doc.getElementById(e);
3519 // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick
3520 if (e && e.id !== n)
3521 return this.doc.getElementsByName(n)[1];
3527 getNext : function(node, selector) {
3528 return this._findSib(node, selector, 'nextSibling');
3531 getPrev : function(node, selector) {
3532 return this._findSib(node, selector, 'previousSibling');
3536 select : function(pa, s) {
3539 return tinymce.dom.Sizzle(pa, t.get(s) || t.get(t.settings.root_element) || t.doc, []);
3542 is : function(n, selector) {
3545 // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance
3546 if (n.length === undefined) {
3547 // Simple all selector
3548 if (selector === '*')
3549 return n.nodeType == 1;
3551 // Simple selector just elements
3552 if (simpleSelectorRe.test(selector)) {
3553 selector = selector.toLowerCase().split(/,/);
3554 n = n.nodeName.toLowerCase();
3556 for (i = selector.length - 1; i >= 0; i--) {
3557 if (selector[i] == n)
3565 return tinymce.dom.Sizzle.matches(selector, n.nodeType ? [n] : n).length > 0;
3569 add : function(p, n, a, h, c) {
3572 return this.run(p, function(p) {
3575 e = is(n, 'string') ? t.doc.createElement(n) : n;
3585 return !c ? p.appendChild(e) : e;
3589 create : function(n, a, h) {
3590 return this.add(this.doc.createElement(n), n, a, h, 1);
3593 createHTML : function(n, a, h) {
3594 var o = '', t = this, k;
3599 if (a.hasOwnProperty(k))
3600 o += ' ' + k + '="' + t.encode(a[k]) + '"';
3603 // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime
3604 if (typeof(h) != "undefined")
3605 return o + '>' + h + '</' + n + '>';
3610 remove : function(node, keep_children) {
3611 return this.run(node, function(node) {
3612 var child, parent = node.parentNode;
3617 if (keep_children) {
3618 while (child = node.firstChild) {
3619 // IE 8 will crash if you don't remove completely empty text nodes
3620 if (!tinymce.isIE || child.nodeType !== 3 || child.nodeValue)
3621 parent.insertBefore(child, node);
3623 node.removeChild(child);
3627 return parent.removeChild(node);
3631 setStyle : function(n, na, v) {
3634 return t.run(n, function(e) {
3639 // Camelcase it, if needed
3640 na = na.replace(/-(\D)/g, function(a, b){
3641 return b.toUpperCase();
3644 // Default px suffix on these
3645 if (t.pixelStyles.test(na) && (tinymce.is(v, 'number') || /^[\-0-9\.]+$/.test(v)))
3650 // IE specific opacity
3652 s.filter = v === '' ? '' : "alpha(opacity=" + (v * 100) + ")";
3654 if (!n.currentStyle || !n.currentStyle.hasLayout)
3655 s.display = 'inline-block';
3658 // Fix for older browsers
3659 s[na] = s['-moz-opacity'] = s['-khtml-opacity'] = v || '';
3663 isIE ? s.styleFloat = v : s.cssFloat = v;
3670 // Force update of the style data
3671 if (t.settings.update_styles)
3672 t.setAttrib(e, 'data-mce-style');
3676 getStyle : function(n, na, c) {
3683 if (this.doc.defaultView && c) {
3685 na = na.replace(/[A-Z]/g, function(a){
3690 return this.doc.defaultView.getComputedStyle(n, null).getPropertyValue(na);
3692 // Old safari might fail
3697 // Camelcase it, if needed
3698 na = na.replace(/-(\D)/g, function(a, b){
3699 return b.toUpperCase();
3703 na = isIE ? 'styleFloat' : 'cssFloat';
3706 if (n.currentStyle && c)
3707 return n.currentStyle[na];
3709 return n.style ? n.style[na] : undefined;
3712 setStyles : function(e, o) {
3713 var t = this, s = t.settings, ol;
3715 ol = s.update_styles;
3716 s.update_styles = 0;
3718 each(o, function(v, n) {
3719 t.setStyle(e, n, v);
3722 // Update style info
3723 s.update_styles = ol;
3724 if (s.update_styles)
3725 t.setAttrib(e, s.cssText);
3728 removeAllAttribs: function(e) {
3729 return this.run(e, function(e) {
3730 var i, attrs = e.attributes;
3731 for (i = attrs.length - 1; i >= 0; i--) {
3732 e.removeAttributeNode(attrs.item(i));
3737 setAttrib : function(e, n, v) {
3745 if (t.settings.strict)
3746 n = n.toLowerCase();
3748 return this.run(e, function(e) {
3753 if (!is(v, 'string')) {
3754 each(v, function(v, n) {
3755 t.setStyle(e, n, v);
3761 // No mce_style for elements with these since they might get resized by the user
3762 if (s.keep_values) {
3763 if (v && !t._isRes(v))
3764 e.setAttribute('data-mce-style', v, 2);
3766 e.removeAttribute('data-mce-style', 2);
3769 e.style.cssText = v;
3773 e.className = v || ''; // Fix IE null bug
3778 if (s.keep_values) {
3779 if (s.url_converter)
3780 v = s.url_converter.call(s.url_converter_scope || t, v, n, e);
3782 t.setAttrib(e, 'data-mce-' + n, v, 2);
3788 e.setAttribute('data-mce-style', v);
3792 if (is(v) && v !== null && v.length !== 0)
3793 e.setAttribute(n, '' + v, 2);
3795 e.removeAttribute(n, 2);
3799 setAttribs : function(e, o) {
3802 return this.run(e, function(e) {
3803 each(o, function(v, n) {
3804 t.setAttrib(e, n, v);
3809 getAttrib : function(e, n, dv) {
3810 var v, t = this, undef;
3814 if (!e || e.nodeType !== 1)
3815 return dv === undef ? false : dv;
3820 // Try the mce variant for these
3821 if (/^(src|href|style|coords|shape)$/.test(n)) {
3822 v = e.getAttribute("data-mce-" + n);
3828 if (isIE && t.props[n]) {
3830 v = v && v.nodeValue ? v.nodeValue : v;
3834 v = e.getAttribute(n, 2);
3836 // Check boolean attribs
3837 if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(n)) {
3838 if (e[t.props[n]] === true && v === '')
3844 // Inner input elements will override attributes on form elements
3845 if (e.nodeName === "FORM" && e.getAttributeNode(n))
3846 return e.getAttributeNode(n).nodeValue;
3848 if (n === 'style') {
3849 v = v || e.style.cssText;
3852 v = t.serializeStyle(t.parseStyle(v), e.nodeName);
3854 if (t.settings.keep_values && !t._isRes(v))
3855 e.setAttribute('data-mce-style', v);
3859 // Remove Apple and WebKit stuff
3860 if (isWebKit && n === "class" && v)
3861 v = v.replace(/(apple|webkit)\-[a-z\-]+/gi, '');
3868 // IE returns 1 as default value
3875 // IE returns +0 as default value for size
3876 if (v === '+0' || v === 20 || v === 0)
3893 // IE returns -1 as default value
3901 // IE returns default value
3902 if (v === 32768 || v === 2147483647 || v === '32768')
3917 v = v.toLowerCase();
3921 // IE has odd anonymous function for event attributes
3922 if (n.indexOf('on') === 0 && v)
3923 v = tinymce._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1', '' + v);
3927 return (v !== undef && v !== null && v !== '') ? '' + v : dv;
3930 getPos : function(n, ro) {
3931 var t = this, x = 0, y = 0, e, d = t.doc, r;
3937 // Use getBoundingClientRect if it exists since it's faster than looping offset nodes
3938 if (n.getBoundingClientRect) {
3939 n = n.getBoundingClientRect();
3940 e = t.boxModel ? d.documentElement : d.body;
3942 // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit
3943 // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position
3944 x = n.left + (d.documentElement.scrollLeft || d.body.scrollLeft) - e.clientTop;
3945 y = n.top + (d.documentElement.scrollTop || d.body.scrollTop) - e.clientLeft;
3947 return {x : x, y : y};
3951 while (r && r != ro && r.nodeType) {
3952 x += r.offsetLeft || 0;
3953 y += r.offsetTop || 0;
3958 while (r && r != ro && r.nodeType) {
3959 x -= r.scrollLeft || 0;
3960 y -= r.scrollTop || 0;
3965 return {x : x, y : y};
3968 parseStyle : function(st) {
3969 return this.styles.parse(st);
3972 serializeStyle : function(o, name) {
3973 return this.styles.serialize(o, name);
3976 loadCSS : function(u) {
3977 var t = this, d = t.doc, head;
3982 head = t.select('head')[0];
3984 each(u.split(','), function(u) {
3991 link = t.create('link', {rel : 'stylesheet', href : tinymce._addVer(u)});
3993 // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug
3994 // This fix seems to resolve that issue by realcing the document ones a stylesheet finishes loading
3995 // It's ugly but it seems to work fine.
3996 if (isIE && d.documentMode && d.recalc) {
3997 link.onload = function() {
4005 head.appendChild(link);
4009 addClass : function(e, c) {
4010 return this.run(e, function(e) {
4016 if (this.hasClass(e, c))
4019 o = this.removeClass(e, c);
4021 return e.className = (o != '' ? (o + ' ') : '') + c;
4025 removeClass : function(e, c) {
4028 return t.run(e, function(e) {
4031 if (t.hasClass(e, c)) {
4033 re = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g");
4035 v = e.className.replace(re, ' ');
4036 v = tinymce.trim(v != ' ' ? v : '');
4042 e.removeAttribute('class');
4043 e.removeAttribute('className');
4053 hasClass : function(n, c) {
4059 return (' ' + n.className + ' ').indexOf(' ' + c + ' ') !== -1;
4062 show : function(e) {
4063 return this.setStyle(e, 'display', 'block');
4066 hide : function(e) {
4067 return this.setStyle(e, 'display', 'none');
4070 isHidden : function(e) {
4073 return !e || e.style.display == 'none' || this.getStyle(e, 'display') == 'none';
4076 uniqueId : function(p) {
4077 return (!p ? 'mce_' : p) + (this.counter++);
4080 setHTML : function(element, html) {
4083 return self.run(element, function(element) {
4085 // Remove all child nodes, IE keeps empty text nodes in DOM
4086 while (element.firstChild)
4087 element.removeChild(element.firstChild);
4090 // IE will remove comments from the beginning
4091 // unless you padd the contents with something
4092 element.innerHTML = '<br />' + html;
4093 element.removeChild(element.firstChild);
4095 // 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
4096 // This seems to fix this problem
4098 // Create new div with HTML contents and a BR infront to keep comments
4099 element = self.create('div');
4100 element.innerHTML = '<br />' + html;
4102 // Add all children from div to target
4103 each (element.childNodes, function(node, i) {
4106 element.appendChild(node);
4110 element.innerHTML = html;
4116 getOuterHTML : function(elm) {
4117 var doc, self = this;
4119 elm = self.get(elm);
4124 if (elm.nodeType === 1 && self.hasOuterHTML)
4125 return elm.outerHTML;
4127 doc = (elm.ownerDocument || self.doc).createElement("body");
4128 doc.appendChild(elm.cloneNode(true));
4130 return doc.innerHTML;
4133 setOuterHTML : function(e, h, d) {
4136 function setHTML(e, h, d) {
4139 tp = d.createElement("body");
4144 t.insertAfter(n.cloneNode(true), e);
4145 n = n.previousSibling;
4151 return this.run(e, function(e) {
4154 // Only set HTML on elements
4155 if (e.nodeType == 1) {
4156 d = d || e.ownerDocument || t.doc;
4160 // Try outerHTML for IE it sometimes produces an unknown runtime error
4161 if (isIE && e.nodeType == 1)
4166 // Fix for unknown runtime error
4175 decode : Entities.decode,
4177 encode : Entities.encodeAllRaw,
4179 insertAfter : function(node, reference_node) {
4180 reference_node = this.get(reference_node);
4182 return this.run(node, function(node) {
4183 var parent, nextSibling;
4185 parent = reference_node.parentNode;
4186 nextSibling = reference_node.nextSibling;
4189 parent.insertBefore(node, nextSibling);
4191 parent.appendChild(node);
4197 isBlock : function(node) {
4198 var type = node.nodeType;
4200 // If it's a node then check the type and use the nodeName
4202 return !!(type === 1 && blockElementsMap[node.nodeName]);
4204 return !!blockElementsMap[node];
4207 replace : function(n, o, k) {
4211 n = n.cloneNode(true);
4213 return t.run(o, function(o) {
4215 each(tinymce.grep(o.childNodes), function(c) {
4220 return o.parentNode.replaceChild(n, o);
4224 rename : function(elm, name) {
4225 var t = this, newElm;
4227 if (elm.nodeName != name.toUpperCase()) {
4228 // Rename block element
4229 newElm = t.create(name);
4231 // Copy attribs to new block
4232 each(t.getAttribs(elm), function(attr_node) {
4233 t.setAttrib(newElm, attr_node.nodeName, t.getAttrib(elm, attr_node.nodeName));
4237 t.replace(newElm, elm, 1);
4240 return newElm || elm;
4243 findCommonAncestor : function(a, b) {
4249 while (pe && ps != pe)
4258 if (!ps && a.ownerDocument)
4259 return a.ownerDocument.documentElement;
4264 toHex : function(s) {
4265 var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s);
4268 s = parseInt(s).toString(16);
4270 return s.length > 1 ? s : '0' + s; // 0 -> 00
4274 s = '#' + hex(c[1]) + hex(c[2]) + hex(c[3]);
4282 getClasses : function() {
4283 var t = this, cl = [], i, lo = {}, f = t.settings.class_filter, ov;
4288 function addClasses(s) {
4290 each(s.imports, function(r) {
4294 each(s.cssRules || s.rules, function(r) {
4295 // Real type or fake it on IE
4296 switch (r.type || 1) {
4299 if (r.selectorText) {
4300 each(r.selectorText.split(','), function(v) {
4301 v = v.replace(/^\s*|\s*$|^\s\./g, "");
4303 // Is internal or it doesn't contain a class
4304 if (/\.mce/.test(v) || !/\.[\w\-]+$/.test(v))
4307 // Remove everything but class name
4309 v = tinymce._replace(/.*\.([a-z0-9_\-]+).*/i, '$1', v);
4312 if (f && !(v = f(v, ov)))
4316 cl.push({'class' : v});
4325 addClasses(r.styleSheet);
4332 each(t.doc.styleSheets, addClasses);
4343 run : function(e, f, s) {
4346 if (t.doc && typeof(e) === 'string')
4353 if (!e.nodeType && (e.length || e.length === 0)) {
4356 each(e, function(e, i) {
4358 if (typeof(e) == 'string')
4359 e = t.doc.getElementById(e);
4361 o.push(f.call(s, e, i));
4368 return f.call(s, e);
4371 getAttribs : function(n) {
4382 // Object will throw exception in IE
4383 if (n.nodeName == 'OBJECT')
4384 return n.attributes;
4386 // IE doesn't keep the selected attribute if you clone option elements
4387 if (n.nodeName === 'OPTION' && this.getAttrib(n, 'selected'))
4388 o.push({specified : 1, nodeName : 'selected'});
4390 // It's crazy that this is faster in IE but it's because it returns all attributes all the time
4391 n.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi, '').replace(/[\w:\-]+/gi, function(a) {
4392 o.push({specified : 1, nodeName : a});
4398 return n.attributes;
4401 isEmpty : function(node, elements) {
4402 var self = this, i, attributes, type, walker, name;
4404 node = node.firstChild;
4406 walker = new tinymce.dom.TreeWalker(node);
4407 elements = elements || self.schema ? self.schema.getNonEmptyElements() : null;
4410 type = node.nodeType;
4413 // Ignore bogus elements
4414 if (node.getAttribute('data-mce-bogus'))
4417 // Keep empty elements like <img />
4418 if (elements && elements[node.nodeName.toLowerCase()])
4421 // Keep elements with data-bookmark attributes or name attribute like <a name="1"></a>
4422 attributes = self.getAttribs(node);
4423 i = node.attributes.length;
4425 name = node.attributes[i].nodeName;
4426 if (name === "name" || name === 'data-mce-bookmark')
4431 // Keep non whitespace text nodes
4432 if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue)))
4434 } while (node = walker.next());
4440 destroy : function(s) {
4446 t.win = t.doc = t.root = t.events = null;
4448 // Manual destroy then remove unload handler
4450 tinymce.removeUnload(t.destroy);
4453 createRng : function() {
4456 return d.createRange ? d.createRange() : new tinymce.dom.Range(this);
4459 nodeIndex : function(node, normalized) {
4460 var idx = 0, lastNodeType, lastNode, nodeType;
4463 for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) {
4464 nodeType = node.nodeType;
4466 // Normalize text nodes
4467 if (normalized && nodeType == 3) {
4468 if (nodeType == lastNodeType || !node.nodeValue.length)
4472 lastNodeType = nodeType;
4479 split : function(pe, e, re) {
4480 var t = this, r = t.createRng(), bef, aft, pa;
4482 // W3C valid browsers tend to leave empty nodes to the left/right side of the contents, this makes sense
4483 // but we don't want that in our code since it serves no purpose for the end user
4484 // For example if this is chopped:
4485 // <p>text 1<span><b>CHOP</b></span>text 2</p>
4487 // <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p>
4488 // this function will then trim of empty edges and produce:
4489 // <p>text 1</p><b>CHOP</b><p>text 2</p>
4490 function trim(node) {
4491 var i, children = node.childNodes, type = node.nodeType;
4493 if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark')
4496 for (i = children.length - 1; i >= 0; i--)
4500 // Keep non whitespace text nodes
4501 if (type == 3 && node.nodeValue.length > 0) {
4502 // If parent element isn't a block or there isn't any useful contents for example "<p> </p>"
4503 if (!t.isBlock(node.parentNode) || tinymce.trim(node.nodeValue).length > 0)
4505 } else if (type == 1) {
4506 // If the only child is a bookmark then move it up
4507 children = node.childNodes;
4508 if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark')
4509 node.parentNode.insertBefore(children[0], node);
4511 // Keep non empty elements or img, hr etc
4512 if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName))
4524 r.setStart(pe.parentNode, t.nodeIndex(pe));
4525 r.setEnd(e.parentNode, t.nodeIndex(e));
4526 bef = r.extractContents();
4530 r.setStart(e.parentNode, t.nodeIndex(e) + 1);
4531 r.setEnd(pe.parentNode, t.nodeIndex(pe) + 1);
4532 aft = r.extractContents();
4534 // Insert before chunk
4536 pa.insertBefore(trim(bef), pe);
4538 // Insert middle chunk
4540 pa.replaceChild(re, e);
4542 pa.insertBefore(e, pe);
4544 // Insert after chunk
4545 pa.insertBefore(trim(aft), pe);
4552 bind : function(target, name, func, scope) {
4556 t.events = new tinymce.dom.EventUtils();
4558 return t.events.add(target, name, func, scope || this);
4561 unbind : function(target, name, func) {
4565 t.events = new tinymce.dom.EventUtils();
4567 return t.events.remove(target, name, func);
4571 _findSib : function(node, selector, name) {
4572 var t = this, f = selector;
4575 // If expression make a function of it using is
4576 if (is(f, 'string')) {
4577 f = function(node) {
4578 return t.is(node, selector);
4582 // Loop all siblings
4583 for (node = node[name]; node; node = node[name]) {
4592 _isRes : function(c) {
4593 // Is live resizble element
4594 return /^(top|left|bottom|right|width|height)/i.test(c) || /;\s*(top|left|bottom|right|width|height)/i.test(c);
4598 walk : function(n, f, s) {
4599 var d = this.doc, w;
4601 if (d.createTreeWalker) {
4602 w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false);
4604 while ((n = w.nextNode()) != null)
4605 f.call(s || this, n);
4607 tinymce.walk(n, f, 'childNodes', s);
4612 toRGB : function(s) {
4613 var c = /^\s*?#([0-9A-F]{2})([0-9A-F]{1,2})([0-9A-F]{2})?\s*?$/.exec(s);
4620 return "rgb(" + parseInt(c[1], 16) + "," + parseInt(c[2], 16) + "," + parseInt(c[3], 16) + ")";
4628 tinymce.DOM = new tinymce.dom.DOMUtils(document, {process_html : 0});
4632 // Range constructor
4633 function Range(dom) {
4641 START_OFFSET = 'startOffset',
4642 START_CONTAINER = 'startContainer',
4643 END_CONTAINER = 'endContainer',
4644 END_OFFSET = 'endOffset',
4645 extend = tinymce.extend,
4646 nodeIndex = dom.nodeIndex;
4650 startContainer : doc,
4655 commonAncestorContainer : doc,
4664 setStart : setStart,
4666 setStartBefore : setStartBefore,
4667 setStartAfter : setStartAfter,
4668 setEndBefore : setEndBefore,
4669 setEndAfter : setEndAfter,
4670 collapse : collapse,
4671 selectNode : selectNode,
4672 selectNodeContents : selectNodeContents,
4673 compareBoundaryPoints : compareBoundaryPoints,
4674 deleteContents : deleteContents,
4675 extractContents : extractContents,
4676 cloneContents : cloneContents,
4677 insertNode : insertNode,
4678 surroundContents : surroundContents,
4679 cloneRange : cloneRange
4682 function setStart(n, o) {
4683 _setEndPoint(TRUE, n, o);
4686 function setEnd(n, o) {
4687 _setEndPoint(FALSE, n, o);
4690 function setStartBefore(n) {
4691 setStart(n.parentNode, nodeIndex(n));
4694 function setStartAfter(n) {
4695 setStart(n.parentNode, nodeIndex(n) + 1);
4698 function setEndBefore(n) {
4699 setEnd(n.parentNode, nodeIndex(n));
4702 function setEndAfter(n) {
4703 setEnd(n.parentNode, nodeIndex(n) + 1);
4706 function collapse(ts) {
4708 t[END_CONTAINER] = t[START_CONTAINER];
4709 t[END_OFFSET] = t[START_OFFSET];
4711 t[START_CONTAINER] = t[END_CONTAINER];
4712 t[START_OFFSET] = t[END_OFFSET];
4718 function selectNode(n) {
4723 function selectNodeContents(n) {
4725 setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length);
4728 function compareBoundaryPoints(h, r) {
4729 var sc = t[START_CONTAINER], so = t[START_OFFSET], ec = t[END_CONTAINER], eo = t[END_OFFSET],
4730 rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset;
4732 // Check START_TO_START
4734 return _compareBoundaryPoints(sc, so, rsc, rso);
4736 // Check START_TO_END
4738 return _compareBoundaryPoints(ec, eo, rsc, rso);
4742 return _compareBoundaryPoints(ec, eo, rec, reo);
4744 // Check END_TO_START
4746 return _compareBoundaryPoints(sc, so, rec, reo);
4749 function deleteContents() {
4753 function extractContents() {
4754 return _traverse(EXTRACT);
4757 function cloneContents() {
4758 return _traverse(CLONE);
4761 function insertNode(n) {
4762 var startContainer = this[START_CONTAINER],
4763 startOffset = this[START_OFFSET], nn, o;
4765 // Node is TEXT_NODE or CDATA
4766 if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) {
4768 // At the start of text
4769 startContainer.parentNode.insertBefore(n, startContainer);
4770 } else if (startOffset >= startContainer.nodeValue.length) {
4771 // At the end of text
4772 dom.insertAfter(n, startContainer);
4774 // Middle, need to split
4775 nn = startContainer.splitText(startOffset);
4776 startContainer.parentNode.insertBefore(n, nn);
4779 // Insert element node
4780 if (startContainer.childNodes.length > 0)
4781 o = startContainer.childNodes[startOffset];
4784 startContainer.insertBefore(n, o);
4786 startContainer.appendChild(n);
4790 function surroundContents(n) {
4791 var f = t.extractContents();
4798 function cloneRange() {
4799 return extend(new Range(dom), {
4800 startContainer : t[START_CONTAINER],
4801 startOffset : t[START_OFFSET],
4802 endContainer : t[END_CONTAINER],
4803 endOffset : t[END_OFFSET],
4804 collapsed : t.collapsed,
4805 commonAncestorContainer : t.commonAncestorContainer
4811 function _getSelectedNode(container, offset) {
4814 if (container.nodeType == 3 /* TEXT_NODE */)
4820 child = container.firstChild;
4821 while (child && offset > 0) {
4823 child = child.nextSibling;
4832 function _isCollapsed() {
4833 return (t[START_CONTAINER] == t[END_CONTAINER] && t[START_OFFSET] == t[END_OFFSET]);
4836 function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) {
4837 var c, offsetC, n, cmnRoot, childA, childB;
4839 // In the first case the boundary-points have the same container. A is before B
4840 // if its offset is less than the offset of B, A is equal to B if its offset is
4841 // equal to the offset of B, and A is after B if its offset is greater than the
4843 if (containerA == containerB) {
4844 if (offsetA == offsetB)
4847 if (offsetA < offsetB)
4848 return -1; // before
4853 // In the second case a child node C of the container of A is an ancestor
4854 // container of B. In this case, A is before B if the offset of A is less than or
4855 // equal to the index of the child node C and A is after B otherwise.
4857 while (c && c.parentNode != containerA)
4862 n = containerA.firstChild;
4864 while (n != c && offsetC < offsetA) {
4869 if (offsetA <= offsetC)
4870 return -1; // before
4875 // In the third case a child node C of the container of B is an ancestor container
4876 // of A. In this case, A is before B if the index of the child node C is less than
4877 // the offset of B and A is after B otherwise.
4879 while (c && c.parentNode != containerB) {
4885 n = containerB.firstChild;
4887 while (n != c && offsetC < offsetB) {
4892 if (offsetC < offsetB)
4893 return -1; // before
4898 // In the fourth case, none of three other cases hold: the containers of A and B
4899 // are siblings or descendants of sibling nodes. In this case, A is before B if
4900 // the container of A is before the container of B in a pre-order traversal of the
4901 // Ranges' context tree and A is after B otherwise.
4902 cmnRoot = dom.findCommonAncestor(containerA, containerB);
4903 childA = containerA;
4905 while (childA && childA.parentNode != cmnRoot)
4906 childA = childA.parentNode;
4911 childB = containerB;
4912 while (childB && childB.parentNode != cmnRoot)
4913 childB = childB.parentNode;
4918 if (childA == childB)
4921 n = cmnRoot.firstChild;
4924 return -1; // before
4933 function _setEndPoint(st, n, o) {
4937 t[START_CONTAINER] = n;
4938 t[START_OFFSET] = o;
4940 t[END_CONTAINER] = n;
4944 // If one boundary-point of a Range is set to have a root container
4945 // other than the current one for the Range, the Range is collapsed to
4946 // the new position. This enforces the restriction that both boundary-
4947 // points of a Range must have the same root container.
4948 ec = t[END_CONTAINER];
4949 while (ec.parentNode)
4952 sc = t[START_CONTAINER];
4953 while (sc.parentNode)
4957 // The start position of a Range is guaranteed to never be after the
4958 // end position. To enforce this restriction, if the start is set to
4959 // be at a position after the end, the Range is collapsed to that
4961 if (_compareBoundaryPoints(t[START_CONTAINER], t[START_OFFSET], t[END_CONTAINER], t[END_OFFSET]) > 0)
4966 t.collapsed = _isCollapsed();
4967 t.commonAncestorContainer = dom.findCommonAncestor(t[START_CONTAINER], t[END_CONTAINER]);
4970 function _traverse(how) {
4971 var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep;
4973 if (t[START_CONTAINER] == t[END_CONTAINER])
4974 return _traverseSameContainer(how);
4976 for (c = t[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
4977 if (p == t[START_CONTAINER])
4978 return _traverseCommonStartContainer(c, how);
4980 ++endContainerDepth;
4983 for (c = t[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
4984 if (p == t[END_CONTAINER])
4985 return _traverseCommonEndContainer(c, how);
4987 ++startContainerDepth;
4990 depthDiff = startContainerDepth - endContainerDepth;
4992 startNode = t[START_CONTAINER];
4993 while (depthDiff > 0) {
4994 startNode = startNode.parentNode;
4998 endNode = t[END_CONTAINER];
4999 while (depthDiff < 0) {
5000 endNode = endNode.parentNode;
5004 // ascend the ancestor hierarchy until we have a common parent.
5005 for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) {
5010 return _traverseCommonAncestors(startNode, endNode, how);
5013 function _traverseSameContainer(how) {
5014 var frag, s, sub, n, cnt, sibling, xferNode;
5017 frag = doc.createDocumentFragment();
5019 // If selection is empty, just return the fragment
5020 if (t[START_OFFSET] == t[END_OFFSET])
5023 // Text node needs special case handling
5024 if (t[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) {
5025 // get the substring
5026 s = t[START_CONTAINER].nodeValue;
5027 sub = s.substring(t[START_OFFSET], t[END_OFFSET]);
5029 // set the original text node to its new value
5031 t[START_CONTAINER].deleteData(t[START_OFFSET], t[END_OFFSET] - t[START_OFFSET]);
5033 // Nothing is partially selected, so collapse to start point
5040 frag.appendChild(doc.createTextNode(sub));
5044 // Copy nodes between the start/end offsets.
5045 n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]);
5046 cnt = t[END_OFFSET] - t[START_OFFSET];
5049 sibling = n.nextSibling;
5050 xferNode = _traverseFullySelected(n, how);
5053 frag.appendChild( xferNode );
5059 // Nothing is partially selected, so collapse to start point
5066 function _traverseCommonStartContainer(endAncestor, how) {
5067 var frag, n, endIdx, cnt, sibling, xferNode;
5070 frag = doc.createDocumentFragment();
5072 n = _traverseRightBoundary(endAncestor, how);
5075 frag.appendChild(n);
5077 endIdx = nodeIndex(endAncestor);
5078 cnt = endIdx - t[START_OFFSET];
5081 // Collapse to just before the endAncestor, which
5082 // is partially selected.
5084 t.setEndBefore(endAncestor);
5091 n = endAncestor.previousSibling;
5093 sibling = n.previousSibling;
5094 xferNode = _traverseFullySelected(n, how);
5097 frag.insertBefore(xferNode, frag.firstChild);
5103 // Collapse to just before the endAncestor, which
5104 // is partially selected.
5106 t.setEndBefore(endAncestor);
5113 function _traverseCommonEndContainer(startAncestor, how) {
5114 var frag, startIdx, n, cnt, sibling, xferNode;
5117 frag = doc.createDocumentFragment();
5119 n = _traverseLeftBoundary(startAncestor, how);
5121 frag.appendChild(n);
5123 startIdx = nodeIndex(startAncestor);
5124 ++startIdx; // Because we already traversed it
5126 cnt = t[END_OFFSET] - startIdx;
5127 n = startAncestor.nextSibling;
5129 sibling = n.nextSibling;
5130 xferNode = _traverseFullySelected(n, how);
5133 frag.appendChild(xferNode);
5140 t.setStartAfter(startAncestor);
5147 function _traverseCommonAncestors(startAncestor, endAncestor, how) {
5148 var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling;
5151 frag = doc.createDocumentFragment();
5153 n = _traverseLeftBoundary(startAncestor, how);
5155 frag.appendChild(n);
5157 commonParent = startAncestor.parentNode;
5158 startOffset = nodeIndex(startAncestor);
5159 endOffset = nodeIndex(endAncestor);
5162 cnt = endOffset - startOffset;
5163 sibling = startAncestor.nextSibling;
5166 nextSibling = sibling.nextSibling;
5167 n = _traverseFullySelected(sibling, how);
5170 frag.appendChild(n);
5172 sibling = nextSibling;
5176 n = _traverseRightBoundary(endAncestor, how);
5179 frag.appendChild(n);
5182 t.setStartAfter(startAncestor);
5189 function _traverseRightBoundary(root, how) {
5190 var next = _getSelectedNode(t[END_CONTAINER], t[END_OFFSET] - 1), parent, clonedParent, prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != t[END_CONTAINER];
5193 return _traverseNode(next, isFullySelected, FALSE, how);
5195 parent = next.parentNode;
5196 clonedParent = _traverseNode(parent, FALSE, FALSE, how);
5200 prevSibling = next.previousSibling;
5201 clonedChild = _traverseNode(next, isFullySelected, FALSE, how);
5204 clonedParent.insertBefore(clonedChild, clonedParent.firstChild);
5206 isFullySelected = TRUE;
5211 return clonedParent;
5213 next = parent.previousSibling;
5214 parent = parent.parentNode;
5216 clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how);
5219 clonedGrandParent.appendChild(clonedParent);
5221 clonedParent = clonedGrandParent;
5225 function _traverseLeftBoundary(root, how) {
5226 var next = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]), isFullySelected = next != t[START_CONTAINER], parent, clonedParent, nextSibling, clonedChild, clonedGrandParent;
5229 return _traverseNode(next, isFullySelected, TRUE, how);
5231 parent = next.parentNode;
5232 clonedParent = _traverseNode(parent, FALSE, TRUE, how);
5236 nextSibling = next.nextSibling;
5237 clonedChild = _traverseNode(next, isFullySelected, TRUE, how);
5240 clonedParent.appendChild(clonedChild);
5242 isFullySelected = TRUE;
5247 return clonedParent;
5249 next = parent.nextSibling;
5250 parent = parent.parentNode;
5252 clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how);
5255 clonedGrandParent.appendChild(clonedParent);
5257 clonedParent = clonedGrandParent;
5261 function _traverseNode(n, isFullySelected, isLeft, how) {
5262 var txtValue, newNodeValue, oldNodeValue, offset, newNode;
5264 if (isFullySelected)
5265 return _traverseFullySelected(n, how);
5267 if (n.nodeType == 3 /* TEXT_NODE */) {
5268 txtValue = n.nodeValue;
5271 offset = t[START_OFFSET];
5272 newNodeValue = txtValue.substring(offset);
5273 oldNodeValue = txtValue.substring(0, offset);
5275 offset = t[END_OFFSET];
5276 newNodeValue = txtValue.substring(0, offset);
5277 oldNodeValue = txtValue.substring(offset);
5281 n.nodeValue = oldNodeValue;
5286 newNode = n.cloneNode(FALSE);
5287 newNode.nodeValue = newNodeValue;
5295 return n.cloneNode(FALSE);
5298 function _traverseFullySelected(n, how) {
5300 return how == CLONE ? n.cloneNode(TRUE) : n;
5302 n.parentNode.removeChild(n);
5310 function Selection(selection) {
5311 var self = this, dom = selection.dom, TRUE = true, FALSE = false;
5313 function getPosition(rng, start) {
5314 var checkRng, startIndex = 0, endIndex, inside,
5315 children, child, offset, index, position = -1, parent;
5317 // Setup test range, collapse it and get the parent
5318 checkRng = rng.duplicate();
5319 checkRng.collapse(start);
5320 parent = checkRng.parentElement();
5322 // Check if the selection is within the right document
5323 if (parent.ownerDocument !== selection.dom.doc)
5326 // IE will report non editable elements as it's parent so look for an editable one
5327 while (parent.contentEditable === "false") {
5328 parent = parent.parentNode;
5331 // If parent doesn't have any children then return that we are inside the element
5332 if (!parent.hasChildNodes()) {
5333 return {node : parent, inside : 1};
5336 // Setup node list and endIndex
5337 children = parent.children;
5338 endIndex = children.length - 1;
5340 // Perform a binary search for the position
5341 while (startIndex <= endIndex) {
5342 index = Math.floor((startIndex + endIndex) / 2);
5344 // Move selection to node and compare the ranges
5345 child = children[index];
5346 checkRng.moveToElementText(child);
5347 position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng);
5349 // Before/after or an exact match
5351 endIndex = index - 1;
5352 } else if (position < 0) {
5353 startIndex = index + 1;
5355 return {node : child};
5359 // Check if child position is before or we didn't find a position
5361 // No element child was found use the parent element and the offset inside that
5363 checkRng.moveToElementText(parent);
5364 checkRng.collapse(true);
5368 checkRng.collapse(false);
5370 checkRng.setEndPoint(start ? 'EndToStart' : 'EndToEnd', rng);
5372 // Fix for edge case: <div style="width: 100px; height:100px;"><table>..</table>ab|c</div>
5373 if (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) > 0) {
5374 checkRng = rng.duplicate();
5375 checkRng.collapse(start);
5378 while (parent == checkRng.parentElement()) {
5379 if (checkRng.move('character', -1) == 0)
5386 offset = offset || checkRng.text.replace('\r\n', ' ').length;
5388 // Child position is after the selection endpoint
5389 checkRng.collapse(true);
5390 checkRng.setEndPoint(start ? 'StartToStart' : 'StartToEnd', rng);
5392 // Get the length of the text to find where the endpoint is relative to it's container
5393 offset = checkRng.text.replace('\r\n', ' ').length;
5396 return {node : child, position : position, offset : offset, inside : inside};
5399 // Returns a W3C DOM compatible range object by using the IE Range API
5400 function getRange() {
5401 var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark, fail;
5403 // If selection is outside the current document just return an empty range
5404 element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
5405 if (element.ownerDocument != dom.doc)
5408 collapsed = selection.isCollapsed();
5410 // Handle control selection
5412 domRange.setStart(element.parentNode, dom.nodeIndex(element));
5413 domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
5418 function findEndPoint(start) {
5419 var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue;
5421 container = endPoint.node;
5422 offset = endPoint.offset;
5424 if (endPoint.inside && !container.hasChildNodes()) {
5425 domRange[start ? 'setStart' : 'setEnd'](container, 0);
5429 if (offset === undef) {
5430 domRange[start ? 'setStartBefore' : 'setEndAfter'](container);
5434 if (endPoint.position < 0) {
5435 sibling = endPoint.inside ? container.firstChild : container.nextSibling;
5438 domRange[start ? 'setStartAfter' : 'setEndAfter'](container);
5443 if (sibling.nodeType == 3)
5444 domRange[start ? 'setStart' : 'setEnd'](sibling, 0);
5446 domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling);
5451 // Find the text node and offset
5453 nodeValue = sibling.nodeValue;
5454 textNodeOffset += nodeValue.length;
5456 // We are at or passed the position we where looking for
5457 if (textNodeOffset >= offset) {
5458 container = sibling;
5459 textNodeOffset -= offset;
5460 textNodeOffset = nodeValue.length - textNodeOffset;
5464 sibling = sibling.nextSibling;
5467 // Find the text node and offset
5468 sibling = container.previousSibling;
5471 return domRange[start ? 'setStartBefore' : 'setEndBefore'](container);
5473 // If there isn't any text to loop then use the first position
5475 if (container.nodeType == 3)
5476 domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length);
5478 domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling);
5484 textNodeOffset += sibling.nodeValue.length;
5486 // We are at or passed the position we where looking for
5487 if (textNodeOffset >= offset) {
5488 container = sibling;
5489 textNodeOffset -= offset;
5493 sibling = sibling.previousSibling;
5497 domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset);
5504 // Find end point if needed
5508 // IE has a nasty bug where text nodes might throw "invalid argument" when you
5509 // access the nodeValue or other properties of text nodes. This seems to happend when
5510 // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it.
5511 if (ex.number == -2147024809) {
5512 // Get the current selection
5513 bookmark = self.getBookmark(2);
5515 // Get start element
5516 tmpRange = ieRange.duplicate();
5517 tmpRange.collapse(true);
5518 element = tmpRange.parentElement();
5522 tmpRange = ieRange.duplicate();
5523 tmpRange.collapse(false);
5524 element2 = tmpRange.parentElement();
5525 element2.innerHTML = element2.innerHTML;
5528 // Remove the broken elements
5529 element.innerHTML = element.innerHTML;
5531 // Restore the selection
5532 self.moveToBookmark(bookmark);
5534 // Since the range has moved we need to re-get it
5535 ieRange = selection.getRng();
5540 // Find end point if needed
5544 throw ex; // Throw other errors
5550 this.getBookmark = function(type) {
5551 var rng = selection.getRng(), start, end, bookmark = {};
5553 function getIndexes(node) {
5554 var node, parent, root, children, i, indexes = [];
5556 parent = node.parentNode;
5557 root = dom.getRoot().parentNode;
5559 while (parent != root) {
5560 children = parent.children;
5562 i = children.length;
5564 if (node === children[i]) {
5571 parent = parent.parentNode;
5577 function getBookmarkEndPoint(start) {
5580 position = getPosition(rng, start);
5583 position : position.position,
5584 offset : position.offset,
5585 indexes : getIndexes(position.node),
5586 inside : position.inside
5591 // Non ubstructive bookmark
5593 // Handle text selection
5595 bookmark.start = getBookmarkEndPoint(true);
5597 if (!selection.isCollapsed())
5598 bookmark.end = getBookmarkEndPoint();
5600 bookmark.start = {ctrl : true, indexes : getIndexes(rng.item(0))};
5606 this.moveToBookmark = function(bookmark) {
5607 var rng, body = dom.doc.body;
5609 function resolveIndexes(indexes) {
5610 var node, i, idx, children;
5612 node = dom.getRoot();
5613 for (i = indexes.length - 1; i >= 0; i--) {
5614 children = node.children;
5617 if (idx <= children.length - 1) {
5618 node = children[idx];
5625 function setBookmarkEndPoint(start) {
5626 var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef;
5629 moveLeft = endPoint.position > 0;
5631 moveRng = body.createTextRange();
5632 moveRng.moveToElementText(resolveIndexes(endPoint.indexes));
5634 offset = endPoint.offset;
5635 if (offset !== undef) {
5636 moveRng.collapse(endPoint.inside || moveLeft);
5637 moveRng.moveStart('character', moveLeft ? -offset : offset);
5639 moveRng.collapse(start);
5641 rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng);
5648 if (bookmark.start) {
5649 if (bookmark.start.ctrl) {
5650 rng = body.createControlRange();
5651 rng.addElement(resolveIndexes(bookmark.start.indexes));
5654 rng = body.createTextRange();
5655 setBookmarkEndPoint(true);
5656 setBookmarkEndPoint();
5662 this.addRange = function(rng) {
5663 var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body;
5665 function setEndPoint(start) {
5666 var container, offset, marker, tmpRng, nodes;
5668 marker = dom.create('a');
5669 container = start ? startContainer : endContainer;
5670 offset = start ? startOffset : endOffset;
5671 tmpRng = ieRng.duplicate();
5673 if (container == doc || container == doc.documentElement) {
5678 if (container.nodeType == 3) {
5679 container.parentNode.insertBefore(marker, container);
5680 tmpRng.moveToElementText(marker);
5681 tmpRng.moveStart('character', offset);
5683 ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
5685 nodes = container.childNodes;
5688 if (offset >= nodes.length) {
5689 dom.insertAfter(marker, nodes[nodes.length - 1]);
5691 container.insertBefore(marker, nodes[offset]);
5694 tmpRng.moveToElementText(marker);
5696 // Empty node selection for example <div>|</div>
5697 marker = doc.createTextNode('\uFEFF');
5698 container.appendChild(marker);
5699 tmpRng.moveToElementText(marker.parentNode);
5700 tmpRng.collapse(TRUE);
5703 ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
5708 // Setup some shorter versions
5709 startContainer = rng.startContainer;
5710 startOffset = rng.startOffset;
5711 endContainer = rng.endContainer;
5712 endOffset = rng.endOffset;
5713 ieRng = body.createTextRange();
5715 // If single element selection then try making a control selection out of it
5716 if (startContainer == endContainer && startContainer.nodeType == 1 && startOffset == endOffset - 1) {
5717 if (startOffset == endOffset - 1) {
5719 ctrlRng = body.createControlRange();
5720 ctrlRng.addElement(startContainer.childNodes[startOffset]);
5729 // Set start/end point of selection
5733 // Select the new range and scroll it into view
5737 // Expose range method
5738 this.getRangeAt = getRange;
5741 // Expose the selection object
5742 tinymce.dom.TridentSelection = Selection;
5747 * Sizzle CSS Selector Engine - v1.0
5748 * Copyright 2009, The Dojo Foundation
5749 * Released under the MIT, BSD, and GPL Licenses.
5750 * More information: http://sizzlejs.com/
5754 var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
5756 toString = Object.prototype.toString,
5757 hasDuplicate = false,
5758 baseHasDuplicate = true;
5760 // Here we check if the JavaScript engine is using some sort of
5761 // optimization where it does not always call our comparision
5762 // function. If that is the case, discard the hasDuplicate value.
5763 // Thus far that includes Google Chrome.
5764 [0, 0].sort(function(){
5765 baseHasDuplicate = false;
5769 var Sizzle = function(selector, context, results, seed) {
5770 results = results || [];
5771 context = context || document;
5773 var origContext = context;
5775 if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
5779 if ( !selector || typeof selector !== "string" ) {
5783 var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
5784 soFar = selector, ret, cur, pop, i;
5786 // Reset the position of the chunker regexp (start from head)
5789 m = chunker.exec(soFar);
5803 if ( parts.length > 1 && origPOS.exec( selector ) ) {
5804 if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
5805 set = posProcess( parts[0] + parts[1], context );
5807 set = Expr.relative[ parts[0] ] ?
5809 Sizzle( parts.shift(), context );
5811 while ( parts.length ) {
5812 selector = parts.shift();
5814 if ( Expr.relative[ selector ] ) {
5815 selector += parts.shift();
5818 set = posProcess( selector, set );
5822 // Take a shortcut and set the context if the root selector is an ID
5823 // (but not if it'll be faster if the inner selector is an ID)
5824 if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
5825 Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
5826 ret = Sizzle.find( parts.shift(), context, contextXML );
5827 context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
5832 { expr: parts.pop(), set: makeArray(seed) } :
5833 Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
5834 set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
5836 if ( parts.length > 0 ) {
5837 checkSet = makeArray(set);
5842 while ( parts.length ) {
5846 if ( !Expr.relative[ cur ] ) {
5852 if ( pop == null ) {
5856 Expr.relative[ cur ]( checkSet, pop, contextXML );
5859 checkSet = parts = [];
5868 Sizzle.error( cur || selector );
5871 if ( toString.call(checkSet) === "[object Array]" ) {
5873 results.push.apply( results, checkSet );
5874 } else if ( context && context.nodeType === 1 ) {
5875 for ( i = 0; checkSet[i] != null; i++ ) {
5876 if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
5877 results.push( set[i] );
5881 for ( i = 0; checkSet[i] != null; i++ ) {
5882 if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
5883 results.push( set[i] );
5888 makeArray( checkSet, results );
5892 Sizzle( extra, origContext, results, seed );
5893 Sizzle.uniqueSort( results );
5899 Sizzle.uniqueSort = function(results){
5901 hasDuplicate = baseHasDuplicate;
5902 results.sort(sortOrder);
5904 if ( hasDuplicate ) {
5905 for ( var i = 1; i < results.length; i++ ) {
5906 if ( results[i] === results[i-1] ) {
5907 results.splice(i--, 1);
5916 Sizzle.matches = function(expr, set){
5917 return Sizzle(expr, null, null, set);
5920 Sizzle.find = function(expr, context, isXML){
5927 for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
5928 var type = Expr.order[i], match;
5930 if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
5931 var left = match[1];
5934 if ( left.substr( left.length - 1 ) !== "\\" ) {
5935 match[1] = (match[1] || "").replace(/\\/g, "");
5936 set = Expr.find[ type ]( match, context, isXML );
5937 if ( set != null ) {
5938 expr = expr.replace( Expr.match[ type ], "" );
5946 set = context.getElementsByTagName("*");
5949 return {set: set, expr: expr};
5952 Sizzle.filter = function(expr, set, inplace, not){
5953 var old = expr, result = [], curLoop = set, match, anyFound,
5954 isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
5956 while ( expr && set.length ) {
5957 for ( var type in Expr.filter ) {
5958 if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
5959 var filter = Expr.filter[ type ], found, item, left = match[1];
5964 if ( left.substr( left.length - 1 ) === "\\" ) {
5968 if ( curLoop === result ) {
5972 if ( Expr.preFilter[ type ] ) {
5973 match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
5976 anyFound = found = true;
5977 } else if ( match === true ) {
5983 for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
5985 found = filter( item, match, i, curLoop );
5986 var pass = not ^ !!found;
5988 if ( inplace && found != null ) {
5994 } else if ( pass ) {
5995 result.push( item );
6002 if ( found !== undefined ) {
6007 expr = expr.replace( Expr.match[ type ], "" );
6018 // Improper expression
6019 if ( expr === old ) {
6020 if ( anyFound == null ) {
6021 Sizzle.error( expr );
6033 Sizzle.error = function( msg ) {
6034 throw "Syntax error, unrecognized expression: " + msg;
6037 var Expr = Sizzle.selectors = {
6038 order: [ "ID", "NAME", "TAG" ],
6040 ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
6041 CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
6042 NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
6043 ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
6044 TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
6045 CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
6046 POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
6047 PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
6051 "class": "className",
6055 href: function(elem){
6056 return elem.getAttribute("href");
6060 "+": function(checkSet, part){
6061 var isPartStr = typeof part === "string",
6062 isTag = isPartStr && !/\W/.test(part),
6063 isPartStrNotTag = isPartStr && !isTag;
6066 part = part.toLowerCase();
6069 for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
6070 if ( (elem = checkSet[i]) ) {
6071 while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
6073 checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
6079 if ( isPartStrNotTag ) {
6080 Sizzle.filter( part, checkSet, true );
6083 ">": function(checkSet, part){
6084 var isPartStr = typeof part === "string",
6085 elem, i = 0, l = checkSet.length;
6087 if ( isPartStr && !/\W/.test(part) ) {
6088 part = part.toLowerCase();
6090 for ( ; i < l; i++ ) {
6093 var parent = elem.parentNode;
6094 checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
6098 for ( ; i < l; i++ ) {
6101 checkSet[i] = isPartStr ?
6103 elem.parentNode === part;
6108 Sizzle.filter( part, checkSet, true );
6112 "": function(checkSet, part, isXML){
6113 var doneName = done++, checkFn = dirCheck, nodeCheck;
6115 if ( typeof part === "string" && !/\W/.test(part) ) {
6116 part = part.toLowerCase();
6118 checkFn = dirNodeCheck;
6121 checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
6123 "~": function(checkSet, part, isXML){
6124 var doneName = done++, checkFn = dirCheck, nodeCheck;
6126 if ( typeof part === "string" && !/\W/.test(part) ) {
6127 part = part.toLowerCase();
6129 checkFn = dirNodeCheck;
6132 checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
6136 ID: function(match, context, isXML){
6137 if ( typeof context.getElementById !== "undefined" && !isXML ) {
6138 var m = context.getElementById(match[1]);
6139 return m ? [m] : [];
6142 NAME: function(match, context){
6143 if ( typeof context.getElementsByName !== "undefined" ) {
6144 var ret = [], results = context.getElementsByName(match[1]);
6146 for ( var i = 0, l = results.length; i < l; i++ ) {
6147 if ( results[i].getAttribute("name") === match[1] ) {
6148 ret.push( results[i] );
6152 return ret.length === 0 ? null : ret;
6155 TAG: function(match, context){
6156 return context.getElementsByTagName(match[1]);
6160 CLASS: function(match, curLoop, inplace, result, not, isXML){
6161 match = " " + match[1].replace(/\\/g, "") + " ";
6167 for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
6169 if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
6171 result.push( elem );
6173 } else if ( inplace ) {
6181 ID: function(match){
6182 return match[1].replace(/\\/g, "");
6184 TAG: function(match, curLoop){
6185 return match[1].toLowerCase();
6187 CHILD: function(match){
6188 if ( match[1] === "nth" ) {
6189 // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
6190 var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
6191 match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
6192 !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
6194 // calculate the numbers (first)n+(last) including if they are negative
6195 match[2] = (test[1] + (test[2] || 1)) - 0;
6196 match[3] = test[3] - 0;
6199 // TODO: Move to normal caching system
6204 ATTR: function(match, curLoop, inplace, result, not, isXML){
6205 var name = match[1].replace(/\\/g, "");
6207 if ( !isXML && Expr.attrMap[name] ) {
6208 match[1] = Expr.attrMap[name];
6211 if ( match[2] === "~=" ) {
6212 match[4] = " " + match[4] + " ";
6217 PSEUDO: function(match, curLoop, inplace, result, not){
6218 if ( match[1] === "not" ) {
6219 // If we're dealing with a complex expression, or a simple one
6220 if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
6221 match[3] = Sizzle(match[3], null, null, curLoop);
6223 var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
6225 result.push.apply( result, ret );
6229 } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
6235 POS: function(match){
6236 match.unshift( true );
6241 enabled: function(elem){
6242 return elem.disabled === false && elem.type !== "hidden";
6244 disabled: function(elem){
6245 return elem.disabled === true;
6247 checked: function(elem){
6248 return elem.checked === true;
6250 selected: function(elem){
6251 // Accessing this property makes selected-by-default
6252 // options in Safari work properly
6253 elem.parentNode.selectedIndex;
6254 return elem.selected === true;
6256 parent: function(elem){
6257 return !!elem.firstChild;
6259 empty: function(elem){
6260 return !elem.firstChild;
6262 has: function(elem, i, match){
6263 return !!Sizzle( match[3], elem ).length;
6265 header: function(elem){
6266 return (/h\d/i).test( elem.nodeName );
6268 text: function(elem){
6269 return "text" === elem.type;
6271 radio: function(elem){
6272 return "radio" === elem.type;
6274 checkbox: function(elem){
6275 return "checkbox" === elem.type;
6277 file: function(elem){
6278 return "file" === elem.type;
6280 password: function(elem){
6281 return "password" === elem.type;
6283 submit: function(elem){
6284 return "submit" === elem.type;
6286 image: function(elem){
6287 return "image" === elem.type;
6289 reset: function(elem){
6290 return "reset" === elem.type;
6292 button: function(elem){
6293 return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
6295 input: function(elem){
6296 return (/input|select|textarea|button/i).test(elem.nodeName);
6300 first: function(elem, i){
6303 last: function(elem, i, match, array){
6304 return i === array.length - 1;
6306 even: function(elem, i){
6309 odd: function(elem, i){
6312 lt: function(elem, i, match){
6313 return i < match[3] - 0;
6315 gt: function(elem, i, match){
6316 return i > match[3] - 0;
6318 nth: function(elem, i, match){
6319 return match[3] - 0 === i;
6321 eq: function(elem, i, match){
6322 return match[3] - 0 === i;
6326 PSEUDO: function(elem, match, i, array){
6327 var name = match[1], filter = Expr.filters[ name ];
6330 return filter( elem, i, match, array );
6331 } else if ( name === "contains" ) {
6332 return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
6333 } else if ( name === "not" ) {
6336 for ( var j = 0, l = not.length; j < l; j++ ) {
6337 if ( not[j] === elem ) {
6344 Sizzle.error( "Syntax error, unrecognized expression: " + name );
6347 CHILD: function(elem, match){
6348 var type = match[1], node = elem;
6352 while ( (node = node.previousSibling) ) {
6353 if ( node.nodeType === 1 ) {
6357 if ( type === "first" ) {
6362 while ( (node = node.nextSibling) ) {
6363 if ( node.nodeType === 1 ) {
6369 var first = match[2], last = match[3];
6371 if ( first === 1 && last === 0 ) {
6375 var doneName = match[0],
6376 parent = elem.parentNode;
6378 if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
6380 for ( node = parent.firstChild; node; node = node.nextSibling ) {
6381 if ( node.nodeType === 1 ) {
6382 node.nodeIndex = ++count;
6385 parent.sizcache = doneName;
6388 var diff = elem.nodeIndex - last;
6389 if ( first === 0 ) {
6392 return ( diff % first === 0 && diff / first >= 0 );
6396 ID: function(elem, match){
6397 return elem.nodeType === 1 && elem.getAttribute("id") === match;
6399 TAG: function(elem, match){
6400 return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
6402 CLASS: function(elem, match){
6403 return (" " + (elem.className || elem.getAttribute("class")) + " ")
6404 .indexOf( match ) > -1;
6406 ATTR: function(elem, match){
6407 var name = match[1],
6408 result = Expr.attrHandle[ name ] ?
6409 Expr.attrHandle[ name ]( elem ) :
6410 elem[ name ] != null ?
6412 elem.getAttribute( name ),
6413 value = result + "",
6417 return result == null ?
6422 value.indexOf(check) >= 0 :
6424 (" " + value + " ").indexOf(check) >= 0 :
6426 value && result !== false :
6430 value.indexOf(check) === 0 :
6432 value.substr(value.length - check.length) === check :
6434 value === check || value.substr(0, check.length + 1) === check + "-" :
6437 POS: function(elem, match, i, array){
6438 var name = match[2], filter = Expr.setFilters[ name ];
6441 return filter( elem, i, match, array );
6447 var origPOS = Expr.match.POS,
6448 fescape = function(all, num){
6449 return "\\" + (num - 0 + 1);
6452 for ( var type in Expr.match ) {
6453 Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
6454 Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
6457 var makeArray = function(array, results) {
6458 array = Array.prototype.slice.call( array, 0 );
6461 results.push.apply( results, array );
6468 // Perform a simple check to determine if the browser is capable of
6469 // converting a NodeList to an array using builtin methods.
6470 // Also verifies that the returned array holds DOM nodes
6471 // (which is not the case in the Blackberry browser)
6473 Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
6475 // Provide a fallback method if it does not work
6477 makeArray = function(array, results) {
6478 var ret = results || [], i = 0;
6480 if ( toString.call(array) === "[object Array]" ) {
6481 Array.prototype.push.apply( ret, array );
6483 if ( typeof array.length === "number" ) {
6484 for ( var l = array.length; i < l; i++ ) {
6485 ret.push( array[i] );
6488 for ( ; array[i]; i++ ) {
6489 ret.push( array[i] );
6500 if ( document.documentElement.compareDocumentPosition ) {
6501 sortOrder = function( a, b ) {
6502 if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
6504 hasDuplicate = true;
6506 return a.compareDocumentPosition ? -1 : 1;
6509 var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
6511 hasDuplicate = true;
6515 } else if ( "sourceIndex" in document.documentElement ) {
6516 sortOrder = function( a, b ) {
6517 if ( !a.sourceIndex || !b.sourceIndex ) {
6519 hasDuplicate = true;
6521 return a.sourceIndex ? -1 : 1;
6524 var ret = a.sourceIndex - b.sourceIndex;
6526 hasDuplicate = true;
6530 } else if ( document.createRange ) {
6531 sortOrder = function( a, b ) {
6532 if ( !a.ownerDocument || !b.ownerDocument ) {
6534 hasDuplicate = true;
6536 return a.ownerDocument ? -1 : 1;
6539 var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
6540 aRange.setStart(a, 0);
6541 aRange.setEnd(a, 0);
6542 bRange.setStart(b, 0);
6543 bRange.setEnd(b, 0);
6544 var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
6546 hasDuplicate = true;
6552 // Utility function for retreiving the text value of an array of DOM nodes
6553 Sizzle.getText = function( elems ) {
6556 for ( var i = 0; elems[i]; i++ ) {
6559 // Get the text from text nodes and CDATA nodes
6560 if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
6561 ret += elem.nodeValue;
6563 // Traverse everything else, except comment nodes
6564 } else if ( elem.nodeType !== 8 ) {
6565 ret += Sizzle.getText( elem.childNodes );
6572 // Check to see if the browser returns elements by name when
6573 // querying by getElementById (and provide a workaround)
6575 // We're going to inject a fake input element with a specified name
6576 var form = document.createElement("div"),
6577 id = "script" + (new Date()).getTime();
6578 form.innerHTML = "<a name='" + id + "'/>";
6580 // Inject it into the root element, check its status, and remove it quickly
6581 var root = document.documentElement;
6582 root.insertBefore( form, root.firstChild );
6584 // The workaround has to do additional checks after a getElementById
6585 // Which slows things down for other browsers (hence the branching)
6586 if ( document.getElementById( id ) ) {
6587 Expr.find.ID = function(match, context, isXML){
6588 if ( typeof context.getElementById !== "undefined" && !isXML ) {
6589 var m = context.getElementById(match[1]);
6590 return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
6594 Expr.filter.ID = function(elem, match){
6595 var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
6596 return elem.nodeType === 1 && node && node.nodeValue === match;
6600 root.removeChild( form );
6601 root = form = null; // release memory in IE
6605 // Check to see if the browser returns only elements
6606 // when doing getElementsByTagName("*")
6608 // Create a fake element
6609 var div = document.createElement("div");
6610 div.appendChild( document.createComment("") );
6612 // Make sure no comments are found
6613 if ( div.getElementsByTagName("*").length > 0 ) {
6614 Expr.find.TAG = function(match, context){
6615 var results = context.getElementsByTagName(match[1]);
6617 // Filter out possible comments
6618 if ( match[1] === "*" ) {
6621 for ( var i = 0; results[i]; i++ ) {
6622 if ( results[i].nodeType === 1 ) {
6623 tmp.push( results[i] );
6634 // Check to see if an attribute returns normalized href attributes
6635 div.innerHTML = "<a href='#'></a>";
6636 if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
6637 div.firstChild.getAttribute("href") !== "#" ) {
6638 Expr.attrHandle.href = function(elem){
6639 return elem.getAttribute("href", 2);
6643 div = null; // release memory in IE
6646 if ( document.querySelectorAll ) {
6648 var oldSizzle = Sizzle, div = document.createElement("div");
6649 div.innerHTML = "<p class='TEST'></p>";
6651 // Safari can't handle uppercase or unicode characters when
6653 if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
6657 Sizzle = function(query, context, extra, seed){
6658 context = context || document;
6660 // Only use querySelectorAll on non-XML documents
6661 // (ID selectors don't work in non-HTML documents)
6662 if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
6664 return makeArray( context.querySelectorAll(query), extra );
6668 return oldSizzle(query, context, extra, seed);
6671 for ( var prop in oldSizzle ) {
6672 Sizzle[ prop ] = oldSizzle[ prop ];
6675 div = null; // release memory in IE
6680 var div = document.createElement("div");
6682 div.innerHTML = "<div class='test e'></div><div class='test'></div>";
6684 // Opera can't find a second classname (in 9.6)
6685 // Also, make sure that getElementsByClassName actually exists
6686 if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
6690 // Safari caches class attributes, doesn't catch changes (in 3.2)
6691 div.lastChild.className = "e";
6693 if ( div.getElementsByClassName("e").length === 1 ) {
6697 Expr.order.splice(1, 0, "CLASS");
6698 Expr.find.CLASS = function(match, context, isXML) {
6699 if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
6700 return context.getElementsByClassName(match[1]);
6704 div = null; // release memory in IE
6707 function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
6708 for ( var i = 0, l = checkSet.length; i < l; i++ ) {
6709 var elem = checkSet[i];
6715 if ( elem.sizcache === doneName ) {
6716 match = checkSet[elem.sizset];
6720 if ( elem.nodeType === 1 && !isXML ){
6721 elem.sizcache = doneName;
6725 if ( elem.nodeName.toLowerCase() === cur ) {
6733 checkSet[i] = match;
6738 function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
6739 for ( var i = 0, l = checkSet.length; i < l; i++ ) {
6740 var elem = checkSet[i];
6746 if ( elem.sizcache === doneName ) {
6747 match = checkSet[elem.sizset];
6751 if ( elem.nodeType === 1 ) {
6753 elem.sizcache = doneName;
6756 if ( typeof cur !== "string" ) {
6757 if ( elem === cur ) {
6762 } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
6771 checkSet[i] = match;
6776 Sizzle.contains = document.compareDocumentPosition ? function(a, b){
6777 return !!(a.compareDocumentPosition(b) & 16);
6779 return a !== b && (a.contains ? a.contains(b) : true);
6782 Sizzle.isXML = function(elem){
6783 // documentElement is verified for cases where it doesn't yet exist
6784 // (such as loading iframes in IE - #4833)
6785 var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
6786 return documentElement ? documentElement.nodeName !== "HTML" : false;
6789 var posProcess = function(selector, context){
6790 var tmpSet = [], later = "", match,
6791 root = context.nodeType ? [context] : context;
6793 // Position selectors must be done after the filter
6794 // And so must :not(positional) so we move all PSEUDOs to the end
6795 while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
6797 selector = selector.replace( Expr.match.PSEUDO, "" );
6800 selector = Expr.relative[selector] ? selector + "*" : selector;
6802 for ( var i = 0, l = root.length; i < l; i++ ) {
6803 Sizzle( selector, root[i], tmpSet );
6806 return Sizzle.filter( later, tmpSet );
6811 window.tinymce.dom.Sizzle = Sizzle;
6816 (function(tinymce) {
6818 var each = tinymce.each, DOM = tinymce.DOM, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, Event;
6820 tinymce.create('tinymce.dom.EventUtils', {
6821 EventUtils : function() {
6826 add : function(o, n, f, s) {
6827 var cb, t = this, el = t.events, r;
6829 if (n instanceof Array) {
6832 each(n, function(n) {
6833 r.push(t.add(o, n, f, s));
6840 if (o && o.hasOwnProperty && o instanceof Array) {
6843 each(o, function(o) {
6845 r.push(t.add(o, n, f, s));
6856 // Setup event callback
6858 // Is all events disabled
6862 e = e || window.event;
6864 // Patch in target, preventDefault and stopPropagation in IE it's W3C valid
6867 e.target = e.srcElement;
6869 // Patch in preventDefault, stopPropagation methods for W3C compatibility
6870 tinymce.extend(e, t._stoppers);
6876 return f.call(s, e);
6879 if (n == 'unload') {
6880 tinymce.unloads.unshift({func : cb});
6893 // Store away listener reference
6907 remove : function(o, n, f) {
6908 var t = this, a = t.events, s = false, r;
6911 if (o && o.hasOwnProperty && o instanceof Array) {
6914 each(o, function(o) {
6916 r.push(t.remove(o, n, f));
6924 each(a, function(e, i) {
6925 if (e.obj == o && e.name == n && (!f || (e.func == f || e.cfunc == f))) {
6927 t._remove(o, n, e.cfunc);
6936 clear : function(o) {
6937 var t = this, a = t.events, i, e;
6942 for (i = a.length - 1; i >= 0; i--) {
6946 t._remove(e.obj, e.name, e.cfunc);
6947 e.obj = e.cfunc = null;
6954 cancel : function(e) {
6960 return this.prevent(e);
6963 stop : function(e) {
6964 if (e.stopPropagation)
6965 e.stopPropagation();
6967 e.cancelBubble = true;
6972 prevent : function(e) {
6973 if (e.preventDefault)
6976 e.returnValue = false;
6981 destroy : function() {
6984 each(t.events, function(e, i) {
6985 t._remove(e.obj, e.name, e.cfunc);
6986 e.obj = e.cfunc = null;
6993 _add : function(o, n, f) {
6995 o.attachEvent('on' + n, f);
6996 else if (o.addEventListener)
6997 o.addEventListener(n, f, false);
7002 _remove : function(o, n, f) {
7006 o.detachEvent('on' + n, f);
7007 else if (o.removeEventListener)
7008 o.removeEventListener(n, f, false);
7012 // Might fail with permission denined on IE so we just ignore that
7017 _pageInit : function(win) {
7020 // Keep it from running more than once
7026 each(t.inits, function(c) {
7033 _wait : function(win) {
7034 var t = this, doc = win.document;
7036 // No need since the document is already loaded
7037 if (win.tinyMCE_GZ && tinyMCE_GZ.loaded) {
7043 if (doc.attachEvent) {
7044 doc.attachEvent("onreadystatechange", function() {
7045 if (doc.readyState === "complete") {
7046 doc.detachEvent("onreadystatechange", arguments.callee);
7051 if (doc.documentElement.doScroll && win == win.top) {
7057 // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author.
7058 // http://javascript.nwbox.com/IEContentLoaded/
7059 doc.documentElement.doScroll("left");
7061 setTimeout(arguments.callee, 0);
7068 } else if (doc.addEventListener) {
7069 t._add(win, 'DOMContentLoaded', function() {
7074 t._add(win, 'load', function() {
7080 preventDefault : function() {
7081 this.returnValue = false;
7084 stopPropagation : function() {
7085 this.cancelBubble = true;
7090 Event = tinymce.dom.Event = new tinymce.dom.EventUtils();
7092 // Dispatch DOM content loaded event for IE and Safari
7093 Event._wait(window);
7095 tinymce.addUnload(function() {
7100 (function(tinymce) {
7101 tinymce.dom.Element = function(id, settings) {
7102 var t = this, dom, el;
7104 t.settings = settings = settings || {};
7106 t.dom = dom = settings.dom || tinymce.DOM;
7108 // Only IE leaks DOM references, this is a lot faster
7113 ('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' +
7114 'setAttrib,setAttribs,getAttrib,addClass,removeClass,' +
7115 'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' +
7116 'isHidden,setHTML,get').split(/,/)
7121 for (i = 0; i < arguments.length; i++)
7122 a.push(arguments[i]);
7124 a = dom[k].apply(dom, a);
7132 on : function(n, f, s) {
7133 return tinymce.dom.Event.add(t.id, n, f, s);
7136 getXY : function() {
7138 x : parseInt(t.getStyle('left')),
7139 y : parseInt(t.getStyle('top'))
7143 getSize : function() {
7144 var n = dom.get(t.id);
7147 w : parseInt(t.getStyle('width') || n.clientWidth),
7148 h : parseInt(t.getStyle('height') || n.clientHeight)
7152 moveTo : function(x, y) {
7153 t.setStyles({left : x, top : y});
7156 moveBy : function(x, y) {
7159 t.moveTo(p.x + x, p.y + y);
7162 resizeTo : function(w, h) {
7163 t.setStyles({width : w, height : h});
7166 resizeBy : function(w, h) {
7167 var s = t.getSize();
7169 t.resizeTo(s.w + w, s.h + h);
7172 update : function(k) {
7175 if (tinymce.isIE6 && settings.blocker) {
7179 if (k.indexOf('get') === 0 || k.indexOf('has') === 0 || k.indexOf('is') === 0)
7182 // Remove blocker on remove
7183 if (k == 'remove') {
7184 dom.remove(t.blocker);
7189 t.blocker = dom.uniqueId();
7190 b = dom.add(settings.container || dom.getRoot(), 'iframe', {id : t.blocker, style : 'position:absolute;', frameBorder : 0, src : 'javascript:""'});
7191 dom.setStyle(b, 'opacity', 0);
7193 b = dom.get(t.blocker);
7196 left : t.getStyle('left', 1),
7197 top : t.getStyle('top', 1),
7198 width : t.getStyle('width', 1),
7199 height : t.getStyle('height', 1),
7200 display : t.getStyle('display', 1),
7201 zIndex : parseInt(t.getStyle('zIndex', 1) || 0) - 1
7209 (function(tinymce) {
7210 function trimNl(s) {
7211 return s.replace(/[\n\r]+/g, '');
7215 var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each;
7217 tinymce.create('tinymce.dom.Selection', {
7218 Selection : function(dom, win, serializer) {
7223 t.serializer = serializer;
7227 'onBeforeSetContent',
7229 'onBeforeGetContent',
7235 t[e] = new tinymce.util.Dispatcher(t);
7238 // No W3C Range support
7239 if (!t.win.getSelection)
7240 t.tridentSel = new tinymce.dom.TridentSelection(t);
7242 if (tinymce.isIE && dom.boxModel)
7243 this._fixIESelection();
7246 tinymce.addUnload(t.destroy, t);
7249 setCursorLocation: function(node, offset) {
7250 var t = this; var r = t.dom.createRng();
7251 r.setStart(node, offset);
7252 r.setEnd(node, offset);
7256 getContent : function(s) {
7257 var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n;
7262 s.format = s.format || 'html';
7263 s.forced_root_block = '';
7264 t.onBeforeGetContent.dispatch(t, s);
7266 if (s.format == 'text')
7267 return t.isCollapsed() ? '' : (r.text || (se.toString ? se.toString() : ''));
7269 if (r.cloneContents) {
7270 n = r.cloneContents();
7274 } else if (is(r.item) || is(r.htmlText))
7275 e.innerHTML = r.item ? r.item(0).outerHTML : r.htmlText;
7277 e.innerHTML = r.toString();
7279 // Keep whitespace before and after
7280 if (/^\s/.test(e.innerHTML))
7283 if (/\s+$/.test(e.innerHTML))
7288 s.content = t.isCollapsed() ? '' : wb + t.serializer.serialize(e, s) + wa;
7289 t.onGetContent.dispatch(t, s);
7294 setContent : function(content, args) {
7295 var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp;
7297 args = args || {format : 'html'};
7299 content = args.content = content;
7301 // Dispatch before set content event
7302 if (!args.no_events)
7303 self.onBeforeSetContent.dispatch(self, args);
7305 content = args.content;
7307 if (rng.insertNode) {
7308 // Make caret marker since insertNode places the caret in the beginning of text after insert
7309 content += '<span id="__caret">_</span>';
7311 // Delete and insert new node
7312 if (rng.startContainer == doc && rng.endContainer == doc) {
7313 // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents
7314 doc.body.innerHTML = content;
7316 rng.deleteContents();
7318 if (doc.body.childNodes.length == 0) {
7319 doc.body.innerHTML = content;
7321 // createContextualFragment doesn't exists in IE 9 DOMRanges
7322 if (rng.createContextualFragment) {
7323 rng.insertNode(rng.createContextualFragment(content));
7325 // Fake createContextualFragment call in IE 9
7326 frag = doc.createDocumentFragment();
7327 temp = doc.createElement('div');
7329 frag.appendChild(temp);
7330 temp.outerHTML = content;
7332 rng.insertNode(frag);
7337 // Move to caret marker
7338 caretNode = self.dom.get('__caret');
7340 // Make sure we wrap it compleatly, Opera fails with a simple select call
7341 rng = doc.createRange();
7342 rng.setStartBefore(caretNode);
7343 rng.setEndBefore(caretNode);
7346 // Remove the caret position
7347 self.dom.remove('__caret');
7352 // Might fail on Opera for some odd reason
7356 // Delete content and get caret text selection
7357 doc.execCommand('Delete', false, null);
7358 rng = self.getRng();
7361 rng.pasteHTML(content);
7364 // Dispatch set content event
7365 if (!args.no_events)
7366 self.onSetContent.dispatch(self, args);
7369 getStart : function() {
7370 var rng = this.getRng(), startElement, parentElement, checkRng, node;
7372 if (rng.duplicate || rng.item) {
7373 // Control selection, return first item
7377 // Get start element
7378 checkRng = rng.duplicate();
7379 checkRng.collapse(1);
7380 startElement = checkRng.parentElement();
7382 // Check if range parent is inside the start element, then return the inner parent element
7383 // This will fix issues when a single element is selected, IE would otherwise return the wrong start element
7384 parentElement = node = rng.parentElement();
7385 while (node = node.parentNode) {
7386 if (node == startElement) {
7387 startElement = parentElement;
7392 return startElement;
7394 startElement = rng.startContainer;
7396 if (startElement.nodeType == 1 && startElement.hasChildNodes())
7397 startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)];
7399 if (startElement && startElement.nodeType == 3)
7400 return startElement.parentNode;
7402 return startElement;
7406 getEnd : function() {
7407 var t = this, r = t.getRng(), e, eo;
7409 if (r.duplicate || r.item) {
7415 e = r.parentElement();
7417 if (e && e.nodeName == 'BODY')
7418 return e.lastChild || e;
7425 if (e.nodeType == 1 && e.hasChildNodes())
7426 e = e.childNodes[eo > 0 ? eo - 1 : eo];
7428 if (e && e.nodeType == 3)
7429 return e.parentNode;
7435 getBookmark : function(type, normalized) {
7436 var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, index, chr = '\uFEFF', styles;
7438 function findIndex(name, element) {
7441 each(dom.select(name), function(node, i) {
7442 if (node == element)
7450 function getLocation() {
7451 var rng = t.getRng(true), root = dom.getRoot(), bookmark = {};
7453 function getPoint(rng, start) {
7454 var container = rng[start ? 'startContainer' : 'endContainer'],
7455 offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
7457 if (container.nodeType == 3) {
7459 for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling)
7460 offset += node.nodeValue.length;
7465 childNodes = container.childNodes;
7467 if (offset >= childNodes.length && childNodes.length) {
7469 offset = Math.max(0, childNodes.length - 1);
7472 point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after);
7475 for (; container && container != root; container = container.parentNode)
7476 point.push(t.dom.nodeIndex(container, normalized));
7481 bookmark.start = getPoint(rng, true);
7483 if (!t.isCollapsed())
7484 bookmark.end = getPoint(rng);
7490 return t.tridentSel.getBookmark(type);
7492 return getLocation();
7495 // Handle simple range
7497 return {rng : t.getRng()};
7500 id = dom.uniqueId();
7501 collapsed = tinyMCE.activeEditor.selection.isCollapsed();
7502 styles = 'overflow:hidden;line-height:0px';
7505 if (rng.duplicate || rng.item) {
7508 rng2 = rng.duplicate();
7511 // Insert start marker
7513 rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>');
7515 // Insert end marker
7517 rng2.collapse(false);
7519 // Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p>
7520 rng.moveToElementText(rng2.parentElement());
7521 if (rng.compareEndPoints('StartToEnd', rng2) == 0)
7522 rng2.move('character', -1);
7524 rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');
7527 // IE might throw unspecified error so lets ignore it
7531 // Control selection
7532 element = rng.item(0);
7533 name = element.nodeName;
7535 return {name : name, index : findIndex(name, element)};
7538 element = t.getNode();
7539 name = element.nodeName;
7541 return {name : name, index : findIndex(name, element)};
7544 rng2 = rng.cloneRange();
7546 // Insert end marker
7548 rng2.collapse(false);
7549 rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr));
7553 rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr));
7556 t.moveToBookmark({id : id, keep : 1});
7561 moveToBookmark : function(bookmark) {
7562 var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset;
7565 if (bookmark.start) {
7566 rng = dom.createRng();
7567 root = dom.getRoot();
7569 function setEndPoint(start) {
7570 var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;
7575 // Find container node
7576 for (node = root, i = point.length - 1; i >= 1; i--) {
7577 children = node.childNodes;
7579 if (point[i] > children.length - 1)
7582 node = children[point[i]];
7585 // Move text offset to best suitable location
7586 if (node.nodeType === 3)
7587 offset = Math.min(point[0], node.nodeValue.length);
7589 // Move element offset to best suitable location
7590 if (node.nodeType === 1)
7591 offset = Math.min(point[0], node.childNodes.length);
7593 // Set offset within container node
7595 rng.setStart(node, offset);
7597 rng.setEnd(node, offset);
7604 return t.tridentSel.moveToBookmark(bookmark);
7606 if (setEndPoint(true) && setEndPoint()) {
7609 } else if (bookmark.id) {
7610 function restoreEndPoint(suffix) {
7611 var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;
7614 node = marker.parentNode;
7616 if (suffix == 'start') {
7618 idx = dom.nodeIndex(marker);
7620 node = marker.firstChild;
7624 startContainer = endContainer = node;
7625 startOffset = endOffset = idx;
7628 idx = dom.nodeIndex(marker);
7630 node = marker.firstChild;
7634 endContainer = node;
7639 prev = marker.previousSibling;
7640 next = marker.nextSibling;
7642 // Remove all marker text nodes
7643 each(tinymce.grep(marker.childNodes), function(node) {
7644 if (node.nodeType == 3)
7645 node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
7648 // Remove marker but keep children if for example contents where inserted into the marker
7649 // Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature
7650 while (marker = dom.get(bookmark.id + '_' + suffix))
7651 dom.remove(marker, 1);
7653 // If siblings are text nodes then merge them unless it's Opera since it some how removes the node
7654 // 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
7655 if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) {
7656 idx = prev.nodeValue.length;
7657 prev.appendData(next.nodeValue);
7660 if (suffix == 'start') {
7661 startContainer = endContainer = prev;
7662 startOffset = endOffset = idx;
7664 endContainer = prev;
7672 function addBogus(node) {
7673 // Adds a bogus BR element for empty block elements or just a space on IE since it renders BR elements incorrectly
7674 if (dom.isBlock(node) && !node.innerHTML)
7675 node.innerHTML = !isIE ? '<br data-mce-bogus="1" />' : ' ';
7680 // Restore start/end points
7681 restoreEndPoint('start');
7682 restoreEndPoint('end');
7684 if (startContainer) {
7685 rng = dom.createRng();
7686 rng.setStart(addBogus(startContainer), startOffset);
7687 rng.setEnd(addBogus(endContainer), endOffset);
7690 } else if (bookmark.name) {
7691 t.select(dom.select(bookmark.name)[bookmark.index]);
7692 } else if (bookmark.rng)
7693 t.setRng(bookmark.rng);
7697 select : function(node, content) {
7698 var t = this, dom = t.dom, rng = dom.createRng(), idx;
7701 idx = dom.nodeIndex(node);
7702 rng.setStart(node.parentNode, idx);
7703 rng.setEnd(node.parentNode, idx + 1);
7705 // Find first/last text node or BR element
7707 function setPoint(node, start) {
7708 var walker = new tinymce.dom.TreeWalker(node, node);
7712 if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) {
7714 rng.setStart(node, 0);
7716 rng.setEnd(node, node.nodeValue.length);
7722 if (node.nodeName == 'BR') {
7724 rng.setStartBefore(node);
7726 rng.setEndBefore(node);
7730 } while (node = (start ? walker.next() : walker.prev()));
7743 isCollapsed : function() {
7744 var t = this, r = t.getRng(), s = t.getSel();
7749 if (r.compareEndPoints)
7750 return r.compareEndPoints('StartToEnd', r) === 0;
7752 return !s || r.collapsed;
7755 collapse : function(to_start) {
7756 var self = this, rng = self.getRng(), node;
7758 // Control range on IE
7761 rng = self.win.document.body.createTextRange();
7762 rng.moveToElementText(node);
7765 rng.collapse(!!to_start);
7769 getSel : function() {
7770 var t = this, w = this.win;
7772 return w.getSelection ? w.getSelection() : w.document.selection;
7775 getRng : function(w3c) {
7776 var t = this, s, r, elm, doc = t.win.document;
7778 // Found tridentSel object then we need to use that one
7779 if (w3c && t.tridentSel)
7780 return t.tridentSel.getRangeAt(0);
7784 r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange());
7786 // IE throws unspecified error here if TinyMCE is placed in a frame/iframe
7789 // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet
7790 if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) {
7791 elm = doc.selection.createRange().item(0);
7792 r = doc.createRange();
7793 r.setStartBefore(elm);
7797 // No range found then create an empty one
7798 // This can occur when the editor is placed in a hidden container element on Gecko
7799 // Or on IE when there was an exception
7801 r = doc.createRange ? doc.createRange() : doc.body.createTextRange();
7803 if (t.selectedRange && t.explicitRange) {
7804 if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) {
7805 // Safari, Opera and Chrome only ever select text which causes the range to change.
7806 // This lets us use the originally set range if the selection hasn't been changed by the user.
7807 r = t.explicitRange;
7809 t.selectedRange = null;
7810 t.explicitRange = null;
7817 setRng : function(r) {
7820 if (!t.tridentSel) {
7824 t.explicitRange = r;
7827 s.removeAllRanges();
7829 // IE9 might throw errors here don't know why
7833 t.selectedRange = s.getRangeAt(0);
7838 t.tridentSel.addRange(r);
7842 // Is IE specific range
7846 // Needed for some odd IE bug #1843306
7851 setNode : function(n) {
7854 t.setContent(t.dom.getOuterHTML(n));
7859 getNode : function() {
7860 var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer;
7862 // Range maybe lost after the editor is made visible again
7864 return t.dom.getRoot();
7867 elm = rng.commonAncestorContainer;
7869 // Handle selection a image or other control like element such as anchors
7870 if (!rng.collapsed) {
7871 if (rng.startContainer == rng.endContainer) {
7872 if (rng.endOffset - rng.startOffset < 2) {
7873 if (rng.startContainer.hasChildNodes())
7874 elm = rng.startContainer.childNodes[rng.startOffset];
7878 // If the anchor node is a element instead of a text node then return this element
7879 //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1)
7880 // return sel.anchorNode.childNodes[sel.anchorOffset];
7882 // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.
7883 // This happens when you double click an underlined word in FireFox.
7884 if (start.nodeType === 3 && end.nodeType === 3) {
7885 function skipEmptyTextNodes(n, forwards) {
7887 while (n && n.nodeType === 3 && n.length === 0) {
7888 n = forwards ? n.nextSibling : n.previousSibling;
7892 if (start.length === rng.startOffset) {
7893 start = skipEmptyTextNodes(start.nextSibling, true);
7895 start = start.parentNode;
7897 if (rng.endOffset === 0) {
7898 end = skipEmptyTextNodes(end.previousSibling, false);
7900 end = end.parentNode;
7903 if (start && start === end)
7908 if (elm && elm.nodeType == 3)
7909 return elm.parentNode;
7914 return rng.item ? rng.item(0) : rng.parentElement();
7917 getSelectedBlocks : function(st, en) {
7918 var t = this, dom = t.dom, sb, eb, n, bl = [];
7920 sb = dom.getParent(st || t.getStart(), dom.isBlock);
7921 eb = dom.getParent(en || t.getEnd(), dom.isBlock);
7926 if (sb && eb && sb != eb) {
7929 while ((n = n.nextSibling) && n != eb) {
7941 normalize : function() {
7942 var self = this, rng, normalized;
7944 // Normalize only on non IE browsers for now
7948 function normalizeEndPoint(start) {
7949 var container, offset, walker, dom = self.dom, body = dom.getRoot(), node;
7951 container = rng[(start ? 'start' : 'end') + 'Container'];
7952 offset = rng[(start ? 'start' : 'end') + 'Offset'];
7954 // If the container is a document move it to the body element
7955 if (container.nodeType === 9) {
7956 container = container.body;
7960 // If the container is body try move it into the closest text node or position
7961 // TODO: Add more logic here to handle element selection cases
7962 if (container === body) {
7963 // Resolve the index
7964 if (container.hasChildNodes()) {
7965 container = container.childNodes[Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1)];
7968 // Walk the DOM to find a text node to place the caret at or a BR
7970 walker = new tinymce.dom.TreeWalker(container, body);
7972 // Found a text node use that position
7973 if (node.nodeType === 3) {
7974 offset = start ? 0 : node.nodeValue.length - 1;
7979 // Found a BR element that we can place the caret before
7980 if (node.nodeName === 'BR') {
7981 offset = dom.nodeIndex(node);
7982 container = node.parentNode;
7985 } while (node = (start ? walker.next() : walker.prev()));
7991 // Set endpoint if it was normalized
7993 rng['set' + (start ? 'Start' : 'End')](container, offset);
7996 rng = self.getRng();
7998 // Normalize the end points
7999 normalizeEndPoint(true);
8002 normalizeEndPoint();
8004 // Set the selection if it was normalized
8006 //console.log(self.dom.dumpRng(rng));
8011 destroy : function(s) {
8016 // Manual destroy then remove unload handler
8018 tinymce.removeUnload(t.destroy);
8021 // IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode
8022 _fixIESelection : function() {
8023 var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm;
8025 // Make HTML element unselectable since we are going to handle selection by hand
8026 doc.documentElement.unselectable = true;
8028 // Return range from point or null if it failed
8029 function rngFromPoint(x, y) {
8030 var rng = body.createTextRange();
8033 rng.moveToPoint(x, y);
8035 // IE sometimes throws and exception, so lets just ignore it
8042 // Fires while the selection is changing
8043 function selectionChange(e) {
8046 // Check if the button is down or not
8048 // Create range from mouse position
8049 pointRng = rngFromPoint(e.x, e.y);
8052 // Check if pointRange is before/after selection then change the endPoint
8053 if (pointRng.compareEndPoints('StartToStart', startRng) > 0)
8054 pointRng.setEndPoint('StartToStart', startRng);
8056 pointRng.setEndPoint('EndToEnd', startRng);
8064 // Removes listeners
8065 function endSelection() {
8066 var rng = doc.selection.createRange();
8068 // If the range is collapsed then use the last start range
8069 if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0)
8072 dom.unbind(doc, 'mouseup', endSelection);
8073 dom.unbind(doc, 'mousemove', selectionChange);
8074 startRng = started = 0;
8077 // Detect when user selects outside BODY
8078 dom.bind(doc, ['mousedown', 'contextmenu'], function(e) {
8079 if (e.target.nodeName === 'HTML') {
8083 // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML
8084 htmlElm = doc.documentElement;
8085 if (htmlElm.scrollHeight > htmlElm.clientHeight)
8089 // Setup start position
8090 startRng = rngFromPoint(e.x, e.y);
8092 // Listen for selection change events
8093 dom.bind(doc, 'mouseup', endSelection);
8094 dom.bind(doc, 'mousemove', selectionChange);
8105 (function(tinymce) {
8106 tinymce.dom.Serializer = function(settings, dom, schema) {
8107 var onPreProcess, onPostProcess, isIE = tinymce.isIE, each = tinymce.each, htmlParser;
8109 // Support the old apply_source_formatting option
8110 if (!settings.apply_source_formatting)
8111 settings.indent = false;
8113 settings.remove_trailing_brs = true;
8115 // Default DOM and Schema if they are undefined
8116 dom = dom || tinymce.DOM;
8117 schema = schema || new tinymce.html.Schema(settings);
8118 settings.entity_encoding = settings.entity_encoding || 'named';
8120 onPreProcess = new tinymce.util.Dispatcher(self);
8122 onPostProcess = new tinymce.util.Dispatcher(self);
8124 htmlParser = new tinymce.html.DomParser(settings, schema);
8126 // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed
8127 htmlParser.addAttributeFilter('src,href,style', function(nodes, name) {
8128 var i = nodes.length, node, value, internalName = 'data-mce-' + name, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef;
8133 value = node.attributes.map[internalName];
8134 if (value !== undef) {
8135 // Set external name to internal value and remove internal
8136 node.attr(name, value.length > 0 ? value : null);
8137 node.attr(internalName, null);
8139 // No internal attribute found then convert the value we have in the DOM
8140 value = node.attributes.map[name];
8142 if (name === "style")
8143 value = dom.serializeStyle(dom.parseStyle(value), node.name);
8144 else if (urlConverter)
8145 value = urlConverter.call(urlConverterScope, value, name, node.name);
8147 node.attr(name, value.length > 0 ? value : null);
8152 // Remove internal classes mceItem<..>
8153 htmlParser.addAttributeFilter('class', function(nodes, name) {
8154 var i = nodes.length, node, value;
8158 value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, '');
8159 node.attr('class', value.length > 0 ? value : null);
8163 // Remove bookmark elements
8164 htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) {
8165 var i = nodes.length, node;
8170 if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup)
8175 // Force script into CDATA sections and remove the mce- prefix also add comments around styles
8176 htmlParser.addNodeFilter('script,style', function(nodes, name) {
8177 var i = nodes.length, node, value;
8179 function trim(value) {
8180 return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')
8181 .replace(/^[\r\n]*|[\r\n]*$/g, '')
8182 .replace(/^\s*(\/\/\s*<!--|\/\/\s*<!\[CDATA\[|<!--|<!\[CDATA\[)[\r\n]*/g, '')
8183 .replace(/\s*(\/\/\s*\]\]>|\/\/\s*-->|\]\]>|-->|\]\]-->)\s*$/g, '');
8188 value = node.firstChild ? node.firstChild.value : '';
8190 if (name === "script") {
8191 // Remove mce- prefix from script elements
8192 node.attr('type', (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''));
8194 if (value.length > 0)
8195 node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
8197 if (value.length > 0)
8198 node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
8203 // Convert comments to cdata and handle protected comments
8204 htmlParser.addNodeFilter('#comment', function(nodes, name) {
8205 var i = nodes.length, node;
8210 if (node.value.indexOf('[CDATA[') === 0) {
8211 node.name = '#cdata';
8213 node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');
8214 } else if (node.value.indexOf('mce:protected ') === 0) {
8215 node.name = "#text";
8218 node.value = unescape(node.value).substr(14);
8223 htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) {
8224 var i = nodes.length, node;
8228 if (node.type === 7)
8230 else if (node.type === 1) {
8231 if (name === "input" && !("type" in node.attributes.map))
8232 node.attr('type', 'text');
8237 // Fix list elements, TODO: Replace this later
8238 if (settings.fix_list_elements) {
8239 htmlParser.addNodeFilter('ul,ol', function(nodes, name) {
8240 var i = nodes.length, node, parentNode;
8244 parentNode = node.parent;
8246 if (parentNode.name === 'ul' || parentNode.name === 'ol') {
8247 if (node.prev && node.prev.name === 'li') {
8248 node.prev.append(node);
8255 // Remove internal data attributes
8256 htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style', function(nodes, name) {
8257 var i = nodes.length;
8260 nodes[i].attr(name, null);
8264 // Return public methods
8268 addNodeFilter : htmlParser.addNodeFilter,
8270 addAttributeFilter : htmlParser.addAttributeFilter,
8272 onPreProcess : onPreProcess,
8274 onPostProcess : onPostProcess,
8276 serialize : function(node, args) {
8277 var impl, doc, oldDoc, htmlSerializer, content;
8279 // Explorer won't clone contents of script and style and the
8280 // selected index of select elements are cleared on a clone operation.
8281 if (isIE && dom.select('script,style,select').length > 0) {
8282 content = node.innerHTML;
8283 node = node.cloneNode(false);
8284 dom.setHTML(node, content);
8286 node = node.cloneNode(true);
8288 // Nodes needs to be attached to something in WebKit/Opera
8289 // Older builds of Opera crashes if you attach the node to an document created dynamically
8290 // and since we can't feature detect a crash we need to sniff the acutal build number
8291 // This fix will make DOM ranges and make Sizzle happy!
8292 impl = node.ownerDocument.implementation;
8293 if (impl.createHTMLDocument) {
8294 // Create an empty HTML document
8295 doc = impl.createHTMLDocument("");
8297 // Add the element or it's children if it's a body element to the new document
8298 each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) {
8299 doc.body.appendChild(doc.importNode(node, true));
8302 // Grab first child or body element for serialization
8303 if (node.nodeName != 'BODY')
8304 node = doc.body.firstChild;
8308 // set the new document in DOMUtils so createElement etc works
8314 args.format = args.format || 'html';
8317 if (!args.no_events) {
8319 onPreProcess.dispatch(self, args);
8323 htmlSerializer = new tinymce.html.Serializer(settings, schema);
8325 // Parse and serialize HTML
8326 args.content = htmlSerializer.serialize(
8327 htmlParser.parse(args.getInner ? node.innerHTML : tinymce.trim(dom.getOuterHTML(node), args), args)
8330 // Replace all BOM characters for now until we can find a better solution
8332 args.content = args.content.replace(/\uFEFF/g, '');
8335 if (!args.no_events)
8336 onPostProcess.dispatch(self, args);
8338 // Restore the old document if it was changed
8344 return args.content;
8347 addRules : function(rules) {
8348 schema.addValidElements(rules);
8351 setRules : function(rules) {
8352 schema.setValidElements(rules);
8357 (function(tinymce) {
8358 tinymce.dom.ScriptLoader = function(settings) {
8364 scriptLoadedCallbacks = {},
8365 queueLoadedCallbacks = [],
8369 function loadScript(url, callback) {
8370 var t = this, dom = tinymce.DOM, elm, uri, loc, id;
8372 // Execute callback when script is loaded
8377 elm.onreadystatechange = elm.onload = elm = null;
8383 // Report the error so it's easier for people to spot loading errors
8384 if (typeof(console) !== "undefined" && console.log)
8385 console.log("Failed to load: " + url);
8387 // We can't mark it as done if there is a load error since
8388 // A) We don't want to produce 404 errors on the server and
8389 // B) the onerror event won't fire on all browsers.
8393 id = dom.uniqueId();
8395 if (tinymce.isIE6) {
8396 uri = new tinymce.util.URI(url);
8399 // If script is from same domain and we
8400 // use IE 6 then use XHR since it's more reliable
8401 if (uri.host == loc.hostname && uri.port == loc.port && (uri.protocol + ':') == loc.protocol && uri.protocol.toLowerCase() != 'file') {
8402 tinymce.util.XHR.send({
8403 url : tinymce._addVer(uri.getURI()),
8404 success : function(content) {
8405 // Create new temp script element
8406 var script = dom.create('script', {
8407 type : 'text/javascript'
8410 // Evaluate script in global scope
8411 script.text = content;
8412 document.getElementsByTagName('head')[0].appendChild(script);
8425 // Create new script element
8426 elm = dom.create('script', {
8428 type : 'text/javascript',
8429 src : tinymce._addVer(url)
8432 // Add onload listener for non IE browsers since IE9
8433 // fires onload event before the script is parsed and executed
8437 // Add onerror event will get fired on some browsers but not all of them
8438 elm.onerror = error;
8440 // Opera 9.60 doesn't seem to fire the onreadystate event at correctly
8441 if (!tinymce.isOpera) {
8442 elm.onreadystatechange = function() {
8443 var state = elm.readyState;
8445 // Loaded state is passed on IE 6 however there
8446 // are known issues with this method but we can't use
8447 // XHR in a cross domain loading
8448 if (state == 'complete' || state == 'loaded')
8453 // Most browsers support this feature so we report errors
8454 // for those at least to help users track their missing plugins etc
8455 // todo: Removed since it produced error if the document is unloaded by navigating away, re-add it as an option
8456 /*elm.onerror = function() {
8457 alert('Failed to load: ' + url);
8460 // Add script to document
8461 (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
8464 this.isDone = function(url) {
8465 return states[url] == LOADED;
8468 this.markDone = function(url) {
8469 states[url] = LOADED;
8472 this.add = this.load = function(url, callback, scope) {
8473 var item, state = states[url];
8475 // Add url to load queue
8476 if (state == undefined) {
8478 states[url] = QUEUED;
8482 // Store away callback for later execution
8483 if (!scriptLoadedCallbacks[url])
8484 scriptLoadedCallbacks[url] = [];
8486 scriptLoadedCallbacks[url].push({
8488 scope : scope || this
8493 this.loadQueue = function(callback, scope) {
8494 this.loadScripts(queue, callback, scope);
8497 this.loadScripts = function(scripts, callback, scope) {
8500 function execScriptLoadedCallbacks(url) {
8501 // Execute URL callback functions
8502 tinymce.each(scriptLoadedCallbacks[url], function(callback) {
8503 callback.func.call(callback.scope);
8506 scriptLoadedCallbacks[url] = undefined;
8509 queueLoadedCallbacks.push({
8511 scope : scope || this
8514 loadScripts = function() {
8515 var loadingScripts = tinymce.grep(scripts);
8517 // Current scripts has been handled
8520 // Load scripts that needs to be loaded
8521 tinymce.each(loadingScripts, function(url) {
8522 // Script is already loaded then execute script callbacks directly
8523 if (states[url] == LOADED) {
8524 execScriptLoadedCallbacks(url);
8528 // Is script not loading then start loading it
8529 if (states[url] != LOADING) {
8530 states[url] = LOADING;
8533 loadScript(url, function() {
8534 states[url] = LOADED;
8537 execScriptLoadedCallbacks(url);
8539 // Load more scripts if they where added by the recently loaded script
8545 // No scripts are currently loading then execute all pending queue loaded callbacks
8547 tinymce.each(queueLoadedCallbacks, function(callback) {
8548 callback.func.call(callback.scope);
8551 queueLoadedCallbacks.length = 0;
8559 // Global script loader
8560 tinymce.ScriptLoader = new tinymce.dom.ScriptLoader();
8563 tinymce.dom.TreeWalker = function(start_node, root_node) {
8564 var node = start_node;
8566 function findSibling(node, start_name, sibling_name, shallow) {
8567 var sibling, parent;
8570 // Walk into nodes if it has a start
8571 if (!shallow && node[start_name])
8572 return node[start_name];
8574 // Return the sibling if it has one
8575 if (node != root_node) {
8576 sibling = node[sibling_name];
8580 // Walk up the parents to look for siblings
8581 for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
8582 sibling = parent[sibling_name];
8590 this.current = function() {
8594 this.next = function(shallow) {
8595 return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));
8598 this.prev = function(shallow) {
8599 return (node = findSibling(node, 'lastChild', 'previousSibling', shallow));
8603 (function(tinymce) {
8604 tinymce.dom.RangeUtils = function(dom) {
8605 var INVISIBLE_CHAR = '\uFEFF';
8607 this.walk = function(rng, callback) {
8608 var startContainer = rng.startContainer,
8609 startOffset = rng.startOffset,
8610 endContainer = rng.endContainer,
8611 endOffset = rng.endOffset,
8612 ancestor, startPoint,
8613 endPoint, node, parent, siblings, nodes;
8615 // Handle table cell selection the table plugin enables
8616 // you to fake select table cells and perform formatting actions on them
8617 nodes = dom.select('td.mceSelected,th.mceSelected');
8618 if (nodes.length > 0) {
8619 tinymce.each(nodes, function(node) {
8626 function collectSiblings(node, name, end_node) {
8629 for (; node && node != end_node; node = node[name])
8630 siblings.push(node);
8635 function findEndPoint(node, root) {
8637 if (node.parentNode == root)
8640 node = node.parentNode;
8644 function walkBoundary(start_node, end_node, next) {
8645 var siblingName = next ? 'nextSibling' : 'previousSibling';
8647 for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) {
8648 parent = node.parentNode;
8649 siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName);
8651 if (siblings.length) {
8660 // If index based start position then resolve it
8661 if (startContainer.nodeType == 1 && startContainer.hasChildNodes())
8662 startContainer = startContainer.childNodes[startOffset];
8664 // If index based end position then resolve it
8665 if (endContainer.nodeType == 1 && endContainer.hasChildNodes())
8666 endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)];
8668 // Find common ancestor and end points
8669 ancestor = dom.findCommonAncestor(startContainer, endContainer);
8672 if (startContainer == endContainer)
8673 return callback([startContainer]);
8675 // Process left side
8676 for (node = startContainer; node; node = node.parentNode) {
8677 if (node == endContainer)
8678 return walkBoundary(startContainer, ancestor, true);
8680 if (node == ancestor)
8684 // Process right side
8685 for (node = endContainer; node; node = node.parentNode) {
8686 if (node == startContainer)
8687 return walkBoundary(endContainer, ancestor);
8689 if (node == ancestor)
8693 // Find start/end point
8694 startPoint = findEndPoint(startContainer, ancestor) || startContainer;
8695 endPoint = findEndPoint(endContainer, ancestor) || endContainer;
8698 walkBoundary(startContainer, startPoint, true);
8700 // Walk the middle from start to end point
8701 siblings = collectSiblings(
8702 startPoint == startContainer ? startPoint : startPoint.nextSibling,
8704 endPoint == endContainer ? endPoint.nextSibling : endPoint
8707 if (siblings.length)
8711 walkBoundary(endContainer, endPoint);
8714 /* this.split = function(rng) {
8715 var startContainer = rng.startContainer,
8716 startOffset = rng.startOffset,
8717 endContainer = rng.endContainer,
8718 endOffset = rng.endOffset;
8720 function splitText(node, offset) {
8721 if (offset == node.nodeValue.length)
8722 node.appendData(INVISIBLE_CHAR);
8724 node = node.splitText(offset);
8726 if (node.nodeValue === INVISIBLE_CHAR)
8727 node.nodeValue = '';
8732 // Handle single text node
8733 if (startContainer == endContainer) {
8734 if (startContainer.nodeType == 3) {
8735 if (startOffset != 0)
8736 startContainer = endContainer = splitText(startContainer, startOffset);
8738 if (endOffset - startOffset != startContainer.nodeValue.length)
8739 splitText(startContainer, endOffset - startOffset);
8742 // Split startContainer text node if needed
8743 if (startContainer.nodeType == 3 && startOffset != 0) {
8744 startContainer = splitText(startContainer, startOffset);
8748 // Split endContainer text node if needed
8749 if (endContainer.nodeType == 3 && endOffset != endContainer.nodeValue.length) {
8750 endContainer = splitText(endContainer, endOffset).previousSibling;
8751 endOffset = endContainer.nodeValue.length;
8756 startContainer : startContainer,
8757 startOffset : startOffset,
8758 endContainer : endContainer,
8759 endOffset : endOffset
8765 tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) {
8767 // Compare native IE ranges
8768 if (rng1.item || rng1.duplicate) {
8769 // Both are control ranges and the selected element matches
8770 if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0))
8773 // Both are text ranges and the range matches
8774 if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1))
8777 // Compare w3c ranges
8778 return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset;
8786 (function(tinymce) {
8787 var Event = tinymce.dom.Event, each = tinymce.each;
8789 tinymce.create('tinymce.ui.KeyboardNavigation', {
8790 KeyboardNavigation: function(settings, dom) {
8791 var t = this, root = settings.root, items = settings.items,
8792 enableUpDown = settings.enableUpDown, enableLeftRight = settings.enableLeftRight || !settings.enableUpDown,
8793 excludeFromTabOrder = settings.excludeFromTabOrder,
8794 itemFocussed, itemBlurred, rootKeydown, rootFocussed, focussedId;
8796 dom = dom || tinymce.DOM;
8798 itemFocussed = function(evt) {
8799 focussedId = evt.target.id;
8802 itemBlurred = function(evt) {
8803 dom.setAttrib(evt.target.id, 'tabindex', '-1');
8806 rootFocussed = function(evt) {
8807 var item = dom.get(focussedId);
8808 dom.setAttrib(item, 'tabindex', '0');
8812 t.focus = function() {
8813 dom.get(focussedId).focus();
8816 t.destroy = function() {
8817 each(items, function(item) {
8818 dom.unbind(dom.get(item.id), 'focus', itemFocussed);
8819 dom.unbind(dom.get(item.id), 'blur', itemBlurred);
8822 dom.unbind(dom.get(root), 'focus', rootFocussed);
8823 dom.unbind(dom.get(root), 'keydown', rootKeydown);
8825 items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null;
8826 t.destroy = function() {};
8829 t.moveFocus = function(dir, evt) {
8830 var idx = -1, controls = t.controls, newFocus;
8835 each(items, function(item, index) {
8836 if (item.id === focussedId) {
8844 idx = items.length - 1;
8845 } else if (idx >= items.length) {
8849 newFocus = items[idx];
8850 dom.setAttrib(focussedId, 'tabindex', '-1');
8851 dom.setAttrib(newFocus.id, 'tabindex', '0');
8852 dom.get(newFocus.id).focus();
8854 if (settings.actOnFocus) {
8855 settings.onAction(newFocus.id);
8862 rootKeydown = function(evt) {
8863 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;
8865 switch (evt.keyCode) {
8867 if (enableLeftRight) t.moveFocus(-1);
8871 if (enableLeftRight) t.moveFocus(1);
8875 if (enableUpDown) t.moveFocus(-1);
8879 if (enableUpDown) t.moveFocus(1);
8883 if (settings.onCancel) {
8884 settings.onCancel();
8892 if (settings.onAction) {
8893 settings.onAction(focussedId);
8900 // Set up state and listeners for each item.
8901 each(items, function(item, idx) {
8905 item.id = dom.uniqueId('_mce_item_');
8908 if (excludeFromTabOrder) {
8909 dom.bind(item.id, 'blur', itemBlurred);
8912 tabindex = (idx === 0 ? '0' : '-1');
8915 dom.setAttrib(item.id, 'tabindex', tabindex);
8916 dom.bind(dom.get(item.id), 'focus', itemFocussed);
8919 // Setup initial state for root element.
8921 focussedId = items[0].id;
8924 dom.setAttrib(root, 'tabindex', '-1');
8926 // Setup listeners for root element.
8927 dom.bind(dom.get(root), 'focus', rootFocussed);
8928 dom.bind(dom.get(root), 'keydown', rootKeydown);
8932 (function(tinymce) {
8933 // Shorten class names
8934 var DOM = tinymce.DOM, is = tinymce.is;
8936 tinymce.create('tinymce.ui.Control', {
8937 Control : function(id, s, editor) {
8939 this.settings = s = s || {};
8940 this.rendered = false;
8941 this.onRender = new tinymce.util.Dispatcher(this);
8942 this.classPrefix = '';
8943 this.scope = s.scope || this;
8946 this.editor = editor;
8949 setAriaProperty : function(property, value) {
8950 var element = DOM.get(this.id + '_aria') || DOM.get(this.id);
8952 DOM.setAttrib(element, 'aria-' + property, !!value);
8956 focus : function() {
8957 DOM.get(this.id).focus();
8960 setDisabled : function(s) {
8961 if (s != this.disabled) {
8962 this.setAriaProperty('disabled', s);
8964 this.setState('Disabled', s);
8965 this.setState('Enabled', !s);
8970 isDisabled : function() {
8971 return this.disabled;
8974 setActive : function(s) {
8975 if (s != this.active) {
8976 this.setState('Active', s);
8978 this.setAriaProperty('pressed', s);
8982 isActive : function() {
8986 setState : function(c, s) {
8987 var n = DOM.get(this.id);
8989 c = this.classPrefix + c;
8994 DOM.removeClass(n, c);
8997 isRendered : function() {
8998 return this.rendered;
9001 renderHTML : function() {
9004 renderTo : function(n) {
9005 DOM.setHTML(n, this.renderHTML());
9008 postRender : function() {
9011 // Set pending states
9012 if (is(t.disabled)) {
9025 remove : function() {
9026 DOM.remove(this.id);
9030 destroy : function() {
9031 tinymce.dom.Event.clear(this.id);
9035 tinymce.create('tinymce.ui.Container:tinymce.ui.Control', {
9036 Container : function(id, s, editor) {
9037 this.parent(id, s, editor);
9045 this.lookup[c.id] = c;
9046 this.controls.push(c);
9052 return this.lookup[n];
9057 tinymce.create('tinymce.ui.Separator:tinymce.ui.Control', {
9058 Separator : function(id, s) {
9060 this.classPrefix = 'mceSeparator';
9061 this.setDisabled(true);
9064 renderHTML : function() {
9065 return tinymce.DOM.createHTML('span', {'class' : this.classPrefix, role : 'separator', 'aria-orientation' : 'vertical', tabindex : '-1'});
9069 (function(tinymce) {
9070 var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;
9072 tinymce.create('tinymce.ui.MenuItem:tinymce.ui.Control', {
9073 MenuItem : function(id, s) {
9075 this.classPrefix = 'mceMenuItem';
9078 setSelected : function(s) {
9079 this.setState('Selected', s);
9080 this.setAriaProperty('checked', !!s);
9084 isSelected : function() {
9085 return this.selected;
9088 postRender : function() {
9093 // Set pending state
9095 t.setSelected(t.selected);
9100 (function(tinymce) {
9101 var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;
9103 tinymce.create('tinymce.ui.Menu:tinymce.ui.MenuItem', {
9104 Menu : function(id, s) {
9109 t.collapsed = false;
9111 t.onAddItem = new tinymce.util.Dispatcher(this);
9114 expand : function(d) {
9118 walk(t, function(o) {
9124 t.collapsed = false;
9127 collapse : function(d) {
9131 walk(t, function(o) {
9140 isCollapsed : function() {
9141 return this.collapsed;
9146 o = new tinymce.ui.MenuItem(o.id || DOM.uniqueId(), o);
9148 this.onAddItem.dispatch(this, o);
9150 return this.items[o.id] = o;
9153 addSeparator : function() {
9154 return this.add({separator : true});
9157 addMenu : function(o) {
9159 o = this.createMenu(o);
9166 hasMenus : function() {
9167 return this.menuCount !== 0;
9170 remove : function(o) {
9171 delete this.items[o.id];
9174 removeAll : function() {
9177 walk(t, function(o) {
9189 createMenu : function(o) {
9190 var m = new tinymce.ui.Menu(o.id || DOM.uniqueId(), o);
9192 m.onAddItem.add(this.onAddItem.dispatch, this.onAddItem);
9198 (function(tinymce) {
9199 var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event, Element = tinymce.dom.Element;
9201 tinymce.create('tinymce.ui.DropMenu:tinymce.ui.Menu', {
9202 DropMenu : function(id, s) {
9204 s.container = s.container || DOM.doc.body;
9205 s.offset_x = s.offset_x || 0;
9206 s.offset_y = s.offset_y || 0;
9207 s.vp_offset_x = s.vp_offset_x || 0;
9208 s.vp_offset_y = s.vp_offset_y || 0;
9210 if (is(s.icons) && !s.icons)
9211 s['class'] += ' mceNoIcons';
9214 this.onShowMenu = new tinymce.util.Dispatcher(this);
9215 this.onHideMenu = new tinymce.util.Dispatcher(this);
9216 this.classPrefix = 'mceMenu';
9219 createMenu : function(s) {
9220 var t = this, cs = t.settings, m;
9222 s.container = s.container || cs.container;
9224 s.constrain = s.constrain || cs.constrain;
9225 s['class'] = s['class'] || cs['class'];
9226 s.vp_offset_x = s.vp_offset_x || cs.vp_offset_x;
9227 s.vp_offset_y = s.vp_offset_y || cs.vp_offset_y;
9228 s.keyboard_focus = cs.keyboard_focus;
9229 m = new tinymce.ui.DropMenu(s.id || DOM.uniqueId(), s);
9231 m.onAddItem.add(t.onAddItem.dispatch, t.onAddItem);
9236 focus : function() {
9238 if (t.keyboardNav) {
9239 t.keyboardNav.focus();
9243 update : function() {
9244 var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th;
9246 tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth;
9247 th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight;
9250 t.element.setStyles({width : tw + 2, height : th + 2});
9252 t.element.setStyles({width : tw, height : th});
9255 DOM.setStyle(co, 'width', tw);
9258 DOM.setStyle(co, 'height', th);
9260 if (tb.clientHeight < s.max_height)
9261 DOM.setStyle(co, 'overflow', 'hidden');
9265 showMenu : function(x, y, px) {
9266 var t = this, s = t.settings, co, vp = DOM.getViewPort(), w, h, mx, my, ot = 2, dm, tb, cp = t.classPrefix;
9270 if (t.isMenuVisible)
9274 co = DOM.add(t.settings.container, t.renderNode());
9276 each(t.items, function(o) {
9280 t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});
9282 co = DOM.get('menu_' + t.id);
9284 // Move layer out of sight unless it's Opera since it scrolls to top of page due to an bug
9285 if (!tinymce.isOpera)
9286 DOM.setStyles(co, {left : -0xFFFF , top : -0xFFFF});
9291 x += s.offset_x || 0;
9292 y += s.offset_y || 0;
9296 // Move inside viewport if not submenu
9298 w = co.clientWidth - ot;
9299 h = co.clientHeight - ot;
9303 if ((x + s.vp_offset_x + w) > mx)
9304 x = px ? px - w : Math.max(0, (mx - s.vp_offset_x) - w);
9306 if ((y + s.vp_offset_y + h) > my)
9307 y = Math.max(0, (my - s.vp_offset_y) - h);
9310 DOM.setStyles(co, {left : x , top : y});
9313 t.isMenuVisible = 1;
9314 t.mouseClickFunc = Event.add(co, 'click', function(e) {
9319 if (e && (e = DOM.getParent(e, 'tr')) && !DOM.hasClass(e, cp + 'ItemSub')) {
9331 dm = dm.settings.parent;
9334 if (m.settings.onclick)
9335 m.settings.onclick(e);
9337 return Event.cancel(e); // Cancel to fix onbeforeunload problem
9342 t.mouseOverFunc = Event.add(co, 'mouseover', function(e) {
9346 if (e && (e = DOM.getParent(e, 'tr'))) {
9350 t.lastMenu.collapse(1);
9355 if (e && DOM.hasClass(e, cp + 'ItemSub')) {
9356 //p = DOM.getPos(s.container);
9358 m.showMenu((r.x + r.w - ot), r.y - ot, r.x);
9360 DOM.addClass(DOM.get(m.id).firstChild, cp + 'ItemActive');
9366 Event.add(co, 'keydown', t._keyHandler, t);
9368 t.onShowMenu.dispatch(t);
9370 if (s.keyboard_focus) {
9371 t._setupKeyboardNav();
9375 hideMenu : function(c) {
9376 var t = this, co = DOM.get('menu_' + t.id), e;
9378 if (!t.isMenuVisible)
9381 if (t.keyboardNav) t.keyboardNav.destroy();
9382 Event.remove(co, 'mouseover', t.mouseOverFunc);
9383 Event.remove(co, 'click', t.mouseClickFunc);
9384 Event.remove(co, 'keydown', t._keyHandler);
9386 t.isMenuVisible = 0;
9394 if (e = DOM.get(t.id))
9395 DOM.removeClass(e.firstChild, t.classPrefix + 'ItemActive');
9397 t.onHideMenu.dispatch(t);
9405 if (t.isRendered && (co = DOM.get('menu_' + t.id)))
9406 t._add(DOM.select('tbody', co)[0], o);
9411 collapse : function(d) {
9416 remove : function(o) {
9420 return this.parent(o);
9423 destroy : function() {
9424 var t = this, co = DOM.get('menu_' + t.id);
9426 if (t.keyboardNav) t.keyboardNav.destroy();
9427 Event.remove(co, 'mouseover', t.mouseOverFunc);
9428 Event.remove(DOM.select('a', co), 'focus', t.mouseOverFunc);
9429 Event.remove(co, 'click', t.mouseClickFunc);
9430 Event.remove(co, 'keydown', t._keyHandler);
9438 renderNode : function() {
9439 var t = this, s = t.settings, n, tb, co, w;
9441 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'});
9442 if (t.settings.parent) {
9443 DOM.setAttrib(w, 'aria-parent', 'menu_' + t.settings.parent.id);
9445 co = DOM.add(w, 'div', {role: 'presentation', id : 'menu_' + t.id + '_co', 'class' : t.classPrefix + (s['class'] ? ' ' + s['class'] : '')});
9446 t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});
9449 DOM.add(co, 'span', {'class' : t.classPrefix + 'Line'});
9451 // n = DOM.add(co, 'div', {id : 'menu_' + t.id + '_co', 'class' : 'mceMenuContainer'});
9452 n = DOM.add(co, 'table', {role: 'presentation', id : 'menu_' + t.id + '_tbl', border : 0, cellPadding : 0, cellSpacing : 0});
9453 tb = DOM.add(n, 'tbody');
9455 each(t.items, function(o) {
9464 // Internal functions
9465 _setupKeyboardNav : function(){
9466 var contextMenu, menuItems, t=this;
9467 contextMenu = DOM.select('#menu_' + t.id)[0];
9468 menuItems = DOM.select('a[role=option]', 'menu_' + t.id);
9469 menuItems.splice(0,0,contextMenu);
9470 t.keyboardNav = new tinymce.ui.KeyboardNavigation({
9471 root: 'menu_' + t.id,
9473 onCancel: function() {
9478 contextMenu.focus();
9481 _keyHandler : function(evt) {
9483 switch (evt.keyCode) {
9485 if (t.settings.parent) {
9487 t.settings.parent.focus();
9492 if (t.mouseOverFunc)
9493 t.mouseOverFunc(evt);
9498 _add : function(tb, o) {
9499 var n, s = o.settings, a, ro, it, cp = this.classPrefix, ic;
9502 ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'ItemSeparator'});
9503 DOM.add(ro, 'td', {'class' : cp + 'ItemSeparator'});
9505 if (n = ro.previousSibling)
9506 DOM.addClass(n, 'mceLast');
9511 n = ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'Item ' + cp + 'ItemEnabled'});
9512 n = it = DOM.add(n, s.titleItem ? 'th' : 'td');
9513 n = a = DOM.add(n, 'a', {id: o.id + '_aria', role: s.titleItem ? 'presentation' : 'option', href : 'javascript:;', onclick : "return false;", onmousedown : 'return false;'});
9516 DOM.setAttrib(a, 'aria-haspopup', 'true');
9517 DOM.setAttrib(a, 'aria-owns', 'menu_' + o.id);
9520 DOM.addClass(it, s['class']);
9521 // n = DOM.add(n, 'span', {'class' : 'item'});
9523 ic = DOM.add(n, 'span', {'class' : 'mceIcon' + (s.icon ? ' mce_' + s.icon : '')});
9526 DOM.add(ic, 'img', {src : s.icon_src});
9528 n = DOM.add(n, s.element || 'span', {'class' : 'mceText', title : o.settings.title}, o.settings.title);
9530 if (o.settings.style)
9531 DOM.setAttrib(n, 'style', o.settings.style);
9533 if (tb.childNodes.length == 1)
9534 DOM.addClass(ro, 'mceFirst');
9536 if ((n = ro.previousSibling) && DOM.hasClass(n, cp + 'ItemSeparator'))
9537 DOM.addClass(ro, 'mceFirst');
9540 DOM.addClass(ro, cp + 'ItemSub');
9542 if (n = ro.previousSibling)
9543 DOM.removeClass(n, 'mceLast');
9545 DOM.addClass(ro, 'mceLast');
9549 (function(tinymce) {
9550 var DOM = tinymce.DOM;
9552 tinymce.create('tinymce.ui.Button:tinymce.ui.Control', {
9553 Button : function(id, s, ed) {
9554 this.parent(id, s, ed);
9555 this.classPrefix = 'mceButton';
9558 renderHTML : function() {
9559 var cp = this.classPrefix, s = this.settings, h, l;
9561 l = DOM.encode(s.label || '');
9562 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) + '">';
9563 if (s.image && !(this.editor &&this.editor.forcedHighContrastMode) )
9564 h += '<img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" />' + l;
9566 h += '<span class="mceIcon ' + s['class'] + '"></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : '');
9568 h += '<span class="mceVoiceLabel mceIconOnly" style="display: none;" id="' + this.id + '_voice">' + s.title + '</span>';
9573 postRender : function() {
9574 var t = this, s = t.settings;
9576 tinymce.dom.Event.add(t.id, 'click', function(e) {
9577 if (!t.isDisabled())
9578 return s.onclick.call(s.scope, e);
9584 (function(tinymce) {
9585 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;
9587 tinymce.create('tinymce.ui.ListBox:tinymce.ui.Control', {
9588 ListBox : function(id, s, ed) {
9591 t.parent(id, s, ed);
9595 t.onChange = new Dispatcher(t);
9597 t.onPostRender = new Dispatcher(t);
9599 t.onAdd = new Dispatcher(t);
9601 t.onRenderMenu = new tinymce.util.Dispatcher(this);
9603 t.classPrefix = 'mceListBox';
9606 select : function(va) {
9607 var t = this, fv, f;
9609 if (va == undefined)
9610 return t.selectByIndex(-1);
9612 // Is string or number make function selector
9621 // Do we need to do something?
9622 if (va != t.selectedValue) {
9624 each(t.items, function(o, i) {
9633 t.selectByIndex(-1);
9637 selectByIndex : function(idx) {
9640 if (idx != t.selectedIndex) {
9641 e = DOM.get(t.id + '_text');
9645 t.selectedValue = o.value;
9646 t.selectedIndex = idx;
9647 DOM.setHTML(e, DOM.encode(o.title));
9648 DOM.removeClass(e, 'mceTitle');
9649 DOM.setAttrib(t.id, 'aria-valuenow', o.title);
9651 DOM.setHTML(e, DOM.encode(t.settings.title));
9652 DOM.addClass(e, 'mceTitle');
9653 t.selectedValue = t.selectedIndex = null;
9654 DOM.setAttrib(t.id, 'aria-valuenow', t.settings.title);
9660 add : function(n, v, o) {
9664 o = tinymce.extend(o, {
9670 t.onAdd.dispatch(t, o);
9673 getLength : function() {
9674 return this.items.length;
9677 renderHTML : function() {
9678 var h = '', t = this, s = t.settings, cp = t.classPrefix;
9680 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>';
9681 h += '<td>' + DOM.createHTML('span', {id: t.id + '_voiceDesc', 'class': 'voiceLabel', style:'display:none;'}, t.settings.title);
9682 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>';
9683 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>';
9684 h += '</tr></tbody></table></span>';
9689 showMenu : function() {
9690 var t = this, p2, e = DOM.get(this.id), m;
9692 if (t.isDisabled() || t.items.length == 0)
9695 if (t.menu && t.menu.isMenuVisible)
9696 return t.hideMenu();
9698 if (!t.isMenuRendered) {
9700 t.isMenuRendered = true;
9706 m.settings.offset_x = p2.x;
9707 m.settings.offset_y = p2.y;
9708 m.settings.keyboard_focus = !tinymce.isOpera; // Opera is buggy when it comes to auto focus
9712 m.items[t.oldID].setSelected(0);
9714 each(t.items, function(o) {
9715 if (o.value === t.selectedValue) {
9716 m.items[o.id].setSelected(1);
9721 m.showMenu(0, e.clientHeight);
9723 Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
9724 DOM.addClass(t.id, t.classPrefix + 'Selected');
9726 //DOM.get(t.id + '_text').focus();
9729 hideMenu : function(e) {
9732 if (t.menu && t.menu.isMenuVisible) {
9733 DOM.removeClass(t.id, t.classPrefix + 'Selected');
9735 // Prevent double toogles by canceling the mouse click event to the button
9736 if (e && e.type == "mousedown" && (e.target.id == t.id + '_text' || e.target.id == t.id + '_open'))
9739 if (!e || !DOM.getParent(e.target, '.mceMenu')) {
9740 DOM.removeClass(t.id, t.classPrefix + 'Selected');
9741 Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
9747 renderMenu : function() {
9750 m = t.settings.control_manager.createDropMenu(t.id + '_menu', {
9752 'class' : t.classPrefix + 'Menu mceNoIcons',
9757 m.onHideMenu.add(function() {
9763 title : t.settings.title,
9764 'class' : 'mceMenuItemTitle',
9765 onclick : function() {
9766 if (t.settings.onselect('') !== false)
9767 t.select(''); // Must be runned after
9771 each(t.items, function(o) {
9772 // No value then treat it as a title
9773 if (o.value === undefined) {
9776 'class' : 'mceMenuItemTitle',
9777 onclick : function() {
9778 if (t.settings.onselect('') !== false)
9779 t.select(''); // Must be runned after
9783 o.id = DOM.uniqueId();
9784 o.onclick = function() {
9785 if (t.settings.onselect(o.value) !== false)
9786 t.select(o.value); // Must be runned after
9793 t.onRenderMenu.dispatch(t, m);
9797 postRender : function() {
9798 var t = this, cp = t.classPrefix;
9800 Event.add(t.id, 'click', t.showMenu, t);
9801 Event.add(t.id, 'keydown', function(evt) {
9802 if (evt.keyCode == 32) { // Space
9807 Event.add(t.id, 'focus', function() {
9809 t.keyDownHandler = Event.add(t.id, 'keydown', function(e) {
9810 if (e.keyCode == 40) {
9815 t.keyPressHandler = Event.add(t.id, 'keypress', function(e) {
9817 if (e.keyCode == 13) {
9818 // Fake select on enter
9819 v = t.selectedValue;
9820 t.selectedValue = null; // Needs to be null to fake change
9822 t.settings.onselect(v);
9829 Event.add(t.id, 'blur', function() {
9830 Event.remove(t.id, 'keydown', t.keyDownHandler);
9831 Event.remove(t.id, 'keypress', t.keyPressHandler);
9835 // Old IE doesn't have hover on all elements
9836 if (tinymce.isIE6 || !DOM.boxModel) {
9837 Event.add(t.id, 'mouseover', function() {
9838 if (!DOM.hasClass(t.id, cp + 'Disabled'))
9839 DOM.addClass(t.id, cp + 'Hover');
9842 Event.add(t.id, 'mouseout', function() {
9843 if (!DOM.hasClass(t.id, cp + 'Disabled'))
9844 DOM.removeClass(t.id, cp + 'Hover');
9848 t.onPostRender.dispatch(t, DOM.get(t.id));
9851 destroy : function() {
9854 Event.clear(this.id + '_text');
9855 Event.clear(this.id + '_open');
9859 (function(tinymce) {
9860 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;
9862 tinymce.create('tinymce.ui.NativeListBox:tinymce.ui.ListBox', {
9863 NativeListBox : function(id, s) {
9865 this.classPrefix = 'mceNativeListBox';
9868 setDisabled : function(s) {
9869 DOM.get(this.id).disabled = s;
9870 this.setAriaProperty('disabled', s);
9873 isDisabled : function() {
9874 return DOM.get(this.id).disabled;
9877 select : function(va) {
9878 var t = this, fv, f;
9880 if (va == undefined)
9881 return t.selectByIndex(-1);
9883 // Is string or number make function selector
9892 // Do we need to do something?
9893 if (va != t.selectedValue) {
9895 each(t.items, function(o, i) {
9904 t.selectByIndex(-1);
9908 selectByIndex : function(idx) {
9909 DOM.get(this.id).selectedIndex = idx + 1;
9910 this.selectedValue = this.items[idx] ? this.items[idx].value : null;
9913 add : function(n, v, a) {
9920 DOM.add(DOM.get(this.id), 'option', a, n);
9929 t.onAdd.dispatch(t, o);
9932 getLength : function() {
9933 return this.items.length;
9936 renderHTML : function() {
9939 h = DOM.createHTML('option', {value : ''}, '-- ' + t.settings.title + ' --');
9941 each(t.items, function(it) {
9942 h += DOM.createHTML('option', {value : it.value}, it.title);
9945 h = DOM.createHTML('select', {id : t.id, 'class' : 'mceNativeListBox', 'aria-labelledby': t.id + '_aria'}, h);
9946 h += DOM.createHTML('span', {id : t.id + '_aria', 'style': 'display: none'}, t.settings.title);
9950 postRender : function() {
9951 var t = this, ch, changeListenerAdded = true;
9955 function onChange(e) {
9956 var v = t.items[e.target.selectedIndex - 1];
9958 if (v && (v = v.value)) {
9959 t.onChange.dispatch(t, v);
9961 if (t.settings.onselect)
9962 t.settings.onselect(v);
9966 Event.add(t.id, 'change', onChange);
9968 // Accessibility keyhandler
9969 Event.add(t.id, 'keydown', function(e) {
9972 Event.remove(t.id, 'change', ch);
9973 changeListenerAdded = false;
9975 bf = Event.add(t.id, 'blur', function() {
9976 if (changeListenerAdded) return;
9977 changeListenerAdded = true;
9978 Event.add(t.id, 'change', onChange);
9979 Event.remove(t.id, 'blur', bf);
9982 if (e.keyCode == 13 || e.keyCode == 32) {
9984 return Event.cancel(e);
9988 t.onPostRender.dispatch(t, DOM.get(t.id));
9992 (function(tinymce) {
9993 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;
9995 tinymce.create('tinymce.ui.MenuButton:tinymce.ui.Button', {
9996 MenuButton : function(id, s, ed) {
9997 this.parent(id, s, ed);
9999 this.onRenderMenu = new tinymce.util.Dispatcher(this);
10001 s.menu_container = s.menu_container || DOM.doc.body;
10004 showMenu : function() {
10005 var t = this, p1, p2, e = DOM.get(t.id), m;
10007 if (t.isDisabled())
10010 if (!t.isMenuRendered) {
10012 t.isMenuRendered = true;
10015 if (t.isMenuVisible)
10016 return t.hideMenu();
10018 p1 = DOM.getPos(t.settings.menu_container);
10019 p2 = DOM.getPos(e);
10022 m.settings.offset_x = p2.x;
10023 m.settings.offset_y = p2.y;
10024 m.settings.vp_offset_x = p2.x;
10025 m.settings.vp_offset_y = p2.y;
10026 m.settings.keyboard_focus = t._focused;
10027 m.showMenu(0, e.clientHeight);
10029 Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
10030 t.setState('Selected', 1);
10032 t.isMenuVisible = 1;
10035 renderMenu : function() {
10038 m = t.settings.control_manager.createDropMenu(t.id + '_menu', {
10040 'class' : this.classPrefix + 'Menu',
10041 icons : t.settings.icons
10044 m.onHideMenu.add(function() {
10049 t.onRenderMenu.dispatch(t, m);
10053 hideMenu : function(e) {
10056 // Prevent double toogles by canceling the mouse click event to the button
10057 if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id || e.id === t.id + '_open';}))
10060 if (!e || !DOM.getParent(e.target, '.mceMenu')) {
10061 t.setState('Selected', 0);
10062 Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
10067 t.isMenuVisible = 0;
10070 postRender : function() {
10071 var t = this, s = t.settings;
10073 Event.add(t.id, 'click', function() {
10074 if (!t.isDisabled()) {
10076 s.onclick(t.value);
10085 (function(tinymce) {
10086 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;
10088 tinymce.create('tinymce.ui.SplitButton:tinymce.ui.MenuButton', {
10089 SplitButton : function(id, s, ed) {
10090 this.parent(id, s, ed);
10091 this.classPrefix = 'mceSplitButton';
10094 renderHTML : function() {
10095 var h, t = this, s = t.settings, h1;
10100 h1 = DOM.createHTML('img ', {src : s.image, role: 'presentation', 'class' : 'mceAction ' + s['class']});
10102 h1 = DOM.createHTML('span', {'class' : 'mceAction ' + s['class']}, '');
10104 h1 += DOM.createHTML('span', {'class': 'mceVoiceLabel mceIconOnly', id: t.id + '_voice', style: 'display:none;'}, s.title);
10105 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>';
10107 h1 = DOM.createHTML('span', {'class' : 'mceOpen ' + s['class']}, '<span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span>');
10108 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>';
10110 h += '</tr></tbody>';
10111 h = DOM.createHTML('table', {id : t.id, role: 'presentation', tabindex: '0', 'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h);
10112 return DOM.createHTML('span', {role: 'button', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h);
10115 postRender : function() {
10116 var t = this, s = t.settings, activate;
10119 activate = function(evt) {
10120 if (!t.isDisabled()) {
10121 s.onclick(t.value);
10125 Event.add(t.id + '_action', 'click', activate);
10126 Event.add(t.id, ['click', 'keydown'], function(evt) {
10127 var DOM_VK_SPACE = 32, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_UP = 38, DOM_VK_DOWN = 40;
10128 if ((evt.keyCode === 32 || evt.keyCode === 13 || evt.keyCode === 14) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) {
10131 } else if (evt.type === 'click' || evt.keyCode === DOM_VK_DOWN) {
10138 Event.add(t.id + '_open', 'click', function (evt) {
10142 Event.add([t.id, t.id + '_open'], 'focus', function() {t._focused = 1;});
10143 Event.add([t.id, t.id + '_open'], 'blur', function() {t._focused = 0;});
10145 // Old IE doesn't have hover on all elements
10146 if (tinymce.isIE6 || !DOM.boxModel) {
10147 Event.add(t.id, 'mouseover', function() {
10148 if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled'))
10149 DOM.addClass(t.id, 'mceSplitButtonHover');
10152 Event.add(t.id, 'mouseout', function() {
10153 if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled'))
10154 DOM.removeClass(t.id, 'mceSplitButtonHover');
10159 destroy : function() {
10162 Event.clear(this.id + '_action');
10163 Event.clear(this.id + '_open');
10164 Event.clear(this.id);
10169 (function(tinymce) {
10170 var DOM = tinymce.DOM, Event = tinymce.dom.Event, is = tinymce.is, each = tinymce.each;
10172 tinymce.create('tinymce.ui.ColorSplitButton:tinymce.ui.SplitButton', {
10173 ColorSplitButton : function(id, s, ed) {
10176 t.parent(id, s, ed);
10178 t.settings = s = tinymce.extend({
10179 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',
10181 default_color : '#888888'
10184 t.onShowMenu = new tinymce.util.Dispatcher(t);
10186 t.onHideMenu = new tinymce.util.Dispatcher(t);
10188 t.value = s.default_color;
10191 showMenu : function() {
10192 var t = this, r, p, e, p2;
10194 if (t.isDisabled())
10197 if (!t.isMenuRendered) {
10199 t.isMenuRendered = true;
10202 if (t.isMenuVisible)
10203 return t.hideMenu();
10206 DOM.show(t.id + '_menu');
10207 DOM.addClass(e, 'mceSplitButtonSelected');
10208 p2 = DOM.getPos(e);
10209 DOM.setStyles(t.id + '_menu', {
10211 top : p2.y + e.clientHeight,
10216 Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
10217 t.onShowMenu.dispatch(t);
10220 t._keyHandler = Event.add(t.id + '_menu', 'keydown', function(e) {
10221 if (e.keyCode == 27)
10225 DOM.select('a', t.id + '_menu')[0].focus(); // Select first link
10228 t.isMenuVisible = 1;
10231 hideMenu : function(e) {
10234 if (t.isMenuVisible) {
10235 // Prevent double toogles by canceling the mouse click event to the button
10236 if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';}))
10239 if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) {
10240 DOM.removeClass(t.id, 'mceSplitButtonSelected');
10241 Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
10242 Event.remove(t.id + '_menu', 'keydown', t._keyHandler);
10243 DOM.hide(t.id + '_menu');
10246 t.isMenuVisible = 0;
10250 renderMenu : function() {
10251 var t = this, m, i = 0, s = t.settings, n, tb, tr, w, context;
10253 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;'});
10254 m = DOM.add(w, 'div', {'class' : s['class'] + ' mceSplitButtonMenu'});
10255 DOM.add(m, 'span', {'class' : 'mceMenuLine'});
10257 n = DOM.add(m, 'table', {role: 'presentation', 'class' : 'mceColorSplitMenu'});
10258 tb = DOM.add(n, 'tbody');
10260 // Generate color grid
10262 each(is(s.colors, 'array') ? s.colors : s.colors.split(','), function(c) {
10263 c = c.replace(/^#/, '');
10266 tr = DOM.add(tb, 'tr');
10267 i = s.grid_width - 1;
10270 n = DOM.add(tr, 'td');
10271 n = DOM.add(n, 'a', {
10273 href : 'javascript:;',
10275 backgroundColor : '#' + c
10277 'title': t.editor.getLang('colors.' + c, c),
10278 'data-mce-color' : '#' + c
10281 if (t.editor.forcedHighContrastMode) {
10282 n = DOM.add(n, 'canvas', { width: 16, height: 16, 'aria-hidden': 'true' });
10283 if (n.getContext && (context = n.getContext("2d"))) {
10284 context.fillStyle = '#' + c;
10285 context.fillRect(0, 0, 16, 16);
10287 // No point leaving a canvas element around if it's not supported for drawing on anyway.
10293 if (s.more_colors_func) {
10294 n = DOM.add(tb, 'tr');
10295 n = DOM.add(n, 'td', {colspan : s.grid_width, 'class' : 'mceMoreColors'});
10296 n = DOM.add(n, 'a', {role: 'option', id : t.id + '_more', href : 'javascript:;', onclick : 'return false;', 'class' : 'mceMoreColors'}, s.more_colors_title);
10298 Event.add(n, 'click', function(e) {
10299 s.more_colors_func.call(s.more_colors_scope || this);
10300 return Event.cancel(e); // Cancel to fix onbeforeunload problem
10304 DOM.addClass(m, 'mceColorSplitMenu');
10306 new tinymce.ui.KeyboardNavigation({
10307 root: t.id + '_menu',
10308 items: DOM.select('a', t.id + '_menu'),
10309 onCancel: function() {
10315 // Prevent IE from scrolling and hindering click to occur #4019
10316 Event.add(t.id + '_menu', 'mousedown', function(e) {return Event.cancel(e);});
10318 Event.add(t.id + '_menu', 'click', function(e) {
10321 e = DOM.getParent(e.target, 'a', tb);
10323 if (e && e.nodeName.toLowerCase() == 'a' && (c = e.getAttribute('data-mce-color')))
10326 return Event.cancel(e); // Prevent IE auto save warning
10332 setColor : function(c) {
10333 this.displayColor(c);
10335 this.settings.onselect(c);
10338 displayColor : function(c) {
10341 DOM.setStyle(t.id + '_preview', 'backgroundColor', c);
10346 postRender : function() {
10347 var t = this, id = t.id;
10350 DOM.add(id + '_action', 'div', {id : id + '_preview', 'class' : 'mceColorPreview'});
10351 DOM.setStyle(t.id + '_preview', 'backgroundColor', t.value);
10354 destroy : function() {
10357 Event.clear(this.id + '_menu');
10358 Event.clear(this.id + '_more');
10359 DOM.remove(this.id + '_menu');
10364 (function(tinymce) {
10365 // Shorten class names
10366 var dom = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event;
10367 tinymce.create('tinymce.ui.ToolbarGroup:tinymce.ui.Container', {
10368 renderHTML : function() {
10369 var t = this, h = [], controls = t.controls, each = tinymce.each, settings = t.settings;
10371 h.push('<div id="' + t.id + '" role="group" aria-labelledby="' + t.id + '_voice">');
10372 //TODO: ACC test this out - adding a role = application for getting the landmarks working well.
10373 h.push("<span role='application'>");
10374 h.push('<span id="' + t.id + '_voice" class="mceVoiceLabel" style="display:none;">' + dom.encode(settings.name) + '</span>');
10375 each(controls, function(toolbar) {
10376 h.push(toolbar.renderHTML());
10384 focus : function() {
10385 this.keyNav.focus();
10388 postRender : function() {
10389 var t = this, items = [];
10391 each(t.controls, function(toolbar) {
10392 each (toolbar.controls, function(control) {
10394 items.push(control);
10399 t.keyNav = new tinymce.ui.KeyboardNavigation({
10402 onCancel: function() {
10405 excludeFromTabOrder: !t.settings.tab_focus_toolbar
10409 destroy : function() {
10413 self.keyNav.destroy();
10414 Event.clear(self.id);
10419 (function(tinymce) {
10420 // Shorten class names
10421 var dom = tinymce.DOM, each = tinymce.each;
10422 tinymce.create('tinymce.ui.Toolbar:tinymce.ui.Container', {
10423 renderHTML : function() {
10424 var t = this, h = '', c, co, s = t.settings, i, pr, nx, cl;
10427 for (i=0; i<cl.length; i++) {
10428 // Get current control, prev control, next control and if the control is a list box or not
10433 // Add toolbar start
10435 c = 'mceToolbarStart';
10438 c += ' mceToolbarStartButton';
10439 else if (co.SplitButton)
10440 c += ' mceToolbarStartSplitButton';
10441 else if (co.ListBox)
10442 c += ' mceToolbarStartListBox';
10444 h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->'));
10447 // Add toolbar end before list box and after the previous button
10448 // This is to fix the o2k7 editor skins
10449 if (pr && co.ListBox) {
10450 if (pr.Button || pr.SplitButton)
10451 h += dom.createHTML('td', {'class' : 'mceToolbarEnd'}, dom.createHTML('span', null, '<!-- IE -->'));
10454 // Render control HTML
10456 // IE 8 quick fix, needed to propertly generate a hit area for anchors
10458 h += '<td style="position: relative">' + co.renderHTML() + '</td>';
10460 h += '<td>' + co.renderHTML() + '</td>';
10462 // Add toolbar start after list box and before the next button
10463 // This is to fix the o2k7 editor skins
10464 if (nx && co.ListBox) {
10465 if (nx.Button || nx.SplitButton)
10466 h += dom.createHTML('td', {'class' : 'mceToolbarStart'}, dom.createHTML('span', null, '<!-- IE -->'));
10470 c = 'mceToolbarEnd';
10473 c += ' mceToolbarEndButton';
10474 else if (co.SplitButton)
10475 c += ' mceToolbarEndSplitButton';
10476 else if (co.ListBox)
10477 c += ' mceToolbarEndListBox';
10479 h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->'));
10481 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>');
10486 (function(tinymce) {
10487 var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each;
10489 tinymce.create('tinymce.AddOnManager', {
10490 AddOnManager : function() {
10496 self.onAdd = new Dispatcher(self);
10499 get : function(n) {
10500 if (this.lookup[n]) {
10501 return this.lookup[n].instance;
10507 dependencies : function(n) {
10509 if (this.lookup[n]) {
10510 result = this.lookup[n].dependencies;
10512 return result || [];
10515 requireLangPack : function(n) {
10516 var s = tinymce.settings;
10518 if (s && s.language && s.language_load !== false)
10519 tinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js');
10522 add : function(id, o, dependencies) {
10523 this.items.push(o);
10524 this.lookup[id] = {instance:o, dependencies:dependencies};
10525 this.onAdd.dispatch(this, id, o);
10529 createUrl: function(baseUrl, dep) {
10530 if (typeof dep === "object") {
10533 return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix};
10537 addComponents: function(pluginName, scripts) {
10538 var pluginUrl = this.urls[pluginName];
10539 tinymce.each(scripts, function(script){
10540 tinymce.ScriptLoader.add(pluginUrl+"/"+script);
10544 load : function(n, u, cb, s) {
10545 var t = this, url = u;
10547 function loadDependencies() {
10548 var dependencies = t.dependencies(n);
10549 tinymce.each(dependencies, function(dep) {
10550 var newUrl = t.createUrl(u, dep);
10551 t.load(newUrl.resource, newUrl, undefined, undefined);
10557 cb.call(tinymce.ScriptLoader);
10564 if (typeof u === "object")
10565 url = u.prefix + u.resource + u.suffix;
10567 if (url.indexOf('/') != 0 && url.indexOf('://') == -1)
10568 url = tinymce.baseURL + '/' + url;
10570 t.urls[n] = url.substring(0, url.lastIndexOf('/'));
10573 loadDependencies();
10575 tinymce.ScriptLoader.add(url, loadDependencies, s);
10580 // Create plugin and theme managers
10581 tinymce.PluginManager = new tinymce.AddOnManager();
10582 tinymce.ThemeManager = new tinymce.AddOnManager();
10585 (function(tinymce) {
10587 var each = tinymce.each, extend = tinymce.extend,
10588 DOM = tinymce.DOM, Event = tinymce.dom.Event,
10589 ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
10590 explode = tinymce.explode,
10591 Dispatcher = tinymce.util.Dispatcher, undefined, instanceCounter = 0;
10593 // Setup some URLs where the editor API is located and where the document is
10594 tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
10595 if (!/[\/\\]$/.test(tinymce.documentBaseURL))
10596 tinymce.documentBaseURL += '/';
10598 tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL);
10600 tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL);
10602 // Add before unload listener
10603 // This was required since IE was leaking memory if you added and removed beforeunload listeners
10604 // with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event
10605 tinymce.onBeforeUnload = new Dispatcher(tinymce);
10607 // Must be on window or IE will leak if the editor is placed in frame or iframe
10608 Event.add(window, 'beforeunload', function(e) {
10609 tinymce.onBeforeUnload.dispatch(tinymce, e);
10612 tinymce.onAddEditor = new Dispatcher(tinymce);
10614 tinymce.onRemoveEditor = new Dispatcher(tinymce);
10616 tinymce.EditorManager = extend(tinymce, {
10621 activeEditor : null,
10623 init : function(s) {
10624 var t = this, pl, sl = tinymce.ScriptLoader, e, el = [], ed;
10626 function execCallback(se, n, s) {
10632 if (tinymce.is(f, 'string')) {
10633 s = f.replace(/\.\w+$/, '');
10634 s = s ? tinymce.resolve(s) : 0;
10635 f = tinymce.resolve(f);
10638 return f.apply(s || this, Array.prototype.slice.call(arguments, 2));
10649 Event.add(document, 'init', function() {
10652 execCallback(s, 'onpageload');
10656 l = s.elements || '';
10659 each(explode(l), function(v) {
10661 ed = new tinymce.Editor(v, s);
10665 each(document.forms, function(f) {
10666 each(f.elements, function(e) {
10667 if (e.name === v) {
10668 v = 'mce_editor_' + instanceCounter++;
10669 DOM.setAttrib(e, 'id', v);
10671 ed = new tinymce.Editor(v, s);
10683 case "specific_textareas":
10684 function hasClass(n, c) {
10685 return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
10688 each(DOM.select('textarea'), function(v) {
10689 if (s.editor_deselector && hasClass(v, s.editor_deselector))
10692 if (!s.editor_selector || hasClass(v, s.editor_selector)) {
10693 // Can we use the name
10694 e = DOM.get(v.name);
10698 // Generate unique name if missing or already exists
10699 if (!v.id || t.get(v.id))
10700 v.id = DOM.uniqueId();
10702 ed = new tinymce.Editor(v.id, s);
10710 // Call onInit when all editors are initialized
10714 each(el, function(ed) {
10717 if (!ed.initialized) {
10719 ed.onInit.add(function() {
10724 execCallback(s, 'oninit');
10731 execCallback(s, 'oninit');
10737 get : function(id) {
10738 if (id === undefined)
10739 return this.editors;
10741 return this.editors[id];
10744 getInstanceById : function(id) {
10745 return this.get(id);
10748 add : function(editor) {
10749 var self = this, editors = self.editors;
10751 // Add named and index editor instance
10752 editors[editor.id] = editor;
10753 editors.push(editor);
10755 self._setActive(editor);
10756 self.onAddEditor.dispatch(self, editor);
10762 remove : function(editor) {
10763 var t = this, i, editors = t.editors;
10765 // Not in the collection
10766 if (!editors[editor.id])
10769 delete editors[editor.id];
10771 for (i = 0; i < editors.length; i++) {
10772 if (editors[i] == editor) {
10773 editors.splice(i, 1);
10778 // Select another editor since the active one was removed
10779 if (t.activeEditor == editor)
10780 t._setActive(editors[0]);
10783 t.onRemoveEditor.dispatch(t, editor);
10788 execCommand : function(c, u, v) {
10789 var t = this, ed = t.get(v), w;
10791 // Manager commands
10797 case "mceAddEditor":
10798 case "mceAddControl":
10800 new tinymce.Editor(v, t.settings).render();
10804 case "mceAddFrameControl":
10807 // Add tinyMCE global instance and tinymce namespace to specified window
10808 w.tinyMCE = tinyMCE;
10809 w.tinymce = tinymce;
10811 tinymce.DOM.doc = w.document;
10812 tinymce.DOM.win = w;
10814 ed = new tinymce.Editor(v.element_id, v);
10817 // Fix IE memory leaks
10818 if (tinymce.isIE) {
10821 w.detachEvent('onunload', clr);
10822 w = w.tinyMCE = w.tinymce = null; // IE leak
10825 w.attachEvent('onunload', clr);
10828 v.page_window = null;
10832 case "mceRemoveEditor":
10833 case "mceRemoveControl":
10839 case 'mceToggleEditor':
10841 t.execCommand('mceAddControl', 0, v);
10853 // Run command on active editor
10854 if (t.activeEditor)
10855 return t.activeEditor.execCommand(c, u, v);
10860 execInstanceCommand : function(id, c, u, v) {
10861 var ed = this.get(id);
10864 return ed.execCommand(c, u, v);
10869 triggerSave : function() {
10870 each(this.editors, function(e) {
10875 addI18n : function(p, o) {
10876 var lo, i18n = this.i18n;
10878 if (!tinymce.is(p, 'string')) {
10879 each(p, function(o, lc) {
10880 each(o, function(o, g) {
10881 each(o, function(o, k) {
10882 if (g === 'common')
10883 i18n[lc + '.' + k] = o;
10885 i18n[lc + '.' + g + '.' + k] = o;
10890 each(o, function(o, k) {
10891 i18n[p + '.' + k] = o;
10898 _setActive : function(editor) {
10899 this.selectedInstance = this.activeEditor = editor;
10904 (function(tinymce) {
10905 // Shorten these names
10906 var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend,
10907 Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isGecko = tinymce.isGecko,
10908 isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, is = tinymce.is,
10909 ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
10910 inArray = tinymce.inArray, grep = tinymce.grep, explode = tinymce.explode;
10912 tinymce.create('tinymce.Editor', {
10913 Editor : function(id, s) {
10916 t.id = t.editorId = id;
10918 t.execCommands = {};
10919 t.queryStateCommands = {};
10920 t.queryValueCommands = {};
10922 t.isNotDirty = false;
10926 // Add events to the editor
10930 'onBeforeRenderUI',
10970 'onBeforeSetContent',
10972 'onBeforeGetContent',
10986 'onBeforeExecCommand',
10996 'onSetProgressState'
10998 t[e] = new Dispatcher(t);
11001 t.settings = s = extend({
11004 docs_language : 'en',
11011 document_base_url : tinymce.documentBaseURL,
11012 add_form_submit_trigger : 1,
11014 add_unload_trigger : 1,
11017 remove_script_host : 1,
11018 table_inline_editing : 0,
11019 object_resizing : 1,
11021 accessibility_focus : 1,
11022 custom_shortcuts : 1,
11023 custom_undo_redo_keyboard_shortcuts : 1,
11024 custom_undo_redo_restore_selection : 1,
11025 custom_undo_redo : 1,
11026 doctype : tinymce.isIE6 ? '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' : '<!DOCTYPE>', // Use old doctype on IE 6 to avoid horizontal scroll
11027 visual_table_class : 'mceItemTable',
11029 font_size_style_values : 'xx-small,x-small,small,medium,large,x-large,xx-large',
11030 apply_source_formatting : 1,
11031 directionality : 'ltr',
11032 forced_root_block : 'p',
11034 padd_empty_editor : 1,
11037 force_p_newlines : 1,
11038 indentation : '30px',
11040 fix_table_elements : 1,
11042 convert_fonts_to_spans : true,
11044 indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',
11045 indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',
11047 entity_encoding : 'named',
11048 url_converter : t.convertURL,
11049 url_converter_scope : t,
11053 t.documentBaseURI = new tinymce.util.URI(s.document_base_url || tinymce.documentBaseURL, {
11054 base_uri : tinyMCE.baseURI
11057 t.baseURI = tinymce.baseURI;
11062 t.execCallback('setup', t);
11065 render : function(nst) {
11066 var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader;
11068 // Page is not loaded yet, wait for it
11069 if (!Event.domLoaded) {
11070 Event.add(document, 'init', function() {
11076 tinyMCE.settings = s;
11078 // Element not found, then skip initialization
11079 if (!t.getElement())
11082 // Is a iPad/iPhone and not on iOS5, then skip initialization. We need to sniff
11083 // here since the browser says it has contentEditable support but there is no visible
11084 // caret We will remove this check ones Apple implements full contentEditable support
11085 if (tinymce.isIDevice && !tinymce.isIOS5)
11088 // Add hidden input for non input elements inside form elements
11089 if (!/TEXTAREA|INPUT/i.test(t.getElement().nodeName) && s.hidden_input && DOM.getParent(id, 'form'))
11090 DOM.insertAfter(DOM.create('input', {type : 'hidden', name : id}), id);
11092 if (tinymce.WindowManager)
11093 t.windowManager = new tinymce.WindowManager(t);
11095 if (s.encoding == 'xml') {
11096 t.onGetContent.add(function(ed, o) {
11098 o.content = DOM.encode(o.content);
11102 if (s.add_form_submit_trigger) {
11103 t.onSubmit.addToTop(function() {
11104 if (t.initialized) {
11111 if (s.add_unload_trigger) {
11112 t._beforeUnload = tinyMCE.onBeforeUnload.add(function() {
11113 if (t.initialized && !t.destroyed && !t.isHidden())
11114 t.save({format : 'raw', no_events : true});
11118 tinymce.addUnload(t.destroy, t);
11120 if (s.submit_patch) {
11121 t.onBeforeRenderUI.add(function() {
11122 var n = t.getElement().form;
11128 if (n._mceOldSubmit)
11131 // Check page uses id="submit" or name="submit" for it's submit button
11132 if (!n.submit.nodeType && !n.submit.length) {
11134 n._mceOldSubmit = n.submit;
11135 n.submit = function() {
11136 // Save all instances
11137 tinymce.triggerSave();
11140 return t.formElement._mceOldSubmit(t.formElement);
11149 function loadScripts() {
11150 if (s.language && s.language_load !== false)
11151 sl.add(tinymce.baseURL + '/langs/' + s.language + '.js');
11153 if (s.theme && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme])
11154 ThemeManager.load(s.theme, 'themes/' + s.theme + '/editor_template' + tinymce.suffix + '.js');
11156 each(explode(s.plugins), function(p) {
11157 if (p &&!PluginManager.urls[p]) {
11158 if (p.charAt(0) == '-') {
11159 p = p.substr(1, p.length);
11160 var dependencies = PluginManager.dependencies(p);
11161 each(dependencies, function(dep) {
11162 var defaultSettings = {prefix:'plugins/', resource: dep, suffix:'/editor_plugin' + tinymce.suffix + '.js'};
11163 var dep = PluginManager.createUrl(defaultSettings, dep);
11164 PluginManager.load(dep.resource, dep);
11168 // Skip safari plugin, since it is removed as of 3.3b1
11169 if (p == 'safari') {
11172 PluginManager.load(p, {prefix:'plugins/', resource: p, suffix:'/editor_plugin' + tinymce.suffix + '.js'});
11177 // Init when que is loaded
11178 sl.loadQueue(function() {
11187 init : function() {
11188 var n, t = this, s = t.settings, w, h, e = t.getElement(), o, ti, u, bi, bc, re, i, initializedPlugins = [];
11192 s.aria_label = s.aria_label || DOM.getAttrib(e, 'aria-label', t.getLang('aria.rich_text_area'));
11195 s.theme = s.theme.replace(/-/, '');
11196 o = ThemeManager.get(s.theme);
11199 if (t.theme.init && s.init_theme)
11200 t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, ''));
11202 function initPlugin(p) {
11203 var c = PluginManager.get(p), u = PluginManager.urls[p] || tinymce.documentBaseURL.replace(/\/$/, ''), po;
11204 if (c && tinymce.inArray(initializedPlugins,p) === -1) {
11205 each(PluginManager.dependencies(p), function(dep){
11214 initializedPlugins.push(p);
11219 // Create all plugins
11220 each(explode(s.plugins.replace(/\-/g, '')), initPlugin);
11222 // Setup popup CSS path(s)
11223 if (s.popup_css !== false) {
11225 s.popup_css = t.documentBaseURI.toAbsolute(s.popup_css);
11227 s.popup_css = t.baseURI.toAbsolute("themes/" + s.theme + "/skins/" + s.skin + "/dialog.css");
11230 if (s.popup_css_add)
11231 s.popup_css += ',' + t.documentBaseURI.toAbsolute(s.popup_css_add);
11233 t.controlManager = new tinymce.ControlManager(t);
11235 if (s.custom_undo_redo) {
11236 t.onBeforeExecCommand.add(function(ed, cmd, ui, val, a) {
11237 if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))
11238 t.undoManager.beforeChange();
11241 t.onExecCommand.add(function(ed, cmd, ui, val, a) {
11242 if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))
11243 t.undoManager.add();
11247 t.onExecCommand.add(function(ed, c) {
11248 // Don't refresh the select lists until caret move
11249 if (!/^(FontName|FontSize)$/.test(c))
11253 // Remove ghost selections on images and tables in Gecko
11255 function repaint(a, o) {
11256 if (!o || !o.initial)
11257 t.execCommand('mceRepaint');
11260 t.onUndo.add(repaint);
11261 t.onRedo.add(repaint);
11262 t.onSetContent.add(repaint);
11265 // Enables users to override the control factory
11266 t.onBeforeRenderUI.dispatch(t, t.controlManager);
11270 w = s.width || e.style.width || e.offsetWidth;
11271 h = s.height || e.style.height || e.offsetHeight;
11272 t.orgDisplay = e.style.display;
11273 re = /^[0-9\.]+(|px)$/i;
11275 if (re.test('' + w))
11276 w = Math.max(parseInt(w) + (o.deltaWidth || 0), 100);
11278 if (re.test('' + h))
11279 h = Math.max(parseInt(h) + (o.deltaHeight || 0), 100);
11282 o = t.theme.renderUI({
11286 deltaWidth : s.delta_width,
11287 deltaHeight : s.delta_height
11290 t.editorContainer = o.editorContainer;
11294 // User specified a document.domain value
11295 if (document.domain && location.hostname != document.domain)
11296 tinymce.relaxedDomain = document.domain;
11299 DOM.setStyles(o.sizeContainer || o.editorContainer, {
11304 // Load specified content CSS last
11305 if (s.content_css) {
11306 tinymce.each(explode(s.content_css), function(u) {
11307 t.contentCSS.push(t.documentBaseURI.toAbsolute(u));
11311 h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : '');
11315 t.iframeHTML = s.doctype + '<html><head xmlns="http://www.w3.org/1999/xhtml">';
11317 // We only need to override paths if we have to
11318 // IE has a bug where it remove site absolute urls to relative ones if this is specified
11319 if (s.document_base_url != tinymce.documentBaseURL)
11320 t.iframeHTML += '<base href="' + t.documentBaseURI.getURI() + '" />';
11322 // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode.
11324 t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />';
11326 t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=edge" />';
11328 t.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
11330 // Firefox 2 doesn't load stylesheets correctly this way
11331 if (!isGecko || !/Firefox\/2/.test(navigator.userAgent)) {
11332 for (i = 0; i < t.contentCSS.length; i++)
11333 t.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + t.contentCSS[i] + '" />';
11338 bi = s.body_id || 'tinymce';
11339 if (bi.indexOf('=') != -1) {
11340 bi = t.getParam('body_id', '', 'hash');
11341 bi = bi[t.id] || bi;
11344 bc = s.body_class || '';
11345 if (bc.indexOf('=') != -1) {
11346 bc = t.getParam('body_class', '', 'hash');
11347 bc = bc[t.id] || '';
11350 t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '"></body></html>';
11352 // Domain relaxing enabled, then set document domain
11353 if (tinymce.relaxedDomain && (isIE || (tinymce.isOpera && parseFloat(opera.version()) < 11))) {
11354 // We need to write the contents here in IE since multiple writes messes up refresh button and back button
11355 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();})()';
11359 // TODO: ACC add the appropriate description on this.
11360 n = DOM.add(o.iframeContainer, 'iframe', {
11361 id : t.id + "_ifr",
11362 src : u || 'javascript:""', // Workaround for HTTPS warning in IE6/7
11364 allowTransparency : "true",
11365 title : s.aria_label,
11372 t.contentAreaContainer = o.iframeContainer;
11373 DOM.get(o.editorContainer).style.display = t.orgDisplay;
11374 DOM.get(t.id).style.display = 'none';
11375 DOM.setAttrib(t.id, 'aria-hidden', true);
11377 if (!tinymce.relaxedDomain || !u)
11380 e = n = o = null; // Cleanup
11383 setupIframe : function(filled) {
11384 var t = this, s = t.settings, e = DOM.get(t.id), d = t.getDoc(), h, b;
11386 // Setup iframe body
11387 if ((!isIE || !tinymce.relaxedDomain) && !filled) {
11388 // We need to wait for the load event on Gecko
11389 if (isGecko && !s.readonly) {
11390 t.getWin().addEventListener("DOMContentLoaded", function() {
11391 window.setTimeout(function() {
11392 var b = t.getBody(), undef;
11394 // Editable element needs to have some contents or backspace/delete won't work properly for some odd reason on FF 3.6 or older
11395 b.innerHTML = '<br>';
11397 // Check if Gecko supports contentEditable mode FF2 doesn't
11398 if (b.contentEditable !== undef) {
11399 // Setting the contentEditable off/on seems to force caret mode in the editor and enabled auto focus
11400 b.contentEditable = false;
11401 b.contentEditable = true;
11403 // Caret doesn't get rendered when you mousedown on the HTML element on FF 3.x
11404 t.onMouseDown.add(function(ed, e) {
11405 if (e.target.nodeName === "HTML") {
11406 // Setting the contentEditable off/on seems to force caret mode in the editor and enabled auto focus
11407 b.contentEditable = false;
11408 b.contentEditable = true;
11410 d.designMode = 'on'; // Render the caret
11412 // Remove design mode again after a while so it has some time to execute
11413 window.setTimeout(function() {
11414 d.designMode = 'off';
11415 t.getBody().focus();
11420 d.designMode = 'on';
11422 // Call setup frame once the contentEditable/designMode has been initialized
11423 // since the caret won't be rendered some times otherwise.
11424 t.setupIframe(true);
11430 d.write(t.iframeHTML);
11433 if (tinymce.relaxedDomain)
11434 d.domain = tinymce.relaxedDomain;
11436 // Wait for iframe onload event on Gecko
11437 if (isGecko && !s.readonly)
11441 // It will not steal focus while setting contentEditable
11445 if (!isGecko && !s.readonly)
11446 b.contentEditable = true;
11448 b.disabled = false;
11450 t.schema = new tinymce.html.Schema(s);
11452 t.dom = new tinymce.dom.DOMUtils(t.getDoc(), {
11453 keep_values : true,
11454 url_converter : t.convertURL,
11455 url_converter_scope : t,
11456 hex_colors : s.force_hex_style_colors,
11457 class_filter : s.class_filter,
11459 fix_ie_paragraphs : 1,
11463 t.parser = new tinymce.html.DomParser(s, t.schema);
11465 // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included.
11466 if (!t.settings.allow_html_in_named_anchor) {
11467 t.parser.addAttributeFilter('name', function(nodes, name) {
11468 var i = nodes.length, sibling, prevSibling, parent, node;
11472 if (node.name === 'a' && node.firstChild) {
11473 parent = node.parent;
11475 // Move children after current node
11476 sibling = node.lastChild;
11478 prevSibling = sibling.prev;
11479 parent.insert(sibling, node);
11480 sibling = prevSibling;
11487 // Convert src and href into data-mce-src, data-mce-href and data-mce-style
11488 t.parser.addAttributeFilter('src,href,style', function(nodes, name) {
11489 var i = nodes.length, node, dom = t.dom, value, internalName;
11493 value = node.attr(name);
11494 internalName = 'data-mce-' + name;
11496 // Add internal attribute if we need to we don't on a refresh of the document
11497 if (!node.attributes.map[internalName]) {
11498 if (name === "style")
11499 node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name));
11501 node.attr(internalName, t.convertURL(value, name, node.name));
11506 // Keep scripts from executing
11507 t.parser.addNodeFilter('script', function(nodes, name) {
11508 var i = nodes.length;
11511 nodes[i].attr('type', 'mce-text/javascript');
11514 t.parser.addNodeFilter('#cdata', function(nodes, name) {
11515 var i = nodes.length, node;
11520 node.name = '#comment';
11521 node.value = '[CDATA[' + node.value + ']]';
11525 t.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) {
11526 var i = nodes.length, node, nonEmptyElements = t.schema.getNonEmptyElements();
11531 if (node.isEmpty(nonEmptyElements))
11532 node.empty().append(new tinymce.html.Node('br', 1)).shortEnded = true;
11536 t.serializer = new tinymce.dom.Serializer(s, t.dom, t.schema);
11538 t.selection = new tinymce.dom.Selection(t.dom, t.getWin(), t.serializer);
11540 t.formatter = new tinymce.Formatter(this);
11542 // Register default formats
11543 t.formatter.register({
11545 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}},
11546 {selector : 'img,table', collapsed : false, styles : {'float' : 'left'}}
11550 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}},
11551 {selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}},
11552 {selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}}
11556 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}},
11557 {selector : 'img,table', collapsed : false, styles : {'float' : 'right'}}
11561 {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}}
11565 {inline : 'strong', remove : 'all'},
11566 {inline : 'span', styles : {fontWeight : 'bold'}},
11567 {inline : 'b', remove : 'all'}
11571 {inline : 'em', remove : 'all'},
11572 {inline : 'span', styles : {fontStyle : 'italic'}},
11573 {inline : 'i', remove : 'all'}
11577 {inline : 'span', styles : {textDecoration : 'underline'}, exact : true},
11578 {inline : 'u', remove : 'all'}
11582 {inline : 'span', styles : {textDecoration : 'line-through'}, exact : true},
11583 {inline : 'strike', remove : 'all'}
11586 forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false},
11587 hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false},
11588 fontname : {inline : 'span', styles : {fontFamily : '%value'}},
11589 fontsize : {inline : 'span', styles : {fontSize : '%value'}},
11590 fontsize_class : {inline : 'span', attributes : {'class' : '%value'}},
11591 blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'},
11592 subscript : {inline : 'sub'},
11593 superscript : {inline : 'sup'},
11596 {selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true},
11597 {selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},
11598 {selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}
11602 // Register default block formats
11603 each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) {
11604 t.formatter.register(name, {block : name, remove : 'all'});
11607 // Register user defined formats
11608 t.formatter.register(t.settings.formats);
11610 t.undoManager = new tinymce.UndoManager(t);
11613 t.undoManager.onAdd.add(function(um, l) {
11615 return t.onChange.dispatch(t, l, um);
11618 t.undoManager.onUndo.add(function(um, l) {
11619 return t.onUndo.dispatch(t, l, um);
11622 t.undoManager.onRedo.add(function(um, l) {
11623 return t.onRedo.dispatch(t, l, um);
11626 t.forceBlocks = new tinymce.ForceBlocks(t, {
11627 forced_root_block : s.forced_root_block
11630 t.editorCommands = new tinymce.EditorCommands(t);
11633 t.serializer.onPreProcess.add(function(se, o) {
11634 return t.onPreProcess.dispatch(t, o, se);
11637 t.serializer.onPostProcess.add(function(se, o) {
11638 return t.onPostProcess.dispatch(t, o, se);
11641 t.onPreInit.dispatch(t);
11643 if (!s.gecko_spellcheck)
11644 t.getBody().spellcheck = 0;
11649 t.controlManager.onPostRender.dispatch(t, t.controlManager);
11650 t.onPostRender.dispatch(t);
11652 t.quirks = new tinymce.util.Quirks(this);
11654 if (s.directionality)
11655 t.getBody().dir = s.directionality;
11658 t.getBody().style.whiteSpace = "nowrap";
11660 if (s.handle_node_change_callback) {
11661 t.onNodeChange.add(function(ed, cm, n) {
11662 t.execCallback('handle_node_change_callback', t.id, n, -1, -1, true, t.selection.isCollapsed());
11666 if (s.save_callback) {
11667 t.onSaveContent.add(function(ed, o) {
11668 var h = t.execCallback('save_callback', t.id, o.content, t.getBody());
11675 if (s.onchange_callback) {
11676 t.onChange.add(function(ed, l) {
11677 t.execCallback('onchange_callback', t, l);
11682 t.onBeforeSetContent.add(function(ed, o) {
11684 each(s.protect, function(pattern) {
11685 o.content = o.content.replace(pattern, function(str) {
11686 return '<!--mce:protected ' + escape(str) + '-->';
11693 if (s.convert_newlines_to_brs) {
11694 t.onBeforeSetContent.add(function(ed, o) {
11696 o.content = o.content.replace(/\r?\n/g, '<br />');
11700 if (s.preformatted) {
11701 t.onPostProcess.add(function(ed, o) {
11702 o.content = o.content.replace(/^\s*<pre.*?>/, '');
11703 o.content = o.content.replace(/<\/pre>\s*$/, '');
11706 o.content = '<pre class="mceItemHidden">' + o.content + '</pre>';
11710 if (s.verify_css_classes) {
11711 t.serializer.attribValueFilter = function(n, v) {
11714 if (n == 'class') {
11715 // Build regexp for classes
11716 if (!t.classesRE) {
11717 cl = t.dom.getClasses();
11719 if (cl.length > 0) {
11722 each (cl, function(o) {
11723 s += (s ? '|' : '') + o['class'];
11726 t.classesRE = new RegExp('(' + s + ')', 'gi');
11730 return !t.classesRE || /(\bmceItem\w+\b|\bmceTemp\w+\b)/g.test(v) || t.classesRE.test(v) ? v : '';
11737 if (s.cleanup_callback) {
11738 t.onBeforeSetContent.add(function(ed, o) {
11739 o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
11742 t.onPreProcess.add(function(ed, o) {
11744 t.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o);
11747 t.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o);
11750 t.onPostProcess.add(function(ed, o) {
11752 o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
11755 o.content = t.execCallback('cleanup_callback', 'get_from_editor', o.content, o);
11759 if (s.save_callback) {
11760 t.onGetContent.add(function(ed, o) {
11762 o.content = t.execCallback('save_callback', t.id, o.content, t.getBody());
11766 if (s.handle_event_callback) {
11767 t.onEvent.add(function(ed, e, o) {
11768 if (t.execCallback('handle_event_callback', e, ed, o) === false)
11773 // Add visual aids when new contents is added
11774 t.onSetContent.add(function() {
11775 t.addVisual(t.getBody());
11778 // Remove empty contents
11779 if (s.padd_empty_editor) {
11780 t.onPostProcess.add(function(ed, o) {
11781 o.content = o.content.replace(/^(<p[^>]*>( | |\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, '');
11786 // Fix gecko link bug, when a link is placed at the end of block elements there is
11787 // no way to move the caret behind the link. This fix adds a bogus br element after the link
11788 function fixLinks(ed, o) {
11789 each(ed.dom.select('a'), function(n) {
11790 var pn = n.parentNode;
11792 if (ed.dom.isBlock(pn) && pn.lastChild === n)
11793 ed.dom.add(pn, 'br', {'data-mce-bogus' : 1});
11797 t.onExecCommand.add(function(ed, cmd) {
11798 if (cmd === 'CreateLink')
11802 t.onSetContent.add(t.selection.onSetContent.add(fixLinks));
11805 t.load({initial : true, format : 'html'});
11806 t.startContent = t.getContent({format : 'raw'});
11807 t.undoManager.add();
11808 t.initialized = true;
11810 t.onInit.dispatch(t);
11811 t.execCallback('setupcontent_callback', t.id, t.getBody(), t.getDoc());
11812 t.execCallback('init_instance_callback', t);
11814 t.nodeChanged({initial : 1});
11816 // Load specified content CSS last
11817 each(t.contentCSS, function(u) {
11821 // Handle auto focus
11822 if (s.auto_focus) {
11823 setTimeout(function () {
11824 var ed = tinymce.get(s.auto_focus);
11826 ed.selection.select(ed.getBody(), 1);
11827 ed.selection.collapse(1);
11828 ed.getBody().focus();
11829 ed.getWin().focus();
11837 focus : function(sf) {
11838 var oed, t = this, selection = t.selection, ce = t.settings.content_editable, ieRng, controlElm, doc = t.getDoc();
11841 // Get selected control element
11842 ieRng = selection.getRng();
11844 controlElm = ieRng.item(0);
11847 selection.normalize();
11849 // Is not content editable
11851 t.getWin().focus();
11853 // Focus the body as well since it's contentEditable
11854 if (tinymce.isGecko) {
11855 t.getBody().focus();
11858 // Restore selected control element
11859 // This is needed when for example an image is selected within a
11860 // layer a call to focus will then remove the control selection
11861 if (controlElm && controlElm.ownerDocument == doc) {
11862 ieRng = doc.body.createControlRange();
11863 ieRng.addElement(controlElm);
11869 if (tinymce.activeEditor != t) {
11870 if ((oed = tinymce.activeEditor) != null)
11871 oed.onDeactivate.dispatch(oed, t);
11873 t.onActivate.dispatch(t, oed);
11876 tinymce._setActive(t);
11879 execCallback : function(n) {
11880 var t = this, f = t.settings[n], s;
11885 // Look through lookup
11886 if (t.callbackLookup && (s = t.callbackLookup[n])) {
11891 if (is(f, 'string')) {
11892 s = f.replace(/\.\w+$/, '');
11893 s = s ? tinymce.resolve(s) : 0;
11894 f = tinymce.resolve(f);
11895 t.callbackLookup = t.callbackLookup || {};
11896 t.callbackLookup[n] = {func : f, scope : s};
11899 return f.apply(s || t, Array.prototype.slice.call(arguments, 1));
11902 translate : function(s) {
11903 var c = this.settings.language || 'en', i18n = tinymce.i18n;
11908 return i18n[c + '.' + s] || s.replace(/{\#([^}]+)\}/g, function(a, b) {
11909 return i18n[c + '.' + b] || '{#' + b + '}';
11913 getLang : function(n, dv) {
11914 return tinymce.i18n[(this.settings.language || 'en') + '.' + n] || (is(dv) ? dv : '{#' + n + '}');
11917 getParam : function(n, dv, ty) {
11918 var tr = tinymce.trim, v = is(this.settings[n]) ? this.settings[n] : dv, o;
11920 if (ty === 'hash') {
11923 if (is(v, 'string')) {
11924 each(v.indexOf('=') > 0 ? v.split(/[;,](?![^=;,]*(?:[;,]|$))/) : v.split(','), function(v) {
11928 o[tr(v[0])] = tr(v[1]);
11930 o[tr(v[0])] = tr(v);
11941 nodeChanged : function(o) {
11942 var t = this, s = t.selection, n = s.getStart() || t.getBody();
11944 // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
11945 if (t.initialized) {
11947 n = isIE && n.ownerDocument != t.getDoc() ? t.getBody() : n; // Fix for IE initial state
11949 // Get parents and add them to object
11951 t.dom.getParent(n, function(node) {
11952 if (node.nodeName == 'BODY')
11955 o.parents.push(node);
11958 t.onNodeChange.dispatch(
11960 o ? o.controlManager || t.controlManager : t.controlManager,
11968 addButton : function(n, s) {
11971 t.buttons = t.buttons || {};
11975 addCommand : function(name, callback, scope) {
11976 this.execCommands[name] = {func : callback, scope : scope || this};
11979 addQueryStateHandler : function(name, callback, scope) {
11980 this.queryStateCommands[name] = {func : callback, scope : scope || this};
11983 addQueryValueHandler : function(name, callback, scope) {
11984 this.queryValueCommands[name] = {func : callback, scope : scope || this};
11987 addShortcut : function(pa, desc, cmd_func, sc) {
11990 if (!t.settings.custom_shortcuts)
11993 t.shortcuts = t.shortcuts || {};
11995 if (is(cmd_func, 'string')) {
11998 cmd_func = function() {
11999 t.execCommand(c, false, null);
12003 if (is(cmd_func, 'object')) {
12006 cmd_func = function() {
12007 t.execCommand(c[0], c[1], c[2]);
12011 each(explode(pa), function(pa) {
12014 scope : sc || this,
12021 each(explode(pa, '+'), function(v) {
12030 o.charCode = v.charCodeAt(0);
12031 o.keyCode = v.toUpperCase().charCodeAt(0);
12035 t.shortcuts[(o.ctrl ? 'ctrl' : '') + ',' + (o.alt ? 'alt' : '') + ',' + (o.shift ? 'shift' : '') + ',' + o.keyCode] = o;
12041 execCommand : function(cmd, ui, val, a) {
12042 var t = this, s = 0, o, st;
12044 if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(cmd) && (!a || !a.skip_focus))
12048 t.onBeforeExecCommand.dispatch(t, cmd, ui, val, o);
12052 // Command callback
12053 if (t.execCallback('execcommand_callback', t.id, t.selection.getNode(), cmd, ui, val)) {
12054 t.onExecCommand.dispatch(t, cmd, ui, val, a);
12058 // Registred commands
12059 if (o = t.execCommands[cmd]) {
12060 st = o.func.call(o.scope, ui, val);
12062 // Fall through on true
12064 t.onExecCommand.dispatch(t, cmd, ui, val, a);
12070 each(t.plugins, function(p) {
12071 if (p.execCommand && p.execCommand(cmd, ui, val)) {
12072 t.onExecCommand.dispatch(t, cmd, ui, val, a);
12082 if (t.theme && t.theme.execCommand && t.theme.execCommand(cmd, ui, val)) {
12083 t.onExecCommand.dispatch(t, cmd, ui, val, a);
12088 if (t.editorCommands.execCommand(cmd, ui, val)) {
12089 t.onExecCommand.dispatch(t, cmd, ui, val, a);
12093 // Browser commands
12094 t.getDoc().execCommand(cmd, ui, val);
12095 t.onExecCommand.dispatch(t, cmd, ui, val, a);
12098 queryCommandState : function(cmd) {
12099 var t = this, o, s;
12101 // Is hidden then return undefined
12105 // Registred commands
12106 if (o = t.queryStateCommands[cmd]) {
12107 s = o.func.call(o.scope);
12109 // Fall though on true
12114 // Registred commands
12115 o = t.editorCommands.queryCommandState(cmd);
12119 // Browser commands
12121 return this.getDoc().queryCommandState(cmd);
12123 // Fails sometimes see bug: 1896577
12127 queryCommandValue : function(c) {
12128 var t = this, o, s;
12130 // Is hidden then return undefined
12134 // Registred commands
12135 if (o = t.queryValueCommands[c]) {
12136 s = o.func.call(o.scope);
12138 // Fall though on true
12143 // Registred commands
12144 o = t.editorCommands.queryCommandValue(c);
12148 // Browser commands
12150 return this.getDoc().queryCommandValue(c);
12152 // Fails sometimes see bug: 1896577
12156 show : function() {
12159 DOM.show(t.getContainer());
12164 hide : function() {
12165 var t = this, d = t.getDoc();
12167 // Fixed bug where IE has a blinking cursor left from the editor
12169 d.execCommand('SelectAll');
12171 // We must save before we hide so Safari doesn't crash
12173 DOM.hide(t.getContainer());
12174 DOM.setStyle(t.id, 'display', t.orgDisplay);
12177 isHidden : function() {
12178 return !DOM.isHidden(this.id);
12181 setProgressState : function(b, ti, o) {
12182 this.onSetProgressState.dispatch(this, b, ti, o);
12187 load : function(o) {
12188 var t = this, e = t.getElement(), h;
12194 // Double encode existing entities in the value
12195 h = t.setContent(is(e.value) ? e.value : e.innerHTML, o);
12199 t.onLoadContent.dispatch(t, o);
12201 o.element = e = null;
12207 save : function(o) {
12208 var t = this, e = t.getElement(), h, f;
12210 if (!e || !t.initialized)
12216 // Add undo level will trigger onchange event
12217 if (!o.no_events) {
12218 t.undoManager.typing = false;
12219 t.undoManager.add();
12223 h = o.content = t.getContent(o);
12226 t.onSaveContent.dispatch(t, o);
12230 if (!/TEXTAREA|INPUT/i.test(e.nodeName)) {
12233 // Update hidden form element
12234 if (f = DOM.getParent(t.id, 'form')) {
12235 each(f.elements, function(e) {
12236 if (e.name == t.id) {
12245 o.element = e = null;
12250 setContent : function(content, args) {
12251 var self = this, rootNode, body = self.getBody(), forcedRootBlockName;
12253 // Setup args object
12255 args.format = args.format || 'html';
12257 args.content = content;
12259 // Do preprocessing
12260 if (!args.no_events)
12261 self.onBeforeSetContent.dispatch(self, args);
12263 content = args.content;
12265 // Padd empty content in Gecko and Safari. Commands will otherwise fail on the content
12266 // It will also be impossible to place the caret in the editor unless there is a BR element present
12267 if (!tinymce.isIE && (content.length === 0 || /^\s+$/.test(content))) {
12268 forcedRootBlockName = self.settings.forced_root_block;
12269 if (forcedRootBlockName)
12270 content = '<' + forcedRootBlockName + '><br data-mce-bogus="1"></' + forcedRootBlockName + '>';
12272 content = '<br data-mce-bogus="1">';
12274 body.innerHTML = content;
12275 self.selection.select(body, true);
12276 self.selection.collapse(true);
12280 // Parse and serialize the html
12281 if (args.format !== 'raw') {
12282 content = new tinymce.html.Serializer({}, self.schema).serialize(
12283 self.parser.parse(content)
12287 // Set the new cleaned contents to the editor
12288 args.content = tinymce.trim(content);
12289 self.dom.setHTML(body, args.content);
12291 // Do post processing
12292 if (!args.no_events)
12293 self.onSetContent.dispatch(self, args);
12295 self.selection.normalize();
12297 return args.content;
12300 getContent : function(args) {
12301 var self = this, content;
12303 // Setup args object
12305 args.format = args.format || 'html';
12308 // Do preprocessing
12309 if (!args.no_events)
12310 self.onBeforeGetContent.dispatch(self, args);
12312 // Get raw contents or by default the cleaned contents
12313 if (args.format == 'raw')
12314 content = self.getBody().innerHTML;
12316 content = self.serializer.serialize(self.getBody(), args);
12318 args.content = tinymce.trim(content);
12320 // Do post processing
12321 if (!args.no_events)
12322 self.onGetContent.dispatch(self, args);
12324 return args.content;
12327 isDirty : function() {
12330 return tinymce.trim(self.startContent) != tinymce.trim(self.getContent({format : 'raw', no_events : 1})) && !self.isNotDirty;
12333 getContainer : function() {
12337 t.container = DOM.get(t.editorContainer || t.id + '_parent');
12339 return t.container;
12342 getContentAreaContainer : function() {
12343 return this.contentAreaContainer;
12346 getElement : function() {
12347 return DOM.get(this.settings.content_element || this.id);
12350 getWin : function() {
12353 if (!t.contentWindow) {
12354 e = DOM.get(t.id + "_ifr");
12357 t.contentWindow = e.contentWindow;
12360 return t.contentWindow;
12363 getDoc : function() {
12366 if (!t.contentDocument) {
12370 t.contentDocument = w.document;
12373 return t.contentDocument;
12376 getBody : function() {
12377 return this.bodyElement || this.getDoc().body;
12380 convertURL : function(u, n, e) {
12381 var t = this, s = t.settings;
12383 // Use callback instead
12384 if (s.urlconverter_callback)
12385 return t.execCallback('urlconverter_callback', u, e, true, n);
12387 // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
12388 if (!s.convert_urls || (e && e.nodeName == 'LINK') || u.indexOf('file:') === 0)
12391 // Convert to relative
12392 if (s.relative_urls)
12393 return t.documentBaseURI.toRelative(u);
12395 // Convert to absolute
12396 u = t.documentBaseURI.toAbsolute(u, s.remove_script_host);
12401 addVisual : function(e) {
12402 var t = this, s = t.settings;
12404 e = e || t.getBody();
12406 if (!is(t.hasVisual))
12407 t.hasVisual = s.visual;
12409 each(t.dom.select('table,a', e), function(e) {
12412 switch (e.nodeName) {
12414 v = t.dom.getAttrib(e, 'border');
12416 if (!v || v == '0') {
12418 t.dom.addClass(e, s.visual_table_class);
12420 t.dom.removeClass(e, s.visual_table_class);
12426 v = t.dom.getAttrib(e, 'name');
12430 t.dom.addClass(e, 'mceItemAnchor');
12432 t.dom.removeClass(e, 'mceItemAnchor');
12439 t.onVisualAid.dispatch(t, e, t.hasVisual);
12442 remove : function() {
12443 var t = this, e = t.getContainer();
12445 t.removed = 1; // Cancels post remove event execution
12448 t.execCallback('remove_instance_callback', t);
12449 t.onRemove.dispatch(t);
12451 // Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command
12452 t.onExecCommand.listeners = [];
12458 destroy : function(s) {
12461 // One time is enough
12466 tinymce.removeUnload(t.destroy);
12467 tinyMCE.onBeforeUnload.remove(t._beforeUnload);
12470 if (t.theme && t.theme.destroy)
12473 // Destroy controls, selection and dom
12474 t.controlManager.destroy();
12475 t.selection.destroy();
12478 // Remove all events
12480 // Don't clear the window or document if content editable
12481 // is enabled since other instances might still be present
12482 if (!t.settings.content_editable) {
12483 Event.clear(t.getWin());
12484 Event.clear(t.getDoc());
12487 Event.clear(t.getBody());
12488 Event.clear(t.formElement);
12491 if (t.formElement) {
12492 t.formElement.submit = t.formElement._mceOldSubmit;
12493 t.formElement._mceOldSubmit = null;
12496 t.contentAreaContainer = t.formElement = t.container = t.settings.content_element = t.bodyElement = t.contentDocument = t.contentWindow = null;
12499 t.selection = t.selection.win = t.selection.dom = t.selection.dom.doc = null;
12504 // Internal functions
12506 _addEvents : function() {
12507 // 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset
12508 var t = this, i, s = t.settings, dom = t.dom, lo = {
12509 mouseup : 'onMouseUp',
12510 mousedown : 'onMouseDown',
12513 keydown : 'onKeyDown',
12514 keypress : 'onKeyPress',
12515 submit : 'onSubmit',
12517 contextmenu : 'onContextMenu',
12518 dblclick : 'onDblClick',
12519 paste : 'onPaste' // Doesn't work in all browsers yet
12522 function eventHandler(e, o) {
12525 // Don't fire events when it's removed
12529 // Generic event handler
12530 if (t.onEvent.dispatch(t, e, o) !== false) {
12531 // Specific event handler
12532 t[lo[e.fakeType || e.type]].dispatch(t, e, o);
12537 each(lo, function(v, k) {
12539 case 'contextmenu':
12540 dom.bind(t.getDoc(), k, eventHandler);
12544 dom.bind(t.getBody(), k, function(e) {
12551 dom.bind(t.getElement().form || DOM.getParent(t.id, 'form'), k, eventHandler);
12555 dom.bind(s.content_editable ? t.getBody() : t.getDoc(), k, eventHandler);
12559 dom.bind(s.content_editable ? t.getBody() : (isGecko ? t.getDoc() : t.getWin()), 'focus', function(e) {
12564 // Fixes bug where a specified document_base_uri could result in broken images
12565 // This will also fix drag drop of images in Gecko
12566 if (tinymce.isGecko) {
12567 dom.bind(t.getDoc(), 'DOMNodeInserted', function(e) {
12572 if (e.nodeType === 1 && e.nodeName === 'IMG' && (v = e.getAttribute('data-mce-src')))
12573 e.src = t.documentBaseURI.toAbsolute(v);
12577 // Set various midas options in Gecko
12579 function setOpts() {
12580 var t = this, d = t.getDoc(), s = t.settings;
12582 if (isGecko && !s.readonly) {
12583 if (t._isHidden()) {
12585 if (!s.content_editable) {
12586 d.body.contentEditable = false;
12587 d.body.contentEditable = true;
12590 // Fails if it's hidden
12595 // Try new Gecko method
12596 d.execCommand("styleWithCSS", 0, false);
12599 if (!t._isHidden())
12600 try {d.execCommand("useCSS", 0, true);} catch (ex) {}
12603 if (!s.table_inline_editing)
12604 try {d.execCommand('enableInlineTableEditing', false, false);} catch (ex) {}
12606 if (!s.object_resizing)
12607 try {d.execCommand('enableObjectResizing', false, false);} catch (ex) {}
12611 t.onBeforeExecCommand.add(setOpts);
12612 t.onMouseDown.add(setOpts);
12615 t.onClick.add(function(ed, e) {
12618 // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
12619 // WebKit can't even do simple things like selecting an image
12620 // Needs tobe the setBaseAndExtend or it will fail to select floated images
12621 if (tinymce.isWebKit && e.nodeName == 'IMG')
12622 t.selection.getSel().setBaseAndExtent(e, 0, e, 1);
12624 if (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor'))
12625 t.selection.select(e);
12630 // Add node change handlers
12631 t.onMouseUp.add(t.nodeChanged);
12632 //t.onClick.add(t.nodeChanged);
12633 t.onKeyUp.add(function(ed, e) {
12636 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)
12641 // Add block quote deletion handler
12642 t.onKeyDown.add(function(ed, e) {
12643 // Was the BACKSPACE key pressed?
12644 if (e.keyCode != 8)
12647 var n = ed.selection.getRng().startContainer;
12648 var offset = ed.selection.getRng().startOffset;
12650 while (n && n.nodeType && n.nodeType != 1 && n.parentNode)
12653 // Is the cursor at the beginning of a blockquote?
12654 if (n && n.parentNode && n.parentNode.tagName === 'BLOCKQUOTE' && n.parentNode.firstChild == n && offset == 0) {
12655 // Remove the blockquote
12656 ed.formatter.toggle('blockquote', null, n.parentNode);
12658 // Move the caret to the beginning of n
12659 var rng = ed.selection.getRng();
12660 rng.setStart(n, 0);
12662 ed.selection.setRng(rng);
12663 ed.selection.collapse(false);
12669 // Add reset handler
12670 t.onReset.add(function() {
12671 t.setContent(t.startContent, {format : 'raw'});
12675 if (s.custom_shortcuts) {
12676 if (s.custom_undo_redo_keyboard_shortcuts) {
12677 t.addShortcut('ctrl+z', t.getLang('undo_desc'), 'Undo');
12678 t.addShortcut('ctrl+y', t.getLang('redo_desc'), 'Redo');
12681 // Add default shortcuts for gecko
12682 t.addShortcut('ctrl+b', t.getLang('bold_desc'), 'Bold');
12683 t.addShortcut('ctrl+i', t.getLang('italic_desc'), 'Italic');
12684 t.addShortcut('ctrl+u', t.getLang('underline_desc'), 'Underline');
12686 // BlockFormat shortcuts keys
12687 for (i=1; i<=6; i++)
12688 t.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
12690 t.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']);
12691 t.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']);
12692 t.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']);
12697 if (!e.altKey && !e.ctrlKey && !e.metaKey)
12700 each(t.shortcuts, function(o) {
12701 if (tinymce.isMac && o.ctrl != e.metaKey)
12703 else if (!tinymce.isMac && o.ctrl != e.ctrlKey)
12706 if (o.alt != e.altKey)
12709 if (o.shift != e.shiftKey)
12712 if (e.keyCode == o.keyCode || (e.charCode && e.charCode == o.charCode)) {
12721 t.onKeyUp.add(function(ed, e) {
12725 return Event.cancel(e);
12728 t.onKeyPress.add(function(ed, e) {
12732 return Event.cancel(e);
12735 t.onKeyDown.add(function(ed, e) {
12739 o.func.call(o.scope);
12740 return Event.cancel(e);
12745 if (tinymce.isIE) {
12746 // Fix so resize will only update the width and height attributes not the styles of an image
12747 // It will also block mceItemNoResize items
12748 dom.bind(t.getDoc(), 'controlselect', function(e) {
12749 var re = t.resizeInfo, cb;
12753 // Don't do this action for non image elements
12754 if (e.nodeName !== 'IMG')
12758 dom.unbind(re.node, re.ev, re.cb);
12760 if (!dom.hasClass(e, 'mceItemNoResize')) {
12762 cb = dom.bind(e, ev, function(e) {
12767 if (v = dom.getStyle(e, 'width')) {
12768 dom.setAttrib(e, 'width', v.replace(/[^0-9%]+/g, ''));
12769 dom.setStyle(e, 'width', '');
12772 if (v = dom.getStyle(e, 'height')) {
12773 dom.setAttrib(e, 'height', v.replace(/[^0-9%]+/g, ''));
12774 dom.setStyle(e, 'height', '');
12778 ev = 'resizestart';
12779 cb = dom.bind(e, 'resizestart', Event.cancel, Event);
12782 re = t.resizeInfo = {
12790 if (tinymce.isOpera) {
12791 t.onClick.add(function(ed, e) {
12796 // Add custom undo/redo handlers
12797 if (s.custom_undo_redo) {
12798 function addUndo() {
12799 t.undoManager.typing = false;
12800 t.undoManager.add();
12803 dom.bind(t.getDoc(), 'focusout', function(e) {
12804 if (!t.removed && t.undoManager.typing)
12808 // Add undo level when contents is drag/dropped within the editor
12809 t.dom.bind(t.dom.getRoot(), 'dragend', function(e) {
12813 t.onKeyUp.add(function(ed, e) {
12814 var keyCode = e.keyCode;
12816 if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45 || e.ctrlKey)
12820 t.onKeyDown.add(function(ed, e) {
12821 var keyCode = e.keyCode, sel;
12823 if (keyCode == 8) {
12824 sel = t.getDoc().selection;
12826 // Fix IE control + backspace browser bug
12827 if (sel && sel.createRange && sel.createRange().item) {
12828 t.undoManager.beforeChange();
12829 ed.dom.remove(sel.createRange().item(0));
12832 return Event.cancel(e);
12836 // Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter
12837 if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45) {
12838 // Add position before enter key is pressed, used by IE since it still uses the default browser behavior
12839 // Todo: Remove this once we normalize enter behavior on IE
12840 if (tinymce.isIE && keyCode == 13)
12841 t.undoManager.beforeChange();
12843 if (t.undoManager.typing)
12849 // If key isn't shift,ctrl,alt,capslock,metakey
12850 if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !t.undoManager.typing) {
12851 t.undoManager.beforeChange();
12852 t.undoManager.typing = true;
12853 t.undoManager.add();
12857 t.onMouseDown.add(function() {
12858 if (t.undoManager.typing)
12863 // Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5
12864 // It only fires the nodeChange event every 50ms since it would other wise update the UI when you type and it hogs the CPU
12865 if (tinymce.isWebKit) {
12866 dom.bind(t.getDoc(), 'selectionchange', function() {
12867 if (t.selectionTimer) {
12868 window.clearTimeout(t.selectionTimer);
12869 t.selectionTimer = 0;
12872 t.selectionTimer = window.setTimeout(function() {
12878 // Bug fix for FireFox keeping styles from end of selection instead of start.
12879 if (tinymce.isGecko) {
12880 function getAttributeApplyFunction() {
12881 var template = t.dom.getAttribs(t.selection.getStart().cloneNode(false));
12883 return function() {
12884 var target = t.selection.getStart();
12886 if (target !== t.getBody()) {
12887 t.dom.removeAllAttribs(target);
12889 each(template, function(attr) {
12890 target.setAttributeNode(attr.cloneNode(true));
12896 function isSelectionAcrossElements() {
12897 var s = t.selection;
12899 return !s.isCollapsed() && s.getStart() != s.getEnd();
12902 t.onKeyPress.add(function(ed, e) {
12903 var applyAttributes;
12905 if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {
12906 applyAttributes = getAttributeApplyFunction();
12907 t.getDoc().execCommand('delete', false, null);
12910 return Event.cancel(e);
12914 t.dom.bind(t.getDoc(), 'cut', function(e) {
12915 var applyAttributes;
12917 if (isSelectionAcrossElements()) {
12918 applyAttributes = getAttributeApplyFunction();
12919 t.onKeyUp.addToTop(Event.cancel, Event);
12921 setTimeout(function() {
12923 t.onKeyUp.remove(Event.cancel, Event);
12930 _isHidden : function() {
12936 // Weird, wheres that cursor selection?
12937 s = this.selection.getSel();
12938 return (!s || !s.rangeCount || s.rangeCount == 0);
12943 (function(tinymce) {
12944 // Added for compression purposes
12945 var each = tinymce.each, undefined, TRUE = true, FALSE = false;
12947 tinymce.EditorCommands = function(editor) {
12948 var dom = editor.dom,
12949 selection = editor.selection,
12950 commands = {state: {}, exec : {}, value : {}},
12951 settings = editor.settings,
12954 function execCommand(command, ui, value) {
12957 command = command.toLowerCase();
12958 if (func = commands.exec[command]) {
12959 func(command, ui, value);
12966 function queryCommandState(command) {
12969 command = command.toLowerCase();
12970 if (func = commands.state[command])
12971 return func(command);
12976 function queryCommandValue(command) {
12979 command = command.toLowerCase();
12980 if (func = commands.value[command])
12981 return func(command);
12986 function addCommands(command_list, type) {
12987 type = type || 'exec';
12989 each(command_list, function(callback, command) {
12990 each(command.toLowerCase().split(','), function(command) {
12991 commands[type][command] = callback;
12996 // Expose public methods
12997 tinymce.extend(this, {
12998 execCommand : execCommand,
12999 queryCommandState : queryCommandState,
13000 queryCommandValue : queryCommandValue,
13001 addCommands : addCommands
13006 function execNativeCommand(command, ui, value) {
13007 if (ui === undefined)
13010 if (value === undefined)
13013 return editor.getDoc().execCommand(command, ui, value);
13016 function isFormatMatch(name) {
13017 return editor.formatter.match(name);
13020 function toggleFormat(name, value) {
13021 editor.formatter.toggle(name, value ? {value : value} : undefined);
13024 function storeSelection(type) {
13025 bookmark = selection.getBookmark(type);
13028 function restoreSelection() {
13029 selection.moveToBookmark(bookmark);
13032 // Add execCommand overrides
13034 // Ignore these, added for compatibility
13035 'mceResetDesignMode,mceBeginUndoLevel' : function() {},
13037 // Add undo manager logic
13038 'mceEndUndoLevel,mceAddUndoLevel' : function() {
13039 editor.undoManager.add();
13042 'Cut,Copy,Paste' : function(command) {
13043 var doc = editor.getDoc(), failed;
13045 // Try executing the native command
13047 execNativeCommand(command);
13053 // Present alert message about clipboard access not being available
13054 if (failed || !doc.queryCommandSupported(command)) {
13055 if (tinymce.isGecko) {
13056 editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) {
13058 open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank');
13061 editor.windowManager.alert(editor.getLang('clipboard_no_support'));
13065 // Override unlink command
13066 unlink : function(command) {
13067 if (selection.isCollapsed())
13068 selection.select(selection.getNode());
13070 execNativeCommand(command);
13071 selection.collapse(FALSE);
13074 // Override justify commands to use the text formatter engine
13075 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {
13076 var align = command.substring(7);
13078 // Remove all other alignments first
13079 each('left,center,right,full'.split(','), function(name) {
13081 editor.formatter.remove('align' + name);
13084 toggleFormat('align' + align);
13085 execCommand('mceRepaint');
13088 // Override list commands to fix WebKit bug
13089 'InsertUnorderedList,InsertOrderedList' : function(command) {
13090 var listElm, listParent;
13092 execNativeCommand(command);
13094 // WebKit produces lists within block elements so we need to split them
13095 // we will replace the native list creation logic to custom logic later on
13096 // TODO: Remove this when the list creation logic is removed
13097 listElm = dom.getParent(selection.getNode(), 'ol,ul');
13099 listParent = listElm.parentNode;
13101 // If list is within a text block then split that block
13102 if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
13104 dom.split(listParent, listElm);
13105 restoreSelection();
13110 // Override commands to use the text formatter engine
13111 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {
13112 toggleFormat(command);
13115 // Override commands to use the text formatter engine
13116 'ForeColor,HiliteColor,FontName' : function(command, ui, value) {
13117 toggleFormat(command, value);
13120 FontSize : function(command, ui, value) {
13121 var fontClasses, fontSizes;
13123 // Convert font size 1-7 to styles
13124 if (value >= 1 && value <= 7) {
13125 fontSizes = tinymce.explode(settings.font_size_style_values);
13126 fontClasses = tinymce.explode(settings.font_size_classes);
13129 value = fontClasses[value - 1] || value;
13131 value = fontSizes[value - 1] || value;
13134 toggleFormat(command, value);
13137 RemoveFormat : function(command) {
13138 editor.formatter.remove(command);
13141 mceBlockQuote : function(command) {
13142 toggleFormat('blockquote');
13145 FormatBlock : function(command, ui, value) {
13146 return toggleFormat(value || 'p');
13149 mceCleanup : function() {
13150 var bookmark = selection.getBookmark();
13152 editor.setContent(editor.getContent({cleanup : TRUE}), {cleanup : TRUE});
13154 selection.moveToBookmark(bookmark);
13157 mceRemoveNode : function(command, ui, value) {
13158 var node = value || selection.getNode();
13160 // Make sure that the body node isn't removed
13161 if (node != editor.getBody()) {
13163 editor.dom.remove(node, TRUE);
13164 restoreSelection();
13168 mceSelectNodeDepth : function(command, ui, value) {
13171 dom.getParent(selection.getNode(), function(node) {
13172 if (node.nodeType == 1 && counter++ == value) {
13173 selection.select(node);
13176 }, editor.getBody());
13179 mceSelectNode : function(command, ui, value) {
13180 selection.select(value);
13183 mceInsertContent : function(command, ui, value) {
13184 var parser, serializer, parentNode, rootNode, fragment, args,
13185 marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement;
13187 // Setup parser and serializer
13188 parser = editor.parser;
13189 serializer = new tinymce.html.Serializer({}, editor.schema);
13190 bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>';
13192 // Run beforeSetContent handlers on the HTML to be inserted
13193 args = {content: value, format: 'html'};
13194 selection.onBeforeSetContent.dispatch(selection, args);
13195 value = args.content;
13197 // Add caret at end of contents if it's missing
13198 if (value.indexOf('{$caret}') == -1)
13199 value += '{$caret}';
13201 // Replace the caret marker with a span bookmark element
13202 value = value.replace(/\{\$caret\}/, bookmarkHtml);
13204 // Insert node maker where we will insert the new HTML and get it's parent
13205 if (!selection.isCollapsed())
13206 editor.getDoc().execCommand('Delete', false, null);
13208 parentNode = selection.getNode();
13210 // Parse the fragment within the context of the parent node
13211 args = {context : parentNode.nodeName.toLowerCase()};
13212 fragment = parser.parse(value, args);
13214 // Move the caret to a more suitable location
13215 node = fragment.lastChild;
13216 if (node.attr('id') == 'mce_marker') {
13219 for (node = node.prev; node; node = node.walk(true)) {
13220 if (node.type == 3 || !dom.isBlock(node.name)) {
13221 node.parent.insert(marker, node, node.name === 'br');
13227 // If parser says valid we can insert the contents into that parent
13228 if (!args.invalid) {
13229 value = serializer.serialize(fragment);
13231 // Check if parent is empty or only has one BR element then set the innerHTML of that parent
13232 node = parentNode.firstChild;
13233 node2 = parentNode.lastChild;
13234 if (!node || (node === node2 && node.nodeName === 'BR'))
13235 dom.setHTML(parentNode, value);
13237 selection.setContent(value);
13239 // If the fragment was invalid within that context then we need
13240 // to parse and process the parent it's inserted into
13242 // Insert bookmark node and get the parent
13243 selection.setContent(bookmarkHtml);
13244 parentNode = editor.selection.getNode();
13245 rootNode = editor.getBody();
13247 // Opera will return the document node when selection is in root
13248 if (parentNode.nodeType == 9)
13249 parentNode = node = rootNode;
13253 // Find the ancestor just before the root element
13254 while (node !== rootNode) {
13256 node = node.parentNode;
13259 // Get the outer/inner HTML depending on if we are in the root and parser and serialize that
13260 value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
13261 value = serializer.serialize(
13263 // Need to replace by using a function since $ in the contents would otherwise be a problem
13264 value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
13265 return serializer.serialize(fragment);
13270 // Set the inner/outer HTML depending on if we are in the root or not
13271 if (parentNode == rootNode)
13272 dom.setHTML(rootNode, value);
13274 dom.setOuterHTML(parentNode, value);
13277 marker = dom.get('mce_marker');
13279 // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well
13280 nodeRect = dom.getRect(marker);
13281 viewPortRect = dom.getViewPort(editor.getWin());
13283 // Check if node is out side the viewport if it is then scroll to it
13284 if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) ||
13285 (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) {
13286 viewportBodyElement = tinymce.isIE ? editor.getDoc().documentElement : editor.getBody();
13287 viewportBodyElement.scrollLeft = nodeRect.x;
13288 viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25;
13291 // Move selection before marker and remove it
13292 rng = dom.createRng();
13294 // If previous sibling is a text node set the selection to the end of that node
13295 node = marker.previousSibling;
13296 if (node && node.nodeType == 3) {
13297 rng.setStart(node, node.nodeValue.length);
13299 // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node
13300 rng.setStartBefore(marker);
13301 rng.setEndBefore(marker);
13304 // Remove the marker node and set the new range
13305 dom.remove(marker);
13306 selection.setRng(rng);
13308 // Dispatch after event and add any visual elements needed
13309 selection.onSetContent.dispatch(selection, args);
13310 editor.addVisual();
13313 mceInsertRawHTML : function(command, ui, value) {
13314 selection.setContent('tiny_mce_marker');
13315 editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value }));
13318 mceSetContent : function(command, ui, value) {
13319 editor.setContent(value);
13322 'Indent,Outdent' : function(command) {
13323 var intentValue, indentUnit, value;
13325 // Setup indent level
13326 intentValue = settings.indentation;
13327 indentUnit = /[a-z%]+$/i.exec(intentValue);
13328 intentValue = parseInt(intentValue);
13330 if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {
13331 each(selection.getSelectedBlocks(), function(element) {
13332 if (command == 'outdent') {
13333 value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue);
13334 dom.setStyle(element, 'paddingLeft', value ? value + indentUnit : '');
13336 dom.setStyle(element, 'paddingLeft', (parseInt(element.style.paddingLeft || 0) + intentValue) + indentUnit);
13339 execNativeCommand(command);
13342 mceRepaint : function() {
13345 if (tinymce.isGecko) {
13347 storeSelection(TRUE);
13349 if (selection.getSel())
13350 selection.getSel().selectAllChildren(editor.getBody());
13352 selection.collapse(TRUE);
13353 restoreSelection();
13360 mceToggleFormat : function(command, ui, value) {
13361 editor.formatter.toggle(value);
13364 InsertHorizontalRule : function() {
13365 editor.execCommand('mceInsertContent', false, '<hr />');
13368 mceToggleVisualAid : function() {
13369 editor.hasVisual = !editor.hasVisual;
13370 editor.addVisual();
13373 mceReplaceContent : function(command, ui, value) {
13374 editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'})));
13377 mceInsertLink : function(command, ui, value) {
13378 var link = dom.getParent(selection.getNode(), 'a'), img, style, cls;
13380 if (tinymce.is(value, 'string'))
13381 value = {href : value};
13383 // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
13384 value.href = value.href.replace(' ', '%20');
13387 // WebKit can't create links on floated images for some odd reason
13388 // So, just remove styles and restore it later
13389 if (tinymce.isWebKit) {
13390 img = dom.getParent(selection.getNode(), 'img');
13393 style = img.style.cssText;
13394 cls = img.className;
13395 img.style.cssText = null;
13396 img.className = null;
13400 execNativeCommand('CreateLink', FALSE, 'javascript:mctmp(0);');
13404 img.style.cssText = style;
13406 img.className = cls;
13408 each(dom.select("a[href='javascript:mctmp(0);']"), function(link) {
13409 dom.setAttribs(link, value);
13413 dom.setAttribs(link, value);
13415 editor.dom.remove(link, TRUE);
13419 selectAll : function() {
13420 var root = dom.getRoot(), rng = dom.createRng();
13422 rng.setStart(root, 0);
13423 rng.setEnd(root, root.childNodes.length);
13425 editor.selection.setRng(rng);
13429 // Add queryCommandState overrides
13431 // Override justify commands
13432 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {
13433 return isFormatMatch('align' + command.substring(7));
13436 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {
13437 return isFormatMatch(command);
13440 mceBlockQuote : function() {
13441 return isFormatMatch('blockquote');
13444 Outdent : function() {
13447 if (settings.inline_styles) {
13448 if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0)
13451 if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0)
13455 return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE'));
13458 'InsertUnorderedList,InsertOrderedList' : function(command) {
13459 return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL');
13463 // Add queryCommandValue overrides
13465 'FontSize,FontName' : function(command) {
13466 var value = 0, parent;
13468 if (parent = dom.getParent(selection.getNode(), 'span')) {
13469 if (command == 'fontsize')
13470 value = parent.style.fontSize;
13472 value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase();
13479 // Add undo manager logic
13480 if (settings.custom_undo_redo) {
13482 Undo : function() {
13483 editor.undoManager.undo();
13486 Redo : function() {
13487 editor.undoManager.redo();
13494 (function(tinymce) {
13495 var Dispatcher = tinymce.util.Dispatcher;
13497 tinymce.UndoManager = function(editor) {
13498 var self, index = 0, data = [], beforeBookmark;
13500 function getContent() {
13501 return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}));
13507 onAdd : new Dispatcher(self),
13509 onUndo : new Dispatcher(self),
13511 onRedo : new Dispatcher(self),
13513 beforeChange : function() {
13514 beforeBookmark = editor.selection.getBookmark(2, true);
13517 add : function(level) {
13518 var i, settings = editor.settings, lastLevel;
13520 level = level || {};
13521 level.content = getContent();
13523 // Add undo level if needed
13524 lastLevel = data[index];
13525 if (lastLevel && lastLevel.content == level.content)
13528 // Set before bookmark on previous level
13530 data[index].beforeBookmark = beforeBookmark;
13532 // Time to compress
13533 if (settings.custom_undo_redo_levels) {
13534 if (data.length > settings.custom_undo_redo_levels) {
13535 for (i = 0; i < data.length - 1; i++)
13536 data[i] = data[i + 1];
13539 index = data.length;
13543 // Get a non intrusive normalized bookmark
13544 level.bookmark = editor.selection.getBookmark(2, true);
13546 // Crop array if needed
13547 if (index < data.length - 1)
13548 data.length = index + 1;
13551 index = data.length - 1;
13553 self.onAdd.dispatch(self, level);
13554 editor.isNotDirty = 0;
13559 undo : function() {
13564 self.typing = false;
13568 level = data[--index];
13570 editor.setContent(level.content, {format : 'raw'});
13571 editor.selection.moveToBookmark(level.beforeBookmark);
13573 self.onUndo.dispatch(self, level);
13579 redo : function() {
13582 if (index < data.length - 1) {
13583 level = data[++index];
13585 editor.setContent(level.content, {format : 'raw'});
13586 editor.selection.moveToBookmark(level.bookmark);
13588 self.onRedo.dispatch(self, level);
13594 clear : function() {
13597 self.typing = false;
13600 hasUndo : function() {
13601 return index > 0 || this.typing;
13604 hasRedo : function() {
13605 return index < data.length - 1 && !this.typing;
13611 (function(tinymce) {
13613 var Event = tinymce.dom.Event,
13614 isIE = tinymce.isIE,
13615 isGecko = tinymce.isGecko,
13616 isOpera = tinymce.isOpera,
13617 each = tinymce.each,
13618 extend = tinymce.extend,
13622 function cloneFormats(node) {
13623 var clone, temp, inner;
13626 if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {
13628 temp = node.cloneNode(false);
13629 temp.appendChild(clone);
13632 clone = inner = node.cloneNode(false);
13635 clone.removeAttribute('id');
13637 } while (node = node.parentNode);
13640 return {wrapper : clone, inner : inner};
13643 // Checks if the selection/caret is at the end of the specified block element
13644 function isAtEnd(rng, par) {
13645 var rng2 = par.ownerDocument.createRange();
13647 rng2.setStart(rng.endContainer, rng.endOffset);
13648 rng2.setEndAfter(par);
13650 // 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
13651 return rng2.cloneContents().textContent.length == 0;
13654 function splitList(selection, dom, li) {
13655 var listBlock, block;
13657 if (dom.isEmpty(li)) {
13658 listBlock = dom.getParent(li, 'ul,ol');
13660 if (!dom.getParent(listBlock.parentNode, 'ul,ol')) {
13661 dom.split(listBlock, li);
13662 block = dom.create('p', 0, '<br data-mce-bogus="1" />');
13663 dom.replace(block, li);
13664 selection.select(block, 1);
13673 tinymce.create('tinymce.ForceBlocks', {
13674 ForceBlocks : function(ed) {
13675 var t = this, s = ed.settings, elm;
13679 elm = (s.forced_root_block || 'p').toLowerCase();
13680 s.element = elm.toUpperCase();
13682 ed.onPreInit.add(t.setup, t);
13685 setup : function() {
13686 var t = this, ed = t.editor, s = ed.settings, dom = ed.dom, selection = ed.selection, blockElements = ed.schema.getBlockElements();
13688 // Force root blocks
13689 if (s.forced_root_block) {
13690 function addRootBlocks() {
13691 var node = selection.getStart(), rootNode = ed.getBody(), rng, startContainer, startOffset, endContainer, endOffset, rootBlockNode, tempNode, offset = -0xFFFFFF;
13693 if (!node || node.nodeType !== 1)
13696 // Check if node is wrapped in block
13697 while (node != rootNode) {
13698 if (blockElements[node.nodeName])
13701 node = node.parentNode;
13704 // Get current selection
13705 rng = selection.getRng();
13706 if (rng.setStart) {
13707 startContainer = rng.startContainer;
13708 startOffset = rng.startOffset;
13709 endContainer = rng.endContainer;
13710 endOffset = rng.endOffset;
13712 // Force control range into text range
13714 rng = ed.getDoc().body.createTextRange();
13715 rng.moveToElementText(rng.item(0));
13718 tmpRng = rng.duplicate();
13719 tmpRng.collapse(true);
13720 startOffset = tmpRng.move('character', offset) * -1;
13722 if (!tmpRng.collapsed) {
13723 tmpRng = rng.duplicate();
13724 tmpRng.collapse(false);
13725 endOffset = (tmpRng.move('character', offset) * -1) - startOffset;
13729 // Wrap non block elements and text nodes
13730 for (node = rootNode.firstChild; node; node) {
13731 if (node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName])) {
13732 if (!rootBlockNode) {
13733 rootBlockNode = dom.create(s.forced_root_block);
13734 node.parentNode.insertBefore(rootBlockNode, node);
13738 node = node.nextSibling;
13739 rootBlockNode.appendChild(tempNode);
13741 rootBlockNode = null;
13742 node = node.nextSibling;
13746 if (rng.setStart) {
13747 rng.setStart(startContainer, startOffset);
13748 rng.setEnd(endContainer, endOffset);
13749 selection.setRng(rng);
13752 rng = ed.getDoc().body.createTextRange();
13753 rng.moveToElementText(rootNode);
13754 rng.collapse(true);
13755 rng.moveStart('character', startOffset);
13758 rng.moveEnd('character', endOffset);
13769 ed.onKeyUp.add(addRootBlocks);
13770 ed.onClick.add(addRootBlocks);
13773 if (s.force_br_newlines) {
13774 // Force IE to produce BRs on enter
13776 ed.onKeyPress.add(function(ed, e) {
13779 if (e.keyCode == 13 && selection.getNode().nodeName != 'LI') {
13780 selection.setContent('<br id="__" /> ', {format : 'raw'});
13782 n.removeAttribute('id');
13783 selection.select(n);
13784 selection.collapse();
13785 return Event.cancel(e);
13791 if (s.force_p_newlines) {
13793 ed.onKeyPress.add(function(ed, e) {
13794 if (e.keyCode == 13 && !e.shiftKey && !t.insertPara(e))
13798 // Ungly hack to for IE to preserve the formatting when you press
13799 // enter at the end of a block element with formatted contents
13800 // This logic overrides the browsers default logic with
13801 // custom logic that enables us to control the output
13802 tinymce.addUnload(function() {
13803 t._previousFormats = 0; // Fix IE leak
13806 ed.onKeyPress.add(function(ed, e) {
13807 t._previousFormats = 0;
13809 // Clone the current formats, this will later be applied to the new block contents
13810 if (e.keyCode == 13 && !e.shiftKey && ed.selection.isCollapsed() && s.keep_styles)
13811 t._previousFormats = cloneFormats(ed.selection.getStart());
13814 ed.onKeyUp.add(function(ed, e) {
13815 // Let IE break the element and the wrap the new caret location in the previous formats
13816 if (e.keyCode == 13 && !e.shiftKey) {
13817 var parent = ed.selection.getStart(), fmt = t._previousFormats;
13819 // Parent is an empty block
13820 if (!parent.hasChildNodes() && fmt) {
13821 parent = dom.getParent(parent, dom.isBlock);
13823 if (parent && parent.nodeName != 'LI') {
13824 parent.innerHTML = '';
13826 if (t._previousFormats) {
13827 parent.appendChild(fmt.wrapper);
13828 fmt.inner.innerHTML = '\uFEFF';
13830 parent.innerHTML = '\uFEFF';
13832 selection.select(parent, 1);
13833 selection.collapse(true);
13834 ed.getDoc().execCommand('Delete', false, null);
13835 t._previousFormats = 0;
13843 ed.onKeyDown.add(function(ed, e) {
13844 if ((e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey)
13845 t.backspaceDelete(e, e.keyCode == 8);
13850 // Workaround for missing shift+enter support, http://bugs.webkit.org/show_bug.cgi?id=16973
13851 if (tinymce.isWebKit) {
13852 function insertBr(ed) {
13853 var rng = selection.getRng(), br, div = dom.create('div', null, ' '), divYPos, vpHeight = dom.getViewPort(ed.getWin()).h;
13855 // Insert BR element
13856 rng.insertNode(br = dom.create('br'));
13858 // Place caret after BR
13859 rng.setStartAfter(br);
13860 rng.setEndAfter(br);
13861 selection.setRng(rng);
13863 // Could not place caret after BR then insert an nbsp entity and move the caret
13864 if (selection.getSel().focusNode == br.previousSibling) {
13865 selection.select(dom.insertAfter(dom.doc.createTextNode('\u00a0'), br));
13866 selection.collapse(TRUE);
13869 // Create a temporary DIV after the BR and get the position as it
13870 // seems like getPos() returns 0 for text nodes and BR elements.
13871 dom.insertAfter(div, br);
13872 divYPos = dom.getPos(div).y;
13875 // Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117
13876 if (divYPos > vpHeight) // It is not necessary to scroll if the DIV is inside the view port.
13877 ed.getWin().scrollTo(0, divYPos);
13880 ed.onKeyPress.add(function(ed, e) {
13881 if (e.keyCode == 13 && (e.shiftKey || (s.force_br_newlines && !dom.getParent(selection.getNode(), 'h1,h2,h3,h4,h5,h6,ol,ul')))) {
13888 // IE specific fixes
13890 // Replaces IE:s auto generated paragraphs with the specified element name
13891 if (s.element != 'P') {
13892 ed.onKeyPress.add(function(ed, e) {
13893 t.lastElm = selection.getNode().nodeName;
13896 ed.onKeyUp.add(function(ed, e) {
13897 var bl, n = selection.getNode(), b = ed.getBody();
13899 if (b.childNodes.length === 1 && n.nodeName == 'P') {
13900 n = dom.rename(n, s.element);
13901 selection.select(n);
13902 selection.collapse();
13904 } else if (e.keyCode == 13 && !e.shiftKey && t.lastElm != 'P') {
13905 bl = dom.getParent(n, 'p');
13908 dom.rename(bl, s.element);
13917 getParentBlock : function(n) {
13920 return d.getParent(n, d.isBlock);
13923 insertPara : function(e) {
13924 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;
13925 var rb, ra, dir, sn, so, en, eo, sb, eb, bn, bef, aft, sc, ec, n, vp = dom.getViewPort(ed.getWin()), y, ch, car;
13927 ed.undoManager.beforeChange();
13929 // If root blocks are forced then use Operas default behavior since it's really good
13930 // Removed due to bug: #1853816
13931 // if (se.forced_root_block && isOpera)
13934 // Setup before range
13935 rb = d.createRange();
13937 // If is before the first block element and in body, then move it into first block element
13938 rb.setStart(s.anchorNode, s.anchorOffset);
13941 // Setup after range
13942 ra = d.createRange();
13944 // If is before the first block element and in body, then move it into first block element
13945 ra.setStart(s.focusNode, s.focusOffset);
13948 // Setup start/end points
13949 dir = rb.compareBoundaryPoints(rb.START_TO_END, ra) < 0;
13950 sn = dir ? s.anchorNode : s.focusNode;
13951 so = dir ? s.anchorOffset : s.focusOffset;
13952 en = dir ? s.focusNode : s.anchorNode;
13953 eo = dir ? s.focusOffset : s.anchorOffset;
13955 // If selection is in empty table cell
13956 if (sn === en && /^(TD|TH)$/.test(sn.nodeName)) {
13957 if (sn.firstChild.nodeName == 'BR')
13958 dom.remove(sn.firstChild); // Remove BR
13960 // Create two new block elements
13961 if (sn.childNodes.length == 0) {
13962 ed.dom.add(sn, se.element, null, '<br />');
13963 aft = ed.dom.add(sn, se.element, null, '<br />');
13967 ed.dom.add(sn, se.element, null, n);
13968 aft = ed.dom.add(sn, se.element, null, '<br />');
13971 // Move caret into the last one
13972 r = d.createRange();
13973 r.selectNodeContents(aft);
13975 ed.selection.setRng(r);
13980 // If the caret is in an invalid location in FF we need to move it into the first block
13981 if (sn == b && en == b && b.firstChild && ed.dom.isBlock(b.firstChild)) {
13982 sn = en = sn.firstChild;
13984 rb = d.createRange();
13985 rb.setStart(sn, 0);
13986 ra = d.createRange();
13987 ra.setStart(en, 0);
13990 // Never use body as start or end node
13991 sn = sn.nodeName == "HTML" ? d.body : sn; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
13992 sn = sn.nodeName == "BODY" ? sn.firstChild : sn;
13993 en = en.nodeName == "HTML" ? d.body : en; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
13994 en = en.nodeName == "BODY" ? en.firstChild : en;
13996 // Get start and end blocks
13997 sb = t.getParentBlock(sn);
13998 eb = t.getParentBlock(en);
13999 bn = sb ? sb.nodeName : se.element; // Get block name to create
14001 // Return inside list use default browser behavior
14002 if (n = t.dom.getParent(sb, 'li,pre')) {
14003 if (n.nodeName == 'LI')
14004 return splitList(ed.selection, t.dom, n);
14009 // If caption or absolute layers then always generate new blocks within
14010 if (sb && (sb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
14015 // If caption or absolute layers then always generate new blocks within
14016 if (eb && (eb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
14022 if (/(TD|TABLE|TH|CAPTION)/.test(bn) || (sb && bn == "DIV" && /left|right/gi.test(dom.getStyle(sb, 'float', 1)))) {
14027 // Setup new before and after blocks
14028 bef = (sb && sb.nodeName == bn) ? sb.cloneNode(0) : ed.dom.create(bn);
14029 aft = (eb && eb.nodeName == bn) ? eb.cloneNode(0) : ed.dom.create(bn);
14031 // Remove id from after clone
14032 aft.removeAttribute('id');
14034 // Is header and cursor is at the end, then force paragraph under
14035 if (/^(H[1-6])$/.test(bn) && isAtEnd(r, sb))
14036 aft = ed.dom.create(se.element);
14038 // Find start chop node
14041 if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
14045 } while ((n = n.previousSibling ? n.previousSibling : n.parentNode));
14047 // Find end chop node
14050 if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
14054 } while ((n = n.nextSibling ? n.nextSibling : n.parentNode));
14056 // Place first chop part into before block element
14057 if (sc.nodeName == bn)
14058 rb.setStart(sc, 0);
14060 rb.setStartBefore(sc);
14063 bef.appendChild(rb.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari
14065 // Place secnd chop part within new block element
14067 ra.setEndAfter(ec);
14069 //console.debug(s.focusNode, s.focusOffset);
14072 ra.setStart(en, eo);
14073 aft.appendChild(ra.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari
14075 // Create range around everything
14076 r = d.createRange();
14077 if (!sc.previousSibling && sc.parentNode.nodeName == bn) {
14078 r.setStartBefore(sc.parentNode);
14080 if (rb.startContainer.nodeName == bn && rb.startOffset == 0)
14081 r.setStartBefore(rb.startContainer);
14083 r.setStart(rb.startContainer, rb.startOffset);
14086 if (!ec.nextSibling && ec.parentNode.nodeName == bn)
14087 r.setEndAfter(ec.parentNode);
14089 r.setEnd(ra.endContainer, ra.endOffset);
14091 // Delete and replace it with new block elements
14092 r.deleteContents();
14095 ed.getWin().scrollTo(0, vp.y);
14097 // Never wrap blocks in blocks
14098 if (bef.firstChild && bef.firstChild.nodeName == bn)
14099 bef.innerHTML = bef.firstChild.innerHTML;
14101 if (aft.firstChild && aft.firstChild.nodeName == bn)
14102 aft.innerHTML = aft.firstChild.innerHTML;
14104 function appendStyles(e, en) {
14105 var nl = [], nn, n, i;
14109 // Make clones of style elements
14110 if (se.keep_styles) {
14113 // We only want style specific elements
14114 if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(n.nodeName)) {
14115 nn = n.cloneNode(FALSE);
14116 dom.setAttrib(nn, 'id', ''); // Remove ID since it needs to be unique
14119 } while (n = n.parentNode);
14122 // Append style elements to aft
14123 if (nl.length > 0) {
14124 for (i = nl.length - 1, nn = e; i >= 0; i--)
14125 nn = nn.appendChild(nl[i]);
14127 // Padd most inner style element
14128 nl[0].innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there
14129 return nl[0]; // Move caret to most inner element
14131 e.innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there
14134 // Padd empty blocks
14135 if (dom.isEmpty(bef))
14136 appendStyles(bef, sn);
14138 // Fill empty afterblook with current style
14139 if (dom.isEmpty(aft))
14140 car = appendStyles(aft, en);
14142 // Opera needs this one backwards for older versions
14143 if (isOpera && parseFloat(opera.version()) < 9.5) {
14155 // Move cursor and scroll into view
14156 ed.selection.select(aft, true);
14157 ed.selection.collapse(true);
14159 // 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
14160 y = ed.dom.getPos(aft).y;
14161 //ch = aft.clientHeight;
14163 // Is element within viewport
14164 if (y < vp.y || y + 25 > vp.y + vp.h) {
14165 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
14168 'Element: y=' + y + ', h=' + ch + ', ' +
14169 'Viewport: y=' + vp.y + ", h=" + vp.h + ', bottom=' + (vp.y + vp.h)
14173 ed.undoManager.add();
14178 backspaceDelete : function(e, bs) {
14179 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;
14181 // Delete when caret is behind a element doesn't work correctly on Gecko see #3011651
14182 if (!bs && r.collapsed && sc.nodeType == 1 && r.startOffset == sc.childNodes.length) {
14183 walker = new tinymce.dom.TreeWalker(sc.lastChild, sc);
14185 // Walk the dom backwards until we find a text node
14186 for (n = sc.lastChild; n; n = walker.prev()) {
14187 if (n.nodeType == 3) {
14188 r.setStart(n, n.nodeValue.length);
14196 // The caret sometimes gets stuck in Gecko if you delete empty paragraphs
14197 // This workaround removes the element by hand and moves the caret to the previous element
14198 if (sc && ed.dom.isBlock(sc) && !/^(TD|TH)$/.test(sc.nodeName) && bs) {
14199 if (sc.childNodes.length == 0 || (sc.childNodes.length == 1 && sc.firstChild.nodeName == 'BR')) {
14200 // Find previous block element
14202 while ((n = n.previousSibling) && !ed.dom.isBlock(n)) ;
14205 if (sc != b.firstChild) {
14206 // Find last text node
14207 w = ed.dom.doc.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE);
14208 while (tn = w.nextNode())
14211 // Place caret at the end of last text node
14212 r = ed.getDoc().createRange();
14213 r.setStart(n, n.nodeValue ? n.nodeValue.length : 0);
14214 r.setEnd(n, n.nodeValue ? n.nodeValue.length : 0);
14217 // Remove the target container
14221 return Event.cancel(e);
14229 (function(tinymce) {
14231 var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, extend = tinymce.extend;
14233 tinymce.create('tinymce.ControlManager', {
14234 ControlManager : function(ed, s) {
14240 t.onAdd = new tinymce.util.Dispatcher(t);
14241 t.onPostRender = new tinymce.util.Dispatcher(t);
14242 t.prefix = s.prefix || ed.id + '_';
14245 t.onPostRender.add(function() {
14246 each(t.controls, function(c) {
14252 get : function(id) {
14253 return this.controls[this.prefix + id] || this.controls[id];
14256 setActive : function(id, s) {
14259 if (c = this.get(id))
14265 setDisabled : function(id, s) {
14268 if (c = this.get(id))
14274 add : function(c) {
14278 t.controls[c.id] = c;
14279 t.onAdd.dispatch(c, t);
14285 createControl : function(n) {
14286 var c, t = this, ed = t.editor;
14288 each(ed.plugins, function(p) {
14289 if (p.createControl) {
14290 c = p.createControl(n, t);
14300 return t.createSeparator();
14303 if (!c && ed.buttons && (c = ed.buttons[n]))
14304 return t.createButton(n, c);
14309 createDropMenu : function(id, s, cc) {
14310 var t = this, ed = t.editor, c, bm, v, cls;
14313 'class' : 'mceDropDown',
14314 constrain : ed.settings.constrain_menus
14317 s['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin';
14318 if (v = ed.getParam('skin_variant'))
14319 s['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1);
14321 id = t.prefix + id;
14322 cls = cc || t._cls.dropmenu || tinymce.ui.DropMenu;
14323 c = t.controls[id] = new cls(id, s);
14324 c.onAddItem.add(function(c, o) {
14325 var s = o.settings;
14327 s.title = ed.getLang(s.title, s.title);
14330 s.onclick = function(v) {
14332 ed.execCommand(s.cmd, s.ui || false, s.value);
14337 ed.onRemove.add(function() {
14341 // Fix for bug #1897785, #1898007
14342 if (tinymce.isIE) {
14343 c.onShowMenu.add(function() {
14344 // IE 8 needs focus in order to store away a range with the current collapsed caret location
14347 bm = ed.selection.getBookmark(1);
14350 c.onHideMenu.add(function() {
14352 ed.selection.moveToBookmark(bm);
14361 createListBox : function(id, s, cc) {
14362 var t = this, ed = t.editor, cmd, c, cls;
14367 s.title = ed.translate(s.title);
14368 s.scope = s.scope || ed;
14371 s.onselect = function(v) {
14372 ed.execCommand(s.cmd, s.ui || false, v || s.value);
14378 'class' : 'mce_' + id,
14380 control_manager : t
14383 id = t.prefix + id;
14385 if (ed.settings.use_native_selects)
14386 c = new tinymce.ui.NativeListBox(id, s);
14388 cls = cc || t._cls.listbox || tinymce.ui.ListBox;
14389 c = new cls(id, s, ed);
14392 t.controls[id] = c;
14394 // Fix focus problem in Safari
14395 if (tinymce.isWebKit) {
14396 c.onPostRender.add(function(c, n) {
14397 // Store bookmark on mousedown
14398 Event.add(n, 'mousedown', function() {
14399 ed.bookmark = ed.selection.getBookmark(1);
14402 // Restore on focus, since it might be lost
14403 Event.add(n, 'focus', function() {
14404 ed.selection.moveToBookmark(ed.bookmark);
14405 ed.bookmark = null;
14411 ed.onMouseDown.add(c.hideMenu, c);
14416 createButton : function(id, s, cc) {
14417 var t = this, ed = t.editor, o, c, cls;
14422 s.title = ed.translate(s.title);
14423 s.label = ed.translate(s.label);
14424 s.scope = s.scope || ed;
14426 if (!s.onclick && !s.menu_button) {
14427 s.onclick = function() {
14428 ed.execCommand(s.cmd, s.ui || false, s.value);
14434 'class' : 'mce_' + id,
14435 unavailable_prefix : ed.getLang('unavailable', ''),
14437 control_manager : t
14440 id = t.prefix + id;
14442 if (s.menu_button) {
14443 cls = cc || t._cls.menubutton || tinymce.ui.MenuButton;
14444 c = new cls(id, s, ed);
14445 ed.onMouseDown.add(c.hideMenu, c);
14447 cls = t._cls.button || tinymce.ui.Button;
14448 c = new cls(id, s, ed);
14454 createMenuButton : function(id, s, cc) {
14458 return this.createButton(id, s, cc);
14461 createSplitButton : function(id, s, cc) {
14462 var t = this, ed = t.editor, cmd, c, cls;
14467 s.title = ed.translate(s.title);
14468 s.scope = s.scope || ed;
14471 s.onclick = function(v) {
14472 ed.execCommand(s.cmd, s.ui || false, v || s.value);
14477 s.onselect = function(v) {
14478 ed.execCommand(s.cmd, s.ui || false, v || s.value);
14484 'class' : 'mce_' + id,
14486 control_manager : t
14489 id = t.prefix + id;
14490 cls = cc || t._cls.splitbutton || tinymce.ui.SplitButton;
14491 c = t.add(new cls(id, s, ed));
14492 ed.onMouseDown.add(c.hideMenu, c);
14497 createColorSplitButton : function(id, s, cc) {
14498 var t = this, ed = t.editor, cmd, c, cls, bm;
14503 s.title = ed.translate(s.title);
14504 s.scope = s.scope || ed;
14507 s.onclick = function(v) {
14509 bm = ed.selection.getBookmark(1);
14511 ed.execCommand(s.cmd, s.ui || false, v || s.value);
14516 s.onselect = function(v) {
14517 ed.execCommand(s.cmd, s.ui || false, v || s.value);
14523 'class' : 'mce_' + id,
14524 'menu_class' : ed.getParam('skin') + 'Skin',
14526 more_colors_title : ed.getLang('more_colors')
14529 id = t.prefix + id;
14530 cls = cc || t._cls.colorsplitbutton || tinymce.ui.ColorSplitButton;
14531 c = new cls(id, s, ed);
14532 ed.onMouseDown.add(c.hideMenu, c);
14534 // Remove the menu element when the editor is removed
14535 ed.onRemove.add(function() {
14539 // Fix for bug #1897785, #1898007
14540 if (tinymce.isIE) {
14541 c.onShowMenu.add(function() {
14542 // IE 8 needs focus in order to store away a range with the current collapsed caret location
14544 bm = ed.selection.getBookmark(1);
14547 c.onHideMenu.add(function() {
14549 ed.selection.moveToBookmark(bm);
14558 createToolbar : function(id, s, cc) {
14559 var c, t = this, cls;
14561 id = t.prefix + id;
14562 cls = cc || t._cls.toolbar || tinymce.ui.Toolbar;
14563 c = new cls(id, s, t.editor);
14571 createToolbarGroup : function(id, s, cc) {
14572 var c, t = this, cls;
14573 id = t.prefix + id;
14574 cls = cc || this._cls.toolbarGroup || tinymce.ui.ToolbarGroup;
14575 c = new cls(id, s, t.editor);
14583 createSeparator : function(cc) {
14584 var cls = cc || this._cls.separator || tinymce.ui.Separator;
14589 setControlType : function(n, c) {
14590 return this._cls[n.toLowerCase()] = c;
14593 destroy : function() {
14594 each(this.controls, function(c) {
14598 this.controls = null;
14603 (function(tinymce) {
14604 var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isIE = tinymce.isIE, isOpera = tinymce.isOpera;
14606 tinymce.create('tinymce.WindowManager', {
14607 WindowManager : function(ed) {
14611 t.onOpen = new Dispatcher(t);
14612 t.onClose = new Dispatcher(t);
14617 open : function(s, p) {
14618 var t = this, f = '', x, y, mo = t.editor.settings.dialog_type == 'modal', w, sw, sh, vp = tinymce.DOM.getViewPort(), u;
14620 // Default some options
14623 sw = isOpera ? vp.w : screen.width; // Opera uses windows inside the Opera window
14624 sh = isOpera ? vp.h : screen.height;
14625 s.name = s.name || 'mc_' + new Date().getTime();
14626 s.width = parseInt(s.width || 320);
14627 s.height = parseInt(s.height || 240);
14628 s.resizable = true;
14629 s.left = s.left || parseInt(sw / 2.0) - (s.width / 2.0);
14630 s.top = s.top || parseInt(sh / 2.0) - (s.height / 2.0);
14632 p.mce_width = s.width;
14633 p.mce_height = s.height;
14634 p.mce_auto_focus = s.auto_focus;
14640 s.dialogWidth = s.width + 'px';
14641 s.dialogHeight = s.height + 'px';
14642 s.scroll = s.scrollbars || false;
14646 // Build features string
14647 each(s, function(v, k) {
14648 if (tinymce.is(v, 'boolean'))
14649 v = v ? 'yes' : 'no';
14651 if (!/^(name|url)$/.test(k)) {
14653 f += (f ? ';' : '') + k + ':' + v;
14655 f += (f ? ',' : '') + k + '=' + v;
14661 t.onOpen.dispatch(t, s, p);
14663 u = s.url || s.file;
14664 u = tinymce._addVer(u);
14669 window.showModalDialog(u, window, f);
14671 w = window.open(u, s.name, f);
14677 alert(t.editor.getLang('popup_blocked'));
14680 close : function(w) {
14682 this.onClose.dispatch(this);
14685 createInstance : function(cl, a, b, c, d, e) {
14686 var f = tinymce.resolve(cl);
14688 return new f(a, b, c, d, e);
14691 confirm : function(t, cb, s, w) {
14694 cb.call(s || this, w.confirm(this._decode(this.editor.getLang(t, t))));
14697 alert : function(tx, cb, s, w) {
14701 w.alert(t._decode(t.editor.getLang(tx, tx)));
14707 resizeBy : function(dw, dh, win) {
14708 win.resizeBy(dw, dh);
14711 // Internal functions
14713 _decode : function(s) {
14714 return tinymce.DOM.decode(s).replace(/\\n/g, '\n');
14718 (function(tinymce) {
14719 tinymce.Formatter = function(ed) {
14721 each = tinymce.each,
14723 selection = ed.selection,
14724 TreeWalker = tinymce.dom.TreeWalker,
14725 rangeUtils = new tinymce.dom.RangeUtils(dom),
14726 isValid = ed.schema.isValidChild,
14727 isBlock = dom.isBlock,
14728 forcedRootBlock = ed.settings.forced_root_block,
14729 nodeIndex = dom.nodeIndex,
14730 INVISIBLE_CHAR = '\uFEFF',
14731 MCE_ATTR_RE = /^(src|href|style)$/,
14735 pendingFormats = {apply : [], remove : []};
14737 function isArray(obj) {
14738 return obj instanceof Array;
14741 function getParents(node, selector) {
14742 return dom.getParents(node, selector, dom.getRoot());
14745 function isCaretNode(node) {
14746 return node.nodeType === 1 && (node.face === 'mceinline' || node.style.fontFamily === 'mceinline');
14749 // Public functions
14751 function get(name) {
14752 return name ? formats[name] : formats;
14755 function register(name, format) {
14757 if (typeof(name) !== 'string') {
14758 each(name, function(format, name) {
14759 register(name, format);
14762 // Force format into array and add it to internal collection
14763 format = format.length ? format : [format];
14765 each(format, function(format) {
14766 // Set deep to false by default on selector formats this to avoid removing
14767 // alignment on images inside paragraphs when alignment is changed on paragraphs
14768 if (format.deep === undefined)
14769 format.deep = !format.selector;
14772 if (format.split === undefined)
14773 format.split = !format.selector || format.inline;
14776 if (format.remove === undefined && format.selector && !format.inline)
14777 format.remove = 'none';
14779 // Mark format as a mixed format inline + block level
14780 if (format.selector && format.inline) {
14781 format.mixed = true;
14782 format.block_expand = true;
14785 // Split classes if needed
14786 if (typeof(format.classes) === 'string')
14787 format.classes = format.classes.split(/\s+/);
14790 formats[name] = format;
14795 var getTextDecoration = function(node) {
14798 ed.dom.getParent(node, function(n) {
14799 decoration = ed.dom.getStyle(n, 'text-decoration');
14800 return decoration && decoration !== 'none';
14806 var processUnderlineAndColor = function(node) {
14807 var textDecoration;
14808 if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {
14809 textDecoration = getTextDecoration(node.parentNode);
14810 if (ed.dom.getStyle(node, 'color') && textDecoration) {
14811 ed.dom.setStyle(node, 'text-decoration', textDecoration);
14812 } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) {
14813 ed.dom.setStyle(node, 'text-decoration', null);
14818 function apply(name, vars, node) {
14819 var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed();
14821 function moveStart(rng) {
14822 var container = rng.startContainer,
14823 offset = rng.startOffset,
14826 // Move startContainer/startOffset in to a suitable node
14827 if (container.nodeType == 1 || container.nodeValue === "") {
14828 container = container.nodeType == 1 ? container.childNodes[offset] : container;
14830 // Might fail if the offset is behind the last element in it's container
14832 walker = new TreeWalker(container, container.parentNode);
14833 for (node = walker.current(); node; node = walker.next()) {
14834 if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
14835 rng.setStart(node, 0);
14845 function setElementFormat(elm, fmt) {
14846 fmt = fmt || format;
14849 each(fmt.styles, function(value, name) {
14850 dom.setStyle(elm, name, replaceVars(value, vars));
14853 each(fmt.attributes, function(value, name) {
14854 dom.setAttrib(elm, name, replaceVars(value, vars));
14857 each(fmt.classes, function(value) {
14858 value = replaceVars(value, vars);
14860 if (!dom.hasClass(elm, value))
14861 dom.addClass(elm, value);
14865 function adjustSelectionToVisibleSelection() {
14867 function findSelectionEnd(start, end) {
14868 var walker = new TreeWalker(end);
14869 for (node = walker.current(); node; node = walker.prev()) {
14870 if (node.childNodes.length > 1 || node == start) {
14876 // Adjust selection so that a end container with a end offset of zero is not included in the selection
14877 // as this isn't visible to the user.
14878 var rng = ed.selection.getRng();
14879 var start = rng.startContainer;
14880 var end = rng.endContainer;
14881 if (start != end && rng.endOffset == 0) {
14882 var newEnd = findSelectionEnd(start, end);
14883 var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length;
14884 rng.setEnd(newEnd, endOffset);
14889 function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){
14890 var nodes =[], listIndex =-1, list, startIndex = -1, endIndex = -1, currentWrapElm;
14892 // find the index of the first child list.
14893 each(node.childNodes, function(n, index) {
14894 if (n.nodeName==="UL"||n.nodeName==="OL") {listIndex = index; list=n; return false; }
14897 // get the index of the bookmarks
14898 each(node.childNodes, function(n, index) {
14899 if (n.nodeName==="SPAN" &&dom.getAttrib(n, "data-mce-type")=="bookmark" && n.id==bookmark.id+"_start") {startIndex=index}
14900 if (n.nodeName==="SPAN" &&dom.getAttrib(n, "data-mce-type")=="bookmark" && n.id==bookmark.id+"_end") {endIndex=index}
14903 // if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally
14904 if (listIndex<=0 || (startIndex<listIndex&&endIndex>listIndex)) {
14905 each(tinymce.grep(node.childNodes), process);
14908 currentWrapElm = wrapElm.cloneNode(FALSE);
14910 // create a list of the nodes on the same side of the list as the selection
14911 each(tinymce.grep(node.childNodes), function(n, index) {
14912 if ((startIndex<listIndex && index <listIndex) || (startIndex>listIndex && index >listIndex)) {
14914 n.parentNode.removeChild(n);
14918 // insert the wrapping element either before or after the list.
14919 if (startIndex<listIndex) {
14920 node.insertBefore(currentWrapElm, list);
14921 } else if (startIndex>listIndex) {
14922 node.insertBefore(currentWrapElm, list.nextSibling);
14925 // add the new nodes to the list.
14926 newWrappers.push(currentWrapElm);
14927 each(nodes, function(node){currentWrapElm.appendChild(node)});
14928 return currentWrapElm;
14932 function applyRngStyle(rng, bookmark) {
14933 var newWrappers = [], wrapName, wrapElm;
14935 // Setup wrapper element
14936 wrapName = format.inline || format.block;
14937 wrapElm = dom.create(wrapName);
14938 setElementFormat(wrapElm);
14940 rangeUtils.walk(rng, function(nodes) {
14941 var currentWrapElm;
14943 function process(node) {
14944 var nodeName = node.nodeName.toLowerCase(), parentName = node.parentNode.nodeName.toLowerCase(), found;
14946 // Stop wrapping on br elements
14947 if (isEq(nodeName, 'br')) {
14948 currentWrapElm = 0;
14950 // Remove any br elements when we wrap things
14957 // If node is wrapper type
14958 if (format.wrapper && matchNode(node, name, vars)) {
14959 currentWrapElm = 0;
14963 // Can we rename the block
14964 if (format.block && !format.wrapper && isTextBlock(nodeName)) {
14965 node = dom.rename(node, wrapName);
14966 setElementFormat(node);
14967 newWrappers.push(node);
14968 currentWrapElm = 0;
14972 // Handle selector patterns
14973 if (format.selector) {
14974 // Look for matching formats
14975 each(formatList, function(format) {
14976 // Check collapsed state if it exists
14977 if ('collapsed' in format && format.collapsed !== isCollapsed) {
14981 if (dom.is(node, format.selector) && !isCaretNode(node)) {
14982 setElementFormat(node, format);
14987 // Continue processing if a selector match wasn't found and a inline element is defined
14988 if (!format.inline || found) {
14989 currentWrapElm = 0;
14994 // Is it valid to wrap this item
14995 if (isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
14996 !(node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279)) {
14998 if (!currentWrapElm) {
15000 currentWrapElm = wrapElm.cloneNode(FALSE);
15001 node.parentNode.insertBefore(currentWrapElm, node);
15002 newWrappers.push(currentWrapElm);
15005 currentWrapElm.appendChild(node);
15006 } else if (nodeName == 'li' && bookmark) {
15007 // Start wrapping - if we are in a list node and have a bookmark, then we will always begin by wrapping in a new element.
15008 currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process);
15010 // Start a new wrapper for possible children
15011 currentWrapElm = 0;
15013 each(tinymce.grep(node.childNodes), process);
15015 // End the last wrapper
15016 currentWrapElm = 0;
15020 // Process siblings from range
15021 each(nodes, process);
15024 // Wrap links inside as well, for example color inside a link when the wrapper is around the link
15025 if (format.wrap_links === false) {
15026 each(newWrappers, function(node) {
15027 function process(node) {
15028 var i, currentWrapElm, children;
15030 if (node.nodeName === 'A') {
15031 currentWrapElm = wrapElm.cloneNode(FALSE);
15032 newWrappers.push(currentWrapElm);
15034 children = tinymce.grep(node.childNodes);
15035 for (i = 0; i < children.length; i++)
15036 currentWrapElm.appendChild(children[i]);
15038 node.appendChild(currentWrapElm);
15041 each(tinymce.grep(node.childNodes), process);
15049 each(newWrappers, function(node) {
15052 function getChildCount(node) {
15055 each(node.childNodes, function(node) {
15056 if (!isWhiteSpaceNode(node) && !isBookmarkNode(node))
15063 function mergeStyles(node) {
15066 each(node.childNodes, function(node) {
15067 if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) {
15069 return FALSE; // break loop
15073 // If child was found and of the same type as the current node
15074 if (child && matchName(child, format)) {
15075 clone = child.cloneNode(FALSE);
15076 setElementFormat(clone);
15078 dom.replace(clone, node, TRUE);
15079 dom.remove(child, 1);
15082 return clone || node;
15085 childCount = getChildCount(node);
15087 // Remove empty nodes but only if there is multiple wrappers and they are not block
15088 // elements so never remove single <h1></h1> since that would remove the currrent empty block element where the caret is at
15089 if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) {
15090 dom.remove(node, 1);
15094 if (format.inline || format.wrapper) {
15095 // Merges the current node with it's children of similar type to reduce the number of elements
15096 if (!format.exact && childCount === 1)
15097 node = mergeStyles(node);
15099 // Remove/merge children
15100 each(formatList, function(format) {
15101 // Merge all children of similar type will move styles from child to parent
15102 // this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span>
15103 // will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span>
15104 each(dom.select(format.inline, node), function(child) {
15107 // When wrap_links is set to false we don't want
15108 // to remove the format on children within links
15109 if (format.wrap_links === false) {
15110 parent = child.parentNode;
15113 if (parent.nodeName === 'A')
15115 } while (parent = parent.parentNode);
15118 removeFormat(format, vars, child, format.exact ? child : null);
15122 // Remove child if direct parent is of same type
15123 if (matchNode(node.parentNode, name, vars)) {
15124 dom.remove(node, 1);
15129 // Look for parent with similar style format
15130 if (format.merge_with_parents) {
15131 dom.getParent(node.parentNode, function(parent) {
15132 if (matchNode(parent, name, vars)) {
15133 dom.remove(node, 1);
15140 // Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b>
15142 node = mergeSiblings(getNonWhiteSpaceSibling(node), node);
15143 node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));
15151 rng = dom.createRng();
15153 rng.setStartBefore(node);
15154 rng.setEndAfter(node);
15156 applyRngStyle(expandRng(rng, formatList));
15158 if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
15159 // Obtain selection node before selection is unselected by applyRngStyle()
15160 var curSelNode = ed.selection.getNode();
15162 // Apply formatting to selection
15163 ed.selection.setRng(adjustSelectionToVisibleSelection());
15164 bookmark = selection.getBookmark();
15165 applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark);
15167 // Colored nodes should be underlined so that the color of the underline matches the text color.
15168 if (format.styles && (format.styles.color || format.styles.textDecoration)) {
15169 tinymce.walk(curSelNode, processUnderlineAndColor, 'childNodes');
15170 processUnderlineAndColor(curSelNode);
15173 selection.moveToBookmark(bookmark);
15174 selection.setRng(moveStart(selection.getRng(TRUE)));
15177 performCaretAction('apply', name, vars);
15182 function remove(name, vars, node) {
15183 var formatList = get(name), format = formatList[0], bookmark, i, rng;
15184 function moveStart(rng) {
15185 var container = rng.startContainer,
15186 offset = rng.startOffset,
15187 walker, node, nodes, tmpNode;
15189 // Convert text node into index if possible
15190 if (container.nodeType == 3 && offset >= container.nodeValue.length - 1) {
15191 container = container.parentNode;
15192 offset = nodeIndex(container) + 1;
15195 // Move startContainer/startOffset in to a suitable node
15196 if (container.nodeType == 1) {
15197 nodes = container.childNodes;
15198 container = nodes[Math.min(offset, nodes.length - 1)];
15199 walker = new TreeWalker(container);
15201 // If offset is at end of the parent node walk to the next one
15202 if (offset > nodes.length - 1)
15205 for (node = walker.current(); node; node = walker.next()) {
15206 if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
15207 // IE has a "neat" feature where it moves the start node into the closest element
15208 // we can avoid this by inserting an element before it and then remove it after we set the selection
15209 tmpNode = dom.create('a', null, INVISIBLE_CHAR);
15210 node.parentNode.insertBefore(tmpNode, node);
15212 // Set selection and remove tmpNode
15213 rng.setStart(node, 0);
15214 selection.setRng(rng);
15215 dom.remove(tmpNode);
15223 // Merges the styles for each node
15224 function process(node) {
15225 var children, i, l;
15227 // Grab the children first since the nodelist might be changed
15228 children = tinymce.grep(node.childNodes);
15230 // Process current node
15231 for (i = 0, l = formatList.length; i < l; i++) {
15232 if (removeFormat(formatList[i], vars, node, node))
15236 // Process the children
15238 for (i = 0, l = children.length; i < l; i++)
15239 process(children[i]);
15243 function findFormatRoot(container) {
15246 // Find format root
15247 each(getParents(container.parentNode).reverse(), function(parent) {
15250 // Find format root element
15251 if (!formatRoot && parent.id != '_start' && parent.id != '_end') {
15252 // Is the node matching the format we are looking for
15253 format = matchNode(parent, name, vars);
15254 if (format && format.split !== false)
15255 formatRoot = parent;
15262 function wrapAndSplit(format_root, container, target, split) {
15263 var parent, clone, lastClone, firstClone, i, formatRootParent;
15265 // Format root found then clone formats and split it
15267 formatRootParent = format_root.parentNode;
15269 for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {
15270 clone = parent.cloneNode(FALSE);
15272 for (i = 0; i < formatList.length; i++) {
15273 if (removeFormat(formatList[i], vars, clone, clone)) {
15279 // Build wrapper node
15282 clone.appendChild(lastClone);
15285 firstClone = clone;
15291 // Never split block elements if the format is mixed
15292 if (split && (!format.mixed || !isBlock(format_root)))
15293 container = dom.split(format_root, container);
15295 // Wrap container in cloned formats
15297 target.parentNode.insertBefore(lastClone, target);
15298 firstClone.appendChild(target);
15305 function splitToFormatRoot(container) {
15306 return wrapAndSplit(findFormatRoot(container), container, container, true);
15309 function unwrap(start) {
15310 var node = dom.get(start ? '_start' : '_end'),
15311 out = node[start ? 'firstChild' : 'lastChild'];
15313 // If the end is placed within the start the result will be removed
15314 // So this checks if the out node is a bookmark node if it is it
15315 // checks for another more suitable node
15316 if (isBookmarkNode(out))
15317 out = out[start ? 'firstChild' : 'lastChild'];
15319 dom.remove(node, true);
15324 function removeRngStyle(rng) {
15325 var startContainer, endContainer;
15327 rng = expandRng(rng, formatList, TRUE);
15329 if (format.split) {
15330 startContainer = getContainer(rng, TRUE);
15331 endContainer = getContainer(rng);
15333 if (startContainer != endContainer) {
15334 // Wrap start/end nodes in span element since these might be cloned/moved
15335 startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'});
15336 endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'});
15339 splitToFormatRoot(startContainer);
15340 splitToFormatRoot(endContainer);
15342 // Unwrap start/end to get real elements again
15343 startContainer = unwrap(TRUE);
15344 endContainer = unwrap();
15346 startContainer = endContainer = splitToFormatRoot(startContainer);
15348 // Update range positions since they might have changed after the split operations
15349 rng.startContainer = startContainer.parentNode;
15350 rng.startOffset = nodeIndex(startContainer);
15351 rng.endContainer = endContainer.parentNode;
15352 rng.endOffset = nodeIndex(endContainer) + 1;
15355 // Remove items between start/end
15356 rangeUtils.walk(rng, function(nodes) {
15357 each(nodes, function(node) {
15360 // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined.
15361 if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && getTextDecoration(node.parentNode) === 'underline') {
15362 removeFormat({'deep': false, 'exact': true, 'inline': 'span', 'styles': {'textDecoration' : 'underline'}}, null, node);
15370 rng = dom.createRng();
15371 rng.setStartBefore(node);
15372 rng.setEndAfter(node);
15373 removeRngStyle(rng);
15377 if (!selection.isCollapsed() || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
15378 bookmark = selection.getBookmark();
15379 removeRngStyle(selection.getRng(TRUE));
15380 selection.moveToBookmark(bookmark);
15382 // 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
15383 if (match(name, vars, selection.getStart())) {
15384 moveStart(selection.getRng(true));
15389 performCaretAction('remove', name, vars);
15392 function toggle(name, vars, node) {
15393 var fmt = get(name);
15395 if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0]['toggle']))
15396 remove(name, vars, node);
15398 apply(name, vars, node);
15401 function matchNode(node, name, vars, similar) {
15402 var formatList = get(name), format, i, classes;
15404 function matchItems(node, format, item_name) {
15405 var key, value, items = format[item_name], i;
15409 // Non indexed object
15410 if (items.length === undefined) {
15411 for (key in items) {
15412 if (items.hasOwnProperty(key)) {
15413 if (item_name === 'attributes')
15414 value = dom.getAttrib(node, key);
15416 value = getStyle(node, key);
15418 if (similar && !value && !format.exact)
15421 if ((!similar || format.exact) && !isEq(value, replaceVars(items[key], vars)))
15426 // Only one match needed for indexed arrays
15427 for (i = 0; i < items.length; i++) {
15428 if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i]))
15437 if (formatList && node) {
15438 // Check each format in list
15439 for (i = 0; i < formatList.length; i++) {
15440 format = formatList[i];
15442 // Name name, attributes, styles and classes
15443 if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) {
15445 if (classes = format.classes) {
15446 for (i = 0; i < classes.length; i++) {
15447 if (!dom.hasClass(node, classes[i]))
15458 function match(name, vars, node) {
15461 function matchParents(node) {
15462 // Find first node with similar format settings
15463 node = dom.getParent(node, function(node) {
15464 return !!matchNode(node, name, vars, true);
15467 // Do an exact check on the similar format element
15468 return matchNode(node, name, vars);
15471 // Check specified node
15473 return matchParents(node);
15475 // Check pending formats
15476 if (selection.isCollapsed()) {
15477 for (i = pendingFormats.apply.length - 1; i >= 0; i--) {
15478 if (pendingFormats.apply[i].name == name)
15482 for (i = pendingFormats.remove.length - 1; i >= 0; i--) {
15483 if (pendingFormats.remove[i].name == name)
15487 return matchParents(selection.getNode());
15490 // Check selected node
15491 node = selection.getNode();
15492 if (matchParents(node))
15495 // Check start node if it's different
15496 startNode = selection.getStart();
15497 if (startNode != node) {
15498 if (matchParents(startNode))
15505 function matchAll(names, vars) {
15506 var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name;
15508 // If the selection is collapsed then check pending formats
15509 if (selection.isCollapsed()) {
15510 for (ni = 0; ni < names.length; ni++) {
15511 // If the name is to be removed, then stop it from being added
15512 for (i = pendingFormats.remove.length - 1; i >= 0; i--) {
15515 if (pendingFormats.remove[i].name == name) {
15516 checkedMap[name] = true;
15522 // If the format is to be applied
15523 for (i = pendingFormats.apply.length - 1; i >= 0; i--) {
15524 for (ni = 0; ni < names.length; ni++) {
15527 if (!checkedMap[name] && pendingFormats.apply[i].name == name) {
15528 checkedMap[name] = true;
15529 matchedFormatNames.push(name);
15535 // Check start of selection for formats
15536 startElement = selection.getStart();
15537 dom.getParent(startElement, function(node) {
15540 for (i = 0; i < names.length; i++) {
15543 if (!checkedMap[name] && matchNode(node, name, vars)) {
15544 checkedMap[name] = true;
15545 matchedFormatNames.push(name);
15550 return matchedFormatNames;
15553 function canApply(name) {
15554 var formatList = get(name), startNode, parents, i, x, selector;
15557 startNode = selection.getStart();
15558 parents = getParents(startNode);
15560 for (x = formatList.length - 1; x >= 0; x--) {
15561 selector = formatList[x].selector;
15563 // Format is not selector based, then always return TRUE
15567 for (i = parents.length - 1; i >= 0; i--) {
15568 if (dom.is(parents[i], selector))
15577 // Expose to public
15578 tinymce.extend(this, {
15580 register : register,
15585 matchAll : matchAll,
15586 matchNode : matchNode,
15587 canApply : canApply
15590 // Private functions
15592 function matchName(node, format) {
15593 // Check for inline match
15594 if (isEq(node, format.inline))
15597 // Check for block match
15598 if (isEq(node, format.block))
15601 // Check for selector match
15602 if (format.selector)
15603 return dom.is(node, format.selector);
15606 function isEq(str1, str2) {
15610 str1 = '' + (str1.nodeName || str1);
15611 str2 = '' + (str2.nodeName || str2);
15613 return str1.toLowerCase() == str2.toLowerCase();
15616 function getStyle(node, name) {
15617 var styleVal = dom.getStyle(node, name);
15619 // Force the format to hex
15620 if (name == 'color' || name == 'backgroundColor')
15621 styleVal = dom.toHex(styleVal);
15623 // Opera will return bold as 700
15624 if (name == 'fontWeight' && styleVal == 700)
15627 return '' + styleVal;
15630 function replaceVars(value, vars) {
15631 if (typeof(value) != "string")
15632 value = value(vars);
15634 value = value.replace(/%(\w+)/g, function(str, name) {
15635 return vars[name] || str;
15642 function isWhiteSpaceNode(node) {
15643 return node && node.nodeType === 3 && /^([\s\r\n]+|)$/.test(node.nodeValue);
15646 function wrap(node, name, attrs) {
15647 var wrapper = dom.create(name, attrs);
15649 node.parentNode.insertBefore(wrapper, node);
15650 wrapper.appendChild(node);
15655 function expandRng(rng, format, remove) {
15656 var startContainer = rng.startContainer,
15657 startOffset = rng.startOffset,
15658 endContainer = rng.endContainer,
15659 endOffset = rng.endOffset, sibling, lastIdx, leaf;
15661 // This function walks up the tree if there is no siblings before/after the node
15662 function findParentContainer(container, child_name, sibling_name, root) {
15665 root = root || dom.getRoot();
15668 // Check if we can move up are we at root level or body level
15669 parent = container.parentNode;
15671 // Stop expanding on block elements or root depending on format
15672 if (parent == root || (!format[0].block_expand && isBlock(parent)))
15675 for (sibling = parent[child_name]; sibling && sibling != container; sibling = sibling[sibling_name]) {
15676 if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
15679 if (sibling.nodeType == 3 && !isWhiteSpaceNode(sibling))
15683 container = container.parentNode;
15689 // This function walks down the tree to find the leaf at the selection.
15690 // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node.
15691 function findLeaf(node, offset) {
15692 if (offset === undefined)
15693 offset = node.nodeType === 3 ? node.length : node.childNodes.length;
15694 while (node && node.hasChildNodes()) {
15695 node = node.childNodes[offset];
15697 offset = node.nodeType === 3 ? node.length : node.childNodes.length;
15699 return { node: node, offset: offset };
15702 // If index based start position then resolve it
15703 if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) {
15704 lastIdx = startContainer.childNodes.length - 1;
15705 startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset];
15707 if (startContainer.nodeType == 3)
15711 // If index based end position then resolve it
15712 if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) {
15713 lastIdx = endContainer.childNodes.length - 1;
15714 endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1];
15716 if (endContainer.nodeType == 3)
15717 endOffset = endContainer.nodeValue.length;
15720 // Exclude bookmark nodes if possible
15721 if (isBookmarkNode(startContainer.parentNode))
15722 startContainer = startContainer.parentNode;
15724 if (isBookmarkNode(startContainer))
15725 startContainer = startContainer.nextSibling || startContainer;
15727 if (isBookmarkNode(endContainer.parentNode)) {
15728 endOffset = dom.nodeIndex(endContainer);
15729 endContainer = endContainer.parentNode;
15732 if (isBookmarkNode(endContainer) && endContainer.previousSibling) {
15733 endContainer = endContainer.previousSibling;
15734 endOffset = endContainer.length;
15737 if (format[0].inline) {
15738 // Avoid applying formatting to a trailing space.
15739 leaf = findLeaf(endContainer, endOffset);
15741 while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling)
15742 leaf = findLeaf(leaf.node.previousSibling);
15744 if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 &&
15745 leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') {
15747 if (leaf.offset > 1) {
15748 endContainer = leaf.node;
15749 endContainer.splitText(leaf.offset - 1);
15750 } else if (leaf.node.previousSibling) {
15751 endContainer = leaf.node.previousSibling;
15757 // Move start/end point up the tree if the leaves are sharp and if we are in different containers
15758 // Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!
15759 // This will reduce the number of wrapper elements that needs to be created
15760 // Move start point up the tree
15761 if (format[0].inline || format[0].block_expand) {
15762 startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');
15763 endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');
15766 // Expand start/end container to matching selector
15767 if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) {
15768 function findSelectorEndPoint(container, sibling_name) {
15769 var parents, i, y, curFormat;
15771 if (container.nodeType == 3 && container.nodeValue.length == 0 && container[sibling_name])
15772 container = container[sibling_name];
15774 parents = getParents(container);
15775 for (i = 0; i < parents.length; i++) {
15776 for (y = 0; y < format.length; y++) {
15777 curFormat = format[y];
15779 // If collapsed state is set then skip formats that doesn't match that
15780 if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed)
15783 if (dom.is(parents[i], curFormat.selector))
15791 // Find new startContainer/endContainer if there is better one
15792 startContainer = findSelectorEndPoint(startContainer, 'previousSibling');
15793 endContainer = findSelectorEndPoint(endContainer, 'nextSibling');
15796 // Expand start/end container to matching block element or text node
15797 if (format[0].block || format[0].selector) {
15798 function findBlockEndPoint(container, sibling_name, sibling_name2) {
15801 // Expand to block of similar type
15802 if (!format[0].wrapper)
15803 node = dom.getParent(container, format[0].block);
15805 // Expand to first wrappable block element or any block element
15807 node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock);
15809 // Exclude inner lists from wrapping
15810 if (node && format[0].wrapper)
15811 node = getParents(node, 'ul,ol').reverse()[0] || node;
15813 // Didn't find a block element look for first/last wrappable element
15817 while (node[sibling_name] && !isBlock(node[sibling_name])) {
15818 node = node[sibling_name];
15820 // Break on BR but include it will be removed later on
15821 // we can't remove it now since we need to check if it can be wrapped
15822 if (isEq(node, 'br'))
15827 return node || container;
15830 // Find new startContainer/endContainer if there is better one
15831 startContainer = findBlockEndPoint(startContainer, 'previousSibling');
15832 endContainer = findBlockEndPoint(endContainer, 'nextSibling');
15834 // Non block element then try to expand up the leaf
15835 if (format[0].block) {
15836 if (!isBlock(startContainer))
15837 startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');
15839 if (!isBlock(endContainer))
15840 endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');
15844 // Setup index for startContainer
15845 if (startContainer.nodeType == 1) {
15846 startOffset = nodeIndex(startContainer);
15847 startContainer = startContainer.parentNode;
15850 // Setup index for endContainer
15851 if (endContainer.nodeType == 1) {
15852 endOffset = nodeIndex(endContainer) + 1;
15853 endContainer = endContainer.parentNode;
15856 // Return new range like object
15858 startContainer : startContainer,
15859 startOffset : startOffset,
15860 endContainer : endContainer,
15861 endOffset : endOffset
15865 function removeFormat(format, vars, node, compare_node) {
15866 var i, attrs, stylesModified;
15868 // Check if node matches format
15869 if (!matchName(node, format))
15872 // Should we compare with format attribs and styles
15873 if (format.remove != 'all') {
15875 each(format.styles, function(value, name) {
15876 value = replaceVars(value, vars);
15879 if (typeof(name) === 'number') {
15884 if (!compare_node || isEq(getStyle(compare_node, name), value))
15885 dom.setStyle(node, name, '');
15887 stylesModified = 1;
15890 // Remove style attribute if it's empty
15891 if (stylesModified && dom.getAttrib(node, 'style') == '') {
15892 node.removeAttribute('style');
15893 node.removeAttribute('data-mce-style');
15896 // Remove attributes
15897 each(format.attributes, function(value, name) {
15900 value = replaceVars(value, vars);
15903 if (typeof(name) === 'number') {
15908 if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) {
15909 // Keep internal classes
15910 if (name == 'class') {
15911 value = dom.getAttrib(node, name);
15913 // Build new class value where everything is removed except the internal prefixed classes
15915 each(value.split(/\s+/), function(cls) {
15916 if (/mce\w+/.test(cls))
15917 valueOut += (valueOut ? ' ' : '') + cls;
15920 // We got some internal classes left
15922 dom.setAttrib(node, name, valueOut);
15928 // IE6 has a bug where the attribute doesn't get removed correctly
15929 if (name == "class")
15930 node.removeAttribute('className');
15932 // Remove mce prefixed attributes
15933 if (MCE_ATTR_RE.test(name))
15934 node.removeAttribute('data-mce-' + name);
15936 node.removeAttribute(name);
15941 each(format.classes, function(value) {
15942 value = replaceVars(value, vars);
15944 if (!compare_node || dom.hasClass(compare_node, value))
15945 dom.removeClass(node, value);
15948 // Check for non internal attributes
15949 attrs = dom.getAttribs(node);
15950 for (i = 0; i < attrs.length; i++) {
15951 if (attrs[i].nodeName.indexOf('_') !== 0)
15956 // Remove the inline child if it's empty for example <b> or <span>
15957 if (format.remove != 'none') {
15958 removeNode(node, format);
15963 function removeNode(node, format) {
15964 var parentNode = node.parentNode, rootBlockElm;
15966 if (format.block) {
15967 if (!forcedRootBlock) {
15968 function find(node, next, inc) {
15969 node = getNonWhiteSpaceSibling(node, next, inc);
15971 return !node || (node.nodeName == 'BR' || isBlock(node));
15974 // Append BR elements if needed before we remove the block
15975 if (isBlock(node) && !isBlock(parentNode)) {
15976 if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1))
15977 node.insertBefore(dom.create('br'), node.firstChild);
15979 if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1))
15980 node.appendChild(dom.create('br'));
15983 // Wrap the block in a forcedRootBlock if we are at the root of document
15984 if (parentNode == dom.getRoot()) {
15985 if (!format.list_block || !isEq(node, format.list_block)) {
15986 each(tinymce.grep(node.childNodes), function(node) {
15987 if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) {
15989 rootBlockElm = wrap(node, forcedRootBlock);
15991 rootBlockElm.appendChild(node);
16000 // Never remove nodes that isn't the specified inline element if a selector is specified too
16001 if (format.selector && format.inline && !isEq(format.inline, node))
16004 dom.remove(node, 1);
16007 function getNonWhiteSpaceSibling(node, next, inc) {
16009 next = next ? 'nextSibling' : 'previousSibling';
16011 for (node = inc ? node : node[next]; node; node = node[next]) {
16012 if (node.nodeType == 1 || !isWhiteSpaceNode(node))
16018 function isBookmarkNode(node) {
16019 return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark';
16022 function mergeSiblings(prev, next) {
16023 var marker, sibling, tmpSibling;
16025 function compareElements(node1, node2) {
16026 // Not the same name
16027 if (node1.nodeName != node2.nodeName)
16030 function getAttribs(node) {
16033 each(dom.getAttribs(node), function(attr) {
16034 var name = attr.nodeName.toLowerCase();
16036 // Don't compare internal attributes or style
16037 if (name.indexOf('_') !== 0 && name !== 'style')
16038 attribs[name] = dom.getAttrib(node, name);
16044 function compareObjects(obj1, obj2) {
16047 for (name in obj1) {
16048 // Obj1 has item obj2 doesn't have
16049 if (obj1.hasOwnProperty(name)) {
16050 value = obj2[name];
16052 // Obj2 doesn't have obj1 item
16053 if (value === undefined)
16056 // Obj2 item has a different value
16057 if (obj1[name] != value)
16060 // Delete similar value
16065 // Check if obj 2 has something obj 1 doesn't have
16066 for (name in obj2) {
16067 // Obj2 has item obj1 doesn't have
16068 if (obj2.hasOwnProperty(name))
16075 // Attribs are not the same
16076 if (!compareObjects(getAttribs(node1), getAttribs(node2)))
16079 // Styles are not the same
16080 if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style'))))
16086 // Check if next/prev exists and that they are elements
16087 if (prev && next) {
16088 function findElementSibling(node, sibling_name) {
16089 for (sibling = node; sibling; sibling = sibling[sibling_name]) {
16090 if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0)
16093 if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
16100 // If previous sibling is empty then jump over it
16101 prev = findElementSibling(prev, 'previousSibling');
16102 next = findElementSibling(next, 'nextSibling');
16104 // Compare next and previous nodes
16105 if (compareElements(prev, next)) {
16106 // Append nodes between
16107 for (sibling = prev.nextSibling; sibling && sibling != next;) {
16108 tmpSibling = sibling;
16109 sibling = sibling.nextSibling;
16110 prev.appendChild(tmpSibling);
16113 // Remove next node
16116 // Move children into prev node
16117 each(tinymce.grep(next.childNodes), function(node) {
16118 prev.appendChild(node);
16128 function isTextBlock(name) {
16129 return /^(h[1-6]|p|div|pre|address|dl|dt|dd)$/.test(name);
16132 function getContainer(rng, start) {
16133 var container, offset, lastIdx;
16135 container = rng[start ? 'startContainer' : 'endContainer'];
16136 offset = rng[start ? 'startOffset' : 'endOffset'];
16138 if (container.nodeType == 1) {
16139 lastIdx = container.childNodes.length - 1;
16141 if (!start && offset)
16144 container = container.childNodes[offset > lastIdx ? lastIdx : offset];
16150 function performCaretAction(type, name, vars) {
16151 var i, currentPendingFormats = pendingFormats[type],
16152 otherPendingFormats = pendingFormats[type == 'apply' ? 'remove' : 'apply'];
16154 function hasPending() {
16155 return pendingFormats.apply.length || pendingFormats.remove.length;
16158 function resetPending() {
16159 pendingFormats.apply = [];
16160 pendingFormats.remove = [];
16163 function perform(caret_node) {
16164 // Apply pending formats
16165 each(pendingFormats.apply.reverse(), function(item) {
16166 apply(item.name, item.vars, caret_node);
16168 // Colored nodes should be underlined so that the color of the underline matches the text color.
16169 if (item.name === 'forecolor' && item.vars.value)
16170 processUnderlineAndColor(caret_node.parentNode);
16173 // Remove pending formats
16174 each(pendingFormats.remove.reverse(), function(item) {
16175 remove(item.name, item.vars, caret_node);
16178 dom.remove(caret_node, 1);
16182 // Check if it already exists then ignore it
16183 for (i = currentPendingFormats.length - 1; i >= 0; i--) {
16184 if (currentPendingFormats[i].name == name)
16188 currentPendingFormats.push({name : name, vars : vars});
16190 // Check if it's in the other type, then remove it
16191 for (i = otherPendingFormats.length - 1; i >= 0; i--) {
16192 if (otherPendingFormats[i].name == name)
16193 otherPendingFormats.splice(i, 1);
16196 // Pending apply or remove formats
16197 if (hasPending()) {
16198 ed.getDoc().execCommand('FontName', false, 'mceinline');
16199 pendingFormats.lastRng = selection.getRng();
16201 // IE will convert the current word
16202 each(dom.select('font,span'), function(node) {
16205 if (isCaretNode(node)) {
16206 bookmark = selection.getBookmark();
16208 selection.moveToBookmark(bookmark);
16213 // Only register listeners once if we need to
16214 if (!pendingFormats.isListening && hasPending()) {
16215 pendingFormats.isListening = true;
16216 function performPendingFormat(node, textNode) {
16217 var rng = dom.createRng();
16220 rng.setStart(textNode, textNode.nodeValue.length);
16221 rng.setEnd(textNode, textNode.nodeValue.length);
16222 selection.setRng(rng);
16225 var enterKeyPressed = false;
16227 each('onKeyDown,onKeyUp,onKeyPress,onMouseUp'.split(','), function(event) {
16228 ed[event].addToTop(function(ed, e) {
16229 if (e.keyCode==13 && !e.shiftKey) {
16230 enterKeyPressed = true;
16233 // Do we have pending formats and is the selection moved has moved
16234 if (hasPending() && !tinymce.dom.RangeUtils.compareRanges(pendingFormats.lastRng, selection.getRng())) {
16235 var foundCaret = false;
16236 each(dom.select('font,span'), function(node) {
16240 if (isCaretNode(node)) {
16242 textNode = node.firstChild;
16244 // Find the first text node within node
16245 while (textNode && textNode.nodeType != 3)
16246 textNode = textNode.firstChild;
16249 performPendingFormat(node, textNode);
16255 // no caret - so we are
16256 if (enterKeyPressed && !foundCaret) {
16257 var node = selection.getNode();
16258 var textNode = node;
16260 // Find the first text node within node
16261 while (textNode && textNode.nodeType != 3)
16262 textNode = textNode.firstChild;
16264 node=textNode.parentNode;
16265 while (!isBlock(node)){
16266 node=node.parentNode;
16268 performPendingFormat(node, textNode);
16272 // Always unbind and clear pending styles on keyup
16273 if (e.type == 'keyup' || e.type == 'mouseup') {
16275 enterKeyPressed=false;
16286 tinymce.onAddEditor.add(function(tinymce, ed) {
16287 var filters, fontSizes, dom, settings = ed.settings;
16289 if (settings.inline_styles) {
16290 fontSizes = tinymce.explode(settings.font_size_style_values);
16292 function replaceWithSpan(node, styles) {
16293 tinymce.each(styles, function(value, name) {
16295 dom.setStyle(node, name, value);
16298 dom.rename(node, 'span');
16302 font : function(dom, node) {
16303 replaceWithSpan(node, {
16304 backgroundColor : node.style.backgroundColor,
16305 color : node.color,
16306 fontFamily : node.face,
16307 fontSize : fontSizes[parseInt(node.size) - 1]
16311 u : function(dom, node) {
16312 replaceWithSpan(node, {
16313 textDecoration : 'underline'
16317 strike : function(dom, node) {
16318 replaceWithSpan(node, {
16319 textDecoration : 'line-through'
16324 function convert(editor, params) {
16327 if (settings.convert_fonts_to_spans) {
16328 tinymce.each(dom.select('font,u,strike', params.node), function(node) {
16329 filters[node.nodeName.toLowerCase()](ed.dom, node);
16334 ed.onPreProcess.add(convert);
16335 ed.onSetContent.add(convert);
16337 ed.onInit.add(function() {
16338 ed.selection.onSetContent.add(convert);