Upgrade TinyMCE to v3.4.5
[citadel.git] / webcit / tiny_mce / tiny_mce_src.js
index 09fa85c8f460332000acc9dc6affe20b03c096a6..8c665b09535c46d2bdac3012c7b881f0948b6e2c 100644 (file)
-/**\r
- * $RCSfile: tiny_mce_src.js,v $\r
- * $Revision: 1.281 $\r
- * $Date: 2005/12/02 08:12:07 $\r
- *\r
- * @author Moxiecode\r
- * @copyright Copyright © 2004, Moxiecode Systems AB, All rights reserved.\r
- */\r
+(function(win) {\r
+       var whiteSpaceRe = /^\s*|\s*$/g,\r
+               undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';\r
 \r
-function TinyMCE() {\r
-       this.majorVersion = "2";\r
-       this.minorVersion = "0";\r
-       this.releaseDate = "2005-12-01";\r
-\r
-       this.instances = new Array();\r
-       this.stickyClassesLookup = new Array();\r
-       this.windowArgs = new Array();\r
-       this.loadedFiles = new Array();\r
-       this.configs = new Array();\r
-       this.currentConfig = 0;\r
-       this.eventHandlers = new Array();\r
-\r
-       // Browser check\r
-       var ua = navigator.userAgent;\r
-       this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");\r
-       this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);\r
-       this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);\r
-       this.isGecko = ua.indexOf('Gecko') != -1;\r
-       this.isSafari = ua.indexOf('Safari') != -1;\r
-       this.isOpera = ua.indexOf('Opera') != -1;\r
-       this.isMac = ua.indexOf('Mac') != -1;\r
-       this.isNS7 = ua.indexOf('Netscape/7') != -1;\r
-       this.isNS71 = ua.indexOf('Netscape/7.1') != -1;\r
-       this.dialogCounter = 0;\r
-\r
-       // Fake MSIE on Opera and if Opera fakes IE, Gecko or Safari cancel those\r
-       if (this.isOpera) {\r
-               this.isMSIE = true;\r
-               this.isGecko = false;\r
-               this.isSafari =  false;\r
-       }\r
+       var tinymce = {\r
+               majorVersion : '3',\r
 \r
-       // TinyMCE editor id instance counter\r
-       this.idCounter = 0;\r
-};\r
+               minorVersion : '4.5',\r
 \r
-TinyMCE.prototype.defParam = function(key, def_val) {\r
-       this.settings[key] = tinyMCE.getParam(key, def_val);\r
-};\r
+               releaseDate : '2011-09-06',\r
 \r
-TinyMCE.prototype.init = function(settings) {\r
-       var theme;\r
+               _init : function() {\r
+                       var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v;\r
 \r
-       this.settings = settings;\r
+                       t.isOpera = win.opera && opera.buildNumber;\r
 \r
-       // Check if valid browser has execcommand support\r
-       if (typeof(document.execCommand) == 'undefined')\r
-               return;\r
+                       t.isWebKit = /WebKit/.test(ua);\r
 \r
-       // Get script base path\r
-       if (!tinyMCE.baseURL) {\r
-               var elements = document.getElementsByTagName('script');\r
+                       t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);\r
 \r
-               for (var i=0; i<elements.length; i++) {\r
-                       if (elements[i].src && (elements[i].src.indexOf("tiny_mce.js") != -1 || elements[i].src.indexOf("tiny_mce_src.js") != -1 || elements[i].src.indexOf("tiny_mce_gzip") != -1)) {\r
-                               var src = elements[i].src;\r
+                       t.isIE6 = t.isIE && /MSIE [56]/.test(ua);\r
 \r
-                               tinyMCE.srcMode = (src.indexOf('_src') != -1) ? '_src' : '';\r
-                               src = src.substring(0, src.lastIndexOf('/'));\r
+                       t.isIE7 = t.isIE && /MSIE [7]/.test(ua);\r
 \r
-                               tinyMCE.baseURL = src;\r
-                               break;\r
-                       }\r
-               }\r
-       }\r
+                       t.isIE8 = t.isIE && /MSIE [8]/.test(ua);\r
 \r
-       // Get document base path\r
-       this.documentBasePath = document.location.href;\r
-       if (this.documentBasePath.indexOf('?') != -1)\r
-               this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.indexOf('?'));\r
-       this.documentURL = this.documentBasePath;\r
-       this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.lastIndexOf('/'));\r
-\r
-       // If not HTTP absolute\r
-       if (tinyMCE.baseURL.indexOf('://') == -1 && tinyMCE.baseURL.charAt(0) != '/') {\r
-               // If site absolute\r
-               tinyMCE.baseURL = this.documentBasePath + "/" + tinyMCE.baseURL;\r
-       }\r
+                       t.isIE9 = t.isIE && /MSIE [9]/.test(ua);\r
 \r
-       // Set default values on settings\r
-       this.defParam("mode", "none");\r
-       this.defParam("theme", "advanced");\r
-       this.defParam("plugins", "", true);\r
-       this.defParam("language", "en");\r
-       this.defParam("docs_language", this.settings['language']);\r
-       this.defParam("elements", "");\r
-       this.defParam("textarea_trigger", "mce_editable");\r
-       this.defParam("editor_selector", "");\r
-       this.defParam("editor_deselector", "mceNoEditor");\r
-       this.defParam("valid_elements", "+a[id|style|rel|rev|charset|hreflang|dir|lang|tabindex|accesskey|type|name|href|target|title|class|onfocus|onblur|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup],-strong/b[class|style],-em/i[class|style],-strike[class|style],-u[class|style],+p[style|dir|class|align],-ol[class|style],-ul[class|style],-li[class|style],br,img[id|dir|lang|longdesc|usemap|style|class|src|onmouseover|onmouseout|border=0|alt|title|hspace|vspace|width|height|align],-sub[style|class],-sup[style|class],-blockquote[dir|style],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|style|dir|id|lang|bgcolor|background|bordercolor],-tr[id|lang|dir|class|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor],tbody[id|class],thead[id|class],tfoot[id|class],-td[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor|scope],-th[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|scope],caption[id|lang|dir|class|style],-div[id|dir|class|align|style],-span[style|class|align],-pre[class|align|style],address[class|align|style],-h1[style|dir|class|align],-h2[style|dir|class|align],-h3[style|dir|class|align],-h4[style|dir|class|align],-h5[style|dir|class|align],-h6[style|dir|class|align],hr[class|style],font[face|size|style|id|class|dir|color]");\r
-       this.defParam("extended_valid_elements", "");\r
-       this.defParam("invalid_elements", "");\r
-       this.defParam("encoding", "");\r
-       this.defParam("urlconverter_callback", tinyMCE.getParam("urlconvertor_callback", "TinyMCE.prototype.convertURL"));\r
-       this.defParam("save_callback", "");\r
-       this.defParam("debug", false);\r
-       this.defParam("force_br_newlines", false);\r
-       this.defParam("force_p_newlines", true);\r
-       this.defParam("add_form_submit_trigger", true);\r
-       this.defParam("relative_urls", true);\r
-       this.defParam("remove_script_host", true);\r
-       this.defParam("focus_alert", true);\r
-       this.defParam("document_base_url", this.documentURL);\r
-       this.defParam("visual", true);\r
-       this.defParam("visual_table_class", "mceVisualAid");\r
-       this.defParam("setupcontent_callback", "");\r
-       this.defParam("fix_content_duplication", true);\r
-       this.defParam("custom_undo_redo", true);\r
-       this.defParam("custom_undo_redo_levels", -1);\r
-       this.defParam("custom_undo_redo_keyboard_shortcuts", true);\r
-       this.defParam("verify_css_classes", false);\r
-       this.defParam("verify_html", true);\r
-       this.defParam("apply_source_formatting", false);\r
-       this.defParam("directionality", "ltr");\r
-       this.defParam("cleanup_on_startup", false);\r
-       this.defParam("inline_styles", false);\r
-       this.defParam("convert_newlines_to_brs", false);\r
-       this.defParam("auto_reset_designmode", true);\r
-       this.defParam("entities", "160,nbsp,38,amp,34,quot,162,cent,8364,euro,163,pound,165,yen,169,copy,174,reg,8482,trade,8240,permil,181,micro,183,middot,8226,bull,8230,hellip,8242,prime,8243,Prime,167,sect,182,para,223,szlig,8249,lsaquo,8250,rsaquo,171,laquo,187,raquo,8216,lsquo,8217,rsquo,8220,ldquo,8221,rdquo,8218,sbquo,8222,bdquo,60,lt,62,gt,8804,le,8805,ge,8211,ndash,8212,mdash,175,macr,8254,oline,164,curren,166,brvbar,168,uml,161,iexcl,191,iquest,710,circ,732,tilde,176,deg,8722,minus,177,plusmn,247,divide,8260,frasl,215,times,185,sup1,178,sup2,179,sup3,188,frac14,189,frac12,190,frac34,402,fnof,8747,int,8721,sum,8734,infin,8730,radic,8764,sim,8773,cong,8776,asymp,8800,ne,8801,equiv,8712,isin,8713,notin,8715,ni,8719,prod,8743,and,8744,or,172,not,8745,cap,8746,cup,8706,part,8704,forall,8707,exist,8709,empty,8711,nabla,8727,lowast,8733,prop,8736,ang,180,acute,184,cedil,170,ordf,186,ordm,8224,dagger,8225,Dagger,192,Agrave,194,Acirc,195,Atilde,196,Auml,197,Aring,198,AElig,199,Ccedil,200,Egrave,202,Ecirc,203,Euml,204,Igrave,206,Icirc,207,Iuml,208,ETH,209,Ntilde,210,Ograve,212,Ocirc,213,Otilde,214,Ouml,216,Oslash,338,OElig,217,Ugrave,219,Ucirc,220,Uuml,376,Yuml,222,THORN,224,agrave,226,acirc,227,atilde,228,auml,229,aring,230,aelig,231,ccedil,232,egrave,234,ecirc,235,euml,236,igrave,238,icirc,239,iuml,240,eth,241,ntilde,242,ograve,244,ocirc,245,otilde,246,ouml,248,oslash,339,oelig,249,ugrave,251,ucirc,252,uuml,254,thorn,255,yuml,914,Beta,915,Gamma,916,Delta,917,Epsilon,918,Zeta,919,Eta,920,Theta,921,Iota,922,Kappa,923,Lambda,924,Mu,925,Nu,926,Xi,927,Omicron,928,Pi,929,Rho,931,Sigma,932,Tau,933,Upsilon,934,Phi,935,Chi,936,Psi,937,Omega,945,alpha,946,beta,947,gamma,948,delta,949,epsilon,950,zeta,951,eta,952,theta,953,iota,954,kappa,955,lambda,956,mu,957,nu,958,xi,959,omicron,960,pi,961,rho,962,sigmaf,963,sigma,964,tau,965,upsilon,966,phi,967,chi,968,psi,969,omega,8501,alefsym,982,piv,8476,real,977,thetasym,978,upsih,8472,weierp,8465,image,8592,larr,8593,uarr,8594,rarr,8595,darr,8596,harr,8629,crarr,8656,lArr,8657,uArr,8658,rArr,8659,dArr,8660,hArr,8756,there4,8834,sub,8835,sup,8836,nsub,8838,sube,8839,supe,8853,oplus,8855,otimes,8869,perp,8901,sdot,8968,lceil,8969,rceil,8970,lfloor,8971,rfloor,9001,lang,9002,rang,9674,loz,9824,spades,9827,clubs,9829,hearts,9830,diams,8194,ensp,8195,emsp,8201,thinsp,8204,zwnj,8205,zwj,8206,lrm,8207,rlm,173,shy,233,eacute,237,iacute,243,oacute,250,uacute,193,Aacute,225,aacute,201,Eacute,205,Iacute,211,Oacute,218,Uacute,221,Yacute,253,yacute");\r
-       this.defParam("entity_encoding", "named");\r
-       this.defParam("cleanup_callback", "");\r
-       this.defParam("add_unload_trigger", true);\r
-       this.defParam("ask", false);\r
-       this.defParam("nowrap", false);\r
-       this.defParam("auto_resize", false);\r
-       this.defParam("auto_focus", false);\r
-       this.defParam("cleanup", true);\r
-       this.defParam("remove_linebreaks", true);\r
-       this.defParam("button_tile_map", false);\r
-       this.defParam("submit_patch", true);\r
-       this.defParam("browsers", "msie,safari,gecko,opera");\r
-       this.defParam("dialog_type", "window");\r
-       this.defParam("accessibility_warnings", true);\r
-       this.defParam("merge_styles_invalid_parents", "");\r
-       this.defParam("force_hex_style_colors", true);\r
-       this.defParam("trim_span_elements", true);\r
-       this.defParam("convert_fonts_to_spans", false);\r
-       this.defParam("doctype", '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');\r
-       this.defParam("font_size_classes", '');\r
-       this.defParam("font_size_style_values", 'xx-small,x-small,small,medium,large,x-large,xx-large');\r
-       this.defParam("event_elements", 'a,img');\r
-       this.defParam("convert_urls", true);\r
-       this.defParam("table_inline_editing", false);\r
-       this.defParam("object_resizing", true);\r
-\r
-       // Browser check IE\r
-       if (this.isMSIE && this.settings['browsers'].indexOf('msie') == -1)\r
-               return;\r
+                       t.isGecko = !t.isWebKit && /Gecko/.test(ua);\r
 \r
-       // Browser check Gecko\r
-       if (this.isGecko && this.settings['browsers'].indexOf('gecko') == -1)\r
-               return;\r
+                       t.isMac = ua.indexOf('Mac') != -1;\r
 \r
-       // Browser check Safari\r
-       if (this.isSafari && this.settings['browsers'].indexOf('safari') == -1)\r
-               return;\r
+                       t.isAir = /adobeair/i.test(ua);\r
 \r
-       // Browser check Opera\r
-       if (this.isOpera && this.settings['browsers'].indexOf('opera') == -1)\r
-               return;\r
+                       t.isIDevice = /(iPad|iPhone)/.test(ua);\r
+                       \r
+                       t.isIOS5 = t.isIDevice && ua.match(/AppleWebKit\/(\d*)/)[1]>=534;\r
 \r
-       // If not super absolute make it so\r
-       var baseHREF = tinyMCE.settings['document_base_url'];\r
-       var h = document.location.href;\r
-       var p = h.indexOf('://');\r
-       if (p > 0 && document.location.protocol != "file:") {\r
-               p = h.indexOf('/', p + 3);\r
-               h = h.substring(0, p);\r
+                       // TinyMCE .NET webcontrol might be setting the values for TinyMCE\r
+                       if (win.tinyMCEPreInit) {\r
+                               t.suffix = tinyMCEPreInit.suffix;\r
+                               t.baseURL = tinyMCEPreInit.base;\r
+                               t.query = tinyMCEPreInit.query;\r
+                               return;\r
+                       }\r
 \r
-               if (baseHREF.indexOf('://') == -1)\r
-                       baseHREF = h + baseHREF;\r
+                       // Get suffix and base\r
+                       t.suffix = '';\r
 \r
-               tinyMCE.settings['document_base_url'] = baseHREF;\r
-               tinyMCE.settings['document_base_prefix'] = h;\r
-       }\r
+                       // If base element found, add that infront of baseURL\r
+                       nl = d.getElementsByTagName('base');\r
+                       for (i=0; i<nl.length; i++) {\r
+                               if (v = nl[i].href) {\r
+                                       // Host only value like http://site.com or http://site.com:8008\r
+                                       if (/^https?:\/\/[^\/]+$/.test(v))\r
+                                               v += '/';\r
 \r
-       // Trim away query part\r
-       if (baseHREF.indexOf('?') != -1)\r
-               baseHREF = baseHREF.substring(0, baseHREF.indexOf('?'));\r
-\r
-       this.settings['base_href'] = baseHREF.substring(0, baseHREF.lastIndexOf('/')) + "/";\r
-\r
-       theme = this.settings['theme'];\r
-       this.blockRegExp = new RegExp("^(h[1-6]|p|div|address|pre|form|table|li|ol|ul|td|blockquote|center|dl|dir|fieldset|form|noscript|noframes|menu|isindex)$", "i");\r
-       this.posKeyCodes = new Array(13,45,36,35,33,34,37,38,39,40);\r
-       this.uniqueURL = 'http://tinymce.moxiecode.cp/mce_temp_url'; // Make unique URL non real URL\r
-       this.uniqueTag = '<div id="mceTMPElement" style="display: none">TMP</div>';\r
-\r
-       // Theme url\r
-       this.settings['theme_href'] = tinyMCE.baseURL + "/themes/" + theme;\r
-\r
-       if (!tinyMCE.isMSIE)\r
-               this.settings['force_br_newlines'] = false;\r
-\r
-       if (tinyMCE.getParam("content_css", false)) {\r
-               var cssPath = tinyMCE.getParam("content_css", "");\r
-\r
-               // Is relative\r
-               if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')\r
-                       this.settings['content_css'] = this.documentBasePath + "/" + cssPath;\r
-               else\r
-                       this.settings['content_css'] = cssPath;\r
-       } else\r
-               this.settings['content_css'] = '';\r
-\r
-       if (tinyMCE.getParam("popups_css", false)) {\r
-               var cssPath = tinyMCE.getParam("popups_css", "");\r
-\r
-               // Is relative\r
-               if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')\r
-                       this.settings['popups_css'] = this.documentBasePath + "/" + cssPath;\r
-               else\r
-                       this.settings['popups_css'] = cssPath;\r
-       } else\r
-               this.settings['popups_css'] = tinyMCE.baseURL + "/themes/" + theme + "/css/editor_popup.css";\r
-\r
-       if (tinyMCE.getParam("editor_css", false)) {\r
-               var cssPath = tinyMCE.getParam("editor_css", "");\r
-\r
-               // Is relative\r
-               if (cssPath.indexOf('://') == -1 && cssPath.charAt(0) != '/')\r
-                       this.settings['editor_css'] = this.documentBasePath + "/" + cssPath;\r
-               else\r
-                       this.settings['editor_css'] = cssPath;\r
-       } else\r
-               this.settings['editor_css'] = tinyMCE.baseURL + "/themes/" + theme + "/css/editor_ui.css";\r
-\r
-       if (tinyMCE.settings['debug']) {\r
-               var msg = "Debug: \n";\r
-\r
-               msg += "baseURL: " + this.baseURL + "\n";\r
-               msg += "documentBasePath: " + this.documentBasePath + "\n";\r
-               msg += "content_css: " + this.settings['content_css'] + "\n";\r
-               msg += "popups_css: " + this.settings['popups_css'] + "\n";\r
-               msg += "editor_css: " + this.settings['editor_css'] + "\n";\r
-\r
-               alert(msg);\r
-       }\r
+                                       base = v ? v.match(/.*\//)[0] : ''; // Get only directory\r
+                               }\r
+                       }\r
 \r
-       // Init HTML cleanup\r
-       this._initCleanup();\r
+                       function getBase(n) {\r
+                               if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) {\r
+                                       if (/_(src|dev)\.js/g.test(n.src))\r
+                                               t.suffix = '_src';\r
 \r
-       // Only do this once\r
-       if (this.configs.length == 0) {\r
-               // Is Safari enabled\r
-               if (this.isSafari && this.getParam('safari_warning', true))\r
-                       alert("Safari support is very limited and should be considered experimental.\nSo there is no need to even submit bugreports on this early version.\nYou can disable this message by setting: safari_warning option to false");\r
+                                       if ((p = n.src.indexOf('?')) != -1)\r
+                                               t.query = n.src.substring(p + 1);\r
 \r
-               tinyMCE.addEvent(window, "load", TinyMCE.prototype.onLoad);\r
+                                       t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));\r
 \r
-               if (tinyMCE.isMSIE) {\r
-                       if (tinyMCE.settings['add_unload_trigger']) {\r
-                               tinyMCE.addEvent(window, "unload", TinyMCE.prototype.unloadHandler);\r
-                               tinyMCE.addEvent(window.document, "beforeunload", TinyMCE.prototype.unloadHandler);\r
-                       }\r
-               } else {\r
-                       if (tinyMCE.settings['add_unload_trigger'])\r
-                               tinyMCE.addEvent(window, "unload", function () {tinyMCE.triggerSave(true, true);});\r
-               }\r
-       }\r
+                                       // If path to script is relative and a base href was found add that one infront\r
+                                       // the src property will always be an absolute one on non IE browsers and IE 8\r
+                                       // so this logic will basically only be executed on older IE versions\r
+                                       if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0)\r
+                                               t.baseURL = base + t.baseURL;\r
 \r
-       this.loadScript(tinyMCE.baseURL + '/themes/' + this.settings['theme'] + '/editor_template' + tinyMCE.srcMode + '.js');\r
-       this.loadScript(tinyMCE.baseURL + '/langs/' + this.settings['language'] +  '.js');\r
-       this.loadCSS(this.settings['editor_css']);\r
+                                       return t.baseURL;\r
+                               }\r
 \r
-       // Add plugins\r
-       var themePlugins = tinyMCE.getParam('plugins', '', true, ',');\r
-       if (this.settings['plugins'] != '') {\r
-               for (var i=0; i<themePlugins.length; i++)\r
-                       this.loadScript(tinyMCE.baseURL + '/plugins/' + themePlugins[i] + '/editor_plugin' + tinyMCE.srcMode + '.js');\r
-       }\r
+                               return null;\r
+                       };\r
 \r
-       // Setup entities\r
-       settings['cleanup_entities'] = new Array();\r
-       var entities = tinyMCE.getParam('entities', '', true, ',');\r
-       for (var i=0; i<entities.length; i+=2)\r
-               settings['cleanup_entities']['c' + entities[i]] = entities[i+1];\r
+                       // Check document\r
+                       nl = d.getElementsByTagName('script');\r
+                       for (i=0; i<nl.length; i++) {\r
+                               if (getBase(nl[i]))\r
+                                       return;\r
+                       }\r
 \r
-       // Save away this config\r
-       settings['index'] = this.configs.length;\r
-       this.configs[this.configs.length] = settings;\r
-};\r
+                       // Check head\r
+                       n = d.getElementsByTagName('head')[0];\r
+                       if (n) {\r
+                               nl = n.getElementsByTagName('script');\r
+                               for (i=0; i<nl.length; i++) {\r
+                                       if (getBase(nl[i]))\r
+                                               return;\r
+                               }\r
+                       }\r
 \r
-TinyMCE.prototype.loadScript = function(url) {\r
-       for (var i=0; i<this.loadedFiles.length; i++) {\r
-               if (this.loadedFiles[i] == url)\r
                        return;\r
-       }\r
-\r
-       document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></script>');\r
+               },\r
 \r
-       this.loadedFiles[this.loadedFiles.length] = url;\r
-};\r
+               is : function(o, t) {\r
+                       if (!t)\r
+                               return o !== undefined;\r
 \r
-TinyMCE.prototype.loadCSS = function(url) {\r
-       for (var i=0; i<this.loadedFiles.length; i++) {\r
-               if (this.loadedFiles[i] == url)\r
-                       return;\r
-       }\r
+                       if (t == 'array' && (o.hasOwnProperty && o instanceof Array))\r
+                               return true;\r
 \r
-       document.write('<link href="' + url + '" rel="stylesheet" type="text/css" />');\r
+                       return typeof(o) == t;\r
+               },\r
 \r
-       this.loadedFiles[this.loadedFiles.length] = url;\r
-};\r
+               makeMap : function(items, delim, map) {\r
+                       var i;\r
 \r
-TinyMCE.prototype.importCSS = function(doc, css_file) {\r
-       if (css_file == '')\r
-               return;\r
+                       items = items || [];\r
+                       delim = delim || ',';\r
 \r
-       if (typeof(doc.createStyleSheet) == "undefined") {\r
-               var elm = doc.createElement("link");\r
+                       if (typeof(items) == "string")\r
+                               items = items.split(delim);\r
 \r
-               elm.rel = "stylesheet";\r
-               elm.href = css_file;\r
+                       map = map || {};\r
 \r
-               if ((headArr = doc.getElementsByTagName("head")) != null && headArr.length > 0)\r
-                       headArr[0].appendChild(elm);\r
-       } else\r
-               var styleSheet = doc.createStyleSheet(css_file);\r
-};\r
+                       i = items.length;\r
+                       while (i--)\r
+                               map[items[i]] = {};\r
 \r
-TinyMCE.prototype.confirmAdd = function(e, settings) {\r
-       var elm = tinyMCE.isMSIE ? event.srcElement : e.target;\r
-       var elementId = elm.name ? elm.name : elm.id;\r
+                       return map;\r
+               },\r
 \r
-       tinyMCE.settings = settings;\r
+               each : function(o, cb, s) {\r
+                       var n, l;\r
 \r
-       if (!elm.getAttribute('mce_noask') && confirm(tinyMCELang['lang_edit_confirm']))\r
-               tinyMCE.addMCEControl(elm, elementId);\r
+                       if (!o)\r
+                               return 0;\r
 \r
-       elm.setAttribute('mce_noask', 'true');\r
-};\r
+                       s = s || o;\r
 \r
-TinyMCE.prototype.updateContent = function(form_element_name) {\r
-       // Find MCE instance linked to given form element and copy it's value\r
-       var formElement = document.getElementById(form_element_name);\r
-       for (var n in tinyMCE.instances) {\r
-               var inst = tinyMCE.instances[n];\r
-               if (!tinyMCE.isInstance(inst))\r
-                       continue;\r
+                       if (o.length !== undefined) {\r
+                               // Indexed arrays, needed for Safari\r
+                               for (n=0, l = o.length; n < l; n++) {\r
+                                       if (cb.call(s, o[n], n, o) === false)\r
+                                               return 0;\r
+                               }\r
+                       } else {\r
+                               // Hashtables\r
+                               for (n in o) {\r
+                                       if (o.hasOwnProperty(n)) {\r
+                                               if (cb.call(s, o[n], n, o) === false)\r
+                                                       return 0;\r
+                                       }\r
+                               }\r
+                       }\r
 \r
-               inst.switchSettings();\r
+                       return 1;\r
+               },\r
 \r
-               if (inst.formElement == formElement) {\r
-                       var doc = inst.getDoc();\r
-       \r
-                       tinyMCE._setHTML(doc, inst.formElement.value);\r
 \r
-                       if (!tinyMCE.isMSIE)\r
-                               doc.body.innerHTML = tinyMCE._cleanupHTML(inst, doc, this.settings, doc.body, inst.visualAid);\r
-               }\r
-       }\r
-};\r
+               map : function(a, f) {\r
+                       var o = [];\r
 \r
-TinyMCE.prototype.addMCEControl = function(replace_element, form_element_name, target_document) {\r
-       var id = "mce_editor_" + tinyMCE.idCounter++;\r
-       var inst = new TinyMCEControl(tinyMCE.settings);\r
+                       tinymce.each(a, function(v) {\r
+                               o.push(f(v));\r
+                       });\r
 \r
-       inst.editorId = id;\r
-       this.instances[id] = inst;\r
+                       return o;\r
+               },\r
 \r
-       inst.onAdd(replace_element, form_element_name, target_document);\r
-};\r
+               grep : function(a, f) {\r
+                       var o = [];\r
 \r
-TinyMCE.prototype.triggerSave = function(skip_cleanup, skip_callback) {\r
-       // Cleanup and set all form fields\r
-       for (var n in tinyMCE.instances) {\r
-               var inst = tinyMCE.instances[n];\r
-               if (!tinyMCE.isInstance(inst))\r
-                       continue;\r
+                       tinymce.each(a, function(v) {\r
+                               if (!f || f(v))\r
+                                       o.push(v);\r
+                       });\r
 \r
-               inst.switchSettings();\r
+                       return o;\r
+               },\r
 \r
-               tinyMCE.settings['preformatted'] = false;\r
+               inArray : function(a, v) {\r
+                       var i, l;\r
 \r
-               // Default to false\r
-               if (typeof(skip_cleanup) == "undefined")\r
-                       skip_cleanup = false;\r
+                       if (a) {\r
+                               for (i = 0, l = a.length; i < l; i++) {\r
+                                       if (a[i] === v)\r
+                                               return i;\r
+                               }\r
+                       }\r
 \r
-               // Default to false\r
-               if (typeof(skip_callback) == "undefined")\r
-                       skip_callback = false;\r
+                       return -1;\r
+               },\r
 \r
-               tinyMCE._setHTML(inst.getDoc(), inst.getBody().innerHTML);\r
+               extend : function(o, e) {\r
+                       var i, l, a = arguments;\r
 \r
-               // Remove visual aids when cleanup is disabled\r
-               if (inst.settings['cleanup'] == false) {\r
-                       tinyMCE.handleVisualAid(inst.getBody(), true, false, inst);\r
-                       tinyMCE._setEventsEnabled(inst.getBody(), true);\r
-               }\r
+                       for (i = 1, l = a.length; i < l; i++) {\r
+                               e = a[i];\r
 \r
-               tinyMCE._customCleanup(inst, "submit_content_dom", inst.contentWindow.document.body);\r
-               var htm = skip_cleanup ? inst.getBody().innerHTML : tinyMCE._cleanupHTML(inst, inst.getDoc(), this.settings, inst.getBody(), this.visualAid, true);\r
-               htm = tinyMCE._customCleanup(inst, "submit_content", htm);\r
+                               tinymce.each(e, function(v, n) {\r
+                                       if (v !== undefined)\r
+                                               o[n] = v;\r
+                               });\r
+                       }\r
 \r
-               if (tinyMCE.settings["encoding"] == "xml" || tinyMCE.settings["encoding"] == "html")\r
-                       htm = tinyMCE.convertStringToXML(htm);\r
+                       return o;\r
+               },\r
 \r
-               if (!skip_callback && tinyMCE.settings['save_callback'] != "")\r
-                       var content = eval(tinyMCE.settings['save_callback'] + "(inst.formTargetElementId,htm,inst.getBody());");\r
 \r
-               // Use callback content if available\r
-               if ((typeof(content) != "undefined") && content != null)\r
-                       htm = content;\r
+               trim : function(s) {\r
+                       return (s ? '' + s : '').replace(whiteSpaceRe, '');\r
+               },\r
 \r
-               // Replace some weird entities (Bug: #1056343)\r
-               htm = tinyMCE.regexpReplace(htm, "&#40;", "(", "gi");\r
-               htm = tinyMCE.regexpReplace(htm, "&#41;", ")", "gi");\r
-               htm = tinyMCE.regexpReplace(htm, "&#59;", ";", "gi");\r
-               htm = tinyMCE.regexpReplace(htm, "&#34;", "&quot;", "gi");\r
-               htm = tinyMCE.regexpReplace(htm, "&#94;", "^", "gi");\r
+               create : function(s, p, root) {\r
+                       var t = this, sp, ns, cn, scn, c, de = 0;\r
 \r
-               if (inst.formElement)\r
-                       inst.formElement.value = htm;\r
-       }\r
-};\r
+                       // Parse : <prefix> <class>:<super class>\r
+                       s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);\r
+                       cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name\r
 \r
-TinyMCE.prototype._setEventsEnabled = function(node, state) {\r
-       var events = new Array('onfocus','onblur','onclick','ondblclick',\r
-                               'onmousedown','onmouseup','onmouseover','onmousemove',\r
-                               'onmouseout','onkeypress','onkeydown','onkeydown','onkeyup');\r
+                       // Create namespace for new class\r
+                       ns = t.createNS(s[3].replace(/\.\w+$/, ''), root);\r
 \r
-       var evs = tinyMCE.settings['event_elements'].split(',');\r
-    for (var y=0; y<evs.length; y++){\r
-               var elms = node.getElementsByTagName(evs[y]);\r
-               for (var i=0; i<elms.length; i++) {\r
-                       var event = "";\r
+                       // Class already exists\r
+                       if (ns[cn])\r
+                               return;\r
 \r
-                       for (var x=0; x<events.length; x++) {\r
-                               if ((event = tinyMCE.getAttrib(elms[i], events[x])) != '') {\r
-                                       event = tinyMCE.cleanupEventStr("" + event);\r
+                       // Make pure static class\r
+                       if (s[2] == 'static') {\r
+                               ns[cn] = p;\r
 \r
-                                       if (!state)\r
-                                               event = "return true;" + event;\r
-                                       else\r
-                                               event = event.replace(/^return true;/gi, '');\r
+                               if (this.onCreate)\r
+                                       this.onCreate(s[2], s[3], ns[cn]);\r
 \r
-                                       elms[i].removeAttribute(events[x]);\r
-                                       elms[i].setAttribute(events[x], event);\r
-                               }\r
+                               return;\r
                        }\r
-               }\r
-       }\r
-};\r
-\r
-TinyMCE.prototype.resetForm = function(form_index) {\r
-       var formObj = document.forms[form_index];\r
 \r
-       for (var n in tinyMCE.instances) {\r
-               var inst = tinyMCE.instances[n];\r
-               if (!tinyMCE.isInstance(inst))\r
-                       continue;\r
-\r
-               inst.switchSettings();\r
+                       // Create default constructor\r
+                       if (!p[cn]) {\r
+                               p[cn] = function() {};\r
+                               de = 1;\r
+                       }\r
 \r
-               for (var i=0; i<formObj.elements.length; i++) {\r
-                       if (inst.formTargetElementId == formObj.elements[i].name)\r
-                               inst.getBody().innerHTML = inst.startContent;\r
-               }\r
-       }\r
-};\r
+                       // Add constructor and methods\r
+                       ns[cn] = p[cn];\r
+                       t.extend(ns[cn].prototype, p);\r
+\r
+                       // Extend\r
+                       if (s[5]) {\r
+                               sp = t.resolve(s[5]).prototype;\r
+                               scn = s[5].match(/\.(\w+)$/i)[1]; // Class name\r
+\r
+                               // Extend constructor\r
+                               c = ns[cn];\r
+                               if (de) {\r
+                                       // Add passthrough constructor\r
+                                       ns[cn] = function() {\r
+                                               return sp[scn].apply(this, arguments);\r
+                                       };\r
+                               } else {\r
+                                       // Add inherit constructor\r
+                                       ns[cn] = function() {\r
+                                               this.parent = sp[scn];\r
+                                               return c.apply(this, arguments);\r
+                                       };\r
+                               }\r
+                               ns[cn].prototype[cn] = ns[cn];\r
+\r
+                               // Add super methods\r
+                               t.each(sp, function(f, n) {\r
+                                       ns[cn].prototype[n] = sp[n];\r
+                               });\r
+\r
+                               // Add overridden methods\r
+                               t.each(p, function(f, n) {\r
+                                       // Extend methods if needed\r
+                                       if (sp[n]) {\r
+                                               ns[cn].prototype[n] = function() {\r
+                                                       this.parent = sp[n];\r
+                                                       return f.apply(this, arguments);\r
+                                               };\r
+                                       } else {\r
+                                               if (n != cn)\r
+                                                       ns[cn].prototype[n] = f;\r
+                                       }\r
+                               });\r
+                       }\r
 \r
-TinyMCE.prototype.execInstanceCommand = function(editor_id, command, user_interface, value, focus) {\r
-       var inst = tinyMCE.getInstanceById(editor_id);\r
-       if (inst) {\r
-               if (typeof(focus) == "undefined")\r
-                       focus = true;\r
+                       // Add static methods\r
+                       t.each(p['static'], function(f, n) {\r
+                               ns[cn][n] = f;\r
+                       });\r
 \r
-               if (focus)\r
-                       inst.contentWindow.focus();\r
+                       if (this.onCreate)\r
+                               this.onCreate(s[2], s[3], ns[cn].prototype);\r
+               },\r
 \r
-               // Reset design mode if lost\r
-               inst.autoResetDesignMode();\r
+               walk : function(o, f, n, s) {\r
+                       s = s || this;\r
 \r
-               this.selectedElement = inst.getFocusElement();\r
-               this.selectedInstance = inst;\r
-               tinyMCE.execCommand(command, user_interface, value);\r
+                       if (o) {\r
+                               if (n)\r
+                                       o = o[n];\r
 \r
-               // Cancel event so it doesn't call onbeforeonunlaod\r
-               if (tinyMCE.isMSIE && window.event != null)\r
-                       tinyMCE.cancelEvent(window.event);\r
-       }\r
-};\r
+                               tinymce.each(o, function(o, i) {\r
+                                       if (f.call(s, o, i, n) === false)\r
+                                               return false;\r
 \r
-TinyMCE.prototype.execCommand = function(command, user_interface, value) {\r
-       // Default input\r
-       user_interface = user_interface ? user_interface : false;\r
-       value = value ? value : null;\r
+                                       tinymce.walk(o, f, n, s);\r
+                               });\r
+                       }\r
+               },\r
 \r
-       if (tinyMCE.selectedInstance)\r
-               tinyMCE.selectedInstance.switchSettings();\r
+               createNS : function(n, o) {\r
+                       var i, v;\r
 \r
-       switch (command) {\r
-               case 'mceHelp':\r
-                       var template = new Array();\r
+                       o = o || win;\r
 \r
-                       template['file']   = 'about.htm';\r
-                       template['width']  = 480;\r
-                       template['height'] = 380;\r
+                       n = n.split('.');\r
+                       for (i=0; i<n.length; i++) {\r
+                               v = n[i];\r
 \r
-                       tinyMCE.openWindow(template, {\r
-                               tinymce_version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion,\r
-                               tinymce_releasedate : tinyMCE.releaseDate,\r
-                               inline : "yes"\r
-                       });\r
-               return;\r
+                               if (!o[v])\r
+                                       o[v] = {};\r
 \r
-               case 'mceFocus':\r
-                       var inst = tinyMCE.getInstanceById(value);\r
-                       if (inst)\r
-                               inst.contentWindow.focus();\r
-               return;\r
+                               o = o[v];\r
+                       }\r
 \r
-               case "mceAddControl":\r
-               case "mceAddEditor":\r
-                       tinyMCE.addMCEControl(tinyMCE._getElementById(value), value);\r
-                       return;\r
+                       return o;\r
+               },\r
 \r
-               case "mceAddFrameControl":\r
-                       tinyMCE.addMCEControl(tinyMCE._getElementById(value), value['element'], value['document']);\r
-                       return;\r
+               resolve : function(n, o) {\r
+                       var i, l;\r
 \r
-               case "mceRemoveControl":\r
-               case "mceRemoveEditor":\r
-                       tinyMCE.removeMCEControl(value);\r
-                       return;\r
+                       o = o || win;\r
 \r
-               case "mceResetDesignMode":\r
-                       // Resets the designmode state of the editors in Gecko\r
-                       if (!tinyMCE.isMSIE) {\r
-                               for (var n in tinyMCE.instances) {\r
-                                       if (!tinyMCE.isInstance(tinyMCE.instances[n]))\r
-                                               continue;\r
+                       n = n.split('.');\r
+                       for (i = 0, l = n.length; i < l; i++) {\r
+                               o = o[n[i]];\r
 \r
-                                       try {\r
-                                               tinyMCE.instances[n].getDoc().designMode = "on";\r
-                                       } catch (e) {\r
-                                               // Ignore any errors\r
-                                       }\r
-                               }\r
+                               if (!o)\r
+                                       break;\r
                        }\r
 \r
-                       return;\r
-       }\r
-\r
-       if (this.selectedInstance) {\r
-               this.selectedInstance.execCommand(command, user_interface, value);\r
-       } else if (tinyMCE.settings['focus_alert'])\r
-               alert(tinyMCELang['lang_focus_alert']);\r
-};\r
-\r
-TinyMCE.prototype.eventPatch = function(editor_id) {\r
-       // Remove odd, error\r
-       if (typeof(tinyMCE) == "undefined")\r
-               return true;\r
+                       return o;\r
+               },\r
 \r
-       for (var i=0; i<document.frames.length; i++) {\r
-               try {\r
-                       if (document.frames[i].event) {\r
-                               var event = document.frames[i].event;\r
+               addUnload : function(f, s) {\r
+                       var t = this;\r
 \r
-                               if (!event.target)\r
-                                       event.target = event.srcElement;\r
-\r
-                               TinyMCE.prototype.handleEvent(event);\r
-                               return;\r
-                       }\r
-               } catch (ex) {\r
-                       // Ignore error if iframe is pointing to external URL\r
-               }\r
-       }\r
-};\r
+                       f = {func : f, scope : s || this};\r
 \r
-TinyMCE.prototype.unloadHandler = function() {\r
-       tinyMCE.triggerSave(true, true);\r
-};\r
+                       if (!t.unloads) {\r
+                               function unload() {\r
+                                       var li = t.unloads, o, n;\r
 \r
-TinyMCE.prototype.addEventHandlers = function(editor_id) {\r
-       if (tinyMCE.isMSIE) {\r
-               var doc = document.frames[editor_id].document;\r
+                                       if (li) {\r
+                                               // Call unload handlers\r
+                                               for (n in li) {\r
+                                                       o = li[n];\r
 \r
-               // Event patch\r
-               tinyMCE.addEvent(doc, "keypress", TinyMCE.prototype.eventPatch);\r
-               tinyMCE.addEvent(doc, "keyup", TinyMCE.prototype.eventPatch);\r
-               tinyMCE.addEvent(doc, "keydown", TinyMCE.prototype.eventPatch);\r
-               tinyMCE.addEvent(doc, "mouseup", TinyMCE.prototype.eventPatch);\r
-               tinyMCE.addEvent(doc, "click", TinyMCE.prototype.eventPatch);\r
-       } else {\r
-               var inst = tinyMCE.instances[editor_id];\r
-               var doc = inst.getDoc();\r
+                                                       if (o && o.func)\r
+                                                               o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy\r
+                                               }\r
 \r
-               inst.switchSettings();\r
+                                               // Detach unload function\r
+                                               if (win.detachEvent) {\r
+                                                       win.detachEvent('onbeforeunload', fakeUnload);\r
+                                                       win.detachEvent('onunload', unload);\r
+                                               } else if (win.removeEventListener)\r
+                                                       win.removeEventListener('unload', unload, false);\r
 \r
-               tinyMCE.addEvent(doc, "keypress", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "keydown", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "keyup", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "click", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "mouseup", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "mousedown", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "focus", tinyMCE.handleEvent);\r
-               tinyMCE.addEvent(doc, "blur", tinyMCE.handleEvent);\r
+                                               // Destroy references\r
+                                               t.unloads = o = li = w = unload = 0;\r
 \r
-               eval('try { doc.designMode = "On"; } catch(e) {}');\r
-       }\r
-};\r
+                                               // Run garbarge collector on IE\r
+                                               if (win.CollectGarbage)\r
+                                                       CollectGarbage();\r
+                                       }\r
+                               };\r
+\r
+                               function fakeUnload() {\r
+                                       var d = document;\r
+\r
+                                       // Is there things still loading, then do some magic\r
+                                       if (d.readyState == 'interactive') {\r
+                                               function stop() {\r
+                                                       // Prevent memory leak\r
+                                                       d.detachEvent('onstop', stop);\r
+\r
+                                                       // Call unload handler\r
+                                                       if (unload)\r
+                                                               unload();\r
+\r
+                                                       d = 0;\r
+                                               };\r
+\r
+                                               // Fire unload when the currently loading page is stopped\r
+                                               if (d)\r
+                                                       d.attachEvent('onstop', stop);\r
+\r
+                                               // Remove onstop listener after a while to prevent the unload function\r
+                                               // to execute if the user presses cancel in an onbeforeunload\r
+                                               // confirm dialog and then presses the browser stop button\r
+                                               win.setTimeout(function() {\r
+                                                       if (d)\r
+                                                               d.detachEvent('onstop', stop);\r
+                                               }, 0);\r
+                                       }\r
+                               };\r
 \r
-TinyMCE.prototype._createIFrame = function(replace_element) {\r
-       var iframe = document.createElement("iframe");\r
-       var id = replace_element.getAttribute("id");\r
-       var aw, ah;\r
+                               // Attach unload handler\r
+                               if (win.attachEvent) {\r
+                                       win.attachEvent('onunload', unload);\r
+                                       win.attachEvent('onbeforeunload', fakeUnload);\r
+                               } else if (win.addEventListener)\r
+                                       win.addEventListener('unload', unload, false);\r
 \r
-       aw = "" + tinyMCE.settings['area_width'];\r
-       ah = "" + tinyMCE.settings['area_height'];\r
+                               // Setup initial unload handler array\r
+                               t.unloads = [f];\r
+                       } else\r
+                               t.unloads.push(f);\r
 \r
-       if (aw.indexOf('%') == -1) {\r
-               aw = parseInt(aw);\r
-               aw = aw < 0 ? 300 : aw;\r
-               aw = aw + "px";\r
-       }\r
+                       return f;\r
+               },\r
 \r
-       if (ah.indexOf('%') == -1) {\r
-               ah = parseInt(ah);\r
-               ah = ah < 0 ? 240 : ah;\r
-               ah = ah + "px";\r
-       }\r
+               removeUnload : function(f) {\r
+                       var u = this.unloads, r = null;\r
 \r
-       iframe.setAttribute("id", id);\r
-       //iframe.setAttribute("className", "mceEditorArea");\r
-       iframe.setAttribute("border", "0");\r
-       iframe.setAttribute("frameBorder", "0");\r
-       iframe.setAttribute("marginWidth", "0");\r
-       iframe.setAttribute("marginHeight", "0");\r
-       iframe.setAttribute("leftMargin", "0");\r
-       iframe.setAttribute("topMargin", "0");\r
-       iframe.setAttribute("width", aw);\r
-       iframe.setAttribute("height", ah);\r
-       iframe.setAttribute("allowtransparency", "true");\r
-\r
-       if (tinyMCE.settings["auto_resize"])\r
-               iframe.setAttribute("scrolling", "no");\r
-\r
-       // Must have a src element in MSIE HTTPs breaks aswell as absoute URLs\r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera)\r
-               iframe.setAttribute("src", this.settings['default_document']);\r
-\r
-       iframe.style.width = aw;\r
-       iframe.style.height = ah;\r
-\r
-       // MSIE 5.0 issue\r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera)\r
-               replace_element.outerHTML = iframe.outerHTML;\r
-       else\r
-               replace_element.parentNode.replaceChild(iframe, replace_element);\r
-\r
-       if (tinyMCE.isMSIE)\r
-               return window.frames[id];\r
-       else\r
-               return iframe;\r
-};\r
+                       tinymce.each(u, function(o, i) {\r
+                               if (o && o.func == f) {\r
+                                       u.splice(i, 1);\r
+                                       r = f;\r
+                                       return false;\r
+                               }\r
+                       });\r
 \r
-TinyMCE.prototype.setupContent = function(editor_id) {\r
-       var inst = tinyMCE.instances[editor_id];\r
-       var doc = inst.getDoc();\r
-       var head = doc.getElementsByTagName('head').item(0);\r
-       var content = inst.startContent;\r
+                       return r;\r
+               },\r
 \r
-       tinyMCE.operaOpacityCounter = 100 * tinyMCE.idCounter;\r
+               explode : function(s, d) {\r
+                       return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;\r
+               },\r
 \r
-       inst.switchSettings();\r
+               _addVer : function(u) {\r
+                       var v;\r
 \r
-       // Not loaded correctly hit it again, Mozilla bug #997860\r
-       if (!tinyMCE.isMSIE && tinyMCE.getParam("setupcontent_reload", false) && doc.title != "blank_page") {\r
-               // This part will remove the designMode status\r
-               // Failes first time in Firefox 1.5b2 on Mac\r
-               try {doc.location.href = tinyMCE.baseURL + "/blank.htm";} catch (ex) {}\r
-               window.setTimeout("tinyMCE.setupContent('" + editor_id + "');", 1000);\r
-               return;\r
-       }\r
+                       if (!this.query)\r
+                               return u;\r
 \r
-       if (!head) {\r
-               window.setTimeout("tinyMCE.setupContent('" + editor_id + "');", 10);\r
-               return;\r
-       }\r
+                       v = (u.indexOf('?') == -1 ? '?' : '&') + this.query;\r
 \r
-       // Import theme specific content CSS the user specific\r
-       tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/themes/" + inst.settings['theme'] + "/css/editor_content.css");\r
-       tinyMCE.importCSS(inst.getDoc(), inst.settings['content_css']);\r
-       tinyMCE.executeCallback('init_instance_callback', '_initInstance', 0, inst);\r
+                       if (u.indexOf('#') == -1)\r
+                               return u + v;\r
 \r
-       // Setup span styles\r
-       if (tinyMCE.getParam("convert_fonts_to_spans"))\r
-               inst.getDoc().body.setAttribute('id', 'mceSpanFonts');\r
+                       return u.replace('#', v + '#');\r
+               },\r
 \r
-       if (tinyMCE.settings['nowrap'])\r
-               doc.body.style.whiteSpace = "nowrap";\r
+               // Fix function for IE 9 where regexps isn't working correctly\r
+               // Todo: remove me once MS fixes the bug\r
+               _replace : function(find, replace, str) {\r
+                       // On IE9 we have to fake $x replacement\r
+                       if (isRegExpBroken) {\r
+                               return str.replace(find, function() {\r
+                                       var val = replace, args = arguments, i;\r
 \r
-       doc.body.dir = this.settings['directionality'];\r
-       doc.editorId = editor_id;\r
+                                       for (i = 0; i < args.length - 2; i++) {\r
+                                               if (args[i] === undefined) {\r
+                                                       val = val.replace(new RegExp('\\$' + i, 'g'), '');\r
+                                               } else {\r
+                                                       val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);\r
+                                               }\r
+                                       }\r
 \r
-       // Add on document element in Mozilla\r
-       if (!tinyMCE.isMSIE)\r
-               doc.documentElement.editorId = editor_id;\r
+                                       return val;\r
+                               });\r
+                       }\r
 \r
-       // Setup base element\r
-       var base = doc.createElement("base");\r
-       base.setAttribute('href', tinyMCE.settings['base_href']);\r
-       head.appendChild(base);\r
+                       return str.replace(find, replace);\r
+               }\r
 \r
-       // Replace new line characters to BRs\r
-       if (tinyMCE.settings['convert_newlines_to_brs']) {\r
-               content = tinyMCE.regexpReplace(content, "\r\n", "<br />", "gi");\r
-               content = tinyMCE.regexpReplace(content, "\r", "<br />", "gi");\r
-               content = tinyMCE.regexpReplace(content, "\n", "<br />", "gi");\r
-       }\r
+               };\r
 \r
-       // Open closed anchors\r
-//     content = content.replace(new RegExp('<a(.*?)/>', 'gi'), '<a$1></a>');\r
+       // Initialize the API\r
+       tinymce._init();\r
 \r
-       // Call custom cleanup code\r
-       content = tinyMCE.storeAwayURLs(content);\r
-       content = tinyMCE._customCleanup(inst, "insert_to_editor", content);\r
+       // Expose tinymce namespace to the global namespace (window)\r
+       win.tinymce = win.tinyMCE = tinymce;\r
 \r
-       if (tinyMCE.isMSIE) {\r
-               // Ugly!!!\r
-               window.setInterval('try{tinyMCE.getCSSClasses(document.frames["' + editor_id + '"].document, "' + editor_id + '");}catch(e){}', 500);\r
+       // Describe the different namespaces\r
 \r
-               if (tinyMCE.settings["force_br_newlines"])\r
-                       document.frames[editor_id].document.styleSheets[0].addRule("p", "margin: 0px;");\r
+       })(window);\r
 \r
-               var body = document.frames[editor_id].document.body;\r
 \r
-               tinyMCE.addEvent(body, "beforepaste", TinyMCE.prototype.eventPatch);\r
-               tinyMCE.addEvent(body, "beforecut", TinyMCE.prototype.eventPatch);\r
 \r
-               body.editorId = editor_id;\r
-       }\r
+tinymce.create('tinymce.util.Dispatcher', {\r
+       scope : null,\r
+       listeners : null,\r
 \r
-       content = tinyMCE.cleanupHTMLCode(content);\r
-\r
-       // Fix for bug #958637\r
-       if (!tinyMCE.isMSIE) {\r
-               var contentElement = inst.getDoc().createElement("body");\r
-               var doc = inst.getDoc();\r
-\r
-               contentElement.innerHTML = content;\r
-\r
-               // Remove weridness!\r
-               if (tinyMCE.isGecko && tinyMCE.settings['remove_lt_gt'])\r
-                       content = content.replace(new RegExp('&lt;&gt;', 'g'), "");\r
-\r
-               if (tinyMCE.settings['cleanup_on_startup'])\r
-                       tinyMCE.setInnerHTML(inst.getBody(), tinyMCE._cleanupHTML(inst, doc, this.settings, contentElement));\r
-               else {\r
-                       // Convert all strong/em to b/i\r
-                       content = tinyMCE.regexpReplace(content, "<strong", "<b", "gi");\r
-                       content = tinyMCE.regexpReplace(content, "<em(/?)>", "<i$1>", "gi");\r
-                       content = tinyMCE.regexpReplace(content, "<em ", "<i ", "gi");\r
-                       content = tinyMCE.regexpReplace(content, "</strong>", "</b>", "gi");\r
-                       content = tinyMCE.regexpReplace(content, "</em>", "</i>", "gi");\r
-                       tinyMCE.setInnerHTML(inst.getBody(), content);\r
-               }\r
+       Dispatcher : function(s) {\r
+               this.scope = s || this;\r
+               this.listeners = [];\r
+       },\r
 \r
-               inst.convertAllRelativeURLs();\r
-       } else {\r
-               if (tinyMCE.settings['cleanup_on_startup']) {\r
-                       tinyMCE._setHTML(inst.getDoc(), content);\r
+       add : function(cb, s) {\r
+               this.listeners.push({cb : cb, scope : s || this.scope});\r
 \r
-                       // Produces permission denied error in MSIE 5.5\r
-                       eval('try {tinyMCE.setInnerHTML(inst.getBody(), tinyMCE._cleanupHTML(inst, inst.contentDocument, this.settings, inst.getBody()));} catch(e) {}');\r
-               } else\r
-                       tinyMCE._setHTML(inst.getDoc(), content);\r
-       }\r
+               return cb;\r
+       },\r
 \r
-       // Fix for bug #957681\r
-       //inst.getDoc().designMode = inst.getDoc().designMode;\r
+       addToTop : function(cb, s) {\r
+               this.listeners.unshift({cb : cb, scope : s || this.scope});\r
 \r
-       // Setup element references\r
-       var parentElm = document.getElementById(inst.editorId + '_parent');\r
-       if (parentElm.lastChild.nodeName == "INPUT")\r
-               inst.formElement = tinyMCE.isGecko ? parentElm.firstChild : parentElm.lastChild;\r
-       else\r
-               inst.formElement = tinyMCE.isGecko ? parentElm.previousSibling : parentElm.nextSibling;\r
+               return cb;\r
+       },\r
 \r
-       tinyMCE.handleVisualAid(inst.getBody(), true, tinyMCE.settings['visual'], inst);\r
-       tinyMCE.executeCallback('setupcontent_callback', '_setupContent', 0, editor_id, inst.getBody(), inst.getDoc());\r
+       remove : function(cb) {\r
+               var l = this.listeners, o = null;\r
 \r
-       // Re-add design mode on mozilla\r
-       if (!tinyMCE.isMSIE)\r
-               TinyMCE.prototype.addEventHandlers(editor_id);\r
+               tinymce.each(l, function(c, i) {\r
+                       if (cb == c.cb) {\r
+                               o = cb;\r
+                               l.splice(i, 1);\r
+                               return false;\r
+                       }\r
+               });\r
 \r
-       // Add blur handler\r
-       if (tinyMCE.isMSIE)\r
-               tinyMCE.addEvent(inst.getBody(), "blur", TinyMCE.prototype.eventPatch);\r
+               return o;\r
+       },\r
 \r
-       // Trigger node change, this call locks buttons for tables and so forth\r
-       tinyMCE.selectedInstance = inst;\r
-       tinyMCE.selectedElement = inst.contentWindow.document.body;\r
+       dispatch : function() {\r
+               var s, a = arguments, i, li = this.listeners, c;\r
 \r
-       if (!inst.isHidden())\r
-               tinyMCE.triggerNodeChange(false, true);\r
+               // Needs to be a real loop since the listener count might change while looping\r
+               // And this is also more efficient\r
+               for (i = 0; i<li.length; i++) {\r
+                       c = li[i];\r
+                       s = c.cb.apply(c.scope, a);\r
 \r
-       // Call custom DOM cleanup\r
-       tinyMCE._customCleanup(inst, "insert_to_editor_dom", inst.getBody());\r
-       tinyMCE._customCleanup(inst, "setup_content_dom", inst.getBody());\r
-       tinyMCE._setEventsEnabled(inst.getBody(), false);\r
-       tinyMCE.cleanupAnchors(inst.getDoc());\r
+                       if (s === false)\r
+                               break;\r
+               }\r
 \r
-       if (tinyMCE.getParam("convert_fonts_to_spans"))\r
-               tinyMCE.convertSpansToFonts(inst.getDoc());\r
+               return s;\r
+       }\r
 \r
-       inst.startContent = tinyMCE.trim(inst.getBody().innerHTML);\r
-       inst.undoLevels[inst.undoLevels.length] = inst.startContent;\r
+       });\r
 \r
-       tinyMCE.operaOpacityCounter = -1;\r
-};\r
+(function() {\r
+       var each = tinymce.each;\r
 \r
-TinyMCE.prototype.cleanupHTMLCode = function(s) {\r
-       s = s.replace(/<p \/>/gi, '<p>&nbsp;</p>');\r
-       s = s.replace(/<p>\s*<\/p>/gi, '<p>&nbsp;</p>');\r
+       tinymce.create('tinymce.util.URI', {\r
+               URI : function(u, s) {\r
+                       var t = this, o, a, b, base_url;\r
 \r
-       // Open closed tags like <b/> to <b></b>\r
-//     tinyMCE.debug("f:" + s);\r
-       s = s.replace(/<(h[1-6]|p|div|address|pre|form|table|li|ol|ul|td|b|em|strong|i|strike|u|span|a|ul|ol|li|blockquote)([a-z]*)([^\\|>]*?)\/>/gi, '<$1$2$3></$1$2>');\r
-//     tinyMCE.debug("e:" + s);\r
+                       // Trim whitespace\r
+                       u = tinymce.trim(u);\r
 \r
-       // Remove trailing space <b > to <b>\r
-       s = s.replace(new RegExp('\\s+></', 'gi'), '></');\r
+                       // Default settings\r
+                       s = t.settings = s || {};\r
 \r
-       // Close tags <img></img> to <img/>\r
-       s = s.replace(/<(img|br|hr)(.*?)><\/(img|br|hr)>/gi, '<$1$2 />');\r
+                       // Strange app protocol that isn't http/https or local anchor\r
+                       // For example: mailto,skype,tel etc.\r
+                       if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) {\r
+                               t.source = u;\r
+                               return;\r
+                       }\r
 \r
-       // Weird MSIE bug, <p><hr /></p> breaks runtime?\r
-       if (tinyMCE.isMSIE)\r
-               s = s.replace(/<p><hr \/><\/p>/gi, "<hr>");\r
+                       // Absolute path with no host, fake host and protocol\r
+                       if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)\r
+                               u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;\r
 \r
-       // Convert relative anchors to absolute URLs ex: #something to file.htm#something\r
-       s = s.replace(new RegExp('(href=\"?)(\\s*?#)', 'gi'), '$1' + tinyMCE.settings['document_base_url'] + "#");\r
+                       // Relative path http:// or protocol relative //path\r
+                       if (!/^[\w-]*:?\/\//.test(u)) {\r
+                               base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory;\r
+                               u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u);\r
+                       }\r
 \r
-       return s;\r
-};\r
+                       // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)\r
+                       u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something\r
+                       u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);\r
+                       each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {\r
+                               var s = u[i];\r
 \r
-TinyMCE.prototype.storeAwayURLs = function(s) {\r
-       // Remove all mce_src, mce_href and replace them with new ones\r
-       s = s.replace(new RegExp('mce_src\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');\r
-       s = s.replace(new RegExp('mce_href\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');\r
-       s = s.replace(new RegExp('src\\s*=\\s*\"([^ >\"]*)\"', 'gi'), 'src="$1" mce_src="$1"');\r
-       s = s.replace(new RegExp('href\\s*=\\s*\"([^ >\"]*)\"', 'gi'), 'href="$1" mce_href="$1"');\r
+                               // Zope 3 workaround, they use @@something\r
+                               if (s)\r
+                                       s = s.replace(/\(mce_at\)/g, '@@');\r
 \r
-       return s;\r
-};\r
+                               t[v] = s;\r
+                       });\r
 \r
-TinyMCE.prototype.cancelEvent = function(e) {\r
-       if (tinyMCE.isMSIE) {\r
-               e.returnValue = false;\r
-               e.cancelBubble = true;\r
-       } else\r
-               e.preventDefault();\r
-};\r
+                       if (b = s.base_uri) {\r
+                               if (!t.protocol)\r
+                                       t.protocol = b.protocol;\r
 \r
-TinyMCE.prototype.removeTinyMCEFormElements = function(form_obj) {\r
-       // Check if form is valid\r
-       if (typeof(form_obj) == "undefined" || form_obj == null)\r
-               return;\r
+                               if (!t.userInfo)\r
+                                       t.userInfo = b.userInfo;\r
 \r
-       // If not a form, find the form\r
-       if (form_obj.nodeName != "FORM") {\r
-               if (form_obj.form)\r
-                       form_obj = form_obj.form;\r
-               else\r
-                       form_obj = tinyMCE.getParentElement(form_obj, "form");\r
-       }\r
+                               if (!t.port && t.host == 'mce_host')\r
+                                       t.port = b.port;\r
 \r
-       // Still nothing\r
-       if (form_obj == null)\r
-               return;\r
+                               if (!t.host || t.host == 'mce_host')\r
+                                       t.host = b.host;\r
 \r
-       // Disable all UI form elements that TinyMCE created\r
-       for (var i=0; i<form_obj.elements.length; i++) {\r
-               var elementId = form_obj.elements[i].name ? form_obj.elements[i].name : form_obj.elements[i].id;\r
+                               t.source = '';\r
+                       }\r
 \r
-               if (elementId.indexOf('mce_editor_') == 0)\r
-                       form_obj.elements[i].disabled = true;\r
-       }\r
-};\r
+                       //t.path = t.path || '/';\r
+               },\r
 \r
-TinyMCE.prototype.accessibleEventHandler = function(e) {\r
-       var win = this._win;\r
-       e = tinyMCE.isMSIE ? win.event : e;\r
-       var elm = tinyMCE.isMSIE ? e.srcElement : e.target;\r
+               setPath : function(p) {\r
+                       var t = this;\r
 \r
-       // Piggyback onchange\r
-       if (elm.nodeName == "SELECT" && !elm.oldonchange) {\r
-               elm.oldonchange = elm.onchange;\r
-               elm.onchange = null;\r
-       }\r
+                       p = /^(.*?)\/?(\w+)?$/.exec(p);\r
 \r
-       // Execute onchange and remove piggyback\r
-       if (e.keyCode == 13 || e.keyCode == 32) {\r
-               elm.onchange = elm.oldonchange;\r
-               elm.onchange();\r
-               elm.oldonchange = null;\r
-               tinyMCE.cancelEvent(e);\r
-       }\r
-};\r
+                       // Update path parts\r
+                       t.path = p[0];\r
+                       t.directory = p[1];\r
+                       t.file = p[2];\r
 \r
-TinyMCE.prototype.addSelectAccessibility = function(e, select, win) {\r
-       // Add event handlers \r
-       if (!select._isAccessible) {\r
-               select.onkeydown = tinyMCE.accessibleEventHandler;\r
-               select._isAccessible = true;\r
-               select._win = win;\r
-       }\r
-};\r
+                       // Rebuild source\r
+                       t.source = '';\r
+                       t.getURI();\r
+               },\r
 \r
-TinyMCE.prototype.handleEvent = function(e) {\r
-       // Remove odd, error\r
-       if (typeof(tinyMCE) == "undefined")\r
-               return true;\r
+               toRelative : function(u) {\r
+                       var t = this, o;\r
 \r
-       //tinyMCE.debug(e.type + " " + e.target.nodeName + " " + (e.relatedTarget ? e.relatedTarget.nodeName : ""));\r
+                       if (u === "./")\r
+                               return u;\r
 \r
-       switch (e.type) {\r
-               case "blur":\r
-                       if (tinyMCE.selectedInstance)\r
-                               tinyMCE.selectedInstance.execCommand('mceEndTyping');\r
+                       u = new tinymce.util.URI(u, {base_uri : t});\r
 \r
-                       return;\r
+                       // Not on same domain/port or protocol\r
+                       if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)\r
+                               return u.getURI();\r
 \r
-               case "submit":\r
-                       tinyMCE.removeTinyMCEFormElements(tinyMCE.isMSIE ? window.event.srcElement : e.target);\r
-                       tinyMCE.triggerSave();\r
-                       tinyMCE.isNotDirty = true;\r
-                       return;\r
+                       o = t.toRelPath(t.path, u.path);\r
 \r
-               case "reset":\r
-                       var formObj = tinyMCE.isMSIE ? window.event.srcElement : e.target;\r
+                       // Add query\r
+                       if (u.query)\r
+                               o += '?' + u.query;\r
 \r
-                       for (var i=0; i<document.forms.length; i++) {\r
-                               if (document.forms[i] == formObj)\r
-                                       window.setTimeout('tinyMCE.resetForm(' + i + ');', 10);\r
-                       }\r
+                       // Add anchor\r
+                       if (u.anchor)\r
+                               o += '#' + u.anchor;\r
 \r
-                       return;\r
+                       return o;\r
+               },\r
+       \r
+               toAbsolute : function(u, nh) {\r
+                       var u = new tinymce.util.URI(u, {base_uri : this});\r
 \r
-               case "keypress":\r
-                       if (e.target.editorId) {\r
-                               tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];\r
-                       } else {\r
-                               if (e.target.ownerDocument.editorId)\r
-                                       tinyMCE.selectedInstance = tinyMCE.instances[e.target.ownerDocument.editorId];\r
-                       }\r
+                       return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);\r
+               },\r
 \r
-                       if (tinyMCE.selectedInstance)\r
-                               tinyMCE.selectedInstance.switchSettings();\r
+               toRelPath : function(base, path) {\r
+                       var items, bp = 0, out = '', i, l;\r
 \r
-                       // Insert space instead of &nbsp;\r
-/*                     if (tinyMCE.isGecko && e.charCode == 32) {\r
-                               if (tinyMCE.selectedInstance._insertSpace()) {\r
-                                       // Cancel event\r
-                                       e.preventDefault();\r
-                                       return false;\r
-                               }\r
-                       }*/\r
+                       // Split the paths\r
+                       base = base.substring(0, base.lastIndexOf('/'));\r
+                       base = base.split('/');\r
+                       items = path.split('/');\r
 \r
-                       // Insert P element\r
-                       if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && e.keyCode == 13 && !e.shiftKey) {\r
-                               // Insert P element instead of BR\r
-                               if (tinyMCE.selectedInstance._insertPara(e)) {\r
-                                       // Cancel event\r
-                                       tinyMCE.execCommand("mceAddUndoLevel");\r
-                                       tinyMCE.cancelEvent(e);\r
-                                       return false;\r
+                       if (base.length >= items.length) {\r
+                               for (i = 0, l = base.length; i < l; i++) {\r
+                                       if (i >= items.length || base[i] != items[i]) {\r
+                                               bp = i + 1;\r
+                                               break;\r
+                                       }\r
                                }\r
                        }\r
 \r
-                       // Handle backspace\r
-                       if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && (e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey) {\r
-                               // Insert P element instead of BR\r
-                               if (tinyMCE.selectedInstance._handleBackSpace(e.type)) {\r
-                                       // Cancel event\r
-                                       tinyMCE.execCommand("mceAddUndoLevel");\r
-                                       tinyMCE.cancelEvent(e);\r
-                                       return false;\r
+                       if (base.length < items.length) {\r
+                               for (i = 0, l = items.length; i < l; i++) {\r
+                                       if (i >= base.length || base[i] != items[i]) {\r
+                                               bp = i + 1;\r
+                                               break;\r
+                                       }\r
                                }\r
                        }\r
 \r
-                       // Mozilla custom key handling\r
-                       if (tinyMCE.isGecko && (e.ctrlKey && !e.altKey) && tinyMCE.settings['custom_undo_redo']) {\r
-                               if (tinyMCE.settings['custom_undo_redo_keyboard_shortcuts']) {\r
-                                       if (e.charCode == 122) { // Ctrl+Z\r
-                                               tinyMCE.selectedInstance.execCommand("Undo");\r
-                                               tinyMCE.cancelEvent(e);\r
-                                               return false;\r
-                                       }\r
+                       if (bp == 1)\r
+                               return path;\r
 \r
-                                       if (e.charCode == 121) { // Ctrl+Y\r
-                                               tinyMCE.selectedInstance.execCommand("Redo");\r
-                                               tinyMCE.cancelEvent(e);\r
-                                               return false;\r
-                                       }\r
-                               }\r
+                       for (i = 0, l = base.length - (bp - 1); i < l; i++)\r
+                               out += "../";\r
 \r
-                               if (e.charCode == 98) { // Ctrl+B\r
-                                       tinyMCE.selectedInstance.execCommand("Bold");\r
-                                       tinyMCE.cancelEvent(e);\r
-                                       return false;\r
-                               }\r
+                       for (i = bp - 1, l = items.length; i < l; i++) {\r
+                               if (i != bp - 1)\r
+                                       out += "/" + items[i];\r
+                               else\r
+                                       out += items[i];\r
+                       }\r
 \r
-                               if (e.charCode == 105) { // Ctrl+I\r
-                                       tinyMCE.selectedInstance.execCommand("Italic");\r
-                                       tinyMCE.cancelEvent(e);\r
-                                       return false;\r
-                               }\r
+                       return out;\r
+               },\r
 \r
-                               if (e.charCode == 117) { // Ctrl+U\r
-                                       tinyMCE.selectedInstance.execCommand("Underline");\r
-                                       tinyMCE.cancelEvent(e);\r
-                                       return false;\r
-                               }\r
-                       }\r
+               toAbsPath : function(base, path) {\r
+                       var i, nb = 0, o = [], tr, outPath;\r
 \r
-                       // Return key pressed\r
-                       if (tinyMCE.isMSIE && tinyMCE.settings['force_br_newlines'] && e.keyCode == 13) {\r
-                               if (e.target.editorId)\r
-                                       tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];\r
+                       // Split paths\r
+                       tr = /\/$/.test(path) ? '/' : '';\r
+                       base = base.split('/');\r
+                       path = path.split('/');\r
 \r
-                               if (tinyMCE.selectedInstance) {\r
-                                       var sel = tinyMCE.selectedInstance.getDoc().selection;\r
-                                       var rng = sel.createRange();\r
+                       // Remove empty chunks\r
+                       each(base, function(k) {\r
+                               if (k)\r
+                                       o.push(k);\r
+                       });\r
 \r
-                                       if (tinyMCE.getParentElement(rng.parentElement(), "li") != null)\r
-                                               return false;\r
+                       base = o;\r
 \r
-                                       // Cancel event\r
-                                       e.returnValue = false;\r
-                                       e.cancelBubble = true;\r
+                       // Merge relURLParts chunks\r
+                       for (i = path.length - 1, o = []; i >= 0; i--) {\r
+                               // Ignore empty or .\r
+                               if (path[i].length == 0 || path[i] == ".")\r
+                                       continue;\r
 \r
-                                       // Insert BR element\r
-                                       rng.pasteHTML("<br />");\r
-                                       rng.collapse(false);\r
-                                       rng.select();\r
+                               // Is parent\r
+                               if (path[i] == '..') {\r
+                                       nb++;\r
+                                       continue;\r
+                               }\r
 \r
-                                       tinyMCE.execCommand("mceAddUndoLevel");\r
-                                       tinyMCE.triggerNodeChange(false);\r
-                                       return false;\r
+                               // Move up\r
+                               if (nb > 0) {\r
+                                       nb--;\r
+                                       continue;\r
                                }\r
-                       }\r
 \r
-                       // Backspace or delete\r
-                       if (e.keyCode == 8 || e.keyCode == 46) {\r
-                               tinyMCE.selectedElement = e.target;\r
-                               tinyMCE.linkElement = tinyMCE.getParentElement(e.target, "a");\r
-                               tinyMCE.imgElement = tinyMCE.getParentElement(e.target, "img");\r
-                               tinyMCE.triggerNodeChange(false);\r
+                               o.push(path[i]);\r
                        }\r
 \r
-                       return false;\r
-               break;\r
+                       i = base.length - nb;\r
 \r
-               case "keyup":\r
-               case "keydown":\r
-                       if (e.target.editorId)\r
-                               tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];\r
+                       // If /a/b/c or /\r
+                       if (i <= 0)\r
+                               outPath = o.reverse().join('/');\r
                        else\r
-                               return;\r
+                               outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');\r
 \r
-                       if (tinyMCE.selectedInstance)\r
-                               tinyMCE.selectedInstance.switchSettings();\r
+                       // Add front / if it's needed\r
+                       if (outPath.indexOf('/') !== 0)\r
+                               outPath = '/' + outPath;\r
 \r
-                       var inst = tinyMCE.selectedInstance;\r
+                       // Add traling / if it's needed\r
+                       if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)\r
+                               outPath += tr;\r
 \r
-                       // Handle backspace\r
-                       if (tinyMCE.isGecko && tinyMCE.settings['force_p_newlines'] && (e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey) {\r
-                               // Insert P element instead of BR\r
-                               if (tinyMCE.selectedInstance._handleBackSpace(e.type)) {\r
-                                       // Cancel event\r
-                                       tinyMCE.execCommand("mceAddUndoLevel");\r
-                                       e.preventDefault();\r
-                                       return false;\r
-                               }\r
-                       }\r
+                       return outPath;\r
+               },\r
 \r
-                       tinyMCE.selectedElement = null;\r
-                       tinyMCE.selectedNode = null;\r
-                       var elm = tinyMCE.selectedInstance.getFocusElement();\r
-                       tinyMCE.linkElement = tinyMCE.getParentElement(elm, "a");\r
-                       tinyMCE.imgElement = tinyMCE.getParentElement(elm, "img");\r
-                       tinyMCE.selectedElement = elm;\r
+               getURI : function(nh) {\r
+                       var s, t = this;\r
 \r
-                       // Update visualaids on tabs\r
-                       if (tinyMCE.isGecko && e.type == "keyup" && e.keyCode == 9)\r
-                               tinyMCE.handleVisualAid(tinyMCE.selectedInstance.getBody(), true, tinyMCE.settings['visual'], tinyMCE.selectedInstance);\r
+                       // Rebuild source\r
+                       if (!t.source || nh) {\r
+                               s = '';\r
 \r
-                       // Fix empty elements on return/enter, check where enter occured\r
-                       if (tinyMCE.isMSIE && e.type == "keydown" && e.keyCode == 13)\r
-                               tinyMCE.enterKeyElement = tinyMCE.selectedInstance.getFocusElement();\r
+                               if (!nh) {\r
+                                       if (t.protocol)\r
+                                               s += t.protocol + '://';\r
 \r
-                       // Fix empty elements on return/enter\r
-                       if (tinyMCE.isMSIE && e.type == "keyup" && e.keyCode == 13) {\r
-                               var elm = tinyMCE.enterKeyElement;\r
-                               if (elm) {\r
-                                       var re = new RegExp('^HR|IMG|BR$','g'); // Skip these\r
-                                       var dre = new RegExp('^H[1-6]$','g'); // Add double on these\r
+                                       if (t.userInfo)\r
+                                               s += t.userInfo + '@';\r
 \r
-                                       if (!elm.hasChildNodes() && !re.test(elm.nodeName)) {\r
-                                               if (dre.test(elm.nodeName))\r
-                                                       elm.innerHTML = "&nbsp;&nbsp;";\r
-                                               else\r
-                                                       elm.innerHTML = "&nbsp;";\r
-                                       }\r
-                               }\r
-                       }\r
+                                       if (t.host)\r
+                                               s += t.host;\r
 \r
-                       // Check if it's a position key\r
-                       var keys = tinyMCE.posKeyCodes;\r
-                       var posKey = false;\r
-                       for (var i=0; i<keys.length; i++) {\r
-                               if (keys[i] == e.keyCode) {\r
-                                       posKey = true;\r
-                                       break;\r
+                                       if (t.port)\r
+                                               s += ':' + t.port;\r
                                }\r
-                       }\r
 \r
-                       // MSIE custom key handling\r
-                       if (tinyMCE.isMSIE && tinyMCE.settings['custom_undo_redo']) {\r
-                               var keys = new Array(8,46); // Backspace,Delete\r
-                               for (var i=0; i<keys.length; i++) {\r
-                                       if (keys[i] == e.keyCode) {\r
-                                               if (e.type == "keyup")\r
-                                                       tinyMCE.triggerNodeChange(false);\r
-                                       }\r
-                               }\r
+                               if (t.path)\r
+                                       s += t.path;\r
 \r
-                               if (tinyMCE.settings['custom_undo_redo_keyboard_shortcuts']) {\r
-                                       if (e.keyCode == 90 && (e.ctrlKey && !e.altKey) && e.type == "keydown") { // Ctrl+Z\r
-                                               tinyMCE.selectedInstance.execCommand("Undo");\r
-                                               tinyMCE.triggerNodeChange(false);\r
-                                       }\r
+                               if (t.query)\r
+                                       s += '?' + t.query;\r
 \r
-                                       if (e.keyCode == 89 && (e.ctrlKey && !e.altKey) && e.type == "keydown") { // Ctrl+Y\r
-                                               tinyMCE.selectedInstance.execCommand("Redo");\r
-                                               tinyMCE.triggerNodeChange(false);\r
-                                       }\r
+                               if (t.anchor)\r
+                                       s += '#' + t.anchor;\r
 \r
-                                       if ((e.keyCode == 90 || e.keyCode == 89) && (e.ctrlKey && !e.altKey)) {\r
-                                               // Cancel event\r
-                                               e.returnValue = false;\r
-                                               e.cancelBubble = true;\r
-                                               return false;\r
-                                       }\r
-                               }\r
+                               t.source = s;\r
                        }\r
 \r
-                       // If undo/redo key\r
-                       if ((e.keyCode == 90 || e.keyCode == 89) && (e.ctrlKey && !e.altKey))\r
-                               return true;\r
+                       return t.source;\r
+               }\r
+       });\r
+})();\r
+\r
+(function() {\r
+       var each = tinymce.each;\r
+\r
+       tinymce.create('static tinymce.util.Cookie', {\r
+               getHash : function(n) {\r
+                       var v = this.get(n), h;\r
+\r
+                       if (v) {\r
+                               each(v.split('&'), function(v) {\r
+                                       v = v.split('=');\r
+                                       h = h || {};\r
+                                       h[unescape(v[0])] = unescape(v[1]);\r
+                               });\r
+                       }\r
 \r
-                       // If Ctrl key\r
-                       if (e.keyCode == 17)\r
-                               return true;\r
+                       return h;\r
+               },\r
 \r
-                       // Handle Undo/Redo when typing content\r
+               setHash : function(n, v, e, p, d, s) {\r
+                       var o = '';\r
 \r
-                       // Start typing (non position key)\r
-                       if (!posKey && e.type == "keyup")\r
-                               tinyMCE.execCommand("mceStartTyping");\r
+                       each(v, function(v, k) {\r
+                               o += (!o ? '' : '&') + escape(k) + '=' + escape(v);\r
+                       });\r
 \r
-                       // End typing (position key) or some Ctrl event\r
-                       if (e.type == "keyup" && (posKey || e.ctrlKey))\r
-                               tinyMCE.execCommand("mceEndTyping");\r
+                       this.set(n, o, e, p, d, s);\r
+               },\r
 \r
-                       if (posKey && e.type == "keyup")\r
-                               tinyMCE.triggerNodeChange(false);\r
+               get : function(n) {\r
+                       var c = document.cookie, e, p = n + "=", b;\r
 \r
-                       if (tinyMCE.isMSIE && e.ctrlKey)\r
-                               window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);\r
-               break;\r
+                       // Strict mode\r
+                       if (!c)\r
+                               return;\r
 \r
-               case "mousedown":\r
-               case "mouseup":\r
-               case "click":\r
-               case "focus":\r
-                       if (tinyMCE.selectedInstance)\r
-                               tinyMCE.selectedInstance.switchSettings();\r
+                       b = c.indexOf("; " + p);\r
 \r
-                       // Check instance event trigged on\r
-                       var targetBody = tinyMCE.getParentElement(e.target, "body");\r
-                       for (var instanceName in tinyMCE.instances) {\r
-                               if (!tinyMCE.isInstance(tinyMCE.instances[instanceName]))\r
-                                       continue;\r
+                       if (b == -1) {\r
+                               b = c.indexOf(p);\r
 \r
-                               var inst = tinyMCE.instances[instanceName];\r
+                               if (b != 0)\r
+                                       return null;\r
+                       } else\r
+                               b += 2;\r
 \r
-                               // Reset design mode if lost (on everything just in case)\r
-                               inst.autoResetDesignMode();\r
+                       e = c.indexOf(";", b);\r
 \r
-                               if (inst.getBody() == targetBody) {\r
-                                       tinyMCE.selectedInstance = inst;\r
-                                       tinyMCE.selectedElement = e.target;\r
-                                       tinyMCE.linkElement = tinyMCE.getParentElement(tinyMCE.selectedElement, "a");\r
-                                       tinyMCE.imgElement = tinyMCE.getParentElement(tinyMCE.selectedElement, "img");\r
-                                       break;\r
-                               }\r
-                       }\r
+                       if (e == -1)\r
+                               e = c.length;\r
 \r
-                       if (tinyMCE.isSafari) {\r
-                               tinyMCE.selectedInstance.lastSafariSelection = tinyMCE.selectedInstance.getBookmark();\r
-                               tinyMCE.selectedInstance.lastSafariSelectedElement = tinyMCE.selectedElement;\r
+                       return unescape(c.substring(b + p.length, e));\r
+               },\r
 \r
-                               var lnk = tinyMCE.getParentElement(tinyMCE.selectedElement, "a");\r
+               set : function(n, v, e, p, d, s) {\r
+                       document.cookie = n + "=" + escape(v) +\r
+                               ((e) ? "; expires=" + e.toGMTString() : "") +\r
+                               ((p) ? "; path=" + escape(p) : "") +\r
+                               ((d) ? "; domain=" + d : "") +\r
+                               ((s) ? "; secure" : "");\r
+               },\r
 \r
-                               // Patch the darned link\r
-                               if (lnk && e.type == "mousedown") {\r
-                                       lnk.setAttribute("mce_real_href", lnk.getAttribute("href"));\r
-                                       lnk.setAttribute("href", "javascript:void(0);");\r
-                               }\r
+               remove : function(n, p) {\r
+                       var d = new Date();\r
 \r
-                               // Patch back\r
-                               if (lnk && e.type == "click") {\r
-                                       window.setTimeout(function() {\r
-                                               lnk.setAttribute("href", lnk.getAttribute("mce_real_href"));\r
-                                               lnk.removeAttribute("mce_real_href");\r
-                                       }, 10);\r
-                               }\r
-                       }\r
+                       d.setTime(d.getTime() - 1000);\r
 \r
-                       // Reset selected node\r
-                       if (e.type != "focus")\r
-                               tinyMCE.selectedNode = null;\r
+                       this.set(n, '', d, p, d);\r
+               }\r
+       });\r
+})();\r
 \r
-                       tinyMCE.triggerNodeChange(false);\r
-                       tinyMCE.execCommand("mceEndTyping");\r
+(function() {\r
+       function serialize(o, quote) {\r
+               var i, v, t;\r
 \r
-                       if (e.type == "mouseup")\r
-                               tinyMCE.execCommand("mceAddUndoLevel");\r
+               quote = quote || '"';\r
 \r
-                       // Just in case\r
-                       if (!tinyMCE.selectedInstance && e.target.editorId)\r
-                               tinyMCE.selectedInstance = tinyMCE.instances[e.target.editorId];\r
+               if (o == null)\r
+                       return 'null';\r
 \r
-                       return false;\r
-               break;\r
-    } // end switch\r
-}; // end function\r
+               t = typeof o;\r
 \r
-TinyMCE.prototype.switchClass = function(element, class_name, lock_state) {\r
-       var lockChanged = false;\r
+               if (t == 'string') {\r
+                       v = '\bb\tt\nn\ff\rr\""\'\'\\\\';\r
 \r
-       if (typeof(lock_state) != "undefined" && element != null) {\r
-               element.classLock = lock_state;\r
-               lockChanged = true;\r
-       }\r
+                       return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {\r
+                               // Make sure single quotes never get encoded inside double quotes for JSON compatibility\r
+                               if (quote === '"' && a === "'")\r
+                                       return a;\r
 \r
-       if (element != null && (lockChanged || !element.classLock)) {\r
-               element.oldClassName = element.className;\r
-               element.className = class_name;\r
-       }\r
-};\r
+                               i = v.indexOf(b);\r
 \r
-TinyMCE.prototype.restoreAndSwitchClass = function(element, class_name) {\r
-       if (element != null && !element.classLock) {\r
-               this.restoreClass(element);\r
-               this.switchClass(element, class_name);\r
-       }\r
-};\r
+                               if (i + 1)\r
+                                       return '\\' + v.charAt(i + 1);\r
 \r
-TinyMCE.prototype.switchClassSticky = function(element_name, class_name, lock_state) {\r
-       var element, lockChanged = false;\r
+                               a = b.charCodeAt().toString(16);\r
 \r
-       // Performance issue\r
-       if (!this.stickyClassesLookup[element_name])\r
-               this.stickyClassesLookup[element_name] = document.getElementById(element_name);\r
+                               return '\\u' + '0000'.substring(a.length) + a;\r
+                       }) + quote;\r
+               }\r
 \r
-//     element = document.getElementById(element_name);\r
-       element = this.stickyClassesLookup[element_name];\r
+               if (t == 'object') {\r
+                       if (o.hasOwnProperty && o instanceof Array) {\r
+                                       for (i=0, v = '['; i<o.length; i++)\r
+                                               v += (i > 0 ? ',' : '') + serialize(o[i], quote);\r
 \r
-       if (typeof(lock_state) != "undefined" && element != null) {\r
-               element.classLock = lock_state;\r
-               lockChanged = true;\r
-       }\r
+                                       return v + ']';\r
+                               }\r
 \r
-       if (element != null && (lockChanged || !element.classLock)) {\r
-               element.className = class_name;\r
-               element.oldClassName = class_name;\r
+                               v = '{';\r
 \r
-               // Fix opacity in Opera\r
-               if (tinyMCE.isOpera) {\r
-                       if (class_name == "mceButtonDisabled") {\r
-                               var suffix = "";\r
+                               for (i in o)\r
+                                       v += typeof o[i] != 'function' ? (v.length > 1 ? ',' + quote : quote) + i + quote +':' + serialize(o[i], quote) : '';\r
 \r
-                               if (!element.mceOldSrc)\r
-                                       element.mceOldSrc = element.src;\r
+                               return v + '}';\r
+               }\r
 \r
-                               if (this.operaOpacityCounter > -1)\r
-                                       suffix = '?rnd=' + this.operaOpacityCounter++;\r
+               return '' + o;\r
+       };\r
 \r
-                               element.src = tinyMCE.baseURL + "/themes/" + tinyMCE.getParam("theme") + "/images/opacity.png" + suffix;\r
-                               element.style.backgroundImage = "url('" + element.mceOldSrc + "')";\r
-                       } else {\r
-                               if (element.mceOldSrc) {\r
-                                       element.src = element.mceOldSrc;\r
-                                       element.parentNode.style.backgroundImage = "";\r
-                                       element.mceOldSrc = null;\r
-                               }\r
+       tinymce.util.JSON = {\r
+               serialize: serialize,\r
+\r
+               parse: function(s) {\r
+                       try {\r
+                               return eval('(' + s + ')');\r
+                       } catch (ex) {\r
+                               // Ignore\r
                        }\r
                }\r
-       }\r
-};\r
 \r
-TinyMCE.prototype.restoreClass = function(element) {\r
-       if (element != null && element.oldClassName && !element.classLock) {\r
-               element.className = element.oldClassName;\r
-               element.oldClassName = null;\r
-       }\r
-};\r
+               };\r
+})();\r
+tinymce.create('static tinymce.util.XHR', {\r
+       send : function(o) {\r
+               var x, t, w = window, c = 0;\r
+\r
+               // Default settings\r
+               o.scope = o.scope || this;\r
+               o.success_scope = o.success_scope || o.scope;\r
+               o.error_scope = o.error_scope || o.scope;\r
+               o.async = o.async === false ? false : true;\r
+               o.data = o.data || '';\r
+\r
+               function get(s) {\r
+                       x = 0;\r
+\r
+                       try {\r
+                               x = new ActiveXObject(s);\r
+                       } catch (ex) {\r
+                       }\r
 \r
-TinyMCE.prototype.setClassLock = function(element, lock_state) {\r
-       if (element != null)\r
-               element.classLock = lock_state;\r
-};\r
+                       return x;\r
+               };\r
 \r
-TinyMCE.prototype.addEvent = function(obj, name, handler) {\r
-       if (tinyMCE.isMSIE) {\r
-               obj.attachEvent("on" + name, handler);\r
-       } else\r
-               obj.addEventListener(name, handler, false);\r
-};\r
+               x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP');\r
 \r
-TinyMCE.prototype.submitPatch = function() {\r
-       tinyMCE.removeTinyMCEFormElements(this);\r
-       tinyMCE.triggerSave();\r
-       this.mceOldSubmit();\r
-       tinyMCE.isNotDirty = true;\r
-};\r
+               if (x) {\r
+                       if (x.overrideMimeType)\r
+                               x.overrideMimeType(o.content_type);\r
 \r
-TinyMCE.prototype.onLoad = function() {\r
-       for (var c=0; c<tinyMCE.configs.length; c++) {\r
-               tinyMCE.settings = tinyMCE.configs[c];\r
+                       x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async);\r
 \r
-               var selector = tinyMCE.getParam("editor_selector");\r
-               var deselector = tinyMCE.getParam("editor_deselector");\r
-               var elementRefAr = new Array();\r
+                       if (o.content_type)\r
+                               x.setRequestHeader('Content-Type', o.content_type);\r
 \r
-               // Add submit triggers\r
-               if (document.forms && tinyMCE.settings['add_form_submit_trigger'] && !tinyMCE.submitTriggers) {\r
-                       for (var i=0; i<document.forms.length; i++) {\r
-                               var form = document.forms[i];\r
+                       x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\r
 \r
-                               tinyMCE.addEvent(form, "submit", TinyMCE.prototype.handleEvent);\r
-                               tinyMCE.addEvent(form, "reset", TinyMCE.prototype.handleEvent);\r
-                               tinyMCE.submitTriggers = true; // Do it only once\r
+                       x.send(o.data);\r
 \r
-                               // Patch the form.submit function\r
-                               if (tinyMCE.settings['submit_patch']) {\r
-                                       try {\r
-                                               form.mceOldSubmit = form.submit;\r
-                                               form.submit = TinyMCE.prototype.submitPatch;\r
-                                       } catch (e) {\r
-                                               // Do nothing\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               // Add editor instances based on mode\r
-               var mode = tinyMCE.settings['mode'];\r
-               switch (mode) {\r
-                       case "exact":\r
-                               var elements = tinyMCE.getParam('elements', '', true, ',');\r
+                       function ready() {\r
+                               if (!o.async || x.readyState == 4 || c++ > 10000) {\r
+                                       if (o.success && c < 10000 && x.status == 200)\r
+                                               o.success.call(o.success_scope, '' + x.responseText, x, o);\r
+                                       else if (o.error)\r
+                                               o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);\r
 \r
-                               for (var i=0; i<elements.length; i++) {\r
-                                       var element = tinyMCE._getElementById(elements[i]);\r
-                                       var trigger = element ? element.getAttribute(tinyMCE.settings['textarea_trigger']) : "";\r
+                                       x = null;\r
+                               } else\r
+                                       w.setTimeout(ready, 10);\r
+                       };\r
 \r
-                                       if (tinyMCE.getAttrib(element, "class").indexOf(deselector) != -1)\r
-                                               continue;\r
+                       // Syncronous request\r
+                       if (!o.async)\r
+                               return ready();\r
 \r
-                                       if (trigger == "false")\r
-                                               continue;\r
+                       // Wait for response, onReadyStateChange can not be used since it leaks memory in IE\r
+                       t = w.setTimeout(ready, 10);\r
+               }\r
+       }\r
+});\r
 \r
-                                       if (tinyMCE.settings['ask'] && element) {\r
-                                               elementRefAr[elementRefAr.length] = element;\r
-                                               continue;\r
-                                       }\r
+(function() {\r
+       var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR;\r
 \r
-                                       if (element)\r
-                                               tinyMCE.addMCEControl(element, elements[i]);\r
-                                       else if (tinyMCE.settings['debug'])\r
-                                               alert("Error: Could not find element by id or name: " + elements[i]);\r
-                               }\r
-                       break;\r
+       tinymce.create('tinymce.util.JSONRequest', {\r
+               JSONRequest : function(s) {\r
+                       this.settings = extend({\r
+                       }, s);\r
+                       this.count = 0;\r
+               },\r
 \r
-                       case "specific_textareas":\r
-                       case "textareas":\r
-                               var nodeList = document.getElementsByTagName("textarea");\r
+               send : function(o) {\r
+                       var ecb = o.error, scb = o.success;\r
 \r
-                               for (var i=0; i<nodeList.length; i++) {\r
-                                       var elm = nodeList.item(i);\r
-                                       var trigger = elm.getAttribute(tinyMCE.settings['textarea_trigger']);\r
+                       o = extend(this.settings, o);\r
 \r
-                                       if (selector != '' && tinyMCE.getAttrib(elm, "class").indexOf(selector) == -1)\r
-                                               continue;\r
+                       o.success = function(c, x) {\r
+                               c = JSON.parse(c);\r
 \r
-                                       if (selector != '')\r
-                                               trigger = selector != "" ? "true" : "";\r
+                               if (typeof(c) == 'undefined') {\r
+                                       c = {\r
+                                               error : 'JSON Parse error.'\r
+                                       };\r
+                               }\r
 \r
-                                       if (tinyMCE.getAttrib(elm, "class").indexOf(deselector) != -1)\r
-                                               continue;\r
+                               if (c.error)\r
+                                       ecb.call(o.error_scope || o.scope, c.error, x);\r
+                               else\r
+                                       scb.call(o.success_scope || o.scope, c.result);\r
+                       };\r
 \r
-                                       if ((mode == "specific_textareas" && trigger == "true") || (mode == "textareas" && trigger != "false"))\r
-                                               elementRefAr[elementRefAr.length] = elm;\r
-                               }\r
-                       break;\r
-               }\r
+                       o.error = function(ty, x) {\r
+                               if (ecb)\r
+                                       ecb.call(o.error_scope || o.scope, ty, x);\r
+                       };\r
 \r
-               for (var i=0; i<elementRefAr.length; i++) {\r
-                       var element = elementRefAr[i];\r
-                       var elementId = element.name ? element.name : element.id;\r
+                       o.data = JSON.serialize({\r
+                               id : o.id || 'c' + (this.count++),\r
+                               method : o.method,\r
+                               params : o.params\r
+                       });\r
 \r
-                       if (tinyMCE.settings['ask']) {\r
-                               // Focus breaks in Mozilla\r
-                               if (tinyMCE.isGecko) {\r
-                                       var settings = tinyMCE.settings;\r
+                       // JSON content type for Ruby on rails. Bug: #1883287\r
+                       o.content_type = 'application/json';\r
 \r
-                                       tinyMCE.addEvent(element, "focus", function (e) {window.setTimeout(function() {TinyMCE.prototype.confirmAdd(e, settings);}, 10);});\r
-                               } else {\r
-                                       var settings = tinyMCE.settings;\r
+                       XHR.send(o);\r
+               },\r
 \r
-                                       tinyMCE.addEvent(element, "focus", function () { TinyMCE.prototype.confirmAdd(null, settings); });\r
-                               }\r
-                       } else\r
-                               tinyMCE.addMCEControl(element, elementId);\r
+               'static' : {\r
+                       sendRPC : function(o) {\r
+                               return new tinymce.util.JSONRequest().send(o);\r
+                       }\r
                }\r
+       });\r
+}());\r
+(function(tinymce){\r
+       tinymce.VK = {\r
+               DELETE:46,\r
+               BACKSPACE:8\r
+               \r
+       }\r
 \r
-               // Handle auto focus\r
-               if (tinyMCE.settings['auto_focus']) {\r
-                       window.setTimeout(function () {\r
-                               var inst = tinyMCE.getInstanceById(tinyMCE.settings['auto_focus']);\r
-                               inst.selectNode(inst.getBody(), true, true);\r
-                               inst.contentWindow.focus();\r
-                       }, 10);\r
-               }\r
+})(tinymce);\r
 \r
-               tinyMCE.executeCallback('oninit', '_oninit', 0);\r
-       }\r
-};\r
+(function(tinymce) {\r
+       var VK = tinymce.VK, BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE;\r
 \r
-TinyMCE.prototype.removeMCEControl = function(editor_id) {\r
-       var inst = tinyMCE.getInstanceById(editor_id);\r
+       function cleanupStylesWhenDeleting(ed) {\r
+               var dom = ed.dom, selection = ed.selection;\r
 \r
-       if (inst) {\r
-               inst.switchSettings();\r
+               ed.onKeyDown.add(function(ed, e) {\r
+                       var rng, blockElm, node, clonedSpan, isDelete;\r
 \r
-               editor_id = inst.editorId;\r
-               var html = tinyMCE.getContent(editor_id);\r
+                       isDelete = e.keyCode == DELETE;\r
+                       if (isDelete || e.keyCode == BACKSPACE) {\r
+                               e.preventDefault();\r
+                               rng = selection.getRng();\r
 \r
-               // Remove editor instance from instances array\r
-               var tmpInstances = new Array();\r
-               for (var instanceName in tinyMCE.instances) {\r
-                       var instance = tinyMCE.instances[instanceName];\r
-                       if (!tinyMCE.isInstance(instance))\r
-                               continue;\r
+                               // Find root block\r
+                               blockElm = dom.getParent(rng.startContainer, dom.isBlock);\r
 \r
-                       if (instanceName != editor_id)\r
-                                       tmpInstances[instanceName] = instance;\r
-               }\r
-               tinyMCE.instances = tmpInstances;\r
+                               // On delete clone the root span of the next block element\r
+                               if (isDelete)\r
+                                       blockElm = dom.getNext(blockElm, dom.isBlock);\r
 \r
-               tinyMCE.selectedElement = null;\r
-               tinyMCE.selectedInstance = null;\r
+                               // Locate root span element and clone it since it would otherwise get merged by the "apple-style-span" on delete/backspace\r
+                               if (blockElm) {\r
+                                       node = blockElm.firstChild;\r
 \r
-               // Remove element\r
-               var replaceElement = document.getElementById(editor_id + "_parent");\r
-               var oldTargetElement = inst.oldTargetElement;\r
-               var targetName = oldTargetElement.nodeName.toLowerCase();\r
+                                       if (node && node.nodeName === 'SPAN') {\r
+                                               clonedSpan = node.cloneNode(false);\r
+                                       }\r
+                               }\r
 \r
-               if (targetName == "textarea" || targetName == "input") {\r
-                       // Just show the old text area\r
-                       replaceElement.parentNode.removeChild(replaceElement);\r
-                       oldTargetElement.style.display = "inline";\r
-                       oldTargetElement.value = html;\r
-               } else {\r
-                       oldTargetElement.innerHTML = html;\r
+                               // Do the backspace/delete actiopn\r
+                               ed.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null);\r
 \r
-                       replaceElement.parentNode.insertBefore(oldTargetElement, replaceElement);\r
-                       replaceElement.parentNode.removeChild(replaceElement);\r
-               }\r
-       }\r
-};\r
+                               // Find all odd apple-style-spans\r
+                               blockElm = dom.getParent(rng.startContainer, dom.isBlock);\r
+                               tinymce.each(dom.select('span.Apple-style-span,font.Apple-style-span', blockElm), function(span) {\r
+                                       var rng = dom.createRng();\r
 \r
-TinyMCE.prototype._cleanupElementName = function(element_name, element) {\r
-       var name = "";\r
+                                       // Set range selection before the span we are about to remove\r
+                                       rng.setStartBefore(span);\r
+                                       rng.setEndBefore(span);\r
 \r
-       element_name = element_name.toLowerCase();\r
+                                       if (clonedSpan) {\r
+                                               dom.replace(clonedSpan.cloneNode(false), span, true);\r
+                                       } else {\r
+                                               dom.remove(span, true);\r
+                                       }\r
 \r
-       // Never include body\r
-       if (element_name == "body")\r
-               return null;\r
+                                       // Restore the selection\r
+                                       selection.setRng(rng);\r
+                               });\r
+                       }\r
+               });\r
+       };\r
 \r
-       // If verification mode\r
-       if (tinyMCE.cleanup_verify_html) {\r
-               // Check if invalid element\r
-               for (var i=0; i<tinyMCE.cleanup_invalidElements.length; i++) {\r
-                       if (tinyMCE.cleanup_invalidElements[i] == element_name)\r
-                               return null;\r
-               }\r
+       function emptyEditorWhenDeleting(ed) {\r
+               ed.onKeyUp.add(function(ed, e) {\r
+                       var keyCode = e.keyCode;\r
 \r
-               // Check if valid element\r
-               var validElement = false;\r
-               var elementAttribs = null;\r
-               for (var i=0; i<tinyMCE.cleanup_validElements.length && !elementAttribs; i++) {\r
-                       for (var x=0, n=tinyMCE.cleanup_validElements[i][0].length; x<n; x++) {\r
-                               var elmMatch = tinyMCE.cleanup_validElements[i][0][x];\r
-\r
-                               if (elmMatch.charAt(0) == '+' || elmMatch.charAt(0) == '-')\r
-                                       elmMatch = elmMatch.substring(1);\r
-\r
-                               // Handle wildcard/regexp\r
-                               if (elmMatch.match(new RegExp('\\*|\\?|\\+', 'g')) != null) {\r
-                                       elmMatch = elmMatch.replace(new RegExp('\\?', 'g'), '(\\S?)');\r
-                                       elmMatch = elmMatch.replace(new RegExp('\\+', 'g'), '(\\S+)');\r
-                                       elmMatch = elmMatch.replace(new RegExp('\\*', 'g'), '(\\S*)');\r
-                                       elmMatch = "^" + elmMatch + "$";\r
-                                       if (element_name.match(new RegExp(elmMatch, 'g'))) {\r
-                                               elementAttribs = tinyMCE.cleanup_validElements[i];\r
-                                               validElement = true;\r
-                                               break;\r
-                                       }\r
+                       if (keyCode == DELETE || keyCode == BACKSPACE) {\r
+                               if (ed.dom.isEmpty(ed.getBody())) {\r
+                                       ed.setContent('', {format : 'raw'});\r
+                                       ed.nodeChanged();\r
+                                       return;\r
                                }\r
+                       }\r
+               });\r
+       };\r
+       \r
+       tinymce.create('tinymce.util.Quirks', {\r
+               Quirks: function(ed) {\r
+                       // Load WebKit specific fixed\r
+                       if (tinymce.isWebKit) {\r
+                               cleanupStylesWhenDeleting(ed);\r
+                               emptyEditorWhenDeleting(ed);\r
+                       }\r
 \r
-                               // Handle non regexp\r
-                               if (element_name == elmMatch) {\r
-                                       elementAttribs = tinyMCE.cleanup_validElements[i];\r
-                                       validElement = true;\r
-                                       element_name = elementAttribs[0][0];\r
-                                       break;\r
-                               }\r
+                       // Load IE specific fixes\r
+                       if (tinymce.isIE) {\r
+                               emptyEditorWhenDeleting(ed);\r
                        }\r
                }\r
+       });\r
+})(tinymce);\r
+(function(tinymce) {\r
+       var namedEntities, baseEntities, reverseEntities,\r
+               attrsCharsRegExp = /[&<>\"\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,\r
+               textCharsRegExp = /[<>&\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,\r
+               rawCharsRegExp = /[<>&\"\']/g,\r
+               entityRegExp = /&(#x|#)?([\w]+);/g,\r
+               asciiMap = {\r
+                               128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020",\r
+                               135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152",\r
+                               142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022",\r
+                               150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A",\r
+                               156 : "\u0153", 158 : "\u017E", 159 : "\u0178"\r
+               };\r
+\r
+       // Raw entities\r
+       baseEntities = {\r
+               '\"' : '&quot;', // Needs to be escaped since the YUI compressor would otherwise break the code\r
+               "'" : '&#39;',\r
+               '<' : '&lt;',\r
+               '>' : '&gt;',\r
+               '&' : '&amp;'\r
+       };\r
+\r
+       // Reverse lookup table for raw entities\r
+       reverseEntities = {\r
+               '&lt;' : '<',\r
+               '&gt;' : '>',\r
+               '&amp;' : '&',\r
+               '&quot;' : '"',\r
+               '&apos;' : "'"\r
+       };\r
+\r
+       // Decodes text by using the browser\r
+       function nativeDecode(text) {\r
+               var elm;\r
+\r
+               elm = document.createElement("div");\r
+               elm.innerHTML = text;\r
+\r
+               return elm.textContent || elm.innerText || text;\r
+       };\r
+\r
+       // Build a two way lookup table for the entities\r
+       function buildEntitiesLookup(items, radix) {\r
+               var i, chr, entity, lookup = {};\r
+\r
+               if (items) {\r
+                       items = items.split(',');\r
+                       radix = radix || 10;\r
+\r
+                       // Build entities lookup table\r
+                       for (i = 0; i < items.length; i += 2) {\r
+                               chr = String.fromCharCode(parseInt(items[i], radix));\r
+\r
+                               // Only add non base entities\r
+                               if (!baseEntities[chr]) {\r
+                                       entity = '&' + items[i + 1] + ';';\r
+                                       lookup[chr] = entity;\r
+                                       lookup[entity] = chr;\r
+                               }\r
+                       }\r
 \r
-               if (!validElement)\r
-                       return null;\r
-       }\r
-\r
-       if (element_name.charAt(0) == '+' || element_name.charAt(0) == '-')\r
-               name = element_name.substring(1);\r
-\r
-       // Special Mozilla stuff\r
-       if (!tinyMCE.isMSIE) {\r
-               // Fix for bug #958498\r
-               if (name == "strong" && !tinyMCE.cleanup_on_save)\r
-                       element_name = "b";\r
-               else if (name == "em" && !tinyMCE.cleanup_on_save)\r
-                       element_name = "i";\r
-       }\r
+                       return lookup;\r
+               }\r
+       };\r
+\r
+       // Unpack entities lookup where the numbers are in radix 32 to reduce the size\r
+       namedEntities = buildEntitiesLookup(\r
+               '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +\r
+               '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +\r
+               '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +\r
+               '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +\r
+               '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +\r
+               '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +\r
+               '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +\r
+               '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +\r
+               '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +\r
+               '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +\r
+               'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +\r
+               'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +\r
+               't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +\r
+               'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +\r
+               'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +\r
+               '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +\r
+               '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +\r
+               '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +\r
+               '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +\r
+               '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +\r
+               'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +\r
+               'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +\r
+               'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +\r
+               '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +\r
+               '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro'\r
+       , 32);\r
+\r
+       tinymce.html = tinymce.html || {};\r
+\r
+       tinymce.html.Entities = {\r
+               encodeRaw : function(text, attr) {\r
+                       return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {\r
+                               return baseEntities[chr] || chr;\r
+                       });\r
+               },\r
 \r
-       var elmData = new Object();\r
+               encodeAllRaw : function(text) {\r
+                       return ('' + text).replace(rawCharsRegExp, function(chr) {\r
+                               return baseEntities[chr] || chr;\r
+                       });\r
+               },\r
 \r
-       elmData.element_name = element_name;\r
-       elmData.valid_attribs = elementAttribs;\r
+               encodeNumeric : function(text, attr) {\r
+                       return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {\r
+                               // Multi byte sequence convert it to a single entity\r
+                               if (chr.length > 1)\r
+                                       return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';';\r
 \r
-       return elmData;\r
-};\r
+                               return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';\r
+                       });\r
+               },\r
 \r
-/**\r
- * This function moves CSS styles to/from attributes.\r
- */\r
-TinyMCE.prototype._moveStyle = function(elm, style, attrib) {\r
-       if (tinyMCE.cleanup_inline_styles) {\r
-               var val = tinyMCE.getAttrib(elm, attrib);\r
+               encodeNamed : function(text, attr, entities) {\r
+                       entities = entities || namedEntities;\r
 \r
-               if (val != '') {\r
-                       val = '' + val;\r
+                       return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {\r
+                               return baseEntities[chr] || entities[chr] || chr;\r
+                       });\r
+               },\r
 \r
-                       switch (attrib) {\r
-                               case "background":\r
-                                       val = "url('" + val + "')";\r
-                                       break;\r
+               getEncodeFunc : function(name, entities) {\r
+                       var Entities = tinymce.html.Entities;\r
 \r
-                               case "bordercolor":\r
-                                       if (elm.style.borderStyle == '' || elm.style.borderStyle == 'none')\r
-                                               elm.style.borderStyle = 'solid';\r
-                                       break;\r
+                       entities = buildEntitiesLookup(entities) || namedEntities;\r
 \r
-                               case "border":\r
-                               case "width":\r
-                               case "height":\r
-                                       if (attrib == "border" && elm.style.borderWidth > 0)\r
-                                               return;\r
+                       function encodeNamedAndNumeric(text, attr) {\r
+                               return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {\r
+                                       return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;\r
+                               });\r
+                       };\r
 \r
-                                       if (val.indexOf('%') == -1)\r
-                                               val += 'px';\r
-                                       break;\r
+                       function encodeCustomNamed(text, attr) {\r
+                               return Entities.encodeNamed(text, attr, entities);\r
+                       };\r
 \r
-                               case "vspace":\r
-                               case "hspace":\r
-                                       elm.style.marginTop = val + "px";\r
-                                       elm.style.marginBottom = val + "px";\r
-                                       elm.removeAttribute(attrib);\r
-                                       return;\r
+                       // Replace + with , to be compatible with previous TinyMCE versions\r
+                       name = tinymce.makeMap(name.replace(/\+/g, ','));\r
 \r
-                               case "align":\r
-                                       if (elm.nodeName == "IMG") {\r
-                                               if (tinyMCE.isMSIE)\r
-                                                       elm.style.styleFloat = val;\r
-                                               else\r
-                                                       elm.style.cssFloat = val;\r
-                                       } else\r
-                                               elm.style.textAlign = val;\r
+                       // Named and numeric encoder\r
+                       if (name.named && name.numeric)\r
+                               return encodeNamedAndNumeric;\r
 \r
-                                       elm.removeAttribute(attrib);\r
-                                       return;\r
-                       }\r
+                       // Named encoder\r
+                       if (name.named) {\r
+                               // Custom names\r
+                               if (entities)\r
+                                       return encodeCustomNamed;\r
 \r
-                       if (val != '') {\r
-                               eval('elm.style.' + style + ' = val;');\r
-                               elm.removeAttribute(attrib);\r
+                               return Entities.encodeNamed;\r
                        }\r
-               }\r
-       } else {\r
-               if (style == '')\r
-                       return;\r
 \r
-               var val = eval('elm.style.' + style) == '' ? tinyMCE.getAttrib(elm, attrib) : eval('elm.style.' + style);\r
-               val = val == null ? '' : '' + val;\r
+                       // Numeric\r
+                       if (name.numeric)\r
+                               return Entities.encodeNumeric;\r
 \r
-               switch (attrib) {\r
-                       // Always move background to style\r
-                       case "background":\r
-                               if (val.indexOf('url') == -1 && val != '')\r
-                                       val = "url('" + val + "');";\r
+                       // Raw encoder\r
+                       return Entities.encodeRaw;\r
+               },\r
 \r
-                               if (val != '') {\r
-                                       elm.style.backgroundImage = val;\r
-                                       elm.removeAttribute(attrib);\r
-                               }\r
-                               return;\r
+               decode : function(text) {\r
+                       return text.replace(entityRegExp, function(all, numeric, value) {\r
+                               if (numeric) {\r
+                                       value = parseInt(value, numeric.length === 2 ? 16 : 10);\r
 \r
-                       case "border":\r
-                       case "width":\r
-                       case "height":\r
-                               val = val.replace('px', '');\r
-                               break;\r
+                                       // Support upper UTF\r
+                                       if (value > 0xFFFF) {\r
+                                               value -= 0x10000;\r
 \r
-                       case "align":\r
-                               if (tinyMCE.getAttrib(elm, 'align') == '') {\r
-                                       if (elm.nodeName == "IMG") {\r
-                                               if (tinyMCE.isMSIE && elm.style.styleFloat != '') {\r
-                                                       val = elm.style.styleFloat;\r
-                                                       style = 'styleFloat';\r
-                                               } else if (tinyMCE.isGecko && elm.style.cssFloat != '') {\r
-                                                       val = elm.style.cssFloat;\r
-                                                       style = 'cssFloat';\r
-                                               }\r
-                                       }\r
+                                               return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF));\r
+                                       } else\r
+                                               return asciiMap[value] || String.fromCharCode(value);\r
                                }\r
-                               break;\r
-               }\r
 \r
-               if (val != '') {\r
-                       elm.removeAttribute(attrib);\r
-                       elm.setAttribute(attrib, val);\r
-                       eval('elm.style.' + style + ' = "";');\r
+                               return reverseEntities[all] || namedEntities[all] || nativeDecode(all);\r
+                       });\r
                }\r
+       };\r
+})(tinymce);\r
+\r
+tinymce.html.Styles = function(settings, schema) {\r
+       var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,\r
+               urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,\r
+               styleRegExp = /\s*([^:]+):\s*([^;]+);?/g,\r
+               trimRightRegExp = /\s+$/,\r
+               urlColorRegExp = /rgb/,\r
+               undef, i, encodingLookup = {}, encodingItems;\r
+\r
+       settings = settings || {};\r
+\r
+       encodingItems = '\\" \\\' \\; \\: ; : \uFEFF'.split(' ');\r
+       for (i = 0; i < encodingItems.length; i++) {\r
+               encodingLookup[encodingItems[i]] = '\uFEFF' + i;\r
+               encodingLookup['\uFEFF' + i] = encodingItems[i];\r
        }\r
-};\r
 \r
-TinyMCE.prototype._cleanupAttribute = function(valid_attributes, element_name, attribute_node, element_node) {\r
-       var attribName = attribute_node.nodeName.toLowerCase();\r
-       var attribValue = attribute_node.nodeValue;\r
-       var attribMustBeValue = null;\r
-       var verified = false;\r
-\r
-       // Mozilla attibute, remove them\r
-       if (attribName.indexOf('moz_') != -1)\r
-               return null;\r
-\r
-       if (!tinyMCE.cleanup_on_save && (attribName == "mce_href" || attribName == "mce_src"))\r
-               return {name : attribName, value : attribValue};\r
-\r
-       // Verify attrib\r
-       if (tinyMCE.cleanup_verify_html && !verified) {\r
-               for (var i=1; i<valid_attributes.length; i++) {\r
-                       var attribMatch = valid_attributes[i][0];\r
-                       var re = null;\r
-\r
-                       // Build regexp from wildcard\r
-                       if (attribMatch.match(new RegExp('\\*|\\?|\\+', 'g')) != null) {\r
-                               attribMatch = attribMatch.replace(new RegExp('\\?', 'g'), '(\\S?)');\r
-                               attribMatch = attribMatch.replace(new RegExp('\\+', 'g'), '(\\S+)');\r
-                               attribMatch = attribMatch.replace(new RegExp('\\*', 'g'), '(\\S*)');\r
-                               attribMatch = "^" + attribMatch + "$";\r
-                               re = new RegExp(attribMatch, 'g');\r
-                       }\r
-\r
-                       if ((re && attribName.match(re) != null) || attribName == attribMatch) {\r
-                               verified = true;\r
-                               attribMustBeValue = valid_attributes[i][3];\r
-                               break;\r
-                       }\r
-               }\r
+       function toHex(match, r, g, b) {\r
+               function hex(val) {\r
+                       val = parseInt(val).toString(16);\r
 \r
-               if (!verified)\r
-                       return false;\r
-       } else\r
-               verified = true;\r
-\r
-       // Treat some attribs diffrent\r
-       switch (attribName) {\r
-               case "size":\r
-                       if (tinyMCE.isMSIE5 && element_name == "font")\r
-                               attribValue = element_node.size;\r
-                       break;\r
-\r
-               case "width":\r
-               case "height":\r
-               case "border":\r
-                       // Old MSIE needs this\r
-                       if (tinyMCE.isMSIE5)\r
-                               attribValue = eval("element_node." + attribName);\r
-                       break;\r
-\r
-               case "shape":\r
-                       attribValue = attribValue.toLowerCase();\r
-                       break;\r
-\r
-               case "cellspacing":\r
-                       if (tinyMCE.isMSIE5)\r
-                               attribValue = element_node.cellSpacing;\r
-                       break;\r
-\r
-               case "cellpadding":\r
-                       if (tinyMCE.isMSIE5)\r
-                               attribValue = element_node.cellPadding;\r
-                       break;\r
-\r
-               case "color":\r
-                       if (tinyMCE.isMSIE5 && element_name == "font")\r
-                               attribValue = element_node.color;\r
-                       break;\r
-\r
-               case "class":\r
-                       // Remove mceItem classes from anchors\r
-                       if (tinyMCE.cleanup_on_save && attribValue.indexOf('mceItemAnchor') != -1)\r
-                               attribValue = attribValue.replace(/mceItem[a-z0-9]+/gi, '');\r
-\r
-                       if (element_name == "table" || element_name == "td") {\r
-                               // Handle visual aid\r
-                               if (tinyMCE.cleanup_visual_table_class != "")\r
-                                       attribValue = tinyMCE.getVisualAidClass(attribValue, !tinyMCE.cleanup_on_save);\r
-                       }\r
-\r
-                       if (!tinyMCE._verifyClass(element_node) || attribValue == "")\r
-                               return null;\r
+                       return val.length > 1 ? val : '0' + val; // 0 -> 00\r
+               };\r
 \r
-                       break;\r
-\r
-               case "onfocus":\r
-               case "onblur":\r
-               case "onclick":\r
-               case "ondblclick":\r
-               case "onmousedown":\r
-               case "onmouseup":\r
-               case "onmouseover":\r
-               case "onmousemove":\r
-               case "onmouseout":\r
-               case "onkeypress":\r
-               case "onkeydown":\r
-               case "onkeydown":\r
-               case "onkeyup":\r
-                       attribValue = tinyMCE.cleanupEventStr("" + attribValue);\r
-\r
-                       if (attribValue.indexOf('return false;') == 0)\r
-                               attribValue = attribValue.substring(14);\r
-\r
-                       break;\r
-\r
-               case "style":\r
-                       attribValue = tinyMCE.serializeStyle(tinyMCE.parseStyle(tinyMCE.getAttrib(element_node, "style")));\r
-                       break;\r
-\r
-               // Convert the URLs of these\r
-               case "href":\r
-               case "src":\r
-               case "longdesc":\r
-                       attribValue = tinyMCE.getAttrib(element_node, attribName);\r
-\r
-                       // Use mce_href instead\r
-                       var href = tinyMCE.getAttrib(element_node, "mce_href");\r
-                       if (attribName == "href" && href != "")\r
-                               attribValue = href;\r
-\r
-                       // Use mce_src instead\r
-                       var src = tinyMCE.getAttrib(element_node, "mce_src");\r
-                       if (attribName == "src" && src != "")\r
-                               attribValue = src;\r
-\r
-                       // Always use absolute URLs within TinyMCE\r
-                       if (!tinyMCE.cleanup_on_save)\r
-                               attribValue = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], attribValue);\r
-                       else if (tinyMCE.getParam('convert_urls'))\r
-                               attribValue = eval(tinyMCE.cleanup_urlconverter_callback + "(attribValue, element_node, tinyMCE.cleanup_on_save);");\r
-\r
-                       break;\r
-\r
-               case "colspan":\r
-               case "rowspan":\r
-                       // Not needed\r
-                       if (attribValue == "1")\r
-                               return null;\r
-                       break;\r
+               return '#' + hex(r) + hex(g) + hex(b);\r
+       };\r
 \r
-               // Skip these\r
-               case "_moz-userdefined":\r
-               case "editorid":\r
-               case "mce_href":\r
-               case "mce_src":\r
-                       return null;\r
-       }\r
+       return {\r
+               toHex : function(color) {\r
+                       return color.replace(rgbRegExp, toHex);\r
+               },\r
 \r
-       // Not the must be value\r
-       if (attribMustBeValue != null) {\r
-               var isCorrect = false;\r
-               for (var i=0; i<attribMustBeValue.length; i++) {\r
-                       if (attribValue == attribMustBeValue[i]) {\r
-                               isCorrect = true;\r
-                               break;\r
-                       }\r
-               }\r
+               parse : function(css) {\r
+                       var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this;\r
 \r
-               if (!isCorrect)\r
-                       return null;\r
-       }\r
+                       function compress(prefix, suffix) {\r
+                               var top, right, bottom, left;\r
 \r
-       var attrib = new Object();\r
+                               // Get values and check it it needs compressing\r
+                               top = styles[prefix + '-top' + suffix];\r
+                               if (!top)\r
+                                       return;\r
 \r
-       attrib.name = attribName;\r
-       attrib.value = attribValue;\r
+                               right = styles[prefix + '-right' + suffix];\r
+                               if (top != right)\r
+                                       return;\r
 \r
-       return attrib;\r
-};\r
+                               bottom = styles[prefix + '-bottom' + suffix];\r
+                               if (right != bottom)\r
+                                       return;\r
 \r
-TinyMCE.prototype.clearArray = function(ar) {\r
-       // Since stupid people tend to extend core objects like\r
-       // Array with their own crap I needed to make functions that clean away\r
-       // this junk so the arrays get clean and nice as they should be\r
-       for (var key in ar)\r
-               ar[key] = null;\r
-};\r
+                               left = styles[prefix + '-left' + suffix];\r
+                               if (bottom != left)\r
+                                       return;\r
 \r
-TinyMCE.prototype.isInstance = function(inst) {\r
-       return inst != null && typeof(inst) == "object" && inst.isTinyMCEControl;\r
-};\r
+                               // Compress\r
+                               styles[prefix + suffix] = left;\r
+                               delete styles[prefix + '-top' + suffix];\r
+                               delete styles[prefix + '-right' + suffix];\r
+                               delete styles[prefix + '-bottom' + suffix];\r
+                               delete styles[prefix + '-left' + suffix];\r
+                       };\r
 \r
-TinyMCE.prototype.parseStyle = function(str) {\r
-       var ar = new Array();\r
+                       function canCompress(key) {\r
+                               var value = styles[key], i;\r
 \r
-       if (str == null)\r
-               return ar;\r
+                               if (!value || value.indexOf(' ') < 0)\r
+                                       return;\r
 \r
-       var st = str.split(';');\r
+                               value = value.split(' ');\r
+                               i = value.length;\r
+                               while (i--) {\r
+                                       if (value[i] !== value[0])\r
+                                               return false;\r
+                               }\r
 \r
-       tinyMCE.clearArray(ar);\r
+                               styles[key] = value[0];\r
 \r
-       for (var i=0; i<st.length; i++) {\r
-               if (st[i] == '')\r
-                       continue;\r
+                               return true;\r
+                       };\r
 \r
-               var re = new RegExp('^\\s*([^:]*):\\s*(.*)\\s*$');\r
-               var pa = st[i].replace(re, '$1||$2').split('||');\r
-//tinyMCE.debug(str, pa[0] + "=" + pa[1], st[i].replace(re, '$1||$2'));\r
-               if (pa.length == 2)\r
-                       ar[pa[0].toLowerCase()] = pa[1];\r
-       }\r
+                       function compress2(target, a, b, c) {\r
+                               if (!canCompress(a))\r
+                                       return;\r
 \r
-       return ar;\r
-};\r
+                               if (!canCompress(b))\r
+                                       return;\r
 \r
-TinyMCE.prototype.compressStyle = function(ar, pr, sf, res) {\r
-       var box = new Array();\r
+                               if (!canCompress(c))\r
+                                       return;\r
 \r
-       box[0] = ar[pr + '-top' + sf];\r
-       box[1] = ar[pr + '-left' + sf];\r
-       box[2] = ar[pr + '-right' + sf];\r
-       box[3] = ar[pr + '-bottom' + sf];\r
+                               // Compress\r
+                               styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];\r
+                               delete styles[a];\r
+                               delete styles[b];\r
+                               delete styles[c];\r
+                       };\r
 \r
-       for (var i=0; i<box.length; i++) {\r
-               if (box[i] == null)\r
-                       return;\r
+                       // Encodes the specified string by replacing all \" \' ; : with _<num>\r
+                       function encode(str) {\r
+                               isEncoded = true;\r
 \r
-               for (var a=0; a<box.length; a++) {\r
-                       if (box[a] != box[i])\r
-                               return;\r
-               }\r
-       }\r
+                               return encodingLookup[str];\r
+                       };\r
 \r
-       // They are all the same\r
-       ar[res] = box[0];\r
-       ar[pr + '-top' + sf] = null;\r
-       ar[pr + '-left' + sf] = null;\r
-       ar[pr + '-right' + sf] = null;\r
-       ar[pr + '-bottom' + sf] = null;\r
-};\r
+                       // Decodes the specified string by replacing all _<num> with it's original value \" \' etc\r
+                       // It will also decode the \" \' if keep_slashes is set to fale or omitted\r
+                       function decode(str, keep_slashes) {\r
+                               if (isEncoded) {\r
+                                       str = str.replace(/\uFEFF[0-9]/g, function(str) {\r
+                                               return encodingLookup[str];\r
+                                       });\r
+                               }\r
 \r
-TinyMCE.prototype.serializeStyle = function(ar) {\r
-       var str = "";\r
+                               if (!keep_slashes)\r
+                                       str = str.replace(/\\([\'\";:])/g, "$1");\r
 \r
-       // Compress box\r
-       tinyMCE.compressStyle(ar, "border", "", "border");\r
-       tinyMCE.compressStyle(ar, "border", "-width", "border-width");\r
-       tinyMCE.compressStyle(ar, "border", "-color", "border-color");\r
+                               return str;\r
+                       }\r
 \r
-       for (var key in ar) {\r
-               var val = ar[key];\r
-               if (typeof(val) == 'function')\r
-                       continue;\r
+                       if (css) {\r
+                               // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing\r
+                               css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {\r
+                                       return str.replace(/[;:]/g, encode);\r
+                               });\r
 \r
-               if (val != null && val != '') {\r
-                       val = '' + val; // Force string\r
+                               // Parse styles\r
+                               while (matches = styleRegExp.exec(css)) {\r
+                                       name = matches[1].replace(trimRightRegExp, '').toLowerCase();\r
+                                       value = matches[2].replace(trimRightRegExp, '');\r
 \r
-                       // Fix style URL\r
-                       val = val.replace(new RegExp("url\\(\\'?([^\\']*)\\'?\\)", 'gi'), "url('$1')");\r
+                                       if (name && value.length > 0) {\r
+                                               // Opera will produce 700 instead of bold in their style values\r
+                                               if (name === 'font-weight' && value === '700')\r
+                                                       value = 'bold';\r
+                                               else if (name === 'color' || name === 'background-color') // Lowercase colors like RED\r
+                                                       value = value.toLowerCase();            \r
 \r
-                       // Convert URL\r
-                       if (val.indexOf('url(') != -1 && tinyMCE.getParam('convert_urls')) {\r
-                               var m = new RegExp("url\\('(.*?)'\\)").exec(val);\r
+                                               // Convert RGB colors to HEX\r
+                                               value = value.replace(rgbRegExp, toHex);\r
 \r
-                               if (m.length > 1)\r
-                                       val = "url('" + eval(tinyMCE.getParam('urlconverter_callback') + "(m[1], null, true);") + "')";\r
-                       }\r
+                                               // Convert URLs and force them into url('value') format\r
+                                               value = value.replace(urlOrStrRegExp, function(match, url, url2, url3, str, str2) {\r
+                                                       str = str || str2;\r
 \r
-                       // Force HEX colors\r
-                       if (tinyMCE.getParam("force_hex_style_colors"))\r
-                               val = tinyMCE.convertRGBToHex(val, true);\r
+                                                       if (str) {\r
+                                                               str = decode(str);\r
 \r
-                       if (val != "url('')")\r
-                               str += key.toLowerCase() + ": " + val + "; ";\r
-               }\r
-       }\r
+                                                               // Force strings into single quote format\r
+                                                               return "'" + str.replace(/\'/g, "\\'") + "'";\r
+                                                       }\r
 \r
-       if (new RegExp('; $').test(str))\r
-               str = str.substring(0, str.length - 2);\r
+                                                       url = decode(url || url2 || url3);\r
 \r
-       return str;\r
-};\r
+                                                       // Convert the URL to relative/absolute depending on config\r
+                                                       if (urlConverter)\r
+                                                               url = urlConverter.call(urlConverterScope, url, 'style');\r
 \r
-TinyMCE.prototype.convertRGBToHex = function(s, k) {\r
-       if (s.toLowerCase().indexOf('rgb') != -1) {\r
-               var re = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi");\r
-               var rgb = s.replace(re, "$1,$2,$3,$4,$5").split(',');\r
-               if (rgb.length == 5) {\r
-                       r = parseInt(rgb[1]).toString(16);\r
-                       g = parseInt(rgb[2]).toString(16);\r
-                       b = parseInt(rgb[3]).toString(16);\r
+                                                       // Output new URL format\r
+                                                       return "url('" + url.replace(/\'/g, "\\'") + "')";\r
+                                               });\r
 \r
-                       r = r.length == 1 ? '0' + r : r;\r
-                       g = g.length == 1 ? '0' + g : g;\r
-                       b = b.length == 1 ? '0' + b : b;\r
+                                               styles[name] = isEncoded ? decode(value, true) : value;\r
+                                       }\r
 \r
-                       s = "#" + r + g + b;\r
+                                       styleRegExp.lastIndex = matches.index + matches[0].length;\r
+                               }\r
 \r
-                       if (k)\r
-                               s = rgb[0] + s + rgb[4];\r
-               }\r
-       }\r
+                               // Compress the styles to reduce it's size for example IE will expand styles\r
+                               compress("border", "");\r
+                               compress("border", "-width");\r
+                               compress("border", "-color");\r
+                               compress("border", "-style");\r
+                               compress("padding", "");\r
+                               compress("margin", "");\r
+                               compress2('border', 'border-width', 'border-style', 'border-color');\r
+\r
+                               // Remove pointless border, IE produces these\r
+                               if (styles.border === 'medium none')\r
+                                       delete styles.border;\r
+                       }\r
 \r
-       return s;\r
-};\r
+                       return styles;\r
+               },\r
 \r
-TinyMCE.prototype.convertHexToRGB = function(s) {\r
-       if (s.indexOf('#') != -1) {\r
-               s = s.replace(new RegExp('[^0-9A-F]', 'gi'), '');\r
-               return "rgb(" + parseInt(s.substring(0, 2), 16) + "," + parseInt(s.substring(2, 4), 16) + "," + parseInt(s.substring(4, 6), 16) + ")";\r
-       }\r
+               serialize : function(styles, element_name) {\r
+                       var css = '', name, value;\r
 \r
-       return s;\r
-};\r
+                       function serializeStyles(name) {\r
+                               var styleList, i, l, value;\r
 \r
-TinyMCE.prototype._verifyClass = function(node) {\r
-       // Sometimes the class gets set to null, weird Gecko bug?\r
-       if (tinyMCE.isGecko) {\r
-               var className = node.getAttribute('class');\r
-               if (!className)\r
-                       return false;\r
-       }\r
+                               styleList = schema.styles[name];\r
+                               if (styleList) {\r
+                                       for (i = 0, l = styleList.length; i < l; i++) {\r
+                                               name = styleList[i];\r
+                                               value = styles[name];\r
+\r
+                                               if (value !== undef && value.length > 0)\r
+                                                       css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';\r
+                                       }\r
+                               }\r
+                       };\r
 \r
-       // Trim CSS class\r
-       if (tinyMCE.isMSIE)\r
-               var className = node.getAttribute('className');\r
+                       // Serialize styles according to schema\r
+                       if (element_name && schema && schema.styles) {\r
+                               // Serialize global styles and element specific styles\r
+                               serializeStyles('*');\r
+                               serializeStyles(element_name);\r
+                       } else {\r
+                               // Output the styles in the order they are inside the object\r
+                               for (name in styles) {\r
+                                       value = styles[name];\r
 \r
-       if (tinyMCE.cleanup_verify_css_classes && tinyMCE.cleanup_on_save) {\r
-               var csses = tinyMCE.getCSSClasses();\r
-               nonDefinedCSS = true;\r
-               for (var c=0; c<csses.length; c++) {\r
-                       if (csses[c] == className) {\r
-                               nonDefinedCSS = false;\r
-                               break;\r
+                                       if (value !== undef && value.length > 0)\r
+                                               css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';\r
+                               }\r
                        }\r
-               }\r
 \r
-               if (nonDefinedCSS && className.indexOf('mce_') != 0) {\r
-                       node.removeAttribute('className');\r
-                       node.removeAttribute('class');\r
-                       return false;\r
+                       return css;\r
                }\r
-       }\r
-\r
-       return true;\r
+       };\r
 };\r
 \r
-TinyMCE.prototype.cleanupNode = function(node) {\r
-       var output = "";\r
+(function(tinymce) {\r
+       var transitional = {}, boolAttrMap, blockElementsMap, shortEndedElementsMap, nonEmptyElementsMap, customElementsMap = {},\r
+               defaultWhiteSpaceElementsMap, selfClosingElementsMap, makeMap = tinymce.makeMap, each = tinymce.each;\r
 \r
-       switch (node.nodeType) {\r
-               case 1: // Element\r
-                       var elementData = tinyMCE._cleanupElementName(node.nodeName, node);\r
-                       var elementName = elementData ? elementData.element_name : null;\r
-                       var elementValidAttribs = elementData ? elementData.valid_attribs : null;\r
-                       var elementAttribs = "";\r
-                       var openTag = false, nonEmptyTag = false;\r
+       function split(str, delim) {\r
+               return str.split(delim || ',');\r
+       };\r
 \r
-                       if (elementName != null && elementName.charAt(0) == '+') {\r
-                               elementName = elementName.substring(1);\r
-                               openTag = true;\r
-                       }\r
+       function unpack(lookup, data) {\r
+               var key, elements = {};\r
 \r
-                       if (elementName != null && elementName.charAt(0) == '-') {\r
-                               elementName = elementName.substring(1);\r
-                               nonEmptyTag = true;\r
-                       }\r
+               function replace(value) {\r
+                       return value.replace(/[A-Z]+/g, function(key) {\r
+                               return replace(lookup[key]);\r
+                       });\r
+               };\r
 \r
-                       // Checking DOM tree for MSIE weirdness!!\r
-                       if (tinyMCE.isMSIE && tinyMCE.settings['fix_content_duplication']) {\r
-                               var lookup = tinyMCE.cleanup_elementLookupTable;\r
+               // Unpack lookup\r
+               for (key in lookup) {\r
+                       if (lookup.hasOwnProperty(key))\r
+                               lookup[key] = replace(lookup[key]);\r
+               }\r
 \r
-                               for (var i=0; i<lookup.length; i++) {\r
-                                       // Found element reference else were, hmm?\r
-                                       if (lookup[i] == node)\r
-                                               return output;\r
-                               }\r
+               // Unpack and parse data into object map\r
+               replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) {\r
+                       attributes = split(attributes, '|');\r
 \r
-                               // Add element to lookup table\r
-                               lookup[lookup.length] = node;\r
+                       elements[name] = {\r
+                               attributes : makeMap(attributes),\r
+                               attributesOrder : attributes,\r
+                               children : makeMap(children, '|', {'#comment' : {}})\r
                        }\r
+               });\r
+\r
+               return elements;\r
+       };\r
+\r
+       // Build a lookup table for block elements both lowercase and uppercase\r
+       blockElementsMap = 'h1,h2,h3,h4,h5,h6,hr,p,div,address,pre,form,table,tbody,thead,tfoot,' + \r
+                                               'th,tr,td,li,ol,ul,caption,blockquote,center,dl,dt,dd,dir,fieldset,' + \r
+                                               'noscript,menu,isindex,samp,header,footer,article,section,hgroup';\r
+       blockElementsMap = makeMap(blockElementsMap, ',', makeMap(blockElementsMap.toUpperCase()));\r
+\r
+       // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size\r
+       transitional = unpack({\r
+               Z : 'H|K|N|O|P',\r
+               Y : 'X|form|R|Q',\r
+               ZG : 'E|span|width|align|char|charoff|valign',\r
+               X : 'p|T|div|U|W|isindex|fieldset|table',\r
+               ZF : 'E|align|char|charoff|valign',\r
+               W : 'pre|hr|blockquote|address|center|noframes',\r
+               ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',\r
+               ZD : '[E][S]',\r
+               U : 'ul|ol|dl|menu|dir',\r
+               ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',\r
+               T : 'h1|h2|h3|h4|h5|h6',\r
+               ZB : 'X|S|Q',\r
+               S : 'R|P',\r
+               ZA : 'a|G|J|M|O|P',\r
+               R : 'a|H|K|N|O',\r
+               Q : 'noscript|P',\r
+               P : 'ins|del|script',\r
+               O : 'input|select|textarea|label|button',\r
+               N : 'M|L',\r
+               M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',\r
+               L : 'sub|sup',\r
+               K : 'J|I',\r
+               J : 'tt|i|b|u|s|strike',\r
+               I : 'big|small|font|basefont',\r
+               H : 'G|F',\r
+               G : 'br|span|bdo',\r
+               F : 'object|applet|img|map|iframe',\r
+               E : 'A|B|C',\r
+               D : 'accesskey|tabindex|onfocus|onblur',\r
+               C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',\r
+               B : 'lang|xml:lang|dir',\r
+               A : 'id|class|style|title'\r
+       }, 'script[id|charset|type|language|src|defer|xml:space][]' + \r
+               'style[B|id|type|media|title|xml:space][]' + \r
+               'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + \r
+               'param[id|name|value|valuetype|type][]' + \r
+               'p[E|align][#|S]' + \r
+               'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + \r
+               'br[A|clear][]' + \r
+               'span[E][#|S]' + \r
+               'bdo[A|C|B][#|S]' + \r
+               'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + \r
+               'h1[E|align][#|S]' + \r
+               'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + \r
+               'map[B|C|A|name][X|form|Q|area]' + \r
+               'h2[E|align][#|S]' + \r
+               'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + \r
+               'h3[E|align][#|S]' + \r
+               'tt[E][#|S]' + \r
+               'i[E][#|S]' + \r
+               'b[E][#|S]' + \r
+               'u[E][#|S]' + \r
+               's[E][#|S]' + \r
+               'strike[E][#|S]' + \r
+               'big[E][#|S]' + \r
+               'small[E][#|S]' + \r
+               'font[A|B|size|color|face][#|S]' + \r
+               'basefont[id|size|color|face][]' + \r
+               'em[E][#|S]' + \r
+               'strong[E][#|S]' + \r
+               'dfn[E][#|S]' + \r
+               'code[E][#|S]' + \r
+               'q[E|cite][#|S]' + \r
+               'samp[E][#|S]' + \r
+               'kbd[E][#|S]' + \r
+               'var[E][#|S]' + \r
+               'cite[E][#|S]' + \r
+               'abbr[E][#|S]' + \r
+               'acronym[E][#|S]' + \r
+               'sub[E][#|S]' + \r
+               'sup[E][#|S]' + \r
+               'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + \r
+               'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + \r
+               'optgroup[E|disabled|label][option]' + \r
+               'option[E|selected|disabled|label|value][]' + \r
+               'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + \r
+               'label[E|for|accesskey|onfocus|onblur][#|S]' + \r
+               'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + \r
+               'h4[E|align][#|S]' + \r
+               'ins[E|cite|datetime][#|Y]' + \r
+               'h5[E|align][#|S]' + \r
+               'del[E|cite|datetime][#|Y]' + \r
+               'h6[E|align][#|S]' + \r
+               'div[E|align][#|Y]' + \r
+               'ul[E|type|compact][li]' + \r
+               'li[E|type|value][#|Y]' + \r
+               'ol[E|type|compact|start][li]' + \r
+               'dl[E|compact][dt|dd]' + \r
+               'dt[E][#|S]' + \r
+               'dd[E][#|Y]' + \r
+               'menu[E|compact][li]' + \r
+               'dir[E|compact][li]' + \r
+               'pre[E|width|xml:space][#|ZA]' + \r
+               'hr[E|align|noshade|size|width][]' + \r
+               'blockquote[E|cite][#|Y]' + \r
+               'address[E][#|S|p]' + \r
+               'center[E][#|Y]' + \r
+               'noframes[E][#|Y]' + \r
+               'isindex[A|B|prompt][]' + \r
+               'fieldset[E][#|legend|Y]' + \r
+               'legend[E|accesskey|align][#|S]' + \r
+               'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + \r
+               'caption[E|align][#|S]' + \r
+               'col[ZG][]' + \r
+               'colgroup[ZG][col]' + \r
+               'thead[ZF][tr]' + \r
+               'tr[ZF|bgcolor][th|td]' + \r
+               'th[E|ZE][#|Y]' + \r
+               'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + \r
+               'noscript[E][#|Y]' + \r
+               'td[E|ZE][#|Y]' + \r
+               'tfoot[ZF][tr]' + \r
+               'tbody[ZF][tr]' + \r
+               'area[E|D|shape|coords|href|nohref|alt|target][]' + \r
+               'base[id|href|target][]' + \r
+               'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'\r
+       );\r
+\r
+       boolAttrMap = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected,autoplay,loop,controls');\r
+       shortEndedElementsMap = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,source');\r
+       nonEmptyElementsMap = tinymce.extend(makeMap('td,th,iframe,video,audio,object'), shortEndedElementsMap);\r
+       defaultWhiteSpaceElementsMap = makeMap('pre,script,style,textarea');\r
+       selfClosingElementsMap = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');\r
+\r
+       tinymce.html.Schema = function(settings) {\r
+               var self = this, elements = {}, children = {}, patternElements = [], validStyles, whiteSpaceElementsMap;\r
+\r
+               settings = settings || {};\r
+\r
+               // Allow all elements and attributes if verify_html is set to false\r
+               if (settings.verify_html === false)\r
+                       settings.valid_elements = '*[*]';\r
+\r
+               // Build styles list\r
+               if (settings.valid_styles) {\r
+                       validStyles = {};\r
+\r
+                       // Convert styles into a rule list\r
+                       each(settings.valid_styles, function(value, key) {\r
+                               validStyles[key] = tinymce.explode(value);\r
+                       });\r
+               }\r
 \r
-                       // Element not valid (only render children)\r
-                       if (!elementName) {\r
-                               if (node.hasChildNodes()) {\r
-                                       for (var i=0; i<node.childNodes.length; i++)\r
-                                               output += this.cleanupNode(node.childNodes[i]);\r
+               whiteSpaceElementsMap = settings.whitespace_elements ? makeMap(settings.whitespace_elements) : defaultWhiteSpaceElementsMap;\r
+\r
+               // Converts a wildcard expression string to a regexp for example *a will become /.*a/.\r
+               function patternToRegExp(str) {\r
+                       return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');\r
+               };\r
+\r
+               // Parses the specified valid_elements string and adds to the current rules\r
+               // This function is a bit hard to read since it's heavily optimized for speed\r
+               function addValidElements(valid_elements) {\r
+                       var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,\r
+                               prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value,\r
+                               elementRuleRegExp = /^([#+-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,\r
+                               attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,\r
+                               hasPatternsRegExp = /[*?+]/;\r
+\r
+                       if (valid_elements) {\r
+                               // Split valid elements into an array with rules\r
+                               valid_elements = split(valid_elements);\r
+\r
+                               if (elements['@']) {\r
+                                       globalAttributes = elements['@'].attributes;\r
+                                       globalAttributesOrder = elements['@'].attributesOrder;\r
                                }\r
 \r
-                               return output;\r
-                       }\r
-\r
-                       if (tinyMCE.cleanup_on_save) {\r
-                               if (node.nodeName == "A" && node.className == "mceItemAnchor") {\r
-                                       if (node.hasChildNodes()) {\r
-                                               for (var i=0; i<node.childNodes.length; i++)\r
-                                                       output += this.cleanupNode(node.childNodes[i]);\r
-                                       }\r
+                               // Loop all rules\r
+                               for (ei = 0, el = valid_elements.length; ei < el; ei++) {\r
+                                       // Parse element rule\r
+                                       matches = elementRuleRegExp.exec(valid_elements[ei]);\r
+                                       if (matches) {\r
+                                               // Setup local names for matches\r
+                                               prefix = matches[1];\r
+                                               elementName = matches[2];\r
+                                               outputName = matches[3];\r
+                                               attrData = matches[4];\r
+\r
+                                               // Create new attributes and attributesOrder\r
+                                               attributes = {};\r
+                                               attributesOrder = [];\r
+\r
+                                               // Create the new element\r
+                                               element = {\r
+                                                       attributes : attributes,\r
+                                                       attributesOrder : attributesOrder\r
+                                               };\r
+\r
+                                               // Padd empty elements prefix\r
+                                               if (prefix === '#')\r
+                                                       element.paddEmpty = true;\r
+\r
+                                               // Remove empty elements prefix\r
+                                               if (prefix === '-')\r
+                                                       element.removeEmpty = true;\r
+\r
+                                               // Copy attributes from global rule into current rule\r
+                                               if (globalAttributes) {\r
+                                                       for (key in globalAttributes)\r
+                                                               attributes[key] = globalAttributes[key];\r
+\r
+                                                       attributesOrder.push.apply(attributesOrder, globalAttributesOrder);\r
+                                               }\r
 \r
-                                       return '<a name="' + this.convertStringToXML(node.getAttribute("name")) + '"></a>' + output;\r
-                               }\r
-                       }\r
+                                               // Attributes defined\r
+                                               if (attrData) {\r
+                                                       attrData = split(attrData, '|');\r
+                                                       for (ai = 0, al = attrData.length; ai < al; ai++) {\r
+                                                               matches = attrRuleRegExp.exec(attrData[ai]);\r
+                                                               if (matches) {\r
+                                                                       attr = {};\r
+                                                                       attrType = matches[1];\r
+                                                                       attrName = matches[2].replace(/::/g, ':');\r
+                                                                       prefix = matches[3];\r
+                                                                       value = matches[4];\r
+\r
+                                                                       // Required\r
+                                                                       if (attrType === '!') {\r
+                                                                               element.attributesRequired = element.attributesRequired || [];\r
+                                                                               element.attributesRequired.push(attrName);\r
+                                                                               attr.required = true;\r
+                                                                       }\r
+\r
+                                                                       // Denied from global\r
+                                                                       if (attrType === '-') {\r
+                                                                               delete attributes[attrName];\r
+                                                                               attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1);\r
+                                                                               continue;\r
+                                                                       }\r
+\r
+                                                                       // Default value\r
+                                                                       if (prefix) {\r
+                                                                               // Default value\r
+                                                                               if (prefix === '=') {\r
+                                                                                       element.attributesDefault = element.attributesDefault || [];\r
+                                                                                       element.attributesDefault.push({name: attrName, value: value});\r
+                                                                                       attr.defaultValue = value;\r
+                                                                               }\r
+\r
+                                                                               // Forced value\r
+                                                                               if (prefix === ':') {\r
+                                                                                       element.attributesForced = element.attributesForced || [];\r
+                                                                                       element.attributesForced.push({name: attrName, value: value});\r
+                                                                                       attr.forcedValue = value;\r
+                                                                               }\r
+\r
+                                                                               // Required values\r
+                                                                               if (prefix === '<')\r
+                                                                                       attr.validValues = makeMap(value, '?');\r
+                                                                       }\r
+\r
+                                                                       // Check for attribute patterns\r
+                                                                       if (hasPatternsRegExp.test(attrName)) {\r
+                                                                               element.attributePatterns = element.attributePatterns || [];\r
+                                                                               attr.pattern = patternToRegExp(attrName);\r
+                                                                               element.attributePatterns.push(attr);\r
+                                                                       } else {\r
+                                                                               // Add attribute to order list if it doesn't already exist\r
+                                                                               if (!attributes[attrName])\r
+                                                                                       attributesOrder.push(attrName);\r
+\r
+                                                                               attributes[attrName] = attr;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
 \r
-                       // Remove deprecated attributes\r
-                       var re = new RegExp("^(TABLE|TD|TR)$");\r
-                       if (re.test(node.nodeName)) {\r
-                               // Move attrib to style\r
-                               if ((node.nodeName != "TABLE" || tinyMCE.cleanup_inline_styles) && (width = tinyMCE.getAttrib(node, "width")) != '') {\r
-                                       node.style.width = width.indexOf('%') != -1 ? width : width.replace(/[^0-9]/gi, '') + "px";\r
-                                       node.removeAttribute("width");\r
-                               }\r
+                                               // Global rule, store away these for later usage\r
+                                               if (!globalAttributes && elementName == '@') {\r
+                                                       globalAttributes = attributes;\r
+                                                       globalAttributesOrder = attributesOrder;\r
+                                               }\r
 \r
-                               // Is table and not inline\r
-                               if ((node.nodeName == "TABLE" && !tinyMCE.cleanup_inline_styles) && node.style.width != '') {\r
-                                       tinyMCE.setAttrib(node, "width", node.style.width.replace('px',''));\r
-                                       node.style.width = '';\r
-                               }\r
+                                               // Handle substitute elements such as b/strong\r
+                                               if (outputName) {\r
+                                                       element.outputName = elementName;\r
+                                                       elements[outputName] = element;\r
+                                               }\r
 \r
-                               // Move attrib to style\r
-                               if ((height = tinyMCE.getAttrib(node, "height")) != '') {\r
-                                       height = "" + height; // Force string\r
-                                       node.style.height = height.indexOf('%') != -1 ? height : height.replace(/[^0-9]/gi, '') + "px";\r
-                                       node.removeAttribute("height");\r
+                                               // Add pattern or exact element\r
+                                               if (hasPatternsRegExp.test(elementName)) {\r
+                                                       element.pattern = patternToRegExp(elementName);\r
+                                                       patternElements.push(element);\r
+                                               } else\r
+                                                       elements[elementName] = element;\r
+                                       }\r
                                }\r
                        }\r
+               };\r
 \r
-                       // Handle inline/outline styles\r
-                       if (tinyMCE.cleanup_inline_styles) {\r
-                               var re = new RegExp("^(TABLE|TD|TR|IMG|HR)$");\r
-                               if (re.test(node.nodeName) && tinyMCE.getAttrib(node, "class").indexOf('mceItem') == -1) {\r
-                                       tinyMCE._moveStyle(node, 'width', 'width');\r
-                                       tinyMCE._moveStyle(node, 'height', 'height');\r
-                                       tinyMCE._moveStyle(node, 'borderWidth', 'border');\r
-                                       tinyMCE._moveStyle(node, '', 'vspace');\r
-                                       tinyMCE._moveStyle(node, '', 'hspace');\r
-                                       tinyMCE._moveStyle(node, 'textAlign', 'align');\r
-                                       tinyMCE._moveStyle(node, 'backgroundColor', 'bgColor');\r
-                                       tinyMCE._moveStyle(node, 'borderColor', 'borderColor');\r
-                                       tinyMCE._moveStyle(node, 'backgroundImage', 'background');\r
+               function setValidElements(valid_elements) {\r
+                       elements = {};\r
+                       patternElements = [];\r
 \r
-                                       // Refresh element in old MSIE\r
-                                       if (tinyMCE.isMSIE5)\r
-                                               node.outerHTML = node.outerHTML;\r
-                               } else if (tinyMCE.isBlockElement(node))\r
-                                       tinyMCE._moveStyle(node, 'textAlign', 'align');\r
+                       addValidElements(valid_elements);\r
 \r
-                               if (node.nodeName == "FONT")\r
-                                       tinyMCE._moveStyle(node, 'color', 'color');\r
+                       each(transitional, function(element, name) {\r
+                               children[name] = element.children;\r
+                       });\r
+               };\r
+\r
+               // Adds custom non HTML elements to the schema\r
+               function addCustomElements(custom_elements) {\r
+                       var customElementRegExp = /^(~)?(.+)$/;\r
+\r
+                       if (custom_elements) {\r
+                               each(split(custom_elements), function(rule) {\r
+                                       var matches = customElementRegExp.exec(rule),\r
+                                               inline = matches[1] === '~',\r
+                                               cloneName = inline ? 'span' : 'div',\r
+                                               name = matches[2];\r
+\r
+                                       children[name] = children[cloneName];\r
+                                       customElementsMap[name] = cloneName;\r
+\r
+                                       // If it's not marked as inline then add it to valid block elements\r
+                                       if (!inline)\r
+                                               blockElementsMap[name] = {};\r
+\r
+                                       // Add custom elements at span/div positions\r
+                                       each(children, function(element, child) {\r
+                                               if (element[cloneName])\r
+                                                       element[name] = element[cloneName];\r
+                                       });\r
+                               });\r
                        }\r
+               };\r
 \r
-                       // Set attrib data\r
-                       if (elementValidAttribs) {\r
-                               for (var a=1; a<elementValidAttribs.length; a++) {\r
-                                       var attribName, attribDefaultValue, attribForceValue, attribValue;\r
-\r
-                                       attribName = elementValidAttribs[a][0];\r
-                                       attribDefaultValue = elementValidAttribs[a][1];\r
-                                       attribForceValue = elementValidAttribs[a][2];\r
+               // Adds valid children to the schema object\r
+               function addValidChildren(valid_children) {\r
+                       var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;\r
 \r
-                                       if (attribDefaultValue != null || attribForceValue != null) {\r
-                                               var attribValue = node.getAttribute(attribName);\r
+                       if (valid_children) {\r
+                               each(split(valid_children), function(rule) {\r
+                                       var matches = childRuleRegExp.exec(rule), parent, prefix;\r
 \r
-                                               if (node.getAttribute(attribName) == null || node.getAttribute(attribName) == "")\r
-                                                       attribValue = attribDefaultValue;\r
+                                       if (matches) {\r
+                                               prefix = matches[1];\r
 \r
-                                               attribValue = attribForceValue ? attribForceValue : attribValue;\r
-\r
-                                               // Is to generate id\r
-                                               if (attribValue == "{$uid}")\r
-                                                       attribValue = "uid_" + (tinyMCE.cleanup_idCount++);\r
+                                               // Add/remove items from default\r
+                                               if (prefix)\r
+                                                       parent = children[matches[2]];\r
+                                               else\r
+                                                       parent = children[matches[2]] = {'#comment' : {}};\r
 \r
-                                               // Add visual aid class\r
-                                               if (attribName == "class")\r
-                                                       attribValue = tinyMCE.getVisualAidClass(attribValue, tinyMCE.cleanup_on_save);\r
+                                               parent = children[matches[2]];\r
 \r
-                                               node.setAttribute(attribName, attribValue);\r
-                                               //alert(attribName + "=" + attribValue);\r
+                                               each(split(matches[3], '|'), function(child) {\r
+                                                       if (prefix === '-')\r
+                                                               delete parent[child];\r
+                                                       else\r
+                                                               parent[child] = {};\r
+                                               });\r
                                        }\r
-                               }\r
+                               });\r
                        }\r
+               };\r
 \r
-                       if ((tinyMCE.isMSIE && !tinyMCE.isOpera) && elementName == "style")\r
-                               return "<style>" + node.innerHTML + "</style>";\r
-\r
-                       // Remove empty tables\r
-                       if (elementName == "table" && !node.hasChildNodes())\r
-                               return "";\r
+               function getElementRule(name) {\r
+                       var element = elements[name], i;\r
 \r
-                       // Handle element attributes\r
-                       if (node.attributes.length > 0) {\r
-                               var lastAttrib = "";\r
-\r
-                               for (var i=0; i<node.attributes.length; i++) {\r
-                                       if (node.attributes[i].specified) {\r
-                                               // Is the attrib already processed (removed duplicate attributes in opera TD[align=left])\r
-                                               if (tinyMCE.isOpera) {\r
-                                                       if (node.attributes[i].nodeName == lastAttrib)\r
-                                                               continue;\r
+                       // Exact match found\r
+                       if (element)\r
+                               return element;\r
 \r
-                                                       lastAttrib = node.attributes[i].nodeName;\r
-                                               }\r
+                       // No exact match then try the patterns\r
+                       i = patternElements.length;\r
+                       while (i--) {\r
+                               element = patternElements[i];\r
 \r
-                                               // tinyMCE.debug(node.nodeName, node.attributes[i].nodeName, node.attributes[i].nodeValue, node.innerHTML);\r
-                                               var attrib = tinyMCE._cleanupAttribute(elementValidAttribs, elementName, node.attributes[i], node);\r
-                                               if (attrib && attrib.value != "")\r
-                                                       elementAttribs += " " + attrib.name + "=" + '"' + this.convertStringToXML("" + attrib.value) + '"';\r
-                                       }\r
-                               }\r
+                               if (element.pattern.test(name))\r
+                                       return element;\r
                        }\r
+               };\r
 \r
-                       // MSIE table summary fix (MSIE 5.5)\r
-                       if (tinyMCE.isMSIE && elementName == "table" && node.getAttribute("summary") != null && elementAttribs.indexOf('summary') == -1) {\r
-                               var summary = tinyMCE.getAttrib(node, 'summary');\r
-                               if (summary != '')\r
-                                       elementAttribs += " summary=" + '"' + this.convertStringToXML(summary) + '"';\r
-                       }\r
+               if (!settings.valid_elements) {\r
+                       // No valid elements defined then clone the elements from the transitional spec\r
+                       each(transitional, function(element, name) {\r
+                               elements[name] = {\r
+                                       attributes : element.attributes,\r
+                                       attributesOrder : element.attributesOrder\r
+                               };\r
 \r
-                       // Handle missing attributes in MSIE 5.5\r
-                       if (tinyMCE.isMSIE5 && /^(td|img|a)$/.test(elementName)) {\r
-                               var ma = new Array("scope", "longdesc", "hreflang", "charset", "type");\r
+                               children[name] = element.children;\r
+                       });\r
 \r
-                               for (var u=0; u<ma.length; u++) {\r
-                                       if (node.getAttribute(ma[u]) != null) {\r
-                                               var s = tinyMCE.getAttrib(node, ma[u]);\r
+                       // Switch these\r
+                       each(split('strong/b,em/i'), function(item) {\r
+                               item = split(item, '/');\r
+                               elements[item[1]].outputName = item[0];\r
+                       });\r
 \r
-                                               if (s != '')\r
-                                                       elementAttribs += " " + ma[u] + "=" + '"' + this.convertStringToXML(s) + '"';\r
-                                       }\r
-                               }\r
-                       }\r
+                       // Add default alt attribute for images\r
+                       elements.img.attributesDefault = [{name: 'alt', value: ''}];\r
 \r
-                       // MSIE form element issue\r
-                       if (tinyMCE.isMSIE && elementName == "input") {\r
-                               if (node.type) {\r
-                                       if (!elementAttribs.match(/ type=/g))\r
-                                               elementAttribs += " type=" + '"' + node.type + '"';\r
-                               }\r
+                       // Remove these if they are empty by default\r
+                       each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr'), function(name) {\r
+                               elements[name].removeEmpty = true;\r
+                       });\r
 \r
-                               if (node.value) {\r
-                                       if (!elementAttribs.match(/ value=/g))\r
-                                               elementAttribs += " value=" + '"' + node.value + '"';\r
-                               }\r
-                       }\r
+                       // Padd these by default\r
+                       each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) {\r
+                               elements[name].paddEmpty = true;\r
+                       });\r
+               } else\r
+                       setValidElements(settings.valid_elements);\r
 \r
-                       // Add nbsp to some elements\r
-                       if ((elementName == "p" || elementName == "td") && (node.innerHTML == "" || node.innerHTML == "&nbsp;"))\r
-                               return "<" + elementName + elementAttribs + ">" + this.convertStringToXML(String.fromCharCode(160)) + "</" + elementName + ">";\r
+               addCustomElements(settings.custom_elements);\r
+               addValidChildren(settings.valid_children);\r
+               addValidElements(settings.extended_valid_elements);\r
 \r
-                       // Is MSIE script element\r
-                       if (tinyMCE.isMSIE && elementName == "script")\r
-                               return "<" + elementName + elementAttribs + ">" + node.text + "</" + elementName + ">";\r
+               // Todo: Remove this when we fix list handling to be valid\r
+               addValidChildren('+ol[ul|ol],+ul[ul|ol]');\r
 \r
-                       // Clean up children\r
-                       if (node.hasChildNodes()) {\r
-                               // If not empty span\r
-                               if (!(elementName == "span" && elementAttribs == "" && tinyMCE.getParam("trim_span_elements"))) {\r
-                                       // Force BR\r
-                                       if (elementName == "p" && tinyMCE.cleanup_force_br_newlines)\r
-                                               output += "<div" + elementAttribs + ">";\r
-                                       else\r
-                                               output += "<" + elementName + elementAttribs + ">";\r
-                               }\r
+               // If the user didn't allow span only allow internal spans\r
+               if (!getElementRule('span'))\r
+                       addValidElements('span[!data-mce-type|*]');\r
 \r
-                               for (var i=0; i<node.childNodes.length; i++)\r
-                                       output += this.cleanupNode(node.childNodes[i]);\r
+               // Delete invalid elements\r
+               if (settings.invalid_elements) {\r
+                       tinymce.each(tinymce.explode(settings.invalid_elements), function(item) {\r
+                               if (elements[item])\r
+                                       delete elements[item];\r
+                       });\r
+               }\r
 \r
-                               // If not empty span\r
-                               if (!(elementName == "span" && elementAttribs == "" && tinyMCE.getParam("trim_span_elements"))) {\r
-                                       // Force BR\r
-                                       if (elementName == "p" && tinyMCE.cleanup_force_br_newlines)\r
-                                               output += "</div><br />";\r
-                                       else\r
-                                               output += "</" + elementName + ">";\r
-                               }\r
-                       } else {\r
-                               if (!nonEmptyTag) {\r
-                                       if (openTag)\r
-                                               output += "<" + elementName + elementAttribs + "></" + elementName + ">";\r
-                                       else\r
-                                               output += "<" + elementName + elementAttribs + " />";\r
-                               }\r
-                       }\r
+               self.children = children;\r
 \r
-                       return output;\r
+               self.styles = validStyles;\r
 \r
-               case 3: // Text\r
-                       // Do not convert script elements\r
-                       if (node.parentNode.nodeName == "SCRIPT" || node.parentNode.nodeName == "NOSCRIPT" || node.parentNode.nodeName == "STYLE")\r
-                               return node.nodeValue;\r
+               self.getBoolAttrs = function() {\r
+                       return boolAttrMap;\r
+               };\r
 \r
-                       return this.convertStringToXML(node.nodeValue);\r
+               self.getBlockElements = function() {\r
+                       return blockElementsMap;\r
+               };\r
 \r
-               case 8: // Comment\r
-                       return "<!--" + node.nodeValue + "-->";\r
+               self.getShortEndedElements = function() {\r
+                       return shortEndedElementsMap;\r
+               };\r
 \r
-               default: // Unknown\r
-                       return "[UNKNOWN NODETYPE " + node.nodeType + "]";\r
-       }\r
-};\r
+               self.getSelfClosingElements = function() {\r
+                       return selfClosingElementsMap;\r
+               };\r
 \r
-TinyMCE.prototype.convertStringToXML = function(html_data) {\r
-    var output = "";\r
+               self.getNonEmptyElements = function() {\r
+                       return nonEmptyElementsMap;\r
+               };\r
 \r
-       for (var i=0; i<html_data.length; i++) {\r
-               var chr = html_data.charCodeAt(i);\r
+               self.getWhiteSpaceElements = function() {\r
+                       return whiteSpaceElementsMap;\r
+               };\r
 \r
-               // Numeric entities\r
-               if (tinyMCE.settings['entity_encoding'] == "numeric") {\r
-                       if (chr > 127)\r
-                               output += '&#' + chr + ";";\r
-                       else\r
-                               output += String.fromCharCode(chr);\r
+               self.isValidChild = function(name, child) {\r
+                       var parent = children[name];\r
 \r
-                       continue;\r
-               }\r
+                       return !!(parent && parent[child]);\r
+               };\r
 \r
-               // Raw entities\r
-               if (tinyMCE.settings['entity_encoding'] == "raw") {\r
-                       output += String.fromCharCode(chr);\r
-                       continue;\r
-               }\r
+               self.getElementRule = getElementRule;\r
 \r
-               // Named entities\r
-               if (typeof(tinyMCE.settings['cleanup_entities']["c" + chr]) != 'undefined' && tinyMCE.settings['cleanup_entities']["c" + chr] != '')\r
-                       output += '&' + tinyMCE.settings['cleanup_entities']["c" + chr] + ';';\r
-               else\r
-                       output += '' + String.fromCharCode(chr);\r
-    }\r
+               self.getCustomElements = function() {\r
+                       return customElementsMap;\r
+               };\r
 \r
-    return output;\r
-};\r
+               self.addValidElements = addValidElements;\r
 \r
-TinyMCE.prototype._getCleanupElementName = function(chunk) {\r
-       var pos;\r
+               self.setValidElements = setValidElements;\r
 \r
-       if (chunk.charAt(0) == '+')\r
-               chunk = chunk.substring(1);\r
+               self.addCustomElements = addCustomElements;\r
 \r
-       if (chunk.charAt(0) == '-')\r
-               chunk = chunk.substring(1);\r
+               self.addValidChildren = addValidChildren;\r
+       };\r
 \r
-       if ((pos = chunk.indexOf('/')) != -1)\r
-               chunk = chunk.substring(0, pos);\r
+       // Expose boolMap and blockElementMap as static properties for usage in DOMUtils\r
+       tinymce.html.Schema.boolAttrMap = boolAttrMap;\r
+       tinymce.html.Schema.blockElementsMap = blockElementsMap;\r
+})(tinymce);\r
 \r
-       if ((pos = chunk.indexOf('[')) != -1)\r
-               chunk = chunk.substring(0, pos);\r
+(function(tinymce) {\r
+       tinymce.html.SaxParser = function(settings, schema) {\r
+               var self = this, noop = function() {};\r
 \r
-       return chunk;\r
-};\r
+               settings = settings || {};\r
+               self.schema = schema = schema || new tinymce.html.Schema();\r
 \r
-TinyMCE.prototype._initCleanup = function() {\r
-       // Parse valid elements and attributes\r
-       var validElements = tinyMCE.settings["valid_elements"];\r
-       validElements = validElements.split(',');\r
-\r
-       // Handle extended valid elements\r
-       var extendedValidElements = tinyMCE.settings["extended_valid_elements"];\r
-       extendedValidElements = extendedValidElements.split(',');\r
-       for (var i=0; i<extendedValidElements.length; i++) {\r
-               var elementName = this._getCleanupElementName(extendedValidElements[i]);\r
-               var skipAdd = false;\r
-\r
-               // Check if it's defined before, if so override that one\r
-               for (var x=0; x<validElements.length; x++) {\r
-                       if (this._getCleanupElementName(validElements[x]) == elementName) {\r
-                               validElements[x] = extendedValidElements[i];\r
-                               skipAdd = true;\r
-                               break;\r
-                       }\r
-               }\r
+               if (settings.fix_self_closing !== false)\r
+                       settings.fix_self_closing = true;\r
 \r
-               if (!skipAdd)\r
-                       validElements[validElements.length] = extendedValidElements[i];\r
-       }\r
+               // Add handler functions from settings and setup default handlers\r
+               tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) {\r
+                       if (name)\r
+                               self[name] = settings[name] || noop;\r
+               });\r
 \r
-       for (var i=0; i<validElements.length; i++) {\r
-               var item = validElements[i];\r
+               self.parse = function(html) {\r
+                       var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name, isInternalElement, removeInternalElements,\r
+                               shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue, invalidPrefixRegExp,\r
+                               validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing,\r
+                               tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing, isIE;\r
 \r
-               item = item.replace('[','|');\r
-               item = item.replace(']','');\r
+                       function processEndTag(name) {\r
+                               var pos, i;\r
 \r
-               // Split and convert\r
-               var attribs = item.split('|');\r
-               for (var x=0; x<attribs.length; x++)\r
-                       attribs[x] = attribs[x].toLowerCase();\r
+                               // Find position of parent of the same type\r
+                               pos = stack.length;\r
+                               while (pos--) {\r
+                                       if (stack[pos].name === name)\r
+                                               break;                                          \r
+                               }\r
 \r
-               // Handle change elements\r
-               attribs[0] = attribs[0].split('/');\r
+                               // Found parent\r
+                               if (pos >= 0) {\r
+                                       // Close all the open elements\r
+                                       for (i = stack.length - 1; i >= pos; i--) {\r
+                                               name = stack[i];\r
 \r
-               // Handle default attribute values\r
-               for (var x=1; x<attribs.length; x++) {\r
-                       var attribName = attribs[x];\r
-                       var attribDefault = null;\r
-                       var attribForce = null;\r
-                       var attribMustBe = null;\r
+                                               if (name.valid)\r
+                                                       self.end(name.name);\r
+                                       }\r
 \r
-                       // Default value\r
-                       if ((pos = attribName.indexOf('=')) != -1) {\r
-                               attribDefault = attribName.substring(pos+1);\r
-                               attribName = attribName.substring(0, pos);\r
-                       }\r
+                                       // Remove the open elements from the stack\r
+                                       stack.length = pos;\r
+                               }\r
+                       };\r
 \r
-                       // Force check\r
-                       if ((pos = attribName.indexOf(':')) != -1) {\r
-                               attribForce = attribName.substring(pos+1);\r
-                               attribName = attribName.substring(0, pos);\r
-                       }\r
+                       // Precompile RegExps and map objects\r
+                       tokenRegExp = new RegExp('<(?:' +\r
+                               '(?:!--([\\w\\W]*?)-->)|' + // Comment\r
+                               '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA\r
+                               '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE\r
+                               '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI\r
+                               '(?:\\/([^>]+)>)|' + // End element\r
+                               '(?:([^\\s\\/<>]+)\\s*((?:[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*)>)' + // Start element\r
+                       ')', 'g');\r
+\r
+                       attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g;\r
+                       specialElements = {\r
+                               'script' : /<\/script[^>]*>/gi,\r
+                               'style' : /<\/style[^>]*>/gi,\r
+                               'noscript' : /<\/noscript[^>]*>/gi\r
+                       };\r
 \r
-                       // Force check\r
-                       if ((pos = attribName.indexOf('<')) != -1) {\r
-                               attribMustBe = attribName.substring(pos+1).split('?');\r
-                               attribName = attribName.substring(0, pos);\r
-                       }\r
+                       // Setup lookup tables for empty elements and boolean attributes\r
+                       shortEndedElements = schema.getShortEndedElements();\r
+                       selfClosing = schema.getSelfClosingElements();\r
+                       fillAttrsMap = schema.getBoolAttrs();\r
+                       validate = settings.validate;\r
+                       removeInternalElements = settings.remove_internals;\r
+                       fixSelfClosing = settings.fix_self_closing;\r
+                       isIE = tinymce.isIE;\r
+                       invalidPrefixRegExp = /^:/;\r
+\r
+                       while (matches = tokenRegExp.exec(html)) {\r
+                               // Text\r
+                               if (index < matches.index)\r
+                                       self.text(decode(html.substr(index, matches.index - index)));\r
+\r
+                               if (value = matches[6]) { // End element\r
+                                       value = value.toLowerCase();\r
+\r
+                                       // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements\r
+                                       if (isIE && invalidPrefixRegExp.test(value))\r
+                                               value = value.substr(1);\r
+\r
+                                       processEndTag(value);\r
+                               } else if (value = matches[7]) { // Start element\r
+                                       value = value.toLowerCase();\r
+\r
+                                       // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements\r
+                                       if (isIE && invalidPrefixRegExp.test(value))\r
+                                               value = value.substr(1);\r
+\r
+                                       isShortEnded = value in shortEndedElements;\r
+\r
+                                       // Is self closing tag for example an <li> after an open <li>\r
+                                       if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value)\r
+                                               processEndTag(value);\r
+\r
+                                       // Validate element\r
+                                       if (!validate || (elementRule = schema.getElementRule(value))) {\r
+                                               isValidElement = true;\r
+\r
+                                               // Grab attributes map and patters when validation is enabled\r
+                                               if (validate) {\r
+                                                       validAttributesMap = elementRule.attributes;\r
+                                                       validAttributePatterns = elementRule.attributePatterns;\r
+                                               }\r
 \r
-                       attribs[x] = new Array(attribName, attribDefault, attribForce, attribMustBe);\r
-               }\r
+                                               // Parse attributes\r
+                                               if (attribsValue = matches[8]) {\r
+                                                       isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element\r
+\r
+                                                       // If the element has internal attributes then remove it if we are told to do so\r
+                                                       if (isInternalElement && removeInternalElements)\r
+                                                               isValidElement = false;\r
+\r
+                                                       attrList = [];\r
+                                                       attrList.map = {};\r
+\r
+                                                       attribsValue.replace(attrRegExp, function(match, name, value, val2, val3) {\r
+                                                               var attrRule, i;\r
+\r
+                                                               name = name.toLowerCase();\r
+                                                               value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute\r
+\r
+                                                               // Validate name and value\r
+                                                               if (validate && !isInternalElement && name.indexOf('data-') !== 0) {\r
+                                                                       attrRule = validAttributesMap[name];\r
+\r
+                                                                       // Find rule by pattern matching\r
+                                                                       if (!attrRule && validAttributePatterns) {\r
+                                                                               i = validAttributePatterns.length;\r
+                                                                               while (i--) {\r
+                                                                                       attrRule = validAttributePatterns[i];\r
+                                                                                       if (attrRule.pattern.test(name))\r
+                                                                                               break;\r
+                                                                               }\r
+\r
+                                                                               // No rule matched\r
+                                                                               if (i === -1)\r
+                                                                                       attrRule = null;\r
+                                                                       }\r
+\r
+                                                                       // No attribute rule found\r
+                                                                       if (!attrRule)\r
+                                                                               return;\r
+\r
+                                                                       // Validate value\r
+                                                                       if (attrRule.validValues && !(value in attrRule.validValues))\r
+                                                                               return;\r
+                                                               }\r
+\r
+                                                               // Add attribute to list and map\r
+                                                               attrList.map[name] = value;\r
+                                                               attrList.push({\r
+                                                                       name: name,\r
+                                                                       value: value\r
+                                                               });\r
+                                                       });\r
+                                               } else {\r
+                                                       attrList = [];\r
+                                                       attrList.map = {};\r
+                                               }\r
 \r
-               validElements[i] = attribs;\r
-       }\r
+                                               // Process attributes if validation is enabled\r
+                                               if (validate && !isInternalElement) {\r
+                                                       attributesRequired = elementRule.attributesRequired;\r
+                                                       attributesDefault = elementRule.attributesDefault;\r
+                                                       attributesForced = elementRule.attributesForced;\r
+\r
+                                                       // Handle forced attributes\r
+                                                       if (attributesForced) {\r
+                                                               i = attributesForced.length;\r
+                                                               while (i--) {\r
+                                                                       attr = attributesForced[i];\r
+                                                                       name = attr.name;\r
+                                                                       attrValue = attr.value;\r
+\r
+                                                                       if (attrValue === '{$uid}')\r
+                                                                               attrValue = 'mce_' + idCount++;\r
+\r
+                                                                       attrList.map[name] = attrValue;\r
+                                                                       attrList.push({name: name, value: attrValue});\r
+                                                               }\r
+                                                       }\r
 \r
-       var invalidElements = tinyMCE.settings['invalid_elements'].split(',');\r
-       for (var i=0; i<invalidElements.length; i++)\r
-               invalidElements[i] = invalidElements[i].toLowerCase();\r
+                                                       // Handle default attributes\r
+                                                       if (attributesDefault) {\r
+                                                               i = attributesDefault.length;\r
+                                                               while (i--) {\r
+                                                                       attr = attributesDefault[i];\r
+                                                                       name = attr.name;\r
 \r
-       // Set these for performance\r
-       tinyMCE.settings['cleanup_validElements'] = validElements;\r
-       tinyMCE.settings['cleanup_invalidElements'] = invalidElements;\r
-};\r
+                                                                       if (!(name in attrList.map)) {\r
+                                                                               attrValue = attr.value;\r
 \r
-TinyMCE.prototype._cleanupHTML = function(inst, doc, config, element, visual, on_save) {\r
-       if (!tinyMCE.settings['cleanup']) {\r
-               tinyMCE.handleVisualAid(inst.getBody(), true, false, inst);\r
+                                                                               if (attrValue === '{$uid}')\r
+                                                                                       attrValue = 'mce_' + idCount++;\r
 \r
-               var html = element.innerHTML;\r
+                                                                               attrList.map[name] = attrValue;\r
+                                                                               attrList.push({name: name, value: attrValue});\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
 \r
-               // Remove mce_href/mce_src\r
-               html = html.replace(new RegExp('(mce_href|mce_src)=".*?"', 'gi'), '');\r
-               html = html.replace(/\s+>/gi, '>');\r
+                                                       // Handle required attributes\r
+                                                       if (attributesRequired) {\r
+                                                               i = attributesRequired.length;\r
+                                                               while (i--) {\r
+                                                                       if (attributesRequired[i] in attrList.map)\r
+                                                                               break;\r
+                                                               }\r
+\r
+                                                               // None of the required attributes where found\r
+                                                               if (i === -1)\r
+                                                                       isValidElement = false;\r
+                                                       }\r
 \r
-               return html;\r
-       }\r
+                                                       // Invalidate element if it's marked as bogus\r
+                                                       if (attrList.map['data-mce-bogus'])\r
+                                                               isValidElement = false;\r
+                                               }\r
 \r
-       if (on_save && tinyMCE.getParam("convert_fonts_to_spans"))\r
-               tinyMCE.convertFontsToSpans(doc);\r
+                                               if (isValidElement)\r
+                                                       self.start(value, attrList, isShortEnded);\r
+                                       } else\r
+                                               isValidElement = false;\r
 \r
-       // Call custom cleanup code\r
-       tinyMCE._customCleanup(inst, on_save ? "get_from_editor_dom" : "insert_to_editor_dom", doc.body);\r
+                                       // Treat script, noscript and style a bit different since they may include code that looks like elements\r
+                                       if (endRegExp = specialElements[value]) {\r
+                                               endRegExp.lastIndex = index = matches.index + matches[0].length;\r
 \r
-       // Move bgcolor to style\r
-       var n = doc.getElementsByTagName("font");\r
-       for (var i=0; i<n.length; i++) {\r
-               var c = "";\r
-               if ((c = tinyMCE.getAttrib(n[i], "bgcolor")) != "") {\r
-                       n[i].style.backgroundColor = c;\r
-                       tinyMCE.setAttrib(n[i], "bgcolor", "");\r
-               }\r
-       }\r
+                                               if (matches = endRegExp.exec(html)) {\r
+                                                       if (isValidElement)\r
+                                                               text = html.substr(index, matches.index - index);\r
 \r
-       // Set these for performance\r
-       tinyMCE.cleanup_validElements = tinyMCE.settings['cleanup_validElements'];\r
-       tinyMCE.cleanup_invalidElements = tinyMCE.settings['cleanup_invalidElements'];\r
-       tinyMCE.cleanup_verify_html = tinyMCE.settings['verify_html'];\r
-       tinyMCE.cleanup_force_br_newlines = tinyMCE.settings['force_br_newlines'];\r
-       tinyMCE.cleanup_urlconverter_callback = tinyMCE.settings['urlconverter_callback'];\r
-       tinyMCE.cleanup_verify_css_classes = tinyMCE.settings['verify_css_classes'];\r
-       tinyMCE.cleanup_visual_table_class = tinyMCE.settings['visual_table_class'];\r
-       tinyMCE.cleanup_apply_source_formatting = tinyMCE.settings['apply_source_formatting'];\r
-       tinyMCE.cleanup_inline_styles = tinyMCE.settings['inline_styles'];\r
-       tinyMCE.cleanup_visual_aid = visual;\r
-       tinyMCE.cleanup_on_save = on_save;\r
-       tinyMCE.cleanup_idCount = 0;\r
-       tinyMCE.cleanup_elementLookupTable = new Array();\r
-\r
-       var startTime = new Date().getTime();\r
-\r
-       // Cleanup madness that breaks the editor in MSIE\r
-       if (tinyMCE.isMSIE) {\r
-               // Remove null ids from HR elements, results in runtime error\r
-               var nodes = element.getElementsByTagName("hr");\r
-               for (var i=0; i<nodes.length; i++) {\r
-                       if (nodes[i].id == "null")\r
-                               nodes[i].removeAttribute("id");\r
-               }\r
+                                                       index = matches.index + matches[0].length;\r
+                                               } else {\r
+                                                       text = html.substr(index);\r
+                                                       index = html.length;\r
+                                               }\r
 \r
-               tinyMCE.setInnerHTML(element, tinyMCE.regexpReplace(element.innerHTML, '<p>[ \n\r]*<hr.*>[ \n\r]*</p>', '<hr />', 'gi'));\r
-               tinyMCE.setInnerHTML(element, tinyMCE.regexpReplace(element.innerHTML, '<!([^-(DOCTYPE)]* )|<!/[^-]*>', '', 'gi'));\r
-       }\r
+                                               if (isValidElement && text.length > 0)\r
+                                                       self.text(text, true);\r
 \r
-       var html = this.cleanupNode(element);\r
+                                               if (isValidElement)\r
+                                                       self.end(value);\r
 \r
-       if (tinyMCE.settings['debug'])\r
-               tinyMCE.debug("Cleanup process executed in: " + (new Date().getTime()-startTime) + " ms.");\r
+                                               tokenRegExp.lastIndex = index;\r
+                                               continue;\r
+                                       }\r
 \r
-       // Remove pesky HR paragraphs and other crap\r
-       html = tinyMCE.regexpReplace(html, '<p><hr /></p>', '<hr />');\r
-       html = tinyMCE.regexpReplace(html, '<p>&nbsp;</p><hr /><p>&nbsp;</p>', '<hr />');\r
-       html = tinyMCE.regexpReplace(html, '<td>\\s*<br />\\s*</td>', '<td>&nbsp;</td>');\r
-       html = tinyMCE.regexpReplace(html, '<p>\\s*<br />\\s*</p>', '<p>&nbsp;</p>');\r
-       html = tinyMCE.regexpReplace(html, '<p>\\s*&nbsp;\\s*<br />\\s*&nbsp;\\s*</p>', '<p>&nbsp;</p>');\r
-       html = tinyMCE.regexpReplace(html, '<p>\\s*&nbsp;\\s*<br />\\s*</p>', '<p>&nbsp;</p>');\r
-       html = tinyMCE.regexpReplace(html, '<p>\\s*<br />\\s*&nbsp;\\s*</p>', '<p>&nbsp;</p>');\r
+                                       // Push value on to stack\r
+                                       if (!isShortEnded) {\r
+                                               if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1)\r
+                                                       stack.push({name: value, valid: isValidElement});\r
+                                               else if (isValidElement)\r
+                                                       self.end(value);\r
+                                       }\r
+                               } else if (value = matches[1]) { // Comment\r
+                                       self.comment(value);\r
+                               } else if (value = matches[2]) { // CDATA\r
+                                       self.cdata(value);\r
+                               } else if (value = matches[3]) { // DOCTYPE\r
+                                       self.doctype(value);\r
+                               } else if (value = matches[4]) { // PI\r
+                                       self.pi(value, matches[5]);\r
+                               }\r
 \r
-       // Remove empty anchors\r
-       html = html.replace(new RegExp('<a>(.*?)</a>', 'gi'), '$1');\r
+                               index = matches.index + matches[0].length;\r
+                       }\r
 \r
-       // Remove some mozilla crap\r
-       if (!tinyMCE.isMSIE)\r
-               html = html.replace(new RegExp('<o:p _moz-userdefined="" />', 'g'), "");\r
+                       // Text\r
+                       if (index < html.length)\r
+                               self.text(decode(html.substr(index)));\r
 \r
-       if (tinyMCE.settings['remove_linebreaks'])\r
-               html = html.replace(new RegExp('\r|\n', 'g'), ' ');\r
+                       // Close any open elements\r
+                       for (i = stack.length - 1; i >= 0; i--) {\r
+                               value = stack[i];\r
 \r
-       if (tinyMCE.getParam('apply_source_formatting')) {\r
-               html = html.replace(new RegExp('<(p|div)([^>]*)>', 'g'), "\n<$1$2>\n");\r
-               html = html.replace(new RegExp('<\/(p|div)([^>]*)>', 'g'), "\n</$1$2>\n");\r
-               html = html.replace(new RegExp('<br />', 'g'), "<br />\n");\r
+                               if (value.valid)\r
+                                       self.end(value.name);\r
+                       }\r
+               };\r
        }\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = {\r
+               '#text' : 3,\r
+               '#comment' : 8,\r
+               '#cdata' : 4,\r
+               '#pi' : 7,\r
+               '#doctype' : 10,\r
+               '#document-fragment' : 11\r
+       };\r
+\r
+       // Walks the tree left/right\r
+       function walk(node, root_node, prev) {\r
+               var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next';\r
+\r
+               // Walk into nodes if it has a start\r
+               if (node[startName])\r
+                       return node[startName];\r
+\r
+               // Return the sibling if it has one\r
+               if (node !== root_node) {\r
+                       sibling = node[siblingName];\r
+\r
+                       if (sibling)\r
+                               return sibling;\r
+\r
+                       // Walk up the parents to look for siblings\r
+                       for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) {\r
+                               sibling = parent[siblingName];\r
+\r
+                               if (sibling)\r
+                                       return sibling;\r
+                       }\r
+               }\r
+       };\r
 \r
-       if (tinyMCE.settings['force_br_newlines']) {\r
-               var re = new RegExp('<p>&nbsp;</p>', 'g');\r
-               html = html.replace(re, "<br />");\r
-       }\r
+       function Node(name, type) {\r
+               this.name = name;\r
+               this.type = type;\r
 \r
-       if (tinyMCE.isGecko && tinyMCE.settings['remove_lt_gt']) {\r
-               // Remove weridness!\r
-               var re = new RegExp('&lt;&gt;', 'g');\r
-               html = html.replace(re, "");\r
+               if (type === 1) {\r
+                       this.attributes = [];\r
+                       this.attributes.map = {};\r
+               }\r
        }\r
 \r
-       // Call custom cleanup code\r
-       html = tinyMCE._customCleanup(inst, on_save ? "get_from_editor" : "insert_to_editor", html);\r
+       tinymce.extend(Node.prototype, {\r
+               replace : function(node) {\r
+                       var self = this;\r
 \r
-       // Emtpy node, return empty\r
-       var chk = tinyMCE.regexpReplace(html, "[ \t\r\n]", "").toLowerCase();\r
-       if (chk == "<br/>" || chk == "<br>" || chk == "<p>&nbsp;</p>" || chk == "<p>&#160;</p>" || chk == "<p></p>")\r
-               html = "";\r
+                       if (node.parent)\r
+                               node.remove();\r
 \r
-       if (tinyMCE.settings["preformatted"])\r
-               return "<pre>" + html + "</pre>";\r
+                       self.insert(node, self);\r
+                       self.remove();\r
 \r
-       return html;\r
-};\r
+                       return self;\r
+               },\r
 \r
-TinyMCE.prototype.insertLink = function(href, target, title, onclick, style_class) {\r
-       tinyMCE.execCommand('mceBeginUndoLevel');\r
+               attr : function(name, value) {\r
+                       var self = this, attrs, i, undef;\r
 \r
-       if (this.selectedInstance && this.selectedElement && this.selectedElement.nodeName.toLowerCase() == "img") {\r
-               var doc = this.selectedInstance.getDoc();\r
-               var linkElement = tinyMCE.getParentElement(this.selectedElement, "a");\r
-               var newLink = false;\r
+                       if (typeof name !== "string") {\r
+                               for (i in name)\r
+                                       self.attr(i, name[i]);\r
 \r
-               if (!linkElement) {\r
-                       linkElement = doc.createElement("a");\r
-                       newLink = true;\r
-               }\r
+                               return self;\r
+                       }\r
 \r
-               var mhref = href;\r
-               var thref = eval(tinyMCE.settings['urlconverter_callback'] + "(href, linkElement);");\r
-               mhref = tinyMCE.getParam('convert_urls') ? href : mhref;\r
+                       if (attrs = self.attributes) {\r
+                               if (value !== undef) {\r
+                                       // Remove attribute\r
+                                       if (value === null) {\r
+                                               if (name in attrs.map) {\r
+                                                       delete attrs.map[name];\r
+\r
+                                                       i = attrs.length;\r
+                                                       while (i--) {\r
+                                                               if (attrs[i].name === name) {\r
+                                                                       attrs = attrs.splice(i, 1);\r
+                                                                       return self;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
 \r
-               tinyMCE.setAttrib(linkElement, 'href', thref);\r
-               tinyMCE.setAttrib(linkElement, 'mce_href', mhref);\r
-               tinyMCE.setAttrib(linkElement, 'target', target);\r
-               tinyMCE.setAttrib(linkElement, 'title', title);\r
-        tinyMCE.setAttrib(linkElement, 'onclick', onclick);\r
-               tinyMCE.setAttrib(linkElement, 'class', style_class);\r
+                                               return self;\r
+                                       }\r
 \r
-               if (newLink) {\r
-                       linkElement.appendChild(this.selectedElement.cloneNode(true));\r
-                       this.selectedElement.parentNode.replaceChild(linkElement, this.selectedElement);\r
-               }\r
+                                       // Set attribute\r
+                                       if (name in attrs.map) {\r
+                                               // Set attribute\r
+                                               i = attrs.length;\r
+                                               while (i--) {\r
+                                                       if (attrs[i].name === name) {\r
+                                                               attrs[i].value = value;\r
+                                                               break;\r
+                                                       }\r
+                                               }\r
+                                       } else\r
+                                               attrs.push({name: name, value: value});\r
 \r
-               return;\r
-       }\r
+                                       attrs.map[name] = value;\r
 \r
-       if (!this.linkElement && this.selectedInstance) {\r
-               if (tinyMCE.isSafari) {\r
-                       tinyMCE.execCommand("mceInsertContent", false, '<a href="' + tinyMCE.uniqueURL + '">' + this.selectedInstance.getSelectedHTML() + '</a>');\r
-               } else\r
-                       this.selectedInstance.contentDocument.execCommand("createlink", false, tinyMCE.uniqueURL);\r
+                                       return self;\r
+                               } else {\r
+                                       return attrs.map[name];\r
+                               }\r
+                       }\r
+               },\r
 \r
-               tinyMCE.linkElement = this.getElementByAttributeValue(this.selectedInstance.contentDocument.body, "a", "href", tinyMCE.uniqueURL);\r
+               clone : function() {\r
+                       var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs;\r
 \r
-               var elementArray = this.getElementsByAttributeValue(this.selectedInstance.contentDocument.body, "a", "href", tinyMCE.uniqueURL);\r
+                       // Clone element attributes\r
+                       if (selfAttrs = self.attributes) {\r
+                               cloneAttrs = [];\r
+                               cloneAttrs.map = {};\r
 \r
-               for (var i=0; i<elementArray.length; i++) {\r
-                       var mhref = href;\r
-                       var thref = eval(tinyMCE.settings['urlconverter_callback'] + "(href, elementArray[i]);");\r
-                       mhref = tinyMCE.getParam('convert_urls') ? href : mhref;\r
+                               for (i = 0, l = selfAttrs.length; i < l; i++) {\r
+                                       selfAttr = selfAttrs[i];\r
 \r
-                       tinyMCE.setAttrib(elementArray[i], 'href', thref);\r
-                       tinyMCE.setAttrib(elementArray[i], 'mce_href', mhref);\r
-                       tinyMCE.setAttrib(elementArray[i], 'target', target);\r
-                       tinyMCE.setAttrib(elementArray[i], 'title', title);\r
-            tinyMCE.setAttrib(elementArray[i], 'onclick', onclick);\r
-                       tinyMCE.setAttrib(elementArray[i], 'class', style_class);\r
-               }\r
+                                       // Clone everything except id\r
+                                       if (selfAttr.name !== 'id') {\r
+                                               cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value};\r
+                                               cloneAttrs.map[selfAttr.name] = selfAttr.value;\r
+                                       }\r
+                               }\r
 \r
-               tinyMCE.linkElement = elementArray[0];\r
-       }\r
+                               clone.attributes = cloneAttrs;\r
+                       }\r
 \r
-       if (this.linkElement) {\r
-               var mhref = href;\r
-               href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, this.linkElement);");\r
-               mhref = tinyMCE.getParam('convert_urls') ? href : mhref;\r
-\r
-               tinyMCE.setAttrib(this.linkElement, 'href', href);\r
-               tinyMCE.setAttrib(this.linkElement, 'mce_href', mhref);\r
-               tinyMCE.setAttrib(this.linkElement, 'target', target);\r
-               tinyMCE.setAttrib(this.linkElement, 'title', title);\r
-        tinyMCE.setAttrib(this.linkElement, 'onclick', onclick);\r
-               tinyMCE.setAttrib(this.linkElement, 'class', style_class);\r
-       }\r
+                       clone.value = self.value;\r
+                       clone.shortEnded = self.shortEnded;\r
 \r
-       tinyMCE.execCommand('mceEndUndoLevel');\r
-};\r
+                       return clone;\r
+               },\r
 \r
-TinyMCE.prototype.insertImage = function(src, alt, border, hspace, vspace, width, height, align, title, onmouseover, onmouseout) {\r
-       tinyMCE.execCommand('mceBeginUndoLevel');\r
+               wrap : function(wrapper) {\r
+                       var self = this;\r
 \r
-       if (src == "")\r
-               return;\r
+                       self.parent.insert(wrapper, self);\r
+                       wrapper.append(self);\r
 \r
-       if (!this.imgElement && tinyMCE.isSafari) {\r
-               var html = "";\r
+                       return self;\r
+               },\r
 \r
-               html += '<img src="' + src + '" alt="' + alt + '"';\r
-               html += ' border="' + border + '" hspace="' + hspace + '"';\r
-               html += ' vspace="' + vspace + '" width="' + width + '"';\r
-               html += ' height="' + height + '" align="' + align + '" title="' + title + '" onmouseover="' + onmouseover + '" onmouseout="' + onmouseout + '" />';\r
+               unwrap : function() {\r
+                       var self = this, node, next;\r
 \r
-               tinyMCE.execCommand("mceInsertContent", false, html);\r
-       } else {\r
-               if (!this.imgElement && this.selectedInstance) {\r
-                       if (tinyMCE.isSafari)\r
-                               tinyMCE.execCommand("mceInsertContent", false, '<img src="' + tinyMCE.uniqueURL + '" />');\r
-                       else\r
-                               this.selectedInstance.contentDocument.execCommand("insertimage", false, tinyMCE.uniqueURL);\r
+                       for (node = self.firstChild; node; ) {\r
+                               next = node.next;\r
+                               self.insert(node, self, true);\r
+                               node = next;\r
+                       }\r
 \r
-                       tinyMCE.imgElement = this.getElementByAttributeValue(this.selectedInstance.contentDocument.body, "img", "src", tinyMCE.uniqueURL);\r
-               }\r
-       }\r
+                       self.remove();\r
+               },\r
 \r
-       if (this.imgElement) {\r
-               var needsRepaint = false;\r
-               var msrc = src;\r
+               remove : function() {\r
+                       var self = this, parent = self.parent, next = self.next, prev = self.prev;\r
 \r
-               src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, tinyMCE.imgElement);");\r
+                       if (parent) {\r
+                               if (parent.firstChild === self) {\r
+                                       parent.firstChild = next;\r
 \r
-               if (tinyMCE.getParam('convert_urls'))\r
-                       msrc = src;\r
+                                       if (next)\r
+                                               next.prev = null;\r
+                               } else {\r
+                                       prev.next = next;\r
+                               }\r
 \r
-               if (onmouseover && onmouseover != "")\r
-                       onmouseover = "this.src='" + eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseover, tinyMCE.imgElement);") + "';";\r
+                               if (parent.lastChild === self) {\r
+                                       parent.lastChild = prev;\r
 \r
-               if (onmouseout && onmouseout != "")\r
-                       onmouseout = "this.src='" + eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseout, tinyMCE.imgElement);") + "';";\r
+                                       if (prev)\r
+                                               prev.next = null;\r
+                               } else {\r
+                                       next.prev = prev;\r
+                               }\r
 \r
-               // Use alt as title if it's undefined\r
-               if (typeof(title) == "undefined")\r
-                       title = alt;\r
+                               self.parent = self.next = self.prev = null;\r
+                       }\r
 \r
-               if (width != this.imgElement.getAttribute("width") || height != this.imgElement.getAttribute("height") || align != this.imgElement.getAttribute("align"))\r
-                       needsRepaint = true;\r
+                       return self;\r
+               },\r
 \r
-               tinyMCE.setAttrib(this.imgElement, 'src', src);\r
-               tinyMCE.setAttrib(this.imgElement, 'mce_src', msrc);\r
-               tinyMCE.setAttrib(this.imgElement, 'alt', alt);\r
-               tinyMCE.setAttrib(this.imgElement, 'title', title);\r
-               tinyMCE.setAttrib(this.imgElement, 'align', align);\r
-               tinyMCE.setAttrib(this.imgElement, 'border', border, true);\r
-               tinyMCE.setAttrib(this.imgElement, 'hspace', hspace, true);\r
-               tinyMCE.setAttrib(this.imgElement, 'vspace', vspace, true);\r
-               tinyMCE.setAttrib(this.imgElement, 'width', width, true);\r
-               tinyMCE.setAttrib(this.imgElement, 'height', height, true);\r
-               tinyMCE.setAttrib(this.imgElement, 'onmouseover', onmouseover);\r
-               tinyMCE.setAttrib(this.imgElement, 'onmouseout', onmouseout);\r
+               append : function(node) {\r
+                       var self = this, last;\r
 \r
-               // Fix for bug #989846 - Image resize bug\r
-               if (width && width != "")\r
-                       this.imgElement.style.pixelWidth = width;\r
+                       if (node.parent)\r
+                               node.remove();\r
 \r
-               if (height && height != "")\r
-                       this.imgElement.style.pixelHeight = height;\r
+                       last = self.lastChild;\r
+                       if (last) {\r
+                               last.next = node;\r
+                               node.prev = last;\r
+                               self.lastChild = node;\r
+                       } else\r
+                               self.lastChild = self.firstChild = node;\r
 \r
-               if (needsRepaint)\r
-                       tinyMCE.selectedInstance.repaint();\r
-       }\r
+                       node.parent = self;\r
 \r
-       tinyMCE.execCommand('mceEndUndoLevel');\r
-};\r
+                       return node;\r
+               },\r
 \r
-TinyMCE.prototype.getElementByAttributeValue = function(node, element_name, attrib, value) {\r
-       var elements = this.getElementsByAttributeValue(node, element_name, attrib, value);\r
-       if (elements.length == 0)\r
-               return null;\r
+               insert : function(node, ref_node, before) {\r
+                       var parent;\r
 \r
-       return elements[0];\r
-};\r
+                       if (node.parent)\r
+                               node.remove();\r
 \r
-TinyMCE.prototype.getElementsByAttributeValue = function(node, element_name, attrib, value) {\r
-       var elements = new Array();\r
+                       parent = ref_node.parent || this;\r
 \r
-       if (node && node.nodeName.toLowerCase() == element_name) {\r
-               if (node.getAttribute(attrib) && node.getAttribute(attrib).indexOf(value) != -1)\r
-                       elements[elements.length] = node;\r
-       }\r
+                       if (before) {\r
+                               if (ref_node === parent.firstChild)\r
+                                       parent.firstChild = node;\r
+                               else\r
+                                       ref_node.prev.next = node;\r
 \r
-       if (node && node.hasChildNodes()) {\r
-               for (var x=0, n=node.childNodes.length; x<n; x++) {\r
-                       var childElements = this.getElementsByAttributeValue(node.childNodes[x], element_name, attrib, value);\r
-                       for (var i=0, m=childElements.length; i<m; i++)\r
-                               elements[elements.length] = childElements[i];\r
-               }\r
-       }\r
+                               node.prev = ref_node.prev;\r
+                               node.next = ref_node;\r
+                               ref_node.prev = node;\r
+                       } else {\r
+                               if (ref_node === parent.lastChild)\r
+                                       parent.lastChild = node;\r
+                               else\r
+                                       ref_node.next.prev = node;\r
 \r
-       return elements;\r
-};\r
+                               node.next = ref_node.next;\r
+                               node.prev = ref_node;\r
+                               ref_node.next = node;\r
+                       }\r
 \r
-TinyMCE.prototype.isBlockElement = function(node) {\r
-       return node != null && node.nodeType == 1 && this.blockRegExp.test(node.nodeName);\r
-};\r
+                       node.parent = parent;\r
 \r
-TinyMCE.prototype.getParentBlockElement = function(node) {\r
-       // Search up the tree for block element\r
-       while (node) {\r
-               if (this.blockRegExp.test(node.nodeName))\r
                        return node;\r
+               },\r
 \r
-               node = node.parentNode;\r
-       }\r
-\r
-       return null;\r
-};\r
-\r
-TinyMCE.prototype.getNodeTree = function(node, node_array, type, node_name) {\r
-       if (typeof(type) == "undefined" || node.nodeType == type && (typeof(node_name) == "undefined" || node.nodeName == node_name))\r
-               node_array[node_array.length] = node;\r
-\r
-       if (node.hasChildNodes()) {\r
-               for (var i=0; i<node.childNodes.length; i++)\r
-                       tinyMCE.getNodeTree(node.childNodes[i], node_array, type, node_name);\r
-       }\r
+               getAll : function(name) {\r
+                       var self = this, node, collection = [];\r
 \r
-       return node_array;\r
-};\r
-\r
-TinyMCE.prototype.getParentElement = function(node, names, attrib_name, attrib_value) {\r
-       if (typeof(names) == "undefined") {\r
-               if (node.nodeType == 1)\r
-                       return node;\r
+                       for (node = self.firstChild; node; node = walk(node, self)) {\r
+                               if (node.name === name)\r
+                                       collection.push(node);\r
+                       }\r
 \r
-               // Find parent node that is a element\r
-               while ((node = node.parentNode) != null && node.nodeType != 1) ;\r
+                       return collection;\r
+               },\r
 \r
-               return node;\r
-       }\r
+               empty : function() {\r
+                       var self = this, nodes, i, node;\r
 \r
-       var namesAr = names.split(',');\r
+                       // Remove all children\r
+                       if (self.firstChild) {\r
+                               nodes = [];\r
 \r
-       if (node == null)\r
-               return null;\r
+                               // Collect the children\r
+                               for (node = self.firstChild; node; node = walk(node, self))\r
+                                       nodes.push(node);\r
 \r
-       do {\r
-               for (var i=0; i<namesAr.length; i++) {\r
-                       if (node.nodeName.toLowerCase() == namesAr[i].toLowerCase() || names == "*") {\r
-                               if (typeof(attrib_name) == "undefined")\r
-                                       return node;\r
-                               else if (node.getAttribute(attrib_name)) {\r
-                                       if (typeof(attrib_value) == "undefined") {\r
-                                               if (node.getAttribute(attrib_name) != "")\r
-                                                       return node;\r
-                                       } else if (node.getAttribute(attrib_name) == attrib_value)\r
-                                               return node;\r
+                               // Remove the children\r
+                               i = nodes.length;\r
+                               while (i--) {\r
+                                       node = nodes[i];\r
+                                       node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;\r
                                }\r
                        }\r
-               }\r
-       } while ((node = node.parentNode) != null);\r
-\r
-       return null;\r
-};\r
-\r
-TinyMCE.prototype.convertURL = function(url, node, on_save) {\r
-       var prot = document.location.protocol;\r
-       var host = document.location.hostname;\r
-       var port = document.location.port;\r
-\r
-       // Pass through file protocol\r
-       if (prot == "file:")\r
-               return url;\r
-\r
-       // Something is wrong, remove weirdness\r
-       url = tinyMCE.regexpReplace(url, '(http|https):///', '/');\r
-\r
-       // Mailto link or anchor (Pass through)\r
-       if (url.indexOf('mailto:') != -1 || url.indexOf('javascript:') != -1 || tinyMCE.regexpReplace(url,'[ \t\r\n\+]|%20','').charAt(0) == "#")\r
-               return url;\r
-\r
-       // Fix relative/Mozilla\r
-       if (!tinyMCE.isMSIE && !on_save && url.indexOf("://") == -1 && url.charAt(0) != '/')\r
-               return tinyMCE.settings['base_href'] + url;\r
-\r
-       // Handle relative URLs\r
-       if (on_save && tinyMCE.getParam('relative_urls')) {\r
-               var curl = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], url);\r
-               if (curl.charAt(0) == '/')\r
-                       curl = tinyMCE.settings['document_base_prefix'] + curl;\r
-\r
-               var urlParts = tinyMCE.parseURL(curl);\r
-               var tmpUrlParts = tinyMCE.parseURL(tinyMCE.settings['document_base_url']);\r
 \r
-               // Force relative\r
-               if (urlParts['host'] == tmpUrlParts['host'] && (urlParts['port'] == tmpUrlParts['port']))\r
-                       return tinyMCE.convertAbsoluteURLToRelativeURL(tinyMCE.settings['document_base_url'], curl);\r
-       }\r
-\r
-       // Handle absolute URLs\r
-       if (!tinyMCE.getParam('relative_urls')) {\r
-               var urlParts = tinyMCE.parseURL(url);\r
-               var baseUrlParts = tinyMCE.parseURL(tinyMCE.settings['base_href']);\r
+                       self.firstChild = self.lastChild = null;\r
 \r
-               // Force absolute URLs from relative URLs\r
-               url = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], url);\r
+                       return self;\r
+               },\r
 \r
-               // If anchor and path is the same page\r
-               if (urlParts['anchor'] && urlParts['path'] == baseUrlParts['path'])\r
-                       return "#" + urlParts['anchor'];\r
-       }\r
+               isEmpty : function(elements) {\r
+                       var self = this, node = self.firstChild, i, name;\r
 \r
-       // Remove current domain\r
-       if (tinyMCE.getParam('remove_script_host')) {\r
-               var start = "", portPart = "";\r
+                       if (node) {\r
+                               do {\r
+                                       if (node.type === 1) {\r
+                                               // Ignore bogus elements\r
+                                               if (node.attributes.map['data-mce-bogus'])\r
+                                                       continue;\r
+\r
+                                               // Keep empty elements like <img />\r
+                                               if (elements[node.name])\r
+                                                       return false;\r
+\r
+                                               // Keep elements with data attributes or name attribute like <a name="1"></a>\r
+                                               i = node.attributes.length;\r
+                                               while (i--) {\r
+                                                       name = node.attributes[i].name;\r
+                                                       if (name === "name" || name.indexOf('data-') === 0)\r
+                                                               return false;\r
+                                               }\r
+                                       }\r
 \r
-               if (port != "")\r
-                       portPart = ":" + port;\r
+                                       // Keep non whitespace text nodes\r
+                                       if ((node.type === 3 && !whiteSpaceRegExp.test(node.value)))\r
+                                               return false;\r
+                               } while (node = walk(node, self));\r
+                       }\r
 \r
-               start = prot + "//" + host + portPart + "/";\r
+                       return true;\r
+               },\r
 \r
-               if (url.indexOf(start) == 0)\r
-                       url = url.substring(start.length-1);\r
-       }\r
+               walk : function(prev) {\r
+                       return walk(this, null, prev);\r
+               }\r
+       });\r
 \r
-       return url;\r
-};\r
+       tinymce.extend(Node, {\r
+               create : function(name, attrs) {\r
+                       var node, attrName;\r
 \r
-/**\r
- * Parses a URL in to its diffrent components.\r
- */\r
-TinyMCE.prototype.parseURL = function(url_str) {\r
-       var urlParts = new Array();\r
+                       // Create node\r
+                       node = new Node(name, typeLookup[name] || 1);\r
 \r
-       if (url_str) {\r
-               var pos, lastPos;\r
+                       // Add attributes if needed\r
+                       if (attrs) {\r
+                               for (attrName in attrs)\r
+                                       node.attr(attrName, attrs[attrName]);\r
+                       }\r
 \r
-               // Parse protocol part\r
-               pos = url_str.indexOf('://');\r
-               if (pos != -1) {\r
-                       urlParts['protocol'] = url_str.substring(0, pos);\r
-                       lastPos = pos + 3;\r
+                       return node;\r
                }\r
+       });\r
 \r
-               // Find port or path start\r
-               for (var i=lastPos; i<url_str.length; i++) {\r
-                       var chr = url_str.charAt(i);\r
+       tinymce.html.Node = Node;\r
+})(tinymce);\r
 \r
-                       if (chr == ':')\r
-                               break;\r
+(function(tinymce) {\r
+       var Node = tinymce.html.Node;\r
 \r
-                       if (chr == '/')\r
-                               break;\r
-               }\r
-               pos = i;\r
+       tinymce.html.DomParser = function(settings, schema) {\r
+               var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};\r
 \r
-               // Get host\r
-               urlParts['host'] = url_str.substring(lastPos, pos);\r
+               settings = settings || {};\r
+               settings.validate = "validate" in settings ? settings.validate : true;\r
+               settings.root_name = settings.root_name || 'body';\r
+               self.schema = schema = schema || new tinymce.html.Schema();\r
 \r
-               // Get port\r
-               urlParts['port'] = "";\r
-               lastPos = pos;\r
-               if (url_str.charAt(pos) == ':') {\r
-                       pos = url_str.indexOf('/', lastPos);\r
-                       urlParts['port'] = url_str.substring(lastPos+1, pos);\r
-               }\r
+               function fixInvalidChildren(nodes) {\r
+                       var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i,\r
+                               childClone, nonEmptyElements, nonSplitableElements, sibling, nextNode;\r
 \r
-               // Get path\r
-               lastPos = pos;\r
-               pos = url_str.indexOf('?', lastPos);\r
+                       nonSplitableElements = tinymce.makeMap('tr,td,th,tbody,thead,tfoot,table');\r
+                       nonEmptyElements = schema.getNonEmptyElements();\r
 \r
-               if (pos == -1)\r
-                       pos = url_str.indexOf('#', lastPos);\r
+                       for (ni = 0; ni < nodes.length; ni++) {\r
+                               node = nodes[ni];\r
 \r
-               if (pos == -1)\r
-                       pos = url_str.length;\r
+                               // Already removed\r
+                               if (!node.parent)\r
+                                       continue;\r
 \r
-               urlParts['path'] = url_str.substring(lastPos, pos);\r
+                               // Get list of all parent nodes until we find a valid parent to stick the child into\r
+                               parents = [node];\r
+                               for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent)\r
+                                       parents.push(parent);\r
+\r
+                               // Found a suitable parent\r
+                               if (parent && parents.length > 1) {\r
+                                       // Reverse the array since it makes looping easier\r
+                                       parents.reverse();\r
+\r
+                                       // Clone the related parent and insert that after the moved node\r
+                                       newParent = currentNode = self.filterNode(parents[0].clone());\r
+\r
+                                       // Start cloning and moving children on the left side of the target node\r
+                                       for (i = 0; i < parents.length - 1; i++) {\r
+                                               if (schema.isValidChild(currentNode.name, parents[i].name)) {\r
+                                                       tempNode = self.filterNode(parents[i].clone());\r
+                                                       currentNode.append(tempNode);\r
+                                               } else\r
+                                                       tempNode = currentNode;\r
+\r
+                                               for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) {\r
+                                                       nextNode = childNode.next;\r
+                                                       tempNode.append(childNode);\r
+                                                       childNode = nextNode;\r
+                                               }\r
 \r
-               // Get query\r
-               lastPos = pos;\r
-               if (url_str.charAt(pos) == '?') {\r
-                       pos = url_str.indexOf('#');\r
-                       pos = (pos == -1) ? url_str.length : pos;\r
-                       urlParts['query'] = url_str.substring(lastPos+1, pos);\r
-               }\r
+                                               currentNode = tempNode;\r
+                                       }\r
 \r
-               // Get anchor\r
-               lastPos = pos;\r
-               if (url_str.charAt(pos) == '#') {\r
-                       pos = url_str.length;\r
-                       urlParts['anchor'] = url_str.substring(lastPos+1, pos);\r
-               }\r
-       }\r
+                                       if (!newParent.isEmpty(nonEmptyElements)) {\r
+                                               parent.insert(newParent, parents[0], true);\r
+                                               parent.insert(node, newParent);\r
+                                       } else {\r
+                                               parent.insert(node, parents[0], true);\r
+                                       }\r
 \r
-       return urlParts;\r
-};\r
+                                       // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p>\r
+                                       parent = parents[0];\r
+                                       if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') {\r
+                                               parent.empty().remove();\r
+                                       }\r
+                               } else if (node.parent) {\r
+                                       // If it's an LI try to find a UL/OL for it or wrap it\r
+                                       if (node.name === 'li') {\r
+                                               sibling = node.prev;\r
+                                               if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {\r
+                                                       sibling.append(node);\r
+                                                       continue;\r
+                                               }\r
 \r
-TinyMCE.prototype.serializeURL = function(up) {\r
-       var url = "";\r
+                                               sibling = node.next;\r
+                                               if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {\r
+                                                       sibling.insert(node, sibling.firstChild, true);\r
+                                                       continue;\r
+                                               }\r
 \r
-       if (up['protocol'])\r
-               url += up['protocol'] + "://";\r
+                                               node.wrap(self.filterNode(new Node('ul', 1)));\r
+                                               continue;\r
+                                       }\r
 \r
-       if (up['host'])\r
-               url += up['host'];\r
+                                       // Try wrapping the element in a DIV\r
+                                       if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {\r
+                                               node.wrap(self.filterNode(new Node('div', 1)));\r
+                                       } else {\r
+                                               // We failed wrapping it, then remove or unwrap it\r
+                                               if (node.name === 'style' || node.name === 'script')\r
+                                                       node.empty().remove();\r
+                                               else\r
+                                                       node.unwrap();\r
+                                       }\r
+                               }\r
+                       }\r
+               };\r
 \r
-       if (up['port'])\r
-               url += ":" + up['port'];\r
+               self.filterNode = function(node) {\r
+                       var i, name, list;\r
 \r
-       if (up['path'])\r
-               url += up['path'];\r
+                       // Run element filters\r
+                       if (name in nodeFilters) {\r
+                               list = matchedNodes[name];\r
 \r
-       if (up['query'])\r
-               url += "?" + up['query'];\r
+                               if (list)\r
+                                       list.push(node);\r
+                               else\r
+                                       matchedNodes[name] = [node];\r
+                       }\r
 \r
-       if (up['anchor'])\r
-               url += "#" + up['anchor'];\r
+                       // Run attribute filters\r
+                       i = attributeFilters.length;\r
+                       while (i--) {\r
+                               name = attributeFilters[i].name;\r
 \r
-       return url;\r
-};\r
+                               if (name in node.attributes.map) {\r
+                                       list = matchedAttributes[name];\r
 \r
-/**\r
- * Converts an absolute path to relative path.\r
- */\r
-TinyMCE.prototype.convertAbsoluteURLToRelativeURL = function(base_url, url_to_relative) {\r
-       var baseURL = this.parseURL(base_url);\r
-       var targetURL = this.parseURL(url_to_relative);\r
-       var strTok1;\r
-       var strTok2;\r
-       var breakPoint = 0;\r
-       var outPath = "";\r
-       var forceSlash = false;\r
-\r
-       if (targetURL.path == "")\r
-               targetURL.path = "/";\r
-       else\r
-               forceSlash = true;\r
-\r
-       // Crop away last path part\r
-       base_url = baseURL.path.substring(0, baseURL.path.lastIndexOf('/'));\r
-       strTok1 = base_url.split('/');\r
-       strTok2 = targetURL.path.split('/');\r
-\r
-       if (strTok1.length >= strTok2.length) {\r
-               for (var i=0; i<strTok1.length; i++) {\r
-                       if (i >= strTok2.length || strTok1[i] != strTok2[i]) {\r
-                               breakPoint = i + 1;\r
-                               break;\r
+                                       if (list)\r
+                                               list.push(node);\r
+                                       else\r
+                                               matchedAttributes[name] = [node];\r
+                               }\r
                        }\r
-               }\r
-       }\r
 \r
-       if (strTok1.length < strTok2.length) {\r
-               for (var i=0; i<strTok2.length; i++) {\r
-                       if (i >= strTok1.length || strTok1[i] != strTok2[i]) {\r
-                               breakPoint = i + 1;\r
-                               break;\r
-                       }\r
-               }\r
-       }\r
+                       return node;\r
+               };\r
 \r
-       if (breakPoint == 1)\r
-               return targetURL.path;\r
+               self.addNodeFilter = function(name, callback) {\r
+                       tinymce.each(tinymce.explode(name), function(name) {\r
+                               var list = nodeFilters[name];\r
 \r
-       for (var i=0; i<(strTok1.length-(breakPoint-1)); i++)\r
-               outPath += "../";\r
+                               if (!list)\r
+                                       nodeFilters[name] = list = [];\r
 \r
-       for (var i=breakPoint-1; i<strTok2.length; i++) {\r
-               if (i != (breakPoint-1))\r
-                       outPath += "/" + strTok2[i];\r
-               else\r
-                       outPath += strTok2[i];\r
-       }\r
+                               list.push(callback);\r
+                       });\r
+               };\r
 \r
-       targetURL.protocol = null;\r
-       targetURL.host = null;\r
-       targetURL.port = null;\r
-       targetURL.path = outPath == "" && forceSlash ? "/" : outPath;\r
+               self.addAttributeFilter = function(name, callback) {\r
+                       tinymce.each(tinymce.explode(name), function(name) {\r
+                               var i;\r
 \r
-       // Remove document prefix from local anchors\r
-       var fileName = baseURL.path;\r
-       var pos;\r
+                               for (i = 0; i < attributeFilters.length; i++) {\r
+                                       if (attributeFilters[i].name === name) {\r
+                                               attributeFilters[i].callbacks.push(callback);\r
+                                               return;\r
+                                       }\r
+                               }\r
 \r
-       if ((pos = fileName.lastIndexOf('/')) != -1)\r
-               fileName = fileName.substring(pos + 1);\r
+                               attributeFilters.push({name: name, callbacks: [callback]});\r
+                       });\r
+               };\r
+\r
+               self.parse = function(html, args) {\r
+                       var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate,\r
+                               blockElements, startWhiteSpaceRegExp, invalidChildren = [],\r
+                               endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements, rootBlockName;\r
+\r
+                       args = args || {};\r
+                       matchedNodes = {};\r
+                       matchedAttributes = {};\r
+                       blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());\r
+                       nonEmptyElements = schema.getNonEmptyElements();\r
+                       children = schema.children;\r
+                       validate = settings.validate;\r
+                       rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;\r
+\r
+                       whiteSpaceElements = schema.getWhiteSpaceElements();\r
+                       startWhiteSpaceRegExp = /^[ \t\r\n]+/;\r
+                       endWhiteSpaceRegExp = /[ \t\r\n]+$/;\r
+                       allWhiteSpaceRegExp = /[ \t\r\n]+/g;\r
+\r
+                       function addRootBlocks() {\r
+                               var node = rootNode.firstChild, next, rootBlockNode;\r
+\r
+                               while (node) {\r
+                                       next = node.next;\r
+\r
+                                       if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) {\r
+                                               if (!rootBlockNode) {\r
+                                                       // Create a new root block element\r
+                                                       rootBlockNode = createNode(rootBlockName, 1);\r
+                                                       rootNode.insert(rootBlockNode, node);\r
+                                                       rootBlockNode.append(node);\r
+                                               } else\r
+                                                       rootBlockNode.append(node);\r
+                                       } else {\r
+                                               rootBlockNode = null;\r
+                                       }\r
 \r
-       // Is local anchor\r
-       if (fileName == targetURL.path && targetURL.anchor != "")\r
-               targetURL.path = "";\r
+                                       node = next;\r
+                               };\r
+                       };\r
 \r
-       return this.serializeURL(targetURL);\r
-};\r
+                       function createNode(name, type) {\r
+                               var node = new Node(name, type), list;\r
 \r
-TinyMCE.prototype.convertRelativeToAbsoluteURL = function(base_url, relative_url) {\r
-       var baseURL = TinyMCE.prototype.parseURL(base_url);\r
-       var relURL = TinyMCE.prototype.parseURL(relative_url);\r
+                               if (name in nodeFilters) {\r
+                                       list = matchedNodes[name];\r
 \r
-       if (relative_url == "" || relative_url.charAt(0) == '/' || relative_url.indexOf('://') != -1 || relative_url.indexOf('mailto:') != -1 || relative_url.indexOf('javascript:') != -1)\r
-               return relative_url;\r
+                                       if (list)\r
+                                               list.push(node);\r
+                                       else\r
+                                               matchedNodes[name] = [node];\r
+                               }\r
 \r
-       // Split parts\r
-       baseURLParts = baseURL['path'].split('/');\r
-       relURLParts = relURL['path'].split('/');\r
+                               return node;\r
+                       };\r
 \r
-       // Remove empty chunks\r
-       var newBaseURLParts = new Array();\r
-       for (var i=baseURLParts.length-1; i>=0; i--) {\r
-               if (baseURLParts[i].length == 0)\r
-                       continue;\r
+                       function removeWhitespaceBefore(node) {\r
+                               var textNode, textVal, sibling;\r
 \r
-               newBaseURLParts[newBaseURLParts.length] = baseURLParts[i];\r
-       }\r
-       baseURLParts = newBaseURLParts.reverse();\r
-\r
-       // Merge relURLParts chunks\r
-       var newRelURLParts = new Array();\r
-       var numBack = 0;\r
-       for (var i=relURLParts.length-1; i>=0; i--) {\r
-               if (relURLParts[i].length == 0 || relURLParts[i] == ".")\r
-                       continue;\r
-\r
-               if (relURLParts[i] == '..') {\r
-                       numBack++;\r
-                       continue;\r
-               }\r
+                               for (textNode = node.prev; textNode && textNode.type === 3; ) {\r
+                                       textVal = textNode.value.replace(endWhiteSpaceRegExp, '');\r
 \r
-               if (numBack > 0) {\r
-                       numBack--;\r
-                       continue;\r
-               }\r
+                                       if (textVal.length > 0) {\r
+                                               textNode.value = textVal;\r
+                                               textNode = textNode.prev;\r
+                                       } else {\r
+                                               sibling = textNode.prev;\r
+                                               textNode.remove();\r
+                                               textNode = sibling;\r
+                                       }\r
+                               }\r
+                       };\r
 \r
-               newRelURLParts[newRelURLParts.length] = relURLParts[i];\r
-       }\r
+                       parser = new tinymce.html.SaxParser({\r
+                               validate : validate,\r
+                               fix_self_closing : !validate, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results\r
 \r
-       relURLParts = newRelURLParts.reverse();\r
+                               cdata: function(text) {\r
+                                       node.append(createNode('#cdata', 4)).value = text;\r
+                               },\r
 \r
-       // Remove end from absolute path\r
-       var len = baseURLParts.length-numBack;\r
-       var absPath = (len <= 0 ? "" : "/") + baseURLParts.slice(0, len).join('/') + "/" + relURLParts.join('/');\r
-       var start = "", end = "";\r
+                               text: function(text, raw) {\r
+                                       var textNode;\r
 \r
-       // Build output URL\r
-       relURL.protocol = baseURL.protocol;\r
-       relURL.host = baseURL.host;\r
-       relURL.port = baseURL.port;\r
+                                       // Trim all redundant whitespace on non white space elements\r
+                                       if (!whiteSpaceElements[node.name]) {\r
+                                               text = text.replace(allWhiteSpaceRegExp, ' ');\r
 \r
-       // Re-add trailing slash if it's removed\r
-       if (relURL.path.charAt(relURL.path.length-1) == "/")\r
-               absPath += "/";\r
+                                               if (node.lastChild && blockElements[node.lastChild.name])\r
+                                                       text = text.replace(startWhiteSpaceRegExp, '');\r
+                                       }\r
 \r
-       relURL.path = absPath;\r
+                                       // Do we need to create the node\r
+                                       if (text.length !== 0) {\r
+                                               textNode = createNode('#text', 3);\r
+                                               textNode.raw = !!raw;\r
+                                               node.append(textNode).value = text;\r
+                                       }\r
+                               },\r
+\r
+                               comment: function(text) {\r
+                                       node.append(createNode('#comment', 8)).value = text;\r
+                               },\r
+\r
+                               pi: function(name, text) {\r
+                                       node.append(createNode(name, 7)).value = text;\r
+                                       removeWhitespaceBefore(node);\r
+                               },\r
+\r
+                               doctype: function(text) {\r
+                                       var newNode;\r
+               \r
+                                       newNode = node.append(createNode('#doctype', 10));\r
+                                       newNode.value = text;\r
+                                       removeWhitespaceBefore(node);\r
+                               },\r
+\r
+                               start: function(name, attrs, empty) {\r
+                                       var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent;\r
+\r
+                                       elementRule = validate ? schema.getElementRule(name) : {};\r
+                                       if (elementRule) {\r
+                                               newNode = createNode(elementRule.outputName || name, 1);\r
+                                               newNode.attributes = attrs;\r
+                                               newNode.shortEnded = empty;\r
+\r
+                                               node.append(newNode);\r
+\r
+                                               // Check if node is valid child of the parent node is the child is\r
+                                               // unknown we don't collect it since it's probably a custom element\r
+                                               parent = children[node.name];\r
+                                               if (parent && children[newNode.name] && !parent[newNode.name])\r
+                                                       invalidChildren.push(newNode);\r
+\r
+                                               attrFiltersLen = attributeFilters.length;\r
+                                               while (attrFiltersLen--) {\r
+                                                       attrName = attributeFilters[attrFiltersLen].name;\r
+\r
+                                                       if (attrName in attrs.map) {\r
+                                                               list = matchedAttributes[attrName];\r
+\r
+                                                               if (list)\r
+                                                                       list.push(newNode);\r
+                                                               else\r
+                                                                       matchedAttributes[attrName] = [newNode];\r
+                                                       }\r
+                                               }\r
 \r
-       return TinyMCE.prototype.serializeURL(relURL);\r
-};\r
+                                               // Trim whitespace before block\r
+                                               if (blockElements[name])\r
+                                                       removeWhitespaceBefore(newNode);\r
 \r
-TinyMCE.prototype.getParam = function(name, default_value, strip_whitespace, split_chr) {\r
-       var value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];\r
+                                               // Change current node if the element wasn't empty i.e not <br /> or <img />\r
+                                               if (!empty)\r
+                                                       node = newNode;\r
+                                       }\r
+                               },\r
+\r
+                               end: function(name) {\r
+                                       var textNode, elementRule, text, sibling, tempNode;\r
+\r
+                                       elementRule = validate ? schema.getElementRule(name) : {};\r
+                                       if (elementRule) {\r
+                                               if (blockElements[name]) {\r
+                                                       if (!whiteSpaceElements[node.name]) {\r
+                                                               // Trim whitespace at beginning of block\r
+                                                               for (textNode = node.firstChild; textNode && textNode.type === 3; ) {\r
+                                                                       text = textNode.value.replace(startWhiteSpaceRegExp, '');\r
+\r
+                                                                       if (text.length > 0) {\r
+                                                                               textNode.value = text;\r
+                                                                               textNode = textNode.next;\r
+                                                                       } else {\r
+                                                                               sibling = textNode.next;\r
+                                                                               textNode.remove();\r
+                                                                               textNode = sibling;\r
+                                                                       }\r
+                                                               }\r
+\r
+                                                               // Trim whitespace at end of block\r
+                                                               for (textNode = node.lastChild; textNode && textNode.type === 3; ) {\r
+                                                                       text = textNode.value.replace(endWhiteSpaceRegExp, '');\r
+\r
+                                                                       if (text.length > 0) {\r
+                                                                               textNode.value = text;\r
+                                                                               textNode = textNode.prev;\r
+                                                                       } else {\r
+                                                                               sibling = textNode.prev;\r
+                                                                               textNode.remove();\r
+                                                                               textNode = sibling;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
 \r
-       // Fix bool values\r
-       if (value == "true" || value == "false")\r
-               return (value == "true");\r
+                                                       // Trim start white space\r
+                                                       textNode = node.prev;\r
+                                                       if (textNode && textNode.type === 3) {\r
+                                                               text = textNode.value.replace(startWhiteSpaceRegExp, '');\r
 \r
-       if (strip_whitespace)\r
-               value = tinyMCE.regexpReplace(value, "[ \t\r\n]", "");\r
+                                                               if (text.length > 0)\r
+                                                                       textNode.value = text;\r
+                                                               else\r
+                                                                       textNode.remove();\r
+                                                       }\r
+                                               }\r
 \r
-       if (typeof(split_chr) != "undefined" && split_chr != null) {\r
-               value = value.split(split_chr);\r
-               var outArray = new Array();\r
+                                               // Handle empty nodes\r
+                                               if (elementRule.removeEmpty || elementRule.paddEmpty) {\r
+                                                       if (node.isEmpty(nonEmptyElements)) {\r
+                                                               if (elementRule.paddEmpty)\r
+                                                                       node.empty().append(new Node('#text', '3')).value = '\u00a0';\r
+                                                               else {\r
+                                                                       // Leave nodes that have a name like <a name="name">\r
+                                                                       if (!node.attributes.map.name) {\r
+                                                                               tempNode = node.parent;\r
+                                                                               node.empty().remove();\r
+                                                                               node = tempNode;\r
+                                                                               return;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
 \r
-               for (var i=0; i<value.length; i++) {\r
-                       if (value[i] && value[i] != "")\r
-                               outArray[outArray.length] = value[i];\r
-               }\r
+                                               node = node.parent;\r
+                                       }\r
+                               }\r
+                       }, schema);\r
 \r
-               value = outArray;\r
-       }\r
+                       rootNode = node = new Node(args.context || settings.root_name, 11);\r
 \r
-       return value;\r
-};\r
+                       parser.parse(html);\r
 \r
-TinyMCE.prototype.getLang = function(name, default_value, parse_entities) {\r
-       var value = (typeof(tinyMCELang[name]) == "undefined") ? default_value : tinyMCELang[name];\r
+                       // Fix invalid children or report invalid children in a contextual parsing\r
+                       if (validate && invalidChildren.length) {\r
+                               if (!args.context)\r
+                                       fixInvalidChildren(invalidChildren);\r
+                               else\r
+                                       args.invalid = true;\r
+                       }\r
 \r
-       if (parse_entities)\r
-               value = tinyMCE.entityDecode(value);\r
+                       // Wrap nodes in the root into block elements if the root is body\r
+                       if (rootBlockName && rootNode.name == 'body')\r
+                               addRootBlocks();\r
+\r
+                       // Run filters only when the contents is valid\r
+                       if (!args.invalid) {\r
+                               // Run node filters\r
+                               for (name in matchedNodes) {\r
+                                       list = nodeFilters[name];\r
+                                       nodes = matchedNodes[name];\r
+\r
+                                       // Remove already removed children\r
+                                       fi = nodes.length;\r
+                                       while (fi--) {\r
+                                               if (!nodes[fi].parent)\r
+                                                       nodes.splice(fi, 1);\r
+                                       }\r
 \r
-       return value;\r
-};\r
+                                       for (i = 0, l = list.length; i < l; i++)\r
+                                               list[i](nodes, name, args);\r
+                               }\r
 \r
-TinyMCE.prototype.entityDecode = function(s) {\r
-       var e = document.createElement("div");\r
-       e.innerHTML = s;\r
-       return e.innerHTML;\r
-};\r
+                               // Run attribute filters\r
+                               for (i = 0, l = attributeFilters.length; i < l; i++) {\r
+                                       list = attributeFilters[i];\r
 \r
-TinyMCE.prototype.addToLang = function(prefix, ar) {\r
-       for (var key in ar) {\r
-               if (typeof(ar[key]) == 'function')\r
-                       continue;\r
+                                       if (list.name in matchedAttributes) {\r
+                                               nodes = matchedAttributes[list.name];\r
 \r
-               tinyMCELang[(key.indexOf('lang_') == -1 ? 'lang_' : '') + (prefix != '' ? (prefix + "_") : '') + key] = ar[key];\r
-       }\r
+                                               // Remove already removed children\r
+                                               fi = nodes.length;\r
+                                               while (fi--) {\r
+                                                       if (!nodes[fi].parent)\r
+                                                               nodes.splice(fi, 1);\r
+                                               }\r
 \r
-//     for (var key in ar)\r
-//             tinyMCELang[(key.indexOf('lang_') == -1 ? 'lang_' : '') + (prefix != '' ? (prefix + "_") : '') + key] = "|" + ar[key] + "|";\r
-};\r
+                                               for (fi = 0, fl = list.callbacks.length; fi < fl; fi++)\r
+                                                       list.callbacks[fi](nodes, list.name, args);\r
+                                       }\r
+                               }\r
+                       }\r
 \r
-TinyMCE.prototype.replaceVar = function(replace_haystack, replace_var, replace_str) {\r
-       var re = new RegExp('{\\\$' + replace_var + '}', 'g');\r
-       return replace_haystack.replace(re, replace_str);\r
-};\r
+                       return rootNode;\r
+               };\r
+\r
+               // Remove <br> at end of block elements Gecko and WebKit injects BR elements to\r
+               // make it possible to place the caret inside empty blocks. This logic tries to remove\r
+               // these elements and keep br elements that where intended to be there intact\r
+               if (settings.remove_trailing_brs) {\r
+                       self.addNodeFilter('br', function(nodes, name) {\r
+                               var i, l = nodes.length, node, blockElements = schema.getBlockElements(),\r
+                                       nonEmptyElements = schema.getNonEmptyElements(), parent, prev, prevName;\r
+\r
+                               // Remove brs from body element as well\r
+                               blockElements.body = 1;\r
+\r
+                               // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p>\r
+                               for (i = 0; i < l; i++) {\r
+                                       node = nodes[i];\r
+                                       parent = node.parent;\r
+\r
+                                       if (blockElements[node.parent.name] && node === parent.lastChild) {\r
+                                               // Loop all nodes to the right of the current node and check for other BR elements\r
+                                               // excluding bookmarks since they are invisible\r
+                                               prev = node.prev;\r
+                                               while (prev) {\r
+                                                       prevName = prev.name;\r
+\r
+                                                       // Ignore bookmarks\r
+                                                       if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') {\r
+                                                               // Found a non BR element\r
+                                                               if (prevName !== "br")\r
+                                                                       break;\r
+       \r
+                                                               // Found another br it's a <br><br> structure then don't remove anything\r
+                                                               if (prevName === 'br') {\r
+                                                                       node = null;\r
+                                                                       break;\r
+                                                               }\r
+                                                       }\r
 \r
-TinyMCE.prototype.replaceVars = function(replace_haystack, replace_vars) {\r
-       for (var key in replace_vars) {\r
-               var value = replace_vars[key];\r
-               if (typeof(value) == 'function')\r
-                       continue;\r
+                                                       prev = prev.prev;\r
+                                               }\r
 \r
-               replace_haystack = tinyMCE.replaceVar(replace_haystack, key, value);\r
+                                               if (node) {\r
+                                                       node.remove();\r
+\r
+                                                       // Is the parent to be considered empty after we removed the BR\r
+                                                       if (parent.isEmpty(nonEmptyElements)) {\r
+                                                               elementRule = schema.getElementRule(parent.name);\r
+\r
+                                                               // Remove or padd the element depending on schema rule\r
+                                                               if (elementRule) {\r
+                                                                 if (elementRule.removeEmpty)\r
+                                                                         parent.remove();\r
+                                                                 else if (elementRule.paddEmpty)\r
+                                                                         parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0';\r
+                                                         }\r
+              }\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
        }\r
+})(tinymce);\r
 \r
-       return replace_haystack;\r
-};\r
+tinymce.html.Writer = function(settings) {\r
+       var html = [], indent, indentBefore, indentAfter, encode, htmlOutput;\r
 \r
-TinyMCE.prototype.triggerNodeChange = function(focus, setup_content) {\r
-       if (tinyMCE.settings['handleNodeChangeCallback']) {\r
-               if (tinyMCE.selectedInstance) {\r
-                       var inst = tinyMCE.selectedInstance;\r
-                       var editorId = inst.editorId;\r
-                       var elm = (typeof(setup_content) != "undefined" && setup_content) ? tinyMCE.selectedElement : inst.getFocusElement();\r
-                       var undoIndex = -1;\r
-                       var undoLevels = -1;\r
-                       var anySelection = false;\r
-                       var selectedText = inst.getSelectedText();\r
+       settings = settings || {};\r
+       indent = settings.indent;\r
+       indentBefore = tinymce.makeMap(settings.indent_before || '');\r
+       indentAfter = tinymce.makeMap(settings.indent_after || '');\r
+       encode = tinymce.html.Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);\r
+       htmlOutput = settings.element_format == "html";\r
 \r
-                       inst.switchSettings();\r
+       return {\r
+               start: function(name, attrs, empty) {\r
+                       var i, l, attr, value;\r
 \r
-                       if (tinyMCE.settings["auto_resize"]) {\r
-                               var doc = inst.getDoc();\r
+                       if (indent && indentBefore[name] && html.length > 0) {\r
+                               value = html[html.length - 1];\r
 \r
-                               inst.iframeElement.style.width = doc.body.offsetWidth + "px";\r
-                               inst.iframeElement.style.height = doc.body.offsetHeight + "px";\r
+                               if (value.length > 0 && value !== '\n')\r
+                                       html.push('\n');\r
                        }\r
 \r
-                       if (tinyMCE.selectedElement)\r
-                               anySelection = (tinyMCE.selectedElement.nodeName.toLowerCase() == "img") || (selectedText && selectedText.length > 0);\r
+                       html.push('<', name);\r
 \r
-                       if (tinyMCE.settings['custom_undo_redo']) {\r
-                               undoIndex = inst.undoIndex;\r
-                               undoLevels = inst.undoLevels.length;\r
+                       if (attrs) {\r
+                               for (i = 0, l = attrs.length; i < l; i++) {\r
+                                       attr = attrs[i];\r
+                                       html.push(' ', attr.name, '="', encode(attr.value, true), '"');\r
+                               }\r
                        }\r
 \r
-                       tinyMCE.executeCallback('handleNodeChangeCallback', '_handleNodeChange', 0, editorId, elm, undoIndex, undoLevels, inst.visualAid, anySelection, setup_content);\r
-               }\r
-       }\r
+                       if (!empty || htmlOutput)\r
+                               html[html.length] = '>';\r
+                       else\r
+                               html[html.length] = ' />';\r
 \r
-       if (this.selectedInstance && (typeof(focus) == "undefined" || focus))\r
-               this.selectedInstance.contentWindow.focus();\r
-};\r
+                       if (empty && indent && indentAfter[name] && html.length > 0) {\r
+                               value = html[html.length - 1];\r
 \r
-TinyMCE.prototype._customCleanup = function(inst, type, content) {\r
-       // Call custom cleanup\r
-       var customCleanup = tinyMCE.settings['cleanup_callback'];\r
-       if (customCleanup != "" && eval("typeof(" + customCleanup + ")") != "undefined")\r
-               content = eval(customCleanup + "(type, content, inst);");\r
-\r
-       // Trigger plugin cleanups\r
-       var plugins = tinyMCE.getParam('plugins', '', true, ',');\r
-       for (var i=0; i<plugins.length; i++) {\r
-               if (eval("typeof(TinyMCE_" + plugins[i] +  "_cleanup)") != "undefined")\r
-                       content = eval("TinyMCE_" + plugins[i] +  "_cleanup(type, content, inst);");\r
-       }\r
+                               if (value.length > 0 && value !== '\n')\r
+                                       html.push('\n');\r
+                       }\r
+               },\r
 \r
-       return content;\r
-};\r
+               end: function(name) {\r
+                       var value;\r
 \r
-TinyMCE.prototype.getContent = function(editor_id) {\r
-       if (typeof(editor_id) != "undefined")\r
-               tinyMCE.selectedInstance = tinyMCE.getInstanceById(editor_id);\r
+                       /*if (indent && indentBefore[name] && html.length > 0) {\r
+                               value = html[html.length - 1];\r
 \r
-       if (tinyMCE.selectedInstance) {\r
-               var old = this.selectedInstance.getBody().innerHTML;\r
-               var html = tinyMCE._cleanupHTML(this.selectedInstance, this.selectedInstance.getDoc(), tinyMCE.settings, this.selectedInstance.getBody(), false, true);\r
-               tinyMCE.setInnerHTML(this.selectedInstance.getBody(), old);\r
-               return html;\r
-       }\r
+                               if (value.length > 0 && value !== '\n')\r
+                                       html.push('\n');\r
+                       }*/\r
 \r
-       return null;\r
-};\r
+                       html.push('</', name, '>');\r
 \r
-TinyMCE.prototype.setContent = function(html_content) {\r
-       if (tinyMCE.selectedInstance) {\r
-               tinyMCE.selectedInstance.execCommand('mceSetContent', false, html_content);\r
-               tinyMCE.selectedInstance.repaint();\r
-       }\r
-};\r
+                       if (indent && indentAfter[name] && html.length > 0) {\r
+                               value = html[html.length - 1];\r
 \r
-TinyMCE.prototype.importThemeLanguagePack = function(name) {\r
-       if (typeof(name) == "undefined")\r
-               name = tinyMCE.settings['theme'];\r
+                               if (value.length > 0 && value !== '\n')\r
+                                       html.push('\n');\r
+                       }\r
+               },\r
 \r
-       tinyMCE.loadScript(tinyMCE.baseURL + '/themes/' + name + '/langs/' + tinyMCE.settings['language'] + '.js');\r
-};\r
+               text: function(text, raw) {\r
+                       if (text.length > 0)\r
+                               html[html.length] = raw ? text : encode(text);\r
+               },\r
 \r
-TinyMCE.prototype.importPluginLanguagePack = function(name, valid_languages) {\r
-       var lang = "en";\r
+               cdata: function(text) {\r
+                       html.push('<![CDATA[', text, ']]>');\r
+               },\r
 \r
-       valid_languages = valid_languages.split(',');\r
-       for (var i=0; i<valid_languages.length; i++) {\r
-               if (tinyMCE.settings['language'] == valid_languages[i])\r
-                       lang = tinyMCE.settings['language'];\r
-       }\r
+               comment: function(text) {\r
+                       html.push('<!--', text, '-->');\r
+               },\r
 \r
-       tinyMCE.loadScript(tinyMCE.baseURL + '/plugins/' + name + '/langs/' + lang +  '.js');\r
-};\r
+               pi: function(name, text) {\r
+                       if (text)\r
+                               html.push('<?', name, ' ', text, '?>');\r
+                       else\r
+                               html.push('<?', name, '?>');\r
 \r
-/**\r
- * Adds themeurl, settings and lang to HTML code.\r
- */\r
-TinyMCE.prototype.applyTemplate = function(html, args) {\r
-       html = tinyMCE.replaceVar(html, "themeurl", tinyMCE.themeURL);\r
+                       if (indent)\r
+                               html.push('\n');\r
+               },\r
 \r
-       if (typeof(args) != "undefined")\r
-               html = tinyMCE.replaceVars(html, args);\r
+               doctype: function(text) {\r
+                       html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');\r
+               },\r
 \r
-       html = tinyMCE.replaceVars(html, tinyMCE.settings);\r
-       html = tinyMCE.replaceVars(html, tinyMCELang);\r
+               reset: function() {\r
+                       html.length = 0;\r
+               },\r
 \r
-       return html;\r
+               getContent: function() {\r
+                       return html.join('').replace(/\n$/, '');\r
+               }\r
+       };\r
 };\r
 \r
-TinyMCE.prototype.openWindow = function(template, args) {\r
-       var html, width, height, x, y, resizable, scrollbars, url;\r
-\r
-       args['mce_template_file'] = template['file'];\r
-       args['mce_width'] = template['width'];\r
-       args['mce_height'] = template['height'];\r
-       tinyMCE.windowArgs = args;\r
+(function(tinymce) {\r
+       tinymce.html.Serializer = function(settings, schema) {\r
+               var self = this, writer = new tinymce.html.Writer(settings);\r
+\r
+               settings = settings || {};\r
+               settings.validate = "validate" in settings ? settings.validate : true;\r
+\r
+               self.schema = schema = schema || new tinymce.html.Schema();\r
+               self.writer = writer;\r
+\r
+               self.serialize = function(node) {\r
+                       var handlers, validate;\r
+\r
+                       validate = settings.validate;\r
+\r
+                       handlers = {\r
+                               // #text\r
+                               3: function(node, raw) {\r
+                                       writer.text(node.value, node.raw);\r
+                               },\r
+\r
+                               // #comment\r
+                               8: function(node) {\r
+                                       writer.comment(node.value);\r
+                               },\r
+\r
+                               // Processing instruction\r
+                               7: function(node) {\r
+                                       writer.pi(node.name, node.value);\r
+                               },\r
+\r
+                               // Doctype\r
+                               10: function(node) {\r
+                                       writer.doctype(node.value);\r
+                               },\r
+\r
+                               // CDATA\r
+                               4: function(node) {\r
+                                       writer.cdata(node.value);\r
+                               },\r
+\r
+                               // Document fragment\r
+                               11: function(node) {\r
+                                       if ((node = node.firstChild)) {\r
+                                               do {\r
+                                                       walk(node);\r
+                                               } while (node = node.next);\r
+                                       }\r
+                               }\r
+                       };\r
 \r
-       html = template['html'];\r
-       if (!(width = parseInt(template['width'])))\r
-               width = 320;\r
+                       writer.reset();\r
 \r
-       if (!(height = parseInt(template['height'])))\r
-               height = 200;\r
+                       function walk(node) {\r
+                               var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;\r
 \r
-       // Add to height in M$ due to SP2 WHY DON'T YOU GUYS IMPLEMENT innerWidth of windows!!\r
-       if (tinyMCE.isMSIE)\r
-               height += 40;\r
-       else\r
-               height += 20;\r
+                               if (!handler) {\r
+                                       name = node.name;\r
+                                       isEmpty = node.shortEnded;\r
+                                       attrs = node.attributes;\r
 \r
-       x = parseInt(screen.width / 2.0) - (width / 2.0);\r
-       y = parseInt(screen.height / 2.0) - (height / 2.0);\r
+                                       // Sort attributes\r
+                                       if (validate && attrs && attrs.length > 1) {\r
+                                               sortedAttrs = [];\r
+                                               sortedAttrs.map = {};\r
 \r
-       resizable = (args && args['resizable']) ? args['resizable'] : "no";\r
-       scrollbars = (args && args['scrollbars']) ? args['scrollbars'] : "no";\r
+                                               elementRule = schema.getElementRule(node.name);\r
+                                               for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {\r
+                                                       attrName = elementRule.attributesOrder[i];\r
 \r
-       if (template['file'].charAt(0) != '/' && template['file'].indexOf('://') == -1)\r
-               url = tinyMCE.baseURL + "/themes/" + tinyMCE.getParam("theme") + "/" + template['file'];\r
-       else\r
-               url = template['file'];\r
+                                                       if (attrName in attrs.map) {\r
+                                                               attrValue = attrs.map[attrName];\r
+                                                               sortedAttrs.map[attrName] = attrValue;\r
+                                                               sortedAttrs.push({name: attrName, value: attrValue});\r
+                                                       }\r
+                                               }\r
 \r
-       // Replace all args as variables in URL\r
-       for (var name in args) {\r
-               if (typeof(args[name]) == 'function')\r
-                       continue;\r
+                                               for (i = 0, l = attrs.length; i < l; i++) {\r
+                                                       attrName = attrs[i].name;\r
 \r
-               url = tinyMCE.replaceVar(url, name, escape(args[name]));\r
-       }\r
+                                                       if (!(attrName in sortedAttrs.map)) {\r
+                                                               attrValue = attrs.map[attrName];\r
+                                                               sortedAttrs.map[attrName] = attrValue;\r
+                                                               sortedAttrs.push({name: attrName, value: attrValue});\r
+                                                       }\r
+                                               }\r
 \r
-       if (html) {\r
-               html = tinyMCE.replaceVar(html, "css", this.settings['popups_css']);\r
-               html = tinyMCE.applyTemplate(html, args);\r
+                                               attrs = sortedAttrs;\r
+                                       }\r
 \r
-               var win = window.open("", "mcePopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=yes,minimizable=" + resizable + ",modal=yes,width=" + width + ",height=" + height + ",resizable=" + resizable);\r
-               if (win == null) {\r
-                       alert(tinyMCELang['lang_popup_blocked']);\r
-                       return;\r
-               }\r
+                                       writer.start(node.name, attrs, isEmpty);\r
 \r
-               win.document.write(html);\r
-               win.document.close();\r
-               win.resizeTo(width, height);\r
-               win.focus();\r
-       } else {\r
-               if ((tinyMCE.isMSIE && !tinyMCE.isOpera) && resizable != 'yes' && tinyMCE.settings["dialog_type"] == "modal") {\r
-            var features = "resizable:" + resizable \r
-                + ";scroll:"\r
-                + scrollbars + ";status:yes;center:yes;help:no;dialogWidth:"\r
-                + width + "px;dialogHeight:" + height + "px;";\r
+                                       if (!isEmpty) {\r
+                                               if ((node = node.firstChild)) {\r
+                                                       do {\r
+                                                               walk(node);\r
+                                                       } while (node = node.next);\r
+                                               }\r
 \r
-                       window.showModalDialog(url, window, features);\r
-               } else {\r
-                       var modal = (resizable == "yes") ? "no" : "yes";\r
+                                               writer.end(name);\r
+                                       }\r
+                               } else\r
+                                       handler(node);\r
+                       }\r
 \r
-                       if (tinyMCE.isGecko && tinyMCE.isMac)\r
-                               modal = "no";\r
+                       // Serialize element and treat all non elements as fragments\r
+                       if (node.type == 1 && !settings.inner)\r
+                               walk(node);\r
+                       else\r
+                               handlers[11](node);\r
 \r
-                       if (template['close_previous'] != "no")\r
-                               try {tinyMCE.lastWindow.close();} catch (ex) {}\r
+                       return writer.getContent();\r
+               };\r
+       }\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       // Shorten names\r
+       var each = tinymce.each,\r
+               is = tinymce.is,\r
+               isWebKit = tinymce.isWebKit,\r
+               isIE = tinymce.isIE,\r
+               Entities = tinymce.html.Entities,\r
+               simpleSelectorRe = /^([a-z0-9],?)+$/i,\r
+               blockElementsMap = tinymce.html.Schema.blockElementsMap,\r
+               whiteSpaceRegExp = /^[ \t\r\n]*$/;\r
+\r
+       tinymce.create('tinymce.dom.DOMUtils', {\r
+               doc : null,\r
+               root : null,\r
+               files : null,\r
+               pixelStyles : /^(top|left|bottom|right|width|height|borderWidth)$/,\r
+               props : {\r
+                       "for" : "htmlFor",\r
+                       "class" : "className",\r
+                       className : "className",\r
+                       checked : "checked",\r
+                       disabled : "disabled",\r
+                       maxlength : "maxLength",\r
+                       readonly : "readOnly",\r
+                       selected : "selected",\r
+                       value : "value",\r
+                       id : "id",\r
+                       name : "name",\r
+                       type : "type"\r
+               },\r
+\r
+               DOMUtils : function(d, s) {\r
+                       var t = this, globalStyle, name;\r
+\r
+                       t.doc = d;\r
+                       t.win = window;\r
+                       t.files = {};\r
+                       t.cssFlicker = false;\r
+                       t.counter = 0;\r
+                       t.stdMode = !tinymce.isIE || d.documentMode >= 8;\r
+                       t.boxModel = !tinymce.isIE || d.compatMode == "CSS1Compat" || t.stdMode;\r
+                       t.hasOuterHTML = "outerHTML" in d.createElement("a");\r
+\r
+                       t.settings = s = tinymce.extend({\r
+                               keep_values : false,\r
+                               hex_colors : 1\r
+                       }, s);\r
+                       \r
+                       t.schema = s.schema;\r
+                       t.styles = new tinymce.html.Styles({\r
+                               url_converter : s.url_converter,\r
+                               url_converter_scope : s.url_converter_scope\r
+                       }, s.schema);\r
+\r
+                       // Fix IE6SP2 flicker and check it failed for pre SP2\r
+                       if (tinymce.isIE6) {\r
+                               try {\r
+                                       d.execCommand('BackgroundImageCache', false, true);\r
+                               } catch (e) {\r
+                                       t.cssFlicker = true;\r
+                               }\r
+                       }\r
 \r
-                       var win = window.open(url, "mcePopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=" + modal + ",minimizable=" + resizable + ",modal=" + modal + ",width=" + width + ",height=" + height + ",resizable=" + resizable);\r
-                       if (win == null) {\r
-                               alert(tinyMCELang['lang_popup_blocked']);\r
-                               return;\r
+                       if (isIE && s.schema) {\r
+                               // Add missing HTML 4/5 elements to IE\r
+                               ('abbr article aside audio canvas ' +\r
+                               'details figcaption figure footer ' +\r
+                               'header hgroup mark menu meter nav ' +\r
+                               'output progress section summary ' +\r
+                               'time video').replace(/\w+/g, function(name) {\r
+                                       d.createElement(name);\r
+                               });\r
+\r
+                               // Create all custom elements\r
+                               for (name in s.schema.getCustomElements()) {\r
+                                       d.createElement(name);\r
+                               }\r
                        }\r
 \r
-                       if (template['close_previous'] != "no")\r
-                               tinyMCE.lastWindow = win;\r
+                       tinymce.addUnload(t.destroy, t);\r
+               },\r
 \r
-                       eval('try { win.resizeTo(width, height); } catch(e) { }');\r
+               getRoot : function() {\r
+                       var t = this, s = t.settings;\r
 \r
-                       // Make it bigger if statusbar is forced\r
-                       if (tinyMCE.isGecko) {\r
-                               if (win.document.defaultView.statusbar.visible)\r
-                                       win.resizeBy(0, tinyMCE.isMac ? 10 : 24);\r
-                       }\r
+                       return (s && t.get(s.root_element)) || t.doc.body;\r
+               },\r
 \r
-                       win.focus();\r
-               }\r
-       }\r
-};\r
+               getViewPort : function(w) {\r
+                       var d, b;\r
 \r
-TinyMCE.prototype.closeWindow = function(win) {\r
-       win.close();\r
-};\r
+                       w = !w ? this.win : w;\r
+                       d = w.document;\r
+                       b = this.boxModel ? d.documentElement : d.body;\r
 \r
-TinyMCE.prototype.getVisualAidClass = function(class_name, state) {\r
-       var aidClass = tinyMCE.settings['visual_table_class'];\r
+                       // Returns viewport size excluding scrollbars\r
+                       return {\r
+                               x : w.pageXOffset || b.scrollLeft,\r
+                               y : w.pageYOffset || b.scrollTop,\r
+                               w : w.innerWidth || b.clientWidth,\r
+                               h : w.innerHeight || b.clientHeight\r
+                       };\r
+               },\r
 \r
-       if (typeof(state) == "undefined")\r
-               state = tinyMCE.settings['visual'];\r
+               getRect : function(e) {\r
+                       var p, t = this, sr;\r
 \r
-       // Split\r
-       var classNames = new Array();\r
-       var ar = class_name.split(' ');\r
-       for (var i=0; i<ar.length; i++) {\r
-               if (ar[i] == aidClass)\r
-                       ar[i] = "";\r
+                       e = t.get(e);\r
+                       p = t.getPos(e);\r
+                       sr = t.getSize(e);\r
 \r
-               if (ar[i] != "")\r
-                       classNames[classNames.length] = ar[i];\r
-       }\r
+                       return {\r
+                               x : p.x,\r
+                               y : p.y,\r
+                               w : sr.w,\r
+                               h : sr.h\r
+                       };\r
+               },\r
 \r
-       if (state)\r
-               classNames[classNames.length] = aidClass;\r
+               getSize : function(e) {\r
+                       var t = this, w, h;\r
 \r
-       // Glue\r
-       var className = "";\r
-       for (var i=0; i<classNames.length; i++) {\r
-               if (i > 0)\r
-                       className += " ";\r
+                       e = t.get(e);\r
+                       w = t.getStyle(e, 'width');\r
+                       h = t.getStyle(e, 'height');\r
 \r
-               className += classNames[i];\r
-       }\r
+                       // Non pixel value, then force offset/clientWidth\r
+                       if (w.indexOf('px') === -1)\r
+                               w = 0;\r
 \r
-       return className;\r
-};\r
+                       // Non pixel value, then force offset/clientWidth\r
+                       if (h.indexOf('px') === -1)\r
+                               h = 0;\r
 \r
-TinyMCE.prototype.handleVisualAid = function(el, deep, state, inst) {\r
-       if (!el)\r
-               return;\r
+                       return {\r
+                               w : parseInt(w) || e.offsetWidth || e.clientWidth,\r
+                               h : parseInt(h) || e.offsetHeight || e.clientHeight\r
+                       };\r
+               },\r
 \r
-       var tableElement = null;\r
+               getParent : function(n, f, r) {\r
+                       return this.getParents(n, f, r, false);\r
+               },\r
 \r
-       switch (el.nodeName) {\r
-               case "TABLE":\r
-                       var oldW = el.style.width;\r
-                       var oldH = el.style.height;\r
-                       var bo = tinyMCE.getAttrib(el, "border");\r
+               getParents : function(n, f, r, c) {\r
+                       var t = this, na, se = t.settings, o = [];\r
 \r
-                       bo = bo == "" || bo == "0" ? true : false;\r
+                       n = t.get(n);\r
+                       c = c === undefined;\r
 \r
-                       tinyMCE.setAttrib(el, "class", tinyMCE.getVisualAidClass(tinyMCE.getAttrib(el, "class"), state && bo));\r
+                       if (se.strict_root)\r
+                               r = r || t.getRoot();\r
 \r
-                       el.style.width = oldW;\r
-                       el.style.height = oldH;\r
+                       // Wrap node name as func\r
+                       if (is(f, 'string')) {\r
+                               na = f;\r
 \r
-                       for (var y=0; y<el.rows.length; y++) {\r
-                               for (var x=0; x<el.rows[y].cells.length; x++) {\r
-                                       var cn = tinyMCE.getVisualAidClass(tinyMCE.getAttrib(el.rows[y].cells[x], "class"), state && bo);\r
-                                       tinyMCE.setAttrib(el.rows[y].cells[x], "class", cn);\r
+                               if (f === '*') {\r
+                                       f = function(n) {return n.nodeType == 1;};\r
+                               } else {\r
+                                       f = function(n) {\r
+                                               return t.is(n, na);\r
+                                       };\r
                                }\r
                        }\r
 \r
-                       break;\r
+                       while (n) {\r
+                               if (n == r || !n.nodeType || n.nodeType === 9)\r
+                                       break;\r
 \r
-               case "A":\r
-                       var anchorName = tinyMCE.getAttrib(el, "name");\r
+                               if (!f || f(n)) {\r
+                                       if (c)\r
+                                               o.push(n);\r
+                                       else\r
+                                               return n;\r
+                               }\r
 \r
-                       if (anchorName != '' && state) {\r
-                               el.title = anchorName;\r
-                               el.className = 'mceItemAnchor';\r
-                       } else if (anchorName != '' && !state)\r
-                               el.className = '';\r
+                               n = n.parentNode;\r
+                       }\r
 \r
-                       break;\r
-       }\r
+                       return c ? o : null;\r
+               },\r
 \r
-       if (deep && el.hasChildNodes()) {\r
-               for (var i=0; i<el.childNodes.length; i++)\r
-                       tinyMCE.handleVisualAid(el.childNodes[i], deep, state, inst);\r
-       }\r
-};\r
+               get : function(e) {\r
+                       var n;\r
 \r
-TinyMCE.prototype.getAttrib = function(elm, name, default_value) {\r
-       if (typeof(default_value) == "undefined")\r
-               default_value = "";\r
+                       if (e && this.doc && typeof(e) == 'string') {\r
+                               n = e;\r
+                               e = this.doc.getElementById(e);\r
 \r
-       // Not a element\r
-       if (!elm || elm.nodeType != 1)\r
-               return default_value;\r
+                               // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick\r
+                               if (e && e.id !== n)\r
+                                       return this.doc.getElementsByName(n)[1];\r
+                       }\r
 \r
-       var v = elm.getAttribute(name);\r
+                       return e;\r
+               },\r
 \r
-       // Try className for class attrib\r
-       if (name == "class" && !v)\r
-               v = elm.className;\r
+               getNext : function(node, selector) {\r
+                       return this._findSib(node, selector, 'nextSibling');\r
+               },\r
 \r
-       // Workaround for a issue with Firefox 1.5rc2+\r
-       if (tinyMCE.isGecko && name == "src" && elm.src != null && elm.src != "")\r
-               v = elm.src;\r
+               getPrev : function(node, selector) {\r
+                       return this._findSib(node, selector, 'previousSibling');\r
+               },\r
 \r
-       // Workaround for a issue with Firefox 1.5rc2+\r
-       if (tinyMCE.isGecko && name == "href" && elm.href != null && elm.href != "")\r
-               v = elm.href;\r
 \r
-       if (name == "style" && !tinyMCE.isOpera)\r
-               v = elm.style.cssText;\r
+               select : function(pa, s) {\r
+                       var t = this;\r
 \r
-       return (v && v != "") ? v : default_value;\r
-};\r
+                       return tinymce.dom.Sizzle(pa, t.get(s) || t.get(t.settings.root_element) || t.doc, []);\r
+               },\r
 \r
-TinyMCE.prototype.setAttrib = function(element, name, value, fix_value) {\r
-       if (typeof(value) == "number" && value != null)\r
-               value = "" + value;\r
+               is : function(n, selector) {\r
+                       var i;\r
 \r
-       if (fix_value) {\r
-               if (value == null)\r
-                       value = "";\r
+                       // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance\r
+                       if (n.length === undefined) {\r
+                               // Simple all selector\r
+                               if (selector === '*')\r
+                                       return n.nodeType == 1;\r
 \r
-               var re = new RegExp('[^0-9%]', 'g');\r
-               value = value.replace(re, '');\r
-       }\r
+                               // Simple selector just elements\r
+                               if (simpleSelectorRe.test(selector)) {\r
+                                       selector = selector.toLowerCase().split(/,/);\r
+                                       n = n.nodeName.toLowerCase();\r
 \r
-       if (name == "style")\r
-               element.style.cssText = value;\r
+                                       for (i = selector.length - 1; i >= 0; i--) {\r
+                                               if (selector[i] == n)\r
+                                                       return true;\r
+                                       }\r
 \r
-       if (name == "class")\r
-               element.className = value;\r
+                                       return false;\r
+                               }\r
+                       }\r
 \r
-       if (value != null && value != "" && value != -1)\r
-               element.setAttribute(name, value);\r
-       else\r
-               element.removeAttribute(name);\r
+                       return tinymce.dom.Sizzle.matches(selector, n.nodeType ? [n] : n).length > 0;\r
+               },\r
+\r
+\r
+               add : function(p, n, a, h, c) {\r
+                       var t = this;\r
+\r
+                       return this.run(p, function(p) {\r
+                               var e, k;\r
+\r
+                               e = is(n, 'string') ? t.doc.createElement(n) : n;\r
+                               t.setAttribs(e, a);\r
+\r
+                               if (h) {\r
+                                       if (h.nodeType)\r
+                                               e.appendChild(h);\r
+                                       else\r
+                                               t.setHTML(e, h);\r
+                               }\r
+\r
+                               return !c ? p.appendChild(e) : e;\r
+                       });\r
+               },\r
+\r
+               create : function(n, a, h) {\r
+                       return this.add(this.doc.createElement(n), n, a, h, 1);\r
+               },\r
+\r
+               createHTML : function(n, a, h) {\r
+                       var o = '', t = this, k;\r
+\r
+                       o += '<' + n;\r
+\r
+                       for (k in a) {\r
+                               if (a.hasOwnProperty(k))\r
+                                       o += ' ' + k + '="' + t.encode(a[k]) + '"';\r
+                       }\r
+\r
+                       // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime\r
+                       if (typeof(h) != "undefined")\r
+                               return o + '>' + h + '</' + n + '>';\r
+\r
+                       return o + ' />';\r
+               },\r
+\r
+               remove : function(node, keep_children) {\r
+                       return this.run(node, function(node) {\r
+                               var child, parent = node.parentNode;\r
+\r
+                               if (!parent)\r
+                                       return null;\r
+\r
+                               if (keep_children) {\r
+                                       while (child = node.firstChild) {\r
+                                               // IE 8 will crash if you don't remove completely empty text nodes\r
+                                               if (!tinymce.isIE || child.nodeType !== 3 || child.nodeValue)\r
+                                                       parent.insertBefore(child, node);\r
+                                               else\r
+                                                       node.removeChild(child);\r
+                                       }\r
+                               }\r
+\r
+                               return parent.removeChild(node);\r
+                       });\r
+               },\r
+\r
+               setStyle : function(n, na, v) {\r
+                       var t = this;\r
+\r
+                       return t.run(n, function(e) {\r
+                               var s, i;\r
+\r
+                               s = e.style;\r
+\r
+                               // Camelcase it, if needed\r
+                               na = na.replace(/-(\D)/g, function(a, b){\r
+                                       return b.toUpperCase();\r
+                               });\r
+\r
+                               // Default px suffix on these\r
+                               if (t.pixelStyles.test(na) && (tinymce.is(v, 'number') || /^[\-0-9\.]+$/.test(v)))\r
+                                       v += 'px';\r
+\r
+                               switch (na) {\r
+                                       case 'opacity':\r
+                                               // IE specific opacity\r
+                                               if (isIE) {\r
+                                                       s.filter = v === '' ? '' : "alpha(opacity=" + (v * 100) + ")";\r
+\r
+                                                       if (!n.currentStyle || !n.currentStyle.hasLayout)\r
+                                                               s.display = 'inline-block';\r
+                                               }\r
+\r
+                                               // Fix for older browsers\r
+                                               s[na] = s['-moz-opacity'] = s['-khtml-opacity'] = v || '';\r
+                                               break;\r
+\r
+                                       case 'float':\r
+                                               isIE ? s.styleFloat = v : s.cssFloat = v;\r
+                                               break;\r
+                                       \r
+                                       default:\r
+                                               s[na] = v || '';\r
+                               }\r
+\r
+                               // Force update of the style data\r
+                               if (t.settings.update_styles)\r
+                                       t.setAttrib(e, 'data-mce-style');\r
+                       });\r
+               },\r
+\r
+               getStyle : function(n, na, c) {\r
+                       n = this.get(n);\r
+\r
+                       if (!n)\r
+                               return;\r
+\r
+                       // Gecko\r
+                       if (this.doc.defaultView && c) {\r
+                               // Remove camelcase\r
+                               na = na.replace(/[A-Z]/g, function(a){\r
+                                       return '-' + a;\r
+                               });\r
+\r
+                               try {\r
+                                       return this.doc.defaultView.getComputedStyle(n, null).getPropertyValue(na);\r
+                               } catch (ex) {\r
+                                       // Old safari might fail\r
+                                       return null;\r
+                               }\r
+                       }\r
+\r
+                       // Camelcase it, if needed\r
+                       na = na.replace(/-(\D)/g, function(a, b){\r
+                               return b.toUpperCase();\r
+                       });\r
+\r
+                       if (na == 'float')\r
+                               na = isIE ? 'styleFloat' : 'cssFloat';\r
+\r
+                       // IE & Opera\r
+                       if (n.currentStyle && c)\r
+                               return n.currentStyle[na];\r
+\r
+                       return n.style ? n.style[na] : undefined;\r
+               },\r
+\r
+               setStyles : function(e, o) {\r
+                       var t = this, s = t.settings, ol;\r
+\r
+                       ol = s.update_styles;\r
+                       s.update_styles = 0;\r
+\r
+                       each(o, function(v, n) {\r
+                               t.setStyle(e, n, v);\r
+                       });\r
+\r
+                       // Update style info\r
+                       s.update_styles = ol;\r
+                       if (s.update_styles)\r
+                               t.setAttrib(e, s.cssText);\r
+               },\r
+\r
+               removeAllAttribs: function(e) {\r
+                       return this.run(e, function(e) {\r
+                               var i, attrs = e.attributes;\r
+                               for (i = attrs.length - 1; i >= 0; i--) {\r
+                                       e.removeAttributeNode(attrs.item(i));\r
+                               }\r
+                       });\r
+               },\r
+\r
+               setAttrib : function(e, n, v) {\r
+                       var t = this;\r
+\r
+                       // Whats the point\r
+                       if (!e || !n)\r
+                               return;\r
+\r
+                       // Strict XML mode\r
+                       if (t.settings.strict)\r
+                               n = n.toLowerCase();\r
+\r
+                       return this.run(e, function(e) {\r
+                               var s = t.settings;\r
+\r
+                               switch (n) {\r
+                                       case "style":\r
+                                               if (!is(v, 'string')) {\r
+                                                       each(v, function(v, n) {\r
+                                                               t.setStyle(e, n, v);\r
+                                                       });\r
+\r
+                                                       return;\r
+                                               }\r
+\r
+                                               // No mce_style for elements with these since they might get resized by the user\r
+                                               if (s.keep_values) {\r
+                                                       if (v && !t._isRes(v))\r
+                                                               e.setAttribute('data-mce-style', v, 2);\r
+                                                       else\r
+                                                               e.removeAttribute('data-mce-style', 2);\r
+                                               }\r
+\r
+                                               e.style.cssText = v;\r
+                                               break;\r
+\r
+                                       case "class":\r
+                                               e.className = v || ''; // Fix IE null bug\r
+                                               break;\r
+\r
+                                       case "src":\r
+                                       case "href":\r
+                                               if (s.keep_values) {\r
+                                                       if (s.url_converter)\r
+                                                               v = s.url_converter.call(s.url_converter_scope || t, v, n, e);\r
+\r
+                                                       t.setAttrib(e, 'data-mce-' + n, v, 2);\r
+                                               }\r
+\r
+                                               break;\r
+\r
+                                       case "shape":\r
+                                               e.setAttribute('data-mce-style', v);\r
+                                               break;\r
+                               }\r
+\r
+                               if (is(v) && v !== null && v.length !== 0)\r
+                                       e.setAttribute(n, '' + v, 2);\r
+                               else\r
+                                       e.removeAttribute(n, 2);\r
+                       });\r
+               },\r
+\r
+               setAttribs : function(e, o) {\r
+                       var t = this;\r
+\r
+                       return this.run(e, function(e) {\r
+                               each(o, function(v, n) {\r
+                                       t.setAttrib(e, n, v);\r
+                               });\r
+                       });\r
+               },\r
+\r
+               getAttrib : function(e, n, dv) {\r
+                       var v, t = this, undef;\r
+\r
+                       e = t.get(e);\r
+\r
+                       if (!e || e.nodeType !== 1)\r
+                               return dv === undef ? false : dv;\r
+\r
+                       if (!is(dv))\r
+                               dv = '';\r
+\r
+                       // Try the mce variant for these\r
+                       if (/^(src|href|style|coords|shape)$/.test(n)) {\r
+                               v = e.getAttribute("data-mce-" + n);\r
+\r
+                               if (v)\r
+                                       return v;\r
+                       }\r
+\r
+                       if (isIE && t.props[n]) {\r
+                               v = e[t.props[n]];\r
+                               v = v && v.nodeValue ? v.nodeValue : v;\r
+                       }\r
+\r
+                       if (!v)\r
+                               v = e.getAttribute(n, 2);\r
+\r
+                       // Check boolean attribs\r
+                       if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(n)) {\r
+                               if (e[t.props[n]] === true && v === '')\r
+                                       return n;\r
+\r
+                               return v ? n : '';\r
+                       }\r
+\r
+                       // Inner input elements will override attributes on form elements\r
+                       if (e.nodeName === "FORM" && e.getAttributeNode(n))\r
+                               return e.getAttributeNode(n).nodeValue;\r
+\r
+                       if (n === 'style') {\r
+                               v = v || e.style.cssText;\r
+\r
+                               if (v) {\r
+                                       v = t.serializeStyle(t.parseStyle(v), e.nodeName);\r
+\r
+                                       if (t.settings.keep_values && !t._isRes(v))\r
+                                               e.setAttribute('data-mce-style', v);\r
+                               }\r
+                       }\r
+\r
+                       // Remove Apple and WebKit stuff\r
+                       if (isWebKit && n === "class" && v)\r
+                               v = v.replace(/(apple|webkit)\-[a-z\-]+/gi, '');\r
+\r
+                       // Handle IE issues\r
+                       if (isIE) {\r
+                               switch (n) {\r
+                                       case 'rowspan':\r
+                                       case 'colspan':\r
+                                               // IE returns 1 as default value\r
+                                               if (v === 1)\r
+                                                       v = '';\r
+\r
+                                               break;\r
+\r
+                                       case 'size':\r
+                                               // IE returns +0 as default value for size\r
+                                               if (v === '+0' || v === 20 || v === 0)\r
+                                                       v = '';\r
+\r
+                                               break;\r
+\r
+                                       case 'width':\r
+                                       case 'height':\r
+                                       case 'vspace':\r
+                                       case 'checked':\r
+                                       case 'disabled':\r
+                                       case 'readonly':\r
+                                               if (v === 0)\r
+                                                       v = '';\r
+\r
+                                               break;\r
+\r
+                                       case 'hspace':\r
+                                               // IE returns -1 as default value\r
+                                               if (v === -1)\r
+                                                       v = '';\r
+\r
+                                               break;\r
+\r
+                                       case 'maxlength':\r
+                                       case 'tabindex':\r
+                                               // IE returns default value\r
+                                               if (v === 32768 || v === 2147483647 || v === '32768')\r
+                                                       v = '';\r
+\r
+                                               break;\r
+\r
+                                       case 'multiple':\r
+                                       case 'compact':\r
+                                       case 'noshade':\r
+                                       case 'nowrap':\r
+                                               if (v === 65535)\r
+                                                       return n;\r
+\r
+                                               return dv;\r
+\r
+                                       case 'shape':\r
+                                               v = v.toLowerCase();\r
+                                               break;\r
+\r
+                                       default:\r
+                                               // IE has odd anonymous function for event attributes\r
+                                               if (n.indexOf('on') === 0 && v)\r
+                                                       v = tinymce._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1', '' + v);\r
+                               }\r
+                       }\r
+\r
+                       return (v !== undef && v !== null && v !== '') ? '' + v : dv;\r
+               },\r
+\r
+               getPos : function(n, ro) {\r
+                       var t = this, x = 0, y = 0, e, d = t.doc, r;\r
+\r
+                       n = t.get(n);\r
+                       ro = ro || d.body;\r
+\r
+                       if (n) {\r
+                               // Use getBoundingClientRect if it exists since it's faster than looping offset nodes\r
+                               if (n.getBoundingClientRect) {\r
+                                       n = n.getBoundingClientRect();\r
+                                       e = t.boxModel ? d.documentElement : d.body;\r
+\r
+                                       // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit\r
+                                       // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position\r
+                                       x = n.left + (d.documentElement.scrollLeft || d.body.scrollLeft) - e.clientTop;\r
+                                       y = n.top + (d.documentElement.scrollTop || d.body.scrollTop) - e.clientLeft;\r
+\r
+                                       return {x : x, y : y};\r
+                               }\r
+\r
+                               r = n;\r
+                               while (r && r != ro && r.nodeType) {\r
+                                       x += r.offsetLeft || 0;\r
+                                       y += r.offsetTop || 0;\r
+                                       r = r.offsetParent;\r
+                               }\r
+\r
+                               r = n.parentNode;\r
+                               while (r && r != ro && r.nodeType) {\r
+                                       x -= r.scrollLeft || 0;\r
+                                       y -= r.scrollTop || 0;\r
+                                       r = r.parentNode;\r
+                               }\r
+                       }\r
+\r
+                       return {x : x, y : y};\r
+               },\r
+\r
+               parseStyle : function(st) {\r
+                       return this.styles.parse(st);\r
+               },\r
+\r
+               serializeStyle : function(o, name) {\r
+                       return this.styles.serialize(o, name);\r
+               },\r
+\r
+               loadCSS : function(u) {\r
+                       var t = this, d = t.doc, head;\r
+\r
+                       if (!u)\r
+                               u = '';\r
+\r
+                       head = t.select('head')[0];\r
+\r
+                       each(u.split(','), function(u) {\r
+                               var link;\r
+\r
+                               if (t.files[u])\r
+                                       return;\r
+\r
+                               t.files[u] = true;\r
+                               link = t.create('link', {rel : 'stylesheet', href : tinymce._addVer(u)});\r
+\r
+                               // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug\r
+                               // This fix seems to resolve that issue by realcing the document ones a stylesheet finishes loading\r
+                               // It's ugly but it seems to work fine.\r
+                               if (isIE && d.documentMode && d.recalc) {\r
+                                       link.onload = function() {\r
+                                               if (d.recalc)\r
+                                                       d.recalc();\r
+\r
+                                               link.onload = null;\r
+                                       };\r
+                               }\r
+\r
+                               head.appendChild(link);\r
+                       });\r
+               },\r
+\r
+               addClass : function(e, c) {\r
+                       return this.run(e, function(e) {\r
+                               var o;\r
+\r
+                               if (!c)\r
+                                       return 0;\r
+\r
+                               if (this.hasClass(e, c))\r
+                                       return e.className;\r
+\r
+                               o = this.removeClass(e, c);\r
+\r
+                               return e.className = (o != '' ? (o + ' ') : '') + c;\r
+                       });\r
+               },\r
+\r
+               removeClass : function(e, c) {\r
+                       var t = this, re;\r
+\r
+                       return t.run(e, function(e) {\r
+                               var v;\r
+\r
+                               if (t.hasClass(e, c)) {\r
+                                       if (!re)\r
+                                               re = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g");\r
+\r
+                                       v = e.className.replace(re, ' ');\r
+                                       v = tinymce.trim(v != ' ' ? v : '');\r
+\r
+                                       e.className = v;\r
+\r
+                                       // Empty class attr\r
+                                       if (!v) {\r
+                                               e.removeAttribute('class');\r
+                                               e.removeAttribute('className');\r
+                                       }\r
+\r
+                                       return v;\r
+                               }\r
+\r
+                               return e.className;\r
+                       });\r
+               },\r
+\r
+               hasClass : function(n, c) {\r
+                       n = this.get(n);\r
+\r
+                       if (!n || !c)\r
+                               return false;\r
+\r
+                       return (' ' + n.className + ' ').indexOf(' ' + c + ' ') !== -1;\r
+               },\r
+\r
+               show : function(e) {\r
+                       return this.setStyle(e, 'display', 'block');\r
+               },\r
+\r
+               hide : function(e) {\r
+                       return this.setStyle(e, 'display', 'none');\r
+               },\r
+\r
+               isHidden : function(e) {\r
+                       e = this.get(e);\r
+\r
+                       return !e || e.style.display == 'none' || this.getStyle(e, 'display') == 'none';\r
+               },\r
+\r
+               uniqueId : function(p) {\r
+                       return (!p ? 'mce_' : p) + (this.counter++);\r
+               },\r
+\r
+               setHTML : function(element, html) {\r
+                       var self = this;\r
+\r
+                       return self.run(element, function(element) {\r
+                               if (isIE) {\r
+                                       // Remove all child nodes, IE keeps empty text nodes in DOM\r
+                                       while (element.firstChild)\r
+                                               element.removeChild(element.firstChild);\r
+\r
+                                       try {\r
+                                               // IE will remove comments from the beginning\r
+                                               // unless you padd the contents with something\r
+                                               element.innerHTML = '<br />' + html;\r
+                                               element.removeChild(element.firstChild);\r
+                                       } catch (ex) {\r
+                                               // 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\r
+                                               // This seems to fix this problem\r
+\r
+                                               // Create new div with HTML contents and a BR infront to keep comments\r
+                                               element = self.create('div');\r
+                                               element.innerHTML = '<br />' + html;\r
+\r
+                                               // Add all children from div to target\r
+                                               each (element.childNodes, function(node, i) {\r
+                                                       // Skip br element\r
+                                                       if (i)\r
+                                                               element.appendChild(node);\r
+                                               });\r
+                                       }\r
+                               } else\r
+                                       element.innerHTML = html;\r
+\r
+                               return html;\r
+                       });\r
+               },\r
+\r
+               getOuterHTML : function(elm) {\r
+                       var doc, self = this;\r
+\r
+                       elm = self.get(elm);\r
+\r
+                       if (!elm)\r
+                               return null;\r
+\r
+                       if (elm.nodeType === 1 && self.hasOuterHTML)\r
+                               return elm.outerHTML;\r
+\r
+                       doc = (elm.ownerDocument || self.doc).createElement("body");\r
+                       doc.appendChild(elm.cloneNode(true));\r
+\r
+                       return doc.innerHTML;\r
+               },\r
+\r
+               setOuterHTML : function(e, h, d) {\r
+                       var t = this;\r
+\r
+                       function setHTML(e, h, d) {\r
+                               var n, tp;\r
+\r
+                               tp = d.createElement("body");\r
+                               tp.innerHTML = h;\r
+\r
+                               n = tp.lastChild;\r
+                               while (n) {\r
+                                       t.insertAfter(n.cloneNode(true), e);\r
+                                       n = n.previousSibling;\r
+                               }\r
+\r
+                               t.remove(e);\r
+                       };\r
+\r
+                       return this.run(e, function(e) {\r
+                               e = t.get(e);\r
+\r
+                               // Only set HTML on elements\r
+                               if (e.nodeType == 1) {\r
+                                       d = d || e.ownerDocument || t.doc;\r
+\r
+                                       if (isIE) {\r
+                                               try {\r
+                                                       // Try outerHTML for IE it sometimes produces an unknown runtime error\r
+                                                       if (isIE && e.nodeType == 1)\r
+                                                               e.outerHTML = h;\r
+                                                       else\r
+                                                               setHTML(e, h, d);\r
+                                               } catch (ex) {\r
+                                                       // Fix for unknown runtime error\r
+                                                       setHTML(e, h, d);\r
+                                               }\r
+                                       } else\r
+                                               setHTML(e, h, d);\r
+                               }\r
+                       });\r
+               },\r
+\r
+               decode : Entities.decode,\r
+\r
+               encode : Entities.encodeAllRaw,\r
+\r
+               insertAfter : function(node, reference_node) {\r
+                       reference_node = this.get(reference_node);\r
+\r
+                       return this.run(node, function(node) {\r
+                               var parent, nextSibling;\r
+\r
+                               parent = reference_node.parentNode;\r
+                               nextSibling = reference_node.nextSibling;\r
+\r
+                               if (nextSibling)\r
+                                       parent.insertBefore(node, nextSibling);\r
+                               else\r
+                                       parent.appendChild(node);\r
+\r
+                               return node;\r
+                       });\r
+               },\r
+\r
+               isBlock : function(node) {\r
+                       var type = node.nodeType;\r
+\r
+                       // If it's a node then check the type and use the nodeName\r
+                       if (type)\r
+                               return !!(type === 1 && blockElementsMap[node.nodeName]);\r
+\r
+                       return !!blockElementsMap[node];\r
+               },\r
+\r
+               replace : function(n, o, k) {\r
+                       var t = this;\r
+\r
+                       if (is(o, 'array'))\r
+                               n = n.cloneNode(true);\r
+\r
+                       return t.run(o, function(o) {\r
+                               if (k) {\r
+                                       each(tinymce.grep(o.childNodes), function(c) {\r
+                                               n.appendChild(c);\r
+                                       });\r
+                               }\r
+\r
+                               return o.parentNode.replaceChild(n, o);\r
+                       });\r
+               },\r
+\r
+               rename : function(elm, name) {\r
+                       var t = this, newElm;\r
+\r
+                       if (elm.nodeName != name.toUpperCase()) {\r
+                               // Rename block element\r
+                               newElm = t.create(name);\r
+\r
+                               // Copy attribs to new block\r
+                               each(t.getAttribs(elm), function(attr_node) {\r
+                                       t.setAttrib(newElm, attr_node.nodeName, t.getAttrib(elm, attr_node.nodeName));\r
+                               });\r
+\r
+                               // Replace block\r
+                               t.replace(newElm, elm, 1);\r
+                       }\r
+\r
+                       return newElm || elm;\r
+               },\r
+\r
+               findCommonAncestor : function(a, b) {\r
+                       var ps = a, pe;\r
+\r
+                       while (ps) {\r
+                               pe = b;\r
+\r
+                               while (pe && ps != pe)\r
+                                       pe = pe.parentNode;\r
+\r
+                               if (ps == pe)\r
+                                       break;\r
+\r
+                               ps = ps.parentNode;\r
+                       }\r
+\r
+                       if (!ps && a.ownerDocument)\r
+                               return a.ownerDocument.documentElement;\r
+\r
+                       return ps;\r
+               },\r
+\r
+               toHex : function(s) {\r
+                       var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s);\r
+\r
+                       function hex(s) {\r
+                               s = parseInt(s).toString(16);\r
+\r
+                               return s.length > 1 ? s : '0' + s; // 0 -> 00\r
+                       };\r
+\r
+                       if (c) {\r
+                               s = '#' + hex(c[1]) + hex(c[2]) + hex(c[3]);\r
+\r
+                               return s;\r
+                       }\r
+\r
+                       return s;\r
+               },\r
+\r
+               getClasses : function() {\r
+                       var t = this, cl = [], i, lo = {}, f = t.settings.class_filter, ov;\r
+\r
+                       if (t.classes)\r
+                               return t.classes;\r
+\r
+                       function addClasses(s) {\r
+                               // IE style imports\r
+                               each(s.imports, function(r) {\r
+                                       addClasses(r);\r
+                               });\r
+\r
+                               each(s.cssRules || s.rules, function(r) {\r
+                                       // Real type or fake it on IE\r
+                                       switch (r.type || 1) {\r
+                                               // Rule\r
+                                               case 1:\r
+                                                       if (r.selectorText) {\r
+                                                               each(r.selectorText.split(','), function(v) {\r
+                                                                       v = v.replace(/^\s*|\s*$|^\s\./g, "");\r
+\r
+                                                                       // Is internal or it doesn't contain a class\r
+                                                                       if (/\.mce/.test(v) || !/\.[\w\-]+$/.test(v))\r
+                                                                               return;\r
+\r
+                                                                       // Remove everything but class name\r
+                                                                       ov = v;\r
+                                                                       v = tinymce._replace(/.*\.([a-z0-9_\-]+).*/i, '$1', v);\r
+\r
+                                                                       // Filter classes\r
+                                                                       if (f && !(v = f(v, ov)))\r
+                                                                               return;\r
+\r
+                                                                       if (!lo[v]) {\r
+                                                                               cl.push({'class' : v});\r
+                                                                               lo[v] = 1;\r
+                                                                       }\r
+                                                               });\r
+                                                       }\r
+                                                       break;\r
+\r
+                                               // Import\r
+                                               case 3:\r
+                                                       addClasses(r.styleSheet);\r
+                                                       break;\r
+                                       }\r
+                               });\r
+                       };\r
+\r
+                       try {\r
+                               each(t.doc.styleSheets, addClasses);\r
+                       } catch (ex) {\r
+                               // Ignore\r
+                       }\r
+\r
+                       if (cl.length > 0)\r
+                               t.classes = cl;\r
+\r
+                       return cl;\r
+               },\r
+\r
+               run : function(e, f, s) {\r
+                       var t = this, o;\r
+\r
+                       if (t.doc && typeof(e) === 'string')\r
+                               e = t.get(e);\r
+\r
+                       if (!e)\r
+                               return false;\r
+\r
+                       s = s || this;\r
+                       if (!e.nodeType && (e.length || e.length === 0)) {\r
+                               o = [];\r
+\r
+                               each(e, function(e, i) {\r
+                                       if (e) {\r
+                                               if (typeof(e) == 'string')\r
+                                                       e = t.doc.getElementById(e);\r
+\r
+                                               o.push(f.call(s, e, i));\r
+                                       }\r
+                               });\r
+\r
+                               return o;\r
+                       }\r
+\r
+                       return f.call(s, e);\r
+               },\r
+\r
+               getAttribs : function(n) {\r
+                       var o;\r
+\r
+                       n = this.get(n);\r
+\r
+                       if (!n)\r
+                               return [];\r
+\r
+                       if (isIE) {\r
+                               o = [];\r
+\r
+                               // Object will throw exception in IE\r
+                               if (n.nodeName == 'OBJECT')\r
+                                       return n.attributes;\r
+\r
+                               // IE doesn't keep the selected attribute if you clone option elements\r
+                               if (n.nodeName === 'OPTION' && this.getAttrib(n, 'selected'))\r
+                                       o.push({specified : 1, nodeName : 'selected'});\r
+\r
+                               // It's crazy that this is faster in IE but it's because it returns all attributes all the time\r
+                               n.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi, '').replace(/[\w:\-]+/gi, function(a) {\r
+                                       o.push({specified : 1, nodeName : a});\r
+                               });\r
+\r
+                               return o;\r
+                       }\r
+\r
+                       return n.attributes;\r
+               },\r
+\r
+               isEmpty : function(node, elements) {\r
+                       var self = this, i, attributes, type, walker, name, parentNode;\r
+\r
+                       node = node.firstChild;\r
+                       if (node) {\r
+                               walker = new tinymce.dom.TreeWalker(node);\r
+                               elements = elements || self.schema ? self.schema.getNonEmptyElements() : null;\r
+\r
+                               do {\r
+                                       type = node.nodeType;\r
+\r
+                                       if (type === 1) {\r
+                                               // Ignore bogus elements\r
+                                               if (node.getAttribute('data-mce-bogus'))\r
+                                                       continue;\r
+\r
+                                               // Keep empty elements like <img />\r
+                                               name = node.nodeName.toLowerCase();\r
+                                               if (elements && elements[name]) {\r
+                                                       // Ignore single BR elements in blocks like <p><br /></p>\r
+                                                       parentNode = node.parentNode;\r
+                                                       if (name === 'br' && self.isBlock(parentNode) && parentNode.firstChild === node && parentNode.lastChild === node) {\r
+                                                               continue;\r
+                                                       }\r
+\r
+                                                       return false;\r
+                                               }\r
+\r
+                                               // Keep elements with data-bookmark attributes or name attribute like <a name="1"></a>\r
+                                               attributes = self.getAttribs(node);\r
+                                               i = node.attributes.length;\r
+                                               while (i--) {\r
+                                                       name = node.attributes[i].nodeName;\r
+                                                       if (name === "name" || name === 'data-mce-bookmark')\r
+                                                               return false;\r
+                                               }\r
+                                       }\r
+\r
+                                       // Keep non whitespace text nodes\r
+                                       if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue)))\r
+                                               return false;\r
+                               } while (node = walker.next());\r
+                       }\r
+\r
+                       return true;\r
+               },\r
+\r
+               destroy : function(s) {\r
+                       var t = this;\r
+\r
+                       if (t.events)\r
+                               t.events.destroy();\r
+\r
+                       t.win = t.doc = t.root = t.events = null;\r
+\r
+                       // Manual destroy then remove unload handler\r
+                       if (!s)\r
+                               tinymce.removeUnload(t.destroy);\r
+               },\r
+\r
+               createRng : function() {\r
+                       var d = this.doc;\r
+\r
+                       return d.createRange ? d.createRange() : new tinymce.dom.Range(this);\r
+               },\r
+\r
+               nodeIndex : function(node, normalized) {\r
+                       var idx = 0, lastNodeType, lastNode, nodeType;\r
+\r
+                       if (node) {\r
+                               for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) {\r
+                                       nodeType = node.nodeType;\r
+\r
+                                       // Normalize text nodes\r
+                                       if (normalized && nodeType == 3) {\r
+                                               if (nodeType == lastNodeType || !node.nodeValue.length)\r
+                                                       continue;\r
+                                       }\r
+                                       idx++;\r
+                                       lastNodeType = nodeType;\r
+                               }\r
+                       }\r
+\r
+                       return idx;\r
+               },\r
+\r
+               split : function(pe, e, re) {\r
+                       var t = this, r = t.createRng(), bef, aft, pa;\r
+\r
+                       // W3C valid browsers tend to leave empty nodes to the left/right side of the contents, this makes sense\r
+                       // but we don't want that in our code since it serves no purpose for the end user\r
+                       // For example if this is chopped:\r
+                       //   <p>text 1<span><b>CHOP</b></span>text 2</p>\r
+                       // would produce:\r
+                       //   <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p>\r
+                       // this function will then trim of empty edges and produce:\r
+                       //   <p>text 1</p><b>CHOP</b><p>text 2</p>\r
+                       function trim(node) {\r
+                               var i, children = node.childNodes, type = node.nodeType;\r
+\r
+                               if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark')\r
+                                       return;\r
+\r
+                               for (i = children.length - 1; i >= 0; i--)\r
+                                       trim(children[i]);\r
+\r
+                               if (type != 9) {\r
+                                       // Keep non whitespace text nodes\r
+                                       if (type == 3 && node.nodeValue.length > 0) {\r
+                                               // If parent element isn't a block or there isn't any useful contents for example "<p>   </p>"\r
+                                               if (!t.isBlock(node.parentNode) || tinymce.trim(node.nodeValue).length > 0)\r
+                                                       return;\r
+                                       } else if (type == 1) {\r
+                                               // If the only child is a bookmark then move it up\r
+                                               children = node.childNodes;\r
+                                               if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark')\r
+                                                       node.parentNode.insertBefore(children[0], node);\r
+\r
+                                               // Keep non empty elements or img, hr etc\r
+                                               if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName))\r
+                                                       return;\r
+                                       }\r
+\r
+                                       t.remove(node);\r
+                               }\r
+\r
+                               return node;\r
+                       };\r
+\r
+                       if (pe && e) {\r
+                               // Get before chunk\r
+                               r.setStart(pe.parentNode, t.nodeIndex(pe));\r
+                               r.setEnd(e.parentNode, t.nodeIndex(e));\r
+                               bef = r.extractContents();\r
+\r
+                               // Get after chunk\r
+                               r = t.createRng();\r
+                               r.setStart(e.parentNode, t.nodeIndex(e) + 1);\r
+                               r.setEnd(pe.parentNode, t.nodeIndex(pe) + 1);\r
+                               aft = r.extractContents();\r
+\r
+                               // Insert before chunk\r
+                               pa = pe.parentNode;\r
+                               pa.insertBefore(trim(bef), pe);\r
+\r
+                               // Insert middle chunk\r
+                               if (re)\r
+                                       pa.replaceChild(re, e);\r
+                               else\r
+                                       pa.insertBefore(e, pe);\r
+\r
+                               // Insert after chunk\r
+                               pa.insertBefore(trim(aft), pe);\r
+                               t.remove(pe);\r
+\r
+                               return re || e;\r
+                       }\r
+               },\r
+\r
+               bind : function(target, name, func, scope) {\r
+                       var t = this;\r
+\r
+                       if (!t.events)\r
+                               t.events = new tinymce.dom.EventUtils();\r
+\r
+                       return t.events.add(target, name, func, scope || this);\r
+               },\r
+\r
+               unbind : function(target, name, func) {\r
+                       var t = this;\r
+\r
+                       if (!t.events)\r
+                               t.events = new tinymce.dom.EventUtils();\r
+\r
+                       return t.events.remove(target, name, func);\r
+               },\r
+\r
+\r
+               _findSib : function(node, selector, name) {\r
+                       var t = this, f = selector;\r
+\r
+                       if (node) {\r
+                               // If expression make a function of it using is\r
+                               if (is(f, 'string')) {\r
+                                       f = function(node) {\r
+                                               return t.is(node, selector);\r
+                                       };\r
+                               }\r
+\r
+                               // Loop all siblings\r
+                               for (node = node[name]; node; node = node[name]) {\r
+                                       if (f(node))\r
+                                               return node;\r
+                               }\r
+                       }\r
+\r
+                       return null;\r
+               },\r
+\r
+               _isRes : function(c) {\r
+                       // Is live resizble element\r
+                       return /^(top|left|bottom|right|width|height)/i.test(c) || /;\s*(top|left|bottom|right|width|height)/i.test(c);\r
+               }\r
+\r
+               /*\r
+               walk : function(n, f, s) {\r
+                       var d = this.doc, w;\r
+\r
+                       if (d.createTreeWalker) {\r
+                               w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false);\r
+\r
+                               while ((n = w.nextNode()) != null)\r
+                                       f.call(s || this, n);\r
+                       } else\r
+                               tinymce.walk(n, f, 'childNodes', s);\r
+               }\r
+               */\r
+\r
+               /*\r
+               toRGB : function(s) {\r
+                       var c = /^\s*?#([0-9A-F]{2})([0-9A-F]{1,2})([0-9A-F]{2})?\s*?$/.exec(s);\r
+\r
+                       if (c) {\r
+                               // #FFF -> #FFFFFF\r
+                               if (!is(c[3]))\r
+                                       c[3] = c[2] = c[1];\r
+\r
+                               return "rgb(" + parseInt(c[1], 16) + "," + parseInt(c[2], 16) + "," + parseInt(c[3], 16) + ")";\r
+                       }\r
+\r
+                       return s;\r
+               }\r
+               */\r
+       });\r
+\r
+       tinymce.DOM = new tinymce.dom.DOMUtils(document, {process_html : 0});\r
+})(tinymce);\r
+\r
+(function(ns) {\r
+       // Range constructor\r
+       function Range(dom) {\r
+               var t = this,\r
+                       doc = dom.doc,\r
+                       EXTRACT = 0,\r
+                       CLONE = 1,\r
+                       DELETE = 2,\r
+                       TRUE = true,\r
+                       FALSE = false,\r
+                       START_OFFSET = 'startOffset',\r
+                       START_CONTAINER = 'startContainer',\r
+                       END_CONTAINER = 'endContainer',\r
+                       END_OFFSET = 'endOffset',\r
+                       extend = tinymce.extend,\r
+                       nodeIndex = dom.nodeIndex;\r
+\r
+               extend(t, {\r
+                       // Inital states\r
+                       startContainer : doc,\r
+                       startOffset : 0,\r
+                       endContainer : doc,\r
+                       endOffset : 0,\r
+                       collapsed : TRUE,\r
+                       commonAncestorContainer : doc,\r
+\r
+                       // Range constants\r
+                       START_TO_START : 0,\r
+                       START_TO_END : 1,\r
+                       END_TO_END : 2,\r
+                       END_TO_START : 3,\r
+\r
+                       // Public methods\r
+                       setStart : setStart,\r
+                       setEnd : setEnd,\r
+                       setStartBefore : setStartBefore,\r
+                       setStartAfter : setStartAfter,\r
+                       setEndBefore : setEndBefore,\r
+                       setEndAfter : setEndAfter,\r
+                       collapse : collapse,\r
+                       selectNode : selectNode,\r
+                       selectNodeContents : selectNodeContents,\r
+                       compareBoundaryPoints : compareBoundaryPoints,\r
+                       deleteContents : deleteContents,\r
+                       extractContents : extractContents,\r
+                       cloneContents : cloneContents,\r
+                       insertNode : insertNode,\r
+                       surroundContents : surroundContents,\r
+                       cloneRange : cloneRange\r
+               });\r
+\r
+               function setStart(n, o) {\r
+                       _setEndPoint(TRUE, n, o);\r
+               };\r
+\r
+               function setEnd(n, o) {\r
+                       _setEndPoint(FALSE, n, o);\r
+               };\r
+\r
+               function setStartBefore(n) {\r
+                       setStart(n.parentNode, nodeIndex(n));\r
+               };\r
+\r
+               function setStartAfter(n) {\r
+                       setStart(n.parentNode, nodeIndex(n) + 1);\r
+               };\r
+\r
+               function setEndBefore(n) {\r
+                       setEnd(n.parentNode, nodeIndex(n));\r
+               };\r
+\r
+               function setEndAfter(n) {\r
+                       setEnd(n.parentNode, nodeIndex(n) + 1);\r
+               };\r
+\r
+               function collapse(ts) {\r
+                       if (ts) {\r
+                               t[END_CONTAINER] = t[START_CONTAINER];\r
+                               t[END_OFFSET] = t[START_OFFSET];\r
+                       } else {\r
+                               t[START_CONTAINER] = t[END_CONTAINER];\r
+                               t[START_OFFSET] = t[END_OFFSET];\r
+                       }\r
+\r
+                       t.collapsed = TRUE;\r
+               };\r
+\r
+               function selectNode(n) {\r
+                       setStartBefore(n);\r
+                       setEndAfter(n);\r
+               };\r
+\r
+               function selectNodeContents(n) {\r
+                       setStart(n, 0);\r
+                       setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length);\r
+               };\r
+\r
+               function compareBoundaryPoints(h, r) {\r
+                       var sc = t[START_CONTAINER], so = t[START_OFFSET], ec = t[END_CONTAINER], eo = t[END_OFFSET],\r
+                       rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset;\r
+\r
+                       // Check START_TO_START\r
+                       if (h === 0)\r
+                               return _compareBoundaryPoints(sc, so, rsc, rso);\r
+       \r
+                       // Check START_TO_END\r
+                       if (h === 1)\r
+                               return _compareBoundaryPoints(ec, eo, rsc, rso);\r
+       \r
+                       // Check END_TO_END\r
+                       if (h === 2)\r
+                               return _compareBoundaryPoints(ec, eo, rec, reo);\r
+       \r
+                       // Check END_TO_START\r
+                       if (h === 3) \r
+                               return _compareBoundaryPoints(sc, so, rec, reo);\r
+               };\r
+\r
+               function deleteContents() {\r
+                       _traverse(DELETE);\r
+               };\r
+\r
+               function extractContents() {\r
+                       return _traverse(EXTRACT);\r
+               };\r
+\r
+               function cloneContents() {\r
+                       return _traverse(CLONE);\r
+               };\r
+\r
+               function insertNode(n) {\r
+                       var startContainer = this[START_CONTAINER],\r
+                               startOffset = this[START_OFFSET], nn, o;\r
+\r
+                       // Node is TEXT_NODE or CDATA\r
+                       if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) {\r
+                               if (!startOffset) {\r
+                                       // At the start of text\r
+                                       startContainer.parentNode.insertBefore(n, startContainer);\r
+                               } else if (startOffset >= startContainer.nodeValue.length) {\r
+                                       // At the end of text\r
+                                       dom.insertAfter(n, startContainer);\r
+                               } else {\r
+                                       // Middle, need to split\r
+                                       nn = startContainer.splitText(startOffset);\r
+                                       startContainer.parentNode.insertBefore(n, nn);\r
+                               }\r
+                       } else {\r
+                               // Insert element node\r
+                               if (startContainer.childNodes.length > 0)\r
+                                       o = startContainer.childNodes[startOffset];\r
+\r
+                               if (o)\r
+                                       startContainer.insertBefore(n, o);\r
+                               else\r
+                                       startContainer.appendChild(n);\r
+                       }\r
+               };\r
+\r
+               function surroundContents(n) {\r
+                       var f = t.extractContents();\r
+\r
+                       t.insertNode(n);\r
+                       n.appendChild(f);\r
+                       t.selectNode(n);\r
+               };\r
+\r
+               function cloneRange() {\r
+                       return extend(new Range(dom), {\r
+                               startContainer : t[START_CONTAINER],\r
+                               startOffset : t[START_OFFSET],\r
+                               endContainer : t[END_CONTAINER],\r
+                               endOffset : t[END_OFFSET],\r
+                               collapsed : t.collapsed,\r
+                               commonAncestorContainer : t.commonAncestorContainer\r
+                       });\r
+               };\r
+\r
+               // Private methods\r
+\r
+               function _getSelectedNode(container, offset) {\r
+                       var child;\r
+\r
+                       if (container.nodeType == 3 /* TEXT_NODE */)\r
+                               return container;\r
+\r
+                       if (offset < 0)\r
+                               return container;\r
+\r
+                       child = container.firstChild;\r
+                       while (child && offset > 0) {\r
+                               --offset;\r
+                               child = child.nextSibling;\r
+                       }\r
+\r
+                       if (child)\r
+                               return child;\r
+\r
+                       return container;\r
+               };\r
+\r
+               function _isCollapsed() {\r
+                       return (t[START_CONTAINER] == t[END_CONTAINER] && t[START_OFFSET] == t[END_OFFSET]);\r
+               };\r
+\r
+               function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) {\r
+                       var c, offsetC, n, cmnRoot, childA, childB;\r
+                       \r
+                       // In the first case the boundary-points have the same container. A is before B\r
+                       // if its offset is less than the offset of B, A is equal to B if its offset is\r
+                       // equal to the offset of B, and A is after B if its offset is greater than the\r
+                       // offset of B.\r
+                       if (containerA == containerB) {\r
+                               if (offsetA == offsetB)\r
+                                       return 0; // equal\r
+\r
+                               if (offsetA < offsetB)\r
+                                       return -1; // before\r
+\r
+                               return 1; // after\r
+                       }\r
+\r
+                       // In the second case a child node C of the container of A is an ancestor\r
+                       // container of B. In this case, A is before B if the offset of A is less than or\r
+                       // equal to the index of the child node C and A is after B otherwise.\r
+                       c = containerB;\r
+                       while (c && c.parentNode != containerA)\r
+                               c = c.parentNode;\r
+\r
+                       if (c) {\r
+                               offsetC = 0;\r
+                               n = containerA.firstChild;\r
+\r
+                               while (n != c && offsetC < offsetA) {\r
+                                       offsetC++;\r
+                                       n = n.nextSibling;\r
+                               }\r
+\r
+                               if (offsetA <= offsetC)\r
+                                       return -1; // before\r
+\r
+                               return 1; // after\r
+                       }\r
+\r
+                       // In the third case a child node C of the container of B is an ancestor container\r
+                       // of A. In this case, A is before B if the index of the child node C is less than\r
+                       // the offset of B and A is after B otherwise.\r
+                       c = containerA;\r
+                       while (c && c.parentNode != containerB) {\r
+                               c = c.parentNode;\r
+                       }\r
+\r
+                       if (c) {\r
+                               offsetC = 0;\r
+                               n = containerB.firstChild;\r
+\r
+                               while (n != c && offsetC < offsetB) {\r
+                                       offsetC++;\r
+                                       n = n.nextSibling;\r
+                               }\r
+\r
+                               if (offsetC < offsetB)\r
+                                       return -1; // before\r
+\r
+                               return 1; // after\r
+                       }\r
+\r
+                       // In the fourth case, none of three other cases hold: the containers of A and B\r
+                       // are siblings or descendants of sibling nodes. In this case, A is before B if\r
+                       // the container of A is before the container of B in a pre-order traversal of the\r
+                       // Ranges' context tree and A is after B otherwise.\r
+                       cmnRoot = dom.findCommonAncestor(containerA, containerB);\r
+                       childA = containerA;\r
+\r
+                       while (childA && childA.parentNode != cmnRoot)\r
+                               childA = childA.parentNode;\r
+\r
+                       if (!childA)\r
+                               childA = cmnRoot;\r
+\r
+                       childB = containerB;\r
+                       while (childB && childB.parentNode != cmnRoot)\r
+                               childB = childB.parentNode;\r
+\r
+                       if (!childB)\r
+                               childB = cmnRoot;\r
+\r
+                       if (childA == childB)\r
+                               return 0; // equal\r
+\r
+                       n = cmnRoot.firstChild;\r
+                       while (n) {\r
+                               if (n == childA)\r
+                                       return -1; // before\r
+\r
+                               if (n == childB)\r
+                                       return 1; // after\r
+\r
+                               n = n.nextSibling;\r
+                       }\r
+               };\r
+\r
+               function _setEndPoint(st, n, o) {\r
+                       var ec, sc;\r
+\r
+                       if (st) {\r
+                               t[START_CONTAINER] = n;\r
+                               t[START_OFFSET] = o;\r
+                       } else {\r
+                               t[END_CONTAINER] = n;\r
+                               t[END_OFFSET] = o;\r
+                       }\r
+\r
+                       // If one boundary-point of a Range is set to have a root container\r
+                       // other than the current one for the Range, the Range is collapsed to\r
+                       // the new position. This enforces the restriction that both boundary-\r
+                       // points of a Range must have the same root container.\r
+                       ec = t[END_CONTAINER];\r
+                       while (ec.parentNode)\r
+                               ec = ec.parentNode;\r
+\r
+                       sc = t[START_CONTAINER];\r
+                       while (sc.parentNode)\r
+                               sc = sc.parentNode;\r
+\r
+                       if (sc == ec) {\r
+                               // The start position of a Range is guaranteed to never be after the\r
+                               // end position. To enforce this restriction, if the start is set to\r
+                               // be at a position after the end, the Range is collapsed to that\r
+                               // position.\r
+                               if (_compareBoundaryPoints(t[START_CONTAINER], t[START_OFFSET], t[END_CONTAINER], t[END_OFFSET]) > 0)\r
+                                       t.collapse(st);\r
+                       } else\r
+                               t.collapse(st);\r
+\r
+                       t.collapsed = _isCollapsed();\r
+                       t.commonAncestorContainer = dom.findCommonAncestor(t[START_CONTAINER], t[END_CONTAINER]);\r
+               };\r
+\r
+               function _traverse(how) {\r
+                       var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep;\r
+\r
+                       if (t[START_CONTAINER] == t[END_CONTAINER])\r
+                               return _traverseSameContainer(how);\r
+\r
+                       for (c = t[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {\r
+                               if (p == t[START_CONTAINER])\r
+                                       return _traverseCommonStartContainer(c, how);\r
+\r
+                               ++endContainerDepth;\r
+                       }\r
+\r
+                       for (c = t[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {\r
+                               if (p == t[END_CONTAINER])\r
+                                       return _traverseCommonEndContainer(c, how);\r
+\r
+                               ++startContainerDepth;\r
+                       }\r
+\r
+                       depthDiff = startContainerDepth - endContainerDepth;\r
+\r
+                       startNode = t[START_CONTAINER];\r
+                       while (depthDiff > 0) {\r
+                               startNode = startNode.parentNode;\r
+                               depthDiff--;\r
+                       }\r
+\r
+                       endNode = t[END_CONTAINER];\r
+                       while (depthDiff < 0) {\r
+                               endNode = endNode.parentNode;\r
+                               depthDiff++;\r
+                       }\r
+\r
+                       // ascend the ancestor hierarchy until we have a common parent.\r
+                       for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) {\r
+                               startNode = sp;\r
+                               endNode = ep;\r
+                       }\r
+\r
+                       return _traverseCommonAncestors(startNode, endNode, how);\r
+               };\r
+\r
+                function _traverseSameContainer(how) {\r
+                       var frag, s, sub, n, cnt, sibling, xferNode;\r
+\r
+                       if (how != DELETE)\r
+                               frag = doc.createDocumentFragment();\r
+\r
+                       // If selection is empty, just return the fragment\r
+                       if (t[START_OFFSET] == t[END_OFFSET])\r
+                               return frag;\r
+\r
+                       // Text node needs special case handling\r
+                       if (t[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) {\r
+                               // get the substring\r
+                               s = t[START_CONTAINER].nodeValue;\r
+                               sub = s.substring(t[START_OFFSET], t[END_OFFSET]);\r
+\r
+                               // set the original text node to its new value\r
+                               if (how != CLONE) {\r
+                                       t[START_CONTAINER].deleteData(t[START_OFFSET], t[END_OFFSET] - t[START_OFFSET]);\r
+\r
+                                       // Nothing is partially selected, so collapse to start point\r
+                                       t.collapse(TRUE);\r
+                               }\r
+\r
+                               if (how == DELETE)\r
+                                       return;\r
+\r
+                               frag.appendChild(doc.createTextNode(sub));\r
+                               return frag;\r
+                       }\r
+\r
+                       // Copy nodes between the start/end offsets.\r
+                       n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]);\r
+                       cnt = t[END_OFFSET] - t[START_OFFSET];\r
+\r
+                       while (cnt > 0) {\r
+                               sibling = n.nextSibling;\r
+                               xferNode = _traverseFullySelected(n, how);\r
+\r
+                               if (frag)\r
+                                       frag.appendChild( xferNode );\r
+\r
+                               --cnt;\r
+                               n = sibling;\r
+                       }\r
+\r
+                       // Nothing is partially selected, so collapse to start point\r
+                       if (how != CLONE)\r
+                               t.collapse(TRUE);\r
+\r
+                       return frag;\r
+               };\r
+\r
+               function _traverseCommonStartContainer(endAncestor, how) {\r
+                       var frag, n, endIdx, cnt, sibling, xferNode;\r
+\r
+                       if (how != DELETE)\r
+                               frag = doc.createDocumentFragment();\r
+\r
+                       n = _traverseRightBoundary(endAncestor, how);\r
+\r
+                       if (frag)\r
+                               frag.appendChild(n);\r
+\r
+                       endIdx = nodeIndex(endAncestor);\r
+                       cnt = endIdx - t[START_OFFSET];\r
+\r
+                       if (cnt <= 0) {\r
+                               // Collapse to just before the endAncestor, which\r
+                               // is partially selected.\r
+                               if (how != CLONE) {\r
+                                       t.setEndBefore(endAncestor);\r
+                                       t.collapse(FALSE);\r
+                               }\r
+\r
+                               return frag;\r
+                       }\r
+\r
+                       n = endAncestor.previousSibling;\r
+                       while (cnt > 0) {\r
+                               sibling = n.previousSibling;\r
+                               xferNode = _traverseFullySelected(n, how);\r
+\r
+                               if (frag)\r
+                                       frag.insertBefore(xferNode, frag.firstChild);\r
+\r
+                               --cnt;\r
+                               n = sibling;\r
+                       }\r
+\r
+                       // Collapse to just before the endAncestor, which\r
+                       // is partially selected.\r
+                       if (how != CLONE) {\r
+                               t.setEndBefore(endAncestor);\r
+                               t.collapse(FALSE);\r
+                       }\r
+\r
+                       return frag;\r
+               };\r
+\r
+               function _traverseCommonEndContainer(startAncestor, how) {\r
+                       var frag, startIdx, n, cnt, sibling, xferNode;\r
+\r
+                       if (how != DELETE)\r
+                               frag = doc.createDocumentFragment();\r
+\r
+                       n = _traverseLeftBoundary(startAncestor, how);\r
+                       if (frag)\r
+                               frag.appendChild(n);\r
+\r
+                       startIdx = nodeIndex(startAncestor);\r
+                       ++startIdx; // Because we already traversed it\r
+\r
+                       cnt = t[END_OFFSET] - startIdx;\r
+                       n = startAncestor.nextSibling;\r
+                       while (cnt > 0) {\r
+                               sibling = n.nextSibling;\r
+                               xferNode = _traverseFullySelected(n, how);\r
+\r
+                               if (frag)\r
+                                       frag.appendChild(xferNode);\r
+\r
+                               --cnt;\r
+                               n = sibling;\r
+                       }\r
+\r
+                       if (how != CLONE) {\r
+                               t.setStartAfter(startAncestor);\r
+                               t.collapse(TRUE);\r
+                       }\r
+\r
+                       return frag;\r
+               };\r
+\r
+               function _traverseCommonAncestors(startAncestor, endAncestor, how) {\r
+                       var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling;\r
+\r
+                       if (how != DELETE)\r
+                               frag = doc.createDocumentFragment();\r
+\r
+                       n = _traverseLeftBoundary(startAncestor, how);\r
+                       if (frag)\r
+                               frag.appendChild(n);\r
+\r
+                       commonParent = startAncestor.parentNode;\r
+                       startOffset = nodeIndex(startAncestor);\r
+                       endOffset = nodeIndex(endAncestor);\r
+                       ++startOffset;\r
+\r
+                       cnt = endOffset - startOffset;\r
+                       sibling = startAncestor.nextSibling;\r
+\r
+                       while (cnt > 0) {\r
+                               nextSibling = sibling.nextSibling;\r
+                               n = _traverseFullySelected(sibling, how);\r
+\r
+                               if (frag)\r
+                                       frag.appendChild(n);\r
+\r
+                               sibling = nextSibling;\r
+                               --cnt;\r
+                       }\r
+\r
+                       n = _traverseRightBoundary(endAncestor, how);\r
+\r
+                       if (frag)\r
+                               frag.appendChild(n);\r
+\r
+                       if (how != CLONE) {\r
+                               t.setStartAfter(startAncestor);\r
+                               t.collapse(TRUE);\r
+                       }\r
+\r
+                       return frag;\r
+               };\r
+\r
+               function _traverseRightBoundary(root, how) {\r
+                       var next = _getSelectedNode(t[END_CONTAINER], t[END_OFFSET] - 1), parent, clonedParent, prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != t[END_CONTAINER];\r
+\r
+                       if (next == root)\r
+                               return _traverseNode(next, isFullySelected, FALSE, how);\r
+\r
+                       parent = next.parentNode;\r
+                       clonedParent = _traverseNode(parent, FALSE, FALSE, how);\r
+\r
+                       while (parent) {\r
+                               while (next) {\r
+                                       prevSibling = next.previousSibling;\r
+                                       clonedChild = _traverseNode(next, isFullySelected, FALSE, how);\r
+\r
+                                       if (how != DELETE)\r
+                                               clonedParent.insertBefore(clonedChild, clonedParent.firstChild);\r
+\r
+                                       isFullySelected = TRUE;\r
+                                       next = prevSibling;\r
+                               }\r
+\r
+                               if (parent == root)\r
+                                       return clonedParent;\r
+\r
+                               next = parent.previousSibling;\r
+                               parent = parent.parentNode;\r
+\r
+                               clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how);\r
+\r
+                               if (how != DELETE)\r
+                                       clonedGrandParent.appendChild(clonedParent);\r
+\r
+                               clonedParent = clonedGrandParent;\r
+                       }\r
+               };\r
+\r
+               function _traverseLeftBoundary(root, how) {\r
+                       var next = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]), isFullySelected = next != t[START_CONTAINER], parent, clonedParent, nextSibling, clonedChild, clonedGrandParent;\r
+\r
+                       if (next == root)\r
+                               return _traverseNode(next, isFullySelected, TRUE, how);\r
+\r
+                       parent = next.parentNode;\r
+                       clonedParent = _traverseNode(parent, FALSE, TRUE, how);\r
+\r
+                       while (parent) {\r
+                               while (next) {\r
+                                       nextSibling = next.nextSibling;\r
+                                       clonedChild = _traverseNode(next, isFullySelected, TRUE, how);\r
+\r
+                                       if (how != DELETE)\r
+                                               clonedParent.appendChild(clonedChild);\r
+\r
+                                       isFullySelected = TRUE;\r
+                                       next = nextSibling;\r
+                               }\r
+\r
+                               if (parent == root)\r
+                                       return clonedParent;\r
+\r
+                               next = parent.nextSibling;\r
+                               parent = parent.parentNode;\r
+\r
+                               clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how);\r
+\r
+                               if (how != DELETE)\r
+                                       clonedGrandParent.appendChild(clonedParent);\r
+\r
+                               clonedParent = clonedGrandParent;\r
+                       }\r
+               };\r
+\r
+               function _traverseNode(n, isFullySelected, isLeft, how) {\r
+                       var txtValue, newNodeValue, oldNodeValue, offset, newNode;\r
+\r
+                       if (isFullySelected)\r
+                               return _traverseFullySelected(n, how);\r
+\r
+                       if (n.nodeType == 3 /* TEXT_NODE */) {\r
+                               txtValue = n.nodeValue;\r
+\r
+                               if (isLeft) {\r
+                                       offset = t[START_OFFSET];\r
+                                       newNodeValue = txtValue.substring(offset);\r
+                                       oldNodeValue = txtValue.substring(0, offset);\r
+                               } else {\r
+                                       offset = t[END_OFFSET];\r
+                                       newNodeValue = txtValue.substring(0, offset);\r
+                                       oldNodeValue = txtValue.substring(offset);\r
+                               }\r
+\r
+                               if (how != CLONE)\r
+                                       n.nodeValue = oldNodeValue;\r
+\r
+                               if (how == DELETE)\r
+                                       return;\r
+\r
+                               newNode = n.cloneNode(FALSE);\r
+                               newNode.nodeValue = newNodeValue;\r
+\r
+                               return newNode;\r
+                       }\r
+\r
+                       if (how == DELETE)\r
+                               return;\r
+\r
+                       return n.cloneNode(FALSE);\r
+               };\r
+\r
+               function _traverseFullySelected(n, how) {\r
+                       if (how != DELETE)\r
+                               return how == CLONE ? n.cloneNode(TRUE) : n;\r
+\r
+                       n.parentNode.removeChild(n);\r
+               };\r
+       };\r
+\r
+       ns.Range = Range;\r
+})(tinymce.dom);\r
+\r
+(function() {\r
+       function Selection(selection) {\r
+               var self = this, dom = selection.dom, TRUE = true, FALSE = false;\r
+\r
+               function getPosition(rng, start) {\r
+                       var checkRng, startIndex = 0, endIndex, inside,\r
+                               children, child, offset, index, position = -1, parent;\r
+\r
+                       // Setup test range, collapse it and get the parent\r
+                       checkRng = rng.duplicate();\r
+                       checkRng.collapse(start);\r
+                       parent = checkRng.parentElement();\r
+\r
+                       // Check if the selection is within the right document\r
+                       if (parent.ownerDocument !== selection.dom.doc)\r
+                               return;\r
+\r
+                       // IE will report non editable elements as it's parent so look for an editable one\r
+                       while (parent.contentEditable === "false") {\r
+                               parent = parent.parentNode;\r
+                       }\r
+\r
+                       // If parent doesn't have any children then return that we are inside the element\r
+                       if (!parent.hasChildNodes()) {\r
+                               return {node : parent, inside : 1};\r
+                       }\r
+\r
+                       // Setup node list and endIndex\r
+                       children = parent.children;\r
+                       endIndex = children.length - 1;\r
+\r
+                       // Perform a binary search for the position\r
+                       while (startIndex <= endIndex) {\r
+                               index = Math.floor((startIndex + endIndex) / 2);\r
+\r
+                               // Move selection to node and compare the ranges\r
+                               child = children[index];\r
+                               checkRng.moveToElementText(child);\r
+                               position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng);\r
+\r
+                               // Before/after or an exact match\r
+                               if (position > 0) {\r
+                                       endIndex = index - 1;\r
+                               } else if (position < 0) {\r
+                                       startIndex = index + 1;\r
+                               } else {\r
+                                       return {node : child};\r
+                               }\r
+                       }\r
+\r
+                       // Check if child position is before or we didn't find a position\r
+                       if (position < 0) {\r
+                               // No element child was found use the parent element and the offset inside that\r
+                               if (!child) {\r
+                                       checkRng.moveToElementText(parent);\r
+                                       checkRng.collapse(true);\r
+                                       child = parent;\r
+                                       inside = true;\r
+                               } else\r
+                                       checkRng.collapse(false);\r
+\r
+                               checkRng.setEndPoint(start ? 'EndToStart' : 'EndToEnd', rng);\r
+\r
+                               // Fix for edge case: <div style="width: 100px; height:100px;"><table>..</table>ab|c</div>\r
+                               if (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) > 0) {\r
+                                       checkRng = rng.duplicate();\r
+                                       checkRng.collapse(start);\r
+\r
+                                       offset = -1;\r
+                                       while (parent == checkRng.parentElement()) {\r
+                                               if (checkRng.move('character', -1) == 0)\r
+                                                       break;\r
+\r
+                                               offset++;\r
+                                       }\r
+                               }\r
+\r
+                               offset = offset || checkRng.text.replace('\r\n', ' ').length;\r
+                       } else {\r
+                               // Child position is after the selection endpoint\r
+                               checkRng.collapse(true);\r
+                               checkRng.setEndPoint(start ? 'StartToStart' : 'StartToEnd', rng);\r
+\r
+                               // Get the length of the text to find where the endpoint is relative to it's container\r
+                               offset = checkRng.text.replace('\r\n', ' ').length;\r
+                       }\r
+\r
+                       return {node : child, position : position, offset : offset, inside : inside};\r
+               };\r
+\r
+               // Returns a W3C DOM compatible range object by using the IE Range API\r
+               function getRange() {\r
+                       var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark, fail;\r
+\r
+                       // If selection is outside the current document just return an empty range\r
+                       element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();\r
+                       if (element.ownerDocument != dom.doc)\r
+                               return domRange;\r
+\r
+                       collapsed = selection.isCollapsed();\r
+\r
+                       // Handle control selection\r
+                       if (ieRange.item) {\r
+                               domRange.setStart(element.parentNode, dom.nodeIndex(element));\r
+                               domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);\r
+\r
+                               return domRange;\r
+                       }\r
+\r
+                       function findEndPoint(start) {\r
+                               var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue;\r
+\r
+                               container = endPoint.node;\r
+                               offset = endPoint.offset;\r
+\r
+                               if (endPoint.inside && !container.hasChildNodes()) {\r
+                                       domRange[start ? 'setStart' : 'setEnd'](container, 0);\r
+                                       return;\r
+                               }\r
+\r
+                               if (offset === undef) {\r
+                                       domRange[start ? 'setStartBefore' : 'setEndAfter'](container);\r
+                                       return;\r
+                               }\r
+\r
+                               if (endPoint.position < 0) {\r
+                                       sibling = endPoint.inside ? container.firstChild : container.nextSibling;\r
+\r
+                                       if (!sibling) {\r
+                                               domRange[start ? 'setStartAfter' : 'setEndAfter'](container);\r
+                                               return;\r
+                                       }\r
+\r
+                                       if (!offset) {\r
+                                               if (sibling.nodeType == 3)\r
+                                                       domRange[start ? 'setStart' : 'setEnd'](sibling, 0);\r
+                                               else\r
+                                                       domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling);\r
+\r
+                                               return;\r
+                                       }\r
+\r
+                                       // Find the text node and offset\r
+                                       while (sibling) {\r
+                                               nodeValue = sibling.nodeValue;\r
+                                               textNodeOffset += nodeValue.length;\r
+\r
+                                               // We are at or passed the position we where looking for\r
+                                               if (textNodeOffset >= offset) {\r
+                                                       container = sibling;\r
+                                                       textNodeOffset -= offset;\r
+                                                       textNodeOffset = nodeValue.length - textNodeOffset;\r
+                                                       break;\r
+                                               }\r
+\r
+                                               sibling = sibling.nextSibling;\r
+                                       }\r
+                               } else {\r
+                                       // Find the text node and offset\r
+                                       sibling = container.previousSibling;\r
+\r
+                                       if (!sibling)\r
+                                               return domRange[start ? 'setStartBefore' : 'setEndBefore'](container);\r
+\r
+                                       // If there isn't any text to loop then use the first position\r
+                                       if (!offset) {\r
+                                               if (container.nodeType == 3)\r
+                                                       domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length);\r
+                                               else\r
+                                                       domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling);\r
+\r
+                                               return;\r
+                                       }\r
+\r
+                                       while (sibling) {\r
+                                               textNodeOffset += sibling.nodeValue.length;\r
+\r
+                                               // We are at or passed the position we where looking for\r
+                                               if (textNodeOffset >= offset) {\r
+                                                       container = sibling;\r
+                                                       textNodeOffset -= offset;\r
+                                                       break;\r
+                                               }\r
+\r
+                                               sibling = sibling.previousSibling;\r
+                                       }\r
+                               }\r
+\r
+                               domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset);\r
+                       };\r
+\r
+                       try {\r
+                               // Find start point\r
+                               findEndPoint(true);\r
+\r
+                               // Find end point if needed\r
+                               if (!collapsed)\r
+                                       findEndPoint();\r
+                       } catch (ex) {\r
+                               // IE has a nasty bug where text nodes might throw "invalid argument" when you\r
+                               // access the nodeValue or other properties of text nodes. This seems to happend when\r
+                               // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it.\r
+                               if (ex.number == -2147024809) {\r
+                                       // Get the current selection\r
+                                       bookmark = self.getBookmark(2);\r
+\r
+                                       // Get start element\r
+                                       tmpRange = ieRange.duplicate();\r
+                                       tmpRange.collapse(true);\r
+                                       element = tmpRange.parentElement();\r
+\r
+                                       // Get end element\r
+                                       if (!collapsed) {\r
+                                               tmpRange = ieRange.duplicate();\r
+                                               tmpRange.collapse(false);\r
+                                               element2 = tmpRange.parentElement();\r
+                                               element2.innerHTML = element2.innerHTML;\r
+                                       }\r
+\r
+                                       // Remove the broken elements\r
+                                       element.innerHTML = element.innerHTML;\r
+\r
+                                       // Restore the selection\r
+                                       self.moveToBookmark(bookmark);\r
+\r
+                                       // Since the range has moved we need to re-get it\r
+                                       ieRange = selection.getRng();\r
+\r
+                                       // Find start point\r
+                                       findEndPoint(true);\r
+\r
+                                       // Find end point if needed\r
+                                       if (!collapsed)\r
+                                               findEndPoint();\r
+                               } else\r
+                                       throw ex; // Throw other errors\r
+                       }\r
+\r
+                       return domRange;\r
+               };\r
+\r
+               this.getBookmark = function(type) {\r
+                       var rng = selection.getRng(), start, end, bookmark = {};\r
+\r
+                       function getIndexes(node) {\r
+                               var node, parent, root, children, i, indexes = [];\r
+\r
+                               parent = node.parentNode;\r
+                               root = dom.getRoot().parentNode;\r
+\r
+                               while (parent != root) {\r
+                                       children = parent.children;\r
+\r
+                                       i = children.length;\r
+                                       while (i--) {\r
+                                               if (node === children[i]) {\r
+                                                       indexes.push(i);\r
+                                                       break;\r
+                                               }\r
+                                       }\r
+\r
+                                       node = parent;\r
+                                       parent = parent.parentNode;\r
+                               }\r
+\r
+                               return indexes;\r
+                       };\r
+\r
+                       function getBookmarkEndPoint(start) {\r
+                               var position;\r
+\r
+                               position = getPosition(rng, start);\r
+                               if (position) {\r
+                                       return {\r
+                                               position : position.position,\r
+                                               offset : position.offset,\r
+                                               indexes : getIndexes(position.node),\r
+                                               inside : position.inside\r
+                                       };\r
+                               }\r
+                       };\r
+\r
+                       // Non ubstructive bookmark\r
+                       if (type === 2) {\r
+                               // Handle text selection\r
+                               if (!rng.item) {\r
+                                       bookmark.start = getBookmarkEndPoint(true);\r
+\r
+                                       if (!selection.isCollapsed())\r
+                                               bookmark.end = getBookmarkEndPoint();\r
+                               } else\r
+                                       bookmark.start = {ctrl : true, indexes : getIndexes(rng.item(0))};\r
+                       }\r
+\r
+                       return bookmark;\r
+               };\r
+\r
+               this.moveToBookmark = function(bookmark) {\r
+                       var rng, body = dom.doc.body;\r
+\r
+                       function resolveIndexes(indexes) {\r
+                               var node, i, idx, children;\r
+\r
+                               node = dom.getRoot();\r
+                               for (i = indexes.length - 1; i >= 0; i--) {\r
+                                       children = node.children;\r
+                                       idx = indexes[i];\r
+\r
+                                       if (idx <= children.length - 1) {\r
+                                               node = children[idx];\r
+                                       }\r
+                               }\r
+\r
+                               return node;\r
+                       };\r
+                       \r
+                       function setBookmarkEndPoint(start) {\r
+                               var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef;\r
+\r
+                               if (endPoint) {\r
+                                       moveLeft = endPoint.position > 0;\r
+\r
+                                       moveRng = body.createTextRange();\r
+                                       moveRng.moveToElementText(resolveIndexes(endPoint.indexes));\r
+\r
+                                       offset = endPoint.offset;\r
+                                       if (offset !== undef) {\r
+                                               moveRng.collapse(endPoint.inside || moveLeft);\r
+                                               moveRng.moveStart('character', moveLeft ? -offset : offset);\r
+                                       } else\r
+                                               moveRng.collapse(start);\r
+\r
+                                       rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng);\r
+\r
+                                       if (start)\r
+                                               rng.collapse(true);\r
+                               }\r
+                       };\r
+\r
+                       if (bookmark.start) {\r
+                               if (bookmark.start.ctrl) {\r
+                                       rng = body.createControlRange();\r
+                                       rng.addElement(resolveIndexes(bookmark.start.indexes));\r
+                                       rng.select();\r
+                               } else {\r
+                                       rng = body.createTextRange();\r
+                                       setBookmarkEndPoint(true);\r
+                                       setBookmarkEndPoint();\r
+                                       rng.select();\r
+                               }\r
+                       }\r
+               };\r
+\r
+               this.addRange = function(rng) {\r
+                       var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body;\r
+\r
+                       function setEndPoint(start) {\r
+                               var container, offset, marker, tmpRng, nodes;\r
+\r
+                               marker = dom.create('a');\r
+                               container = start ? startContainer : endContainer;\r
+                               offset = start ? startOffset : endOffset;\r
+                               tmpRng = ieRng.duplicate();\r
+\r
+                               if (container == doc || container == doc.documentElement) {\r
+                                       container = body;\r
+                                       offset = 0;\r
+                               }\r
+\r
+                               if (container.nodeType == 3) {\r
+                                       container.parentNode.insertBefore(marker, container);\r
+                                       tmpRng.moveToElementText(marker);\r
+                                       tmpRng.moveStart('character', offset);\r
+                                       dom.remove(marker);\r
+                                       ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);\r
+                               } else {\r
+                                       nodes = container.childNodes;\r
+\r
+                                       if (nodes.length) {\r
+                                               if (offset >= nodes.length) {\r
+                                                       dom.insertAfter(marker, nodes[nodes.length - 1]);\r
+                                               } else {\r
+                                                       container.insertBefore(marker, nodes[offset]);\r
+                                               }\r
+\r
+                                               tmpRng.moveToElementText(marker);\r
+                                       } else {\r
+                                               // Empty node selection for example <div>|</div>\r
+                                               marker = doc.createTextNode('\uFEFF');\r
+                                               container.appendChild(marker);\r
+                                               tmpRng.moveToElementText(marker.parentNode);\r
+                                               tmpRng.collapse(TRUE);\r
+                                       }\r
+\r
+                                       ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);\r
+                                       dom.remove(marker);\r
+                               }\r
+                       }\r
+\r
+                       // Setup some shorter versions\r
+                       startContainer = rng.startContainer;\r
+                       startOffset = rng.startOffset;\r
+                       endContainer = rng.endContainer;\r
+                       endOffset = rng.endOffset;\r
+                       ieRng = body.createTextRange();\r
+\r
+                       // If single element selection then try making a control selection out of it\r
+                       if (startContainer == endContainer && startContainer.nodeType == 1 && startOffset == endOffset - 1) {\r
+                               if (startOffset == endOffset - 1) {\r
+                                       try {\r
+                                               ctrlRng = body.createControlRange();\r
+                                               ctrlRng.addElement(startContainer.childNodes[startOffset]);\r
+                                               ctrlRng.select();\r
+                                               return;\r
+                                       } catch (ex) {\r
+                                               // Ignore\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       // Set start/end point of selection\r
+                       setEndPoint(true);\r
+                       setEndPoint();\r
+\r
+                       // Select the new range and scroll it into view\r
+                       ieRng.select();\r
+               };\r
+\r
+               // Expose range method\r
+               this.getRangeAt = getRange;\r
+       };\r
+\r
+       // Expose the selection object\r
+       tinymce.dom.TridentSelection = Selection;\r
+})();\r
+\r
+\r
+/*\r
+ * Sizzle CSS Selector Engine - v1.0\r
+ *  Copyright 2009, The Dojo Foundation\r
+ *  Released under the MIT, BSD, and GPL Licenses.\r
+ *  More information: http://sizzlejs.com/\r
+ */\r
+(function(){\r
+\r
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,\r
+       done = 0,\r
+       toString = Object.prototype.toString,\r
+       hasDuplicate = false,\r
+       baseHasDuplicate = true;\r
+\r
+// Here we check if the JavaScript engine is using some sort of\r
+// optimization where it does not always call our comparision\r
+// function. If that is the case, discard the hasDuplicate value.\r
+//   Thus far that includes Google Chrome.\r
+[0, 0].sort(function(){\r
+       baseHasDuplicate = false;\r
+       return 0;\r
+});\r
+\r
+var Sizzle = function(selector, context, results, seed) {\r
+       results = results || [];\r
+       context = context || document;\r
+\r
+       var origContext = context;\r
+\r
+       if ( context.nodeType !== 1 && context.nodeType !== 9 ) {\r
+               return [];\r
+       }\r
+       \r
+       if ( !selector || typeof selector !== "string" ) {\r
+               return results;\r
+       }\r
+\r
+       var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),\r
+               soFar = selector, ret, cur, pop, i;\r
+       \r
+       // Reset the position of the chunker regexp (start from head)\r
+       do {\r
+               chunker.exec("");\r
+               m = chunker.exec(soFar);\r
+\r
+               if ( m ) {\r
+                       soFar = m[3];\r
+               \r
+                       parts.push( m[1] );\r
+               \r
+                       if ( m[2] ) {\r
+                               extra = m[3];\r
+                               break;\r
+                       }\r
+               }\r
+       } while ( m );\r
+\r
+       if ( parts.length > 1 && origPOS.exec( selector ) ) {\r
+               if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {\r
+                       set = posProcess( parts[0] + parts[1], context );\r
+               } else {\r
+                       set = Expr.relative[ parts[0] ] ?\r
+                               [ context ] :\r
+                               Sizzle( parts.shift(), context );\r
+\r
+                       while ( parts.length ) {\r
+                               selector = parts.shift();\r
+\r
+                               if ( Expr.relative[ selector ] ) {\r
+                                       selector += parts.shift();\r
+                               }\r
+                               \r
+                               set = posProcess( selector, set );\r
+                       }\r
+               }\r
+       } else {\r
+               // Take a shortcut and set the context if the root selector is an ID\r
+               // (but not if it'll be faster if the inner selector is an ID)\r
+               if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&\r
+                               Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {\r
+                       ret = Sizzle.find( parts.shift(), context, contextXML );\r
+                       context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];\r
+               }\r
+\r
+               if ( context ) {\r
+                       ret = seed ?\r
+                               { expr: parts.pop(), set: makeArray(seed) } :\r
+                               Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );\r
+                       set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;\r
+\r
+                       if ( parts.length > 0 ) {\r
+                               checkSet = makeArray(set);\r
+                       } else {\r
+                               prune = false;\r
+                       }\r
+\r
+                       while ( parts.length ) {\r
+                               cur = parts.pop();\r
+                               pop = cur;\r
+\r
+                               if ( !Expr.relative[ cur ] ) {\r
+                                       cur = "";\r
+                               } else {\r
+                                       pop = parts.pop();\r
+                               }\r
+\r
+                               if ( pop == null ) {\r
+                                       pop = context;\r
+                               }\r
+\r
+                               Expr.relative[ cur ]( checkSet, pop, contextXML );\r
+                       }\r
+               } else {\r
+                       checkSet = parts = [];\r
+               }\r
+       }\r
+\r
+       if ( !checkSet ) {\r
+               checkSet = set;\r
+       }\r
+\r
+       if ( !checkSet ) {\r
+               Sizzle.error( cur || selector );\r
+       }\r
+\r
+       if ( toString.call(checkSet) === "[object Array]" ) {\r
+               if ( !prune ) {\r
+                       results.push.apply( results, checkSet );\r
+               } else if ( context && context.nodeType === 1 ) {\r
+                       for ( i = 0; checkSet[i] != null; i++ ) {\r
+                               if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {\r
+                                       results.push( set[i] );\r
+                               }\r
+                       }\r
+               } else {\r
+                       for ( i = 0; checkSet[i] != null; i++ ) {\r
+                               if ( checkSet[i] && checkSet[i].nodeType === 1 ) {\r
+                                       results.push( set[i] );\r
+                               }\r
+                       }\r
+               }\r
+       } else {\r
+               makeArray( checkSet, results );\r
+       }\r
+\r
+       if ( extra ) {\r
+               Sizzle( extra, origContext, results, seed );\r
+               Sizzle.uniqueSort( results );\r
+       }\r
+\r
+       return results;\r
+};\r
+\r
+Sizzle.uniqueSort = function(results){\r
+       if ( sortOrder ) {\r
+               hasDuplicate = baseHasDuplicate;\r
+               results.sort(sortOrder);\r
+\r
+               if ( hasDuplicate ) {\r
+                       for ( var i = 1; i < results.length; i++ ) {\r
+                               if ( results[i] === results[i-1] ) {\r
+                                       results.splice(i--, 1);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+\r
+       return results;\r
+};\r
+\r
+Sizzle.matches = function(expr, set){\r
+       return Sizzle(expr, null, null, set);\r
+};\r
+\r
+Sizzle.find = function(expr, context, isXML){\r
+       var set;\r
+\r
+       if ( !expr ) {\r
+               return [];\r
+       }\r
+\r
+       for ( var i = 0, l = Expr.order.length; i < l; i++ ) {\r
+               var type = Expr.order[i], match;\r
+               \r
+               if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {\r
+                       var left = match[1];\r
+                       match.splice(1,1);\r
+\r
+                       if ( left.substr( left.length - 1 ) !== "\\" ) {\r
+                               match[1] = (match[1] || "").replace(/\\/g, "");\r
+                               set = Expr.find[ type ]( match, context, isXML );\r
+                               if ( set != null ) {\r
+                                       expr = expr.replace( Expr.match[ type ], "" );\r
+                                       break;\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+\r
+       if ( !set ) {\r
+               set = context.getElementsByTagName("*");\r
+       }\r
+\r
+       return {set: set, expr: expr};\r
+};\r
+\r
+Sizzle.filter = function(expr, set, inplace, not){\r
+       var old = expr, result = [], curLoop = set, match, anyFound,\r
+               isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);\r
+\r
+       while ( expr && set.length ) {\r
+               for ( var type in Expr.filter ) {\r
+                       if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {\r
+                               var filter = Expr.filter[ type ], found, item, left = match[1];\r
+                               anyFound = false;\r
+\r
+                               match.splice(1,1);\r
+\r
+                               if ( left.substr( left.length - 1 ) === "\\" ) {\r
+                                       continue;\r
+                               }\r
+\r
+                               if ( curLoop === result ) {\r
+                                       result = [];\r
+                               }\r
+\r
+                               if ( Expr.preFilter[ type ] ) {\r
+                                       match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );\r
+\r
+                                       if ( !match ) {\r
+                                               anyFound = found = true;\r
+                                       } else if ( match === true ) {\r
+                                               continue;\r
+                                       }\r
+                               }\r
+\r
+                               if ( match ) {\r
+                                       for ( var i = 0; (item = curLoop[i]) != null; i++ ) {\r
+                                               if ( item ) {\r
+                                                       found = filter( item, match, i, curLoop );\r
+                                                       var pass = not ^ !!found;\r
+\r
+                                                       if ( inplace && found != null ) {\r
+                                                               if ( pass ) {\r
+                                                                       anyFound = true;\r
+                                                               } else {\r
+                                                                       curLoop[i] = false;\r
+                                                               }\r
+                                                       } else if ( pass ) {\r
+                                                               result.push( item );\r
+                                                               anyFound = true;\r
+                                                       }\r
+                                               }\r
+                                       }\r
+                               }\r
+\r
+                               if ( found !== undefined ) {\r
+                                       if ( !inplace ) {\r
+                                               curLoop = result;\r
+                                       }\r
+\r
+                                       expr = expr.replace( Expr.match[ type ], "" );\r
+\r
+                                       if ( !anyFound ) {\r
+                                               return [];\r
+                                       }\r
+\r
+                                       break;\r
+                               }\r
+                       }\r
+               }\r
+\r
+               // Improper expression\r
+               if ( expr === old ) {\r
+                       if ( anyFound == null ) {\r
+                               Sizzle.error( expr );\r
+                       } else {\r
+                               break;\r
+                       }\r
+               }\r
+\r
+               old = expr;\r
+       }\r
+\r
+       return curLoop;\r
+};\r
+\r
+Sizzle.error = function( msg ) {\r
+       throw "Syntax error, unrecognized expression: " + msg;\r
+};\r
+\r
+var Expr = Sizzle.selectors = {\r
+       order: [ "ID", "NAME", "TAG" ],\r
+       match: {\r
+               ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,\r
+               CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,\r
+               NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,\r
+               ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,\r
+               TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,\r
+               CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,\r
+               POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,\r
+               PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/\r
+       },\r
+       leftMatch: {},\r
+       attrMap: {\r
+               "class": "className",\r
+               "for": "htmlFor"\r
+       },\r
+       attrHandle: {\r
+               href: function(elem){\r
+                       return elem.getAttribute("href");\r
+               }\r
+       },\r
+       relative: {\r
+               "+": function(checkSet, part){\r
+                       var isPartStr = typeof part === "string",\r
+                               isTag = isPartStr && !/\W/.test(part),\r
+                               isPartStrNotTag = isPartStr && !isTag;\r
+\r
+                       if ( isTag ) {\r
+                               part = part.toLowerCase();\r
+                       }\r
+\r
+                       for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {\r
+                               if ( (elem = checkSet[i]) ) {\r
+                                       while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}\r
+\r
+                                       checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?\r
+                                               elem || false :\r
+                                               elem === part;\r
+                               }\r
+                       }\r
+\r
+                       if ( isPartStrNotTag ) {\r
+                               Sizzle.filter( part, checkSet, true );\r
+                       }\r
+               },\r
+               ">": function(checkSet, part){\r
+                       var isPartStr = typeof part === "string",\r
+                               elem, i = 0, l = checkSet.length;\r
+\r
+                       if ( isPartStr && !/\W/.test(part) ) {\r
+                               part = part.toLowerCase();\r
+\r
+                               for ( ; i < l; i++ ) {\r
+                                       elem = checkSet[i];\r
+                                       if ( elem ) {\r
+                                               var parent = elem.parentNode;\r
+                                               checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;\r
+                                       }\r
+                               }\r
+                       } else {\r
+                               for ( ; i < l; i++ ) {\r
+                                       elem = checkSet[i];\r
+                                       if ( elem ) {\r
+                                               checkSet[i] = isPartStr ?\r
+                                                       elem.parentNode :\r
+                                                       elem.parentNode === part;\r
+                                       }\r
+                               }\r
+\r
+                               if ( isPartStr ) {\r
+                                       Sizzle.filter( part, checkSet, true );\r
+                               }\r
+                       }\r
+               },\r
+               "": function(checkSet, part, isXML){\r
+                       var doneName = done++, checkFn = dirCheck, nodeCheck;\r
+\r
+                       if ( typeof part === "string" && !/\W/.test(part) ) {\r
+                               part = part.toLowerCase();\r
+                               nodeCheck = part;\r
+                               checkFn = dirNodeCheck;\r
+                       }\r
+\r
+                       checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);\r
+               },\r
+               "~": function(checkSet, part, isXML){\r
+                       var doneName = done++, checkFn = dirCheck, nodeCheck;\r
+\r
+                       if ( typeof part === "string" && !/\W/.test(part) ) {\r
+                               part = part.toLowerCase();\r
+                               nodeCheck = part;\r
+                               checkFn = dirNodeCheck;\r
+                       }\r
+\r
+                       checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);\r
+               }\r
+       },\r
+       find: {\r
+               ID: function(match, context, isXML){\r
+                       if ( typeof context.getElementById !== "undefined" && !isXML ) {\r
+                               var m = context.getElementById(match[1]);\r
+                               return m ? [m] : [];\r
+                       }\r
+               },\r
+               NAME: function(match, context){\r
+                       if ( typeof context.getElementsByName !== "undefined" ) {\r
+                               var ret = [], results = context.getElementsByName(match[1]);\r
+\r
+                               for ( var i = 0, l = results.length; i < l; i++ ) {\r
+                                       if ( results[i].getAttribute("name") === match[1] ) {\r
+                                               ret.push( results[i] );\r
+                                       }\r
+                               }\r
+\r
+                               return ret.length === 0 ? null : ret;\r
+                       }\r
+               },\r
+               TAG: function(match, context){\r
+                       return context.getElementsByTagName(match[1]);\r
+               }\r
+       },\r
+       preFilter: {\r
+               CLASS: function(match, curLoop, inplace, result, not, isXML){\r
+                       match = " " + match[1].replace(/\\/g, "") + " ";\r
+\r
+                       if ( isXML ) {\r
+                               return match;\r
+                       }\r
+\r
+                       for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {\r
+                               if ( elem ) {\r
+                                       if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {\r
+                                               if ( !inplace ) {\r
+                                                       result.push( elem );\r
+                                               }\r
+                                       } else if ( inplace ) {\r
+                                               curLoop[i] = false;\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       return false;\r
+               },\r
+               ID: function(match){\r
+                       return match[1].replace(/\\/g, "");\r
+               },\r
+               TAG: function(match, curLoop){\r
+                       return match[1].toLowerCase();\r
+               },\r
+               CHILD: function(match){\r
+                       if ( match[1] === "nth" ) {\r
+                               // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'\r
+                               var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(\r
+                                       match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||\r
+                                       !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);\r
+\r
+                               // calculate the numbers (first)n+(last) including if they are negative\r
+                               match[2] = (test[1] + (test[2] || 1)) - 0;\r
+                               match[3] = test[3] - 0;\r
+                       }\r
+\r
+                       // TODO: Move to normal caching system\r
+                       match[0] = done++;\r
+\r
+                       return match;\r
+               },\r
+               ATTR: function(match, curLoop, inplace, result, not, isXML){\r
+                       var name = match[1].replace(/\\/g, "");\r
+                       \r
+                       if ( !isXML && Expr.attrMap[name] ) {\r
+                               match[1] = Expr.attrMap[name];\r
+                       }\r
+\r
+                       if ( match[2] === "~=" ) {\r
+                               match[4] = " " + match[4] + " ";\r
+                       }\r
+\r
+                       return match;\r
+               },\r
+               PSEUDO: function(match, curLoop, inplace, result, not){\r
+                       if ( match[1] === "not" ) {\r
+                               // If we're dealing with a complex expression, or a simple one\r
+                               if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {\r
+                                       match[3] = Sizzle(match[3], null, null, curLoop);\r
+                               } else {\r
+                                       var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);\r
+                                       if ( !inplace ) {\r
+                                               result.push.apply( result, ret );\r
+                                       }\r
+                                       return false;\r
+                               }\r
+                       } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {\r
+                               return true;\r
+                       }\r
+                       \r
+                       return match;\r
+               },\r
+               POS: function(match){\r
+                       match.unshift( true );\r
+                       return match;\r
+               }\r
+       },\r
+       filters: {\r
+               enabled: function(elem){\r
+                       return elem.disabled === false && elem.type !== "hidden";\r
+               },\r
+               disabled: function(elem){\r
+                       return elem.disabled === true;\r
+               },\r
+               checked: function(elem){\r
+                       return elem.checked === true;\r
+               },\r
+               selected: function(elem){\r
+                       // Accessing this property makes selected-by-default\r
+                       // options in Safari work properly\r
+                       elem.parentNode.selectedIndex;\r
+                       return elem.selected === true;\r
+               },\r
+               parent: function(elem){\r
+                       return !!elem.firstChild;\r
+               },\r
+               empty: function(elem){\r
+                       return !elem.firstChild;\r
+               },\r
+               has: function(elem, i, match){\r
+                       return !!Sizzle( match[3], elem ).length;\r
+               },\r
+               header: function(elem){\r
+                       return (/h\d/i).test( elem.nodeName );\r
+               },\r
+               text: function(elem){\r
+                       return "text" === elem.type;\r
+               },\r
+               radio: function(elem){\r
+                       return "radio" === elem.type;\r
+               },\r
+               checkbox: function(elem){\r
+                       return "checkbox" === elem.type;\r
+               },\r
+               file: function(elem){\r
+                       return "file" === elem.type;\r
+               },\r
+               password: function(elem){\r
+                       return "password" === elem.type;\r
+               },\r
+               submit: function(elem){\r
+                       return "submit" === elem.type;\r
+               },\r
+               image: function(elem){\r
+                       return "image" === elem.type;\r
+               },\r
+               reset: function(elem){\r
+                       return "reset" === elem.type;\r
+               },\r
+               button: function(elem){\r
+                       return "button" === elem.type || elem.nodeName.toLowerCase() === "button";\r
+               },\r
+               input: function(elem){\r
+                       return (/input|select|textarea|button/i).test(elem.nodeName);\r
+               }\r
+       },\r
+       setFilters: {\r
+               first: function(elem, i){\r
+                       return i === 0;\r
+               },\r
+               last: function(elem, i, match, array){\r
+                       return i === array.length - 1;\r
+               },\r
+               even: function(elem, i){\r
+                       return i % 2 === 0;\r
+               },\r
+               odd: function(elem, i){\r
+                       return i % 2 === 1;\r
+               },\r
+               lt: function(elem, i, match){\r
+                       return i < match[3] - 0;\r
+               },\r
+               gt: function(elem, i, match){\r
+                       return i > match[3] - 0;\r
+               },\r
+               nth: function(elem, i, match){\r
+                       return match[3] - 0 === i;\r
+               },\r
+               eq: function(elem, i, match){\r
+                       return match[3] - 0 === i;\r
+               }\r
+       },\r
+       filter: {\r
+               PSEUDO: function(elem, match, i, array){\r
+                       var name = match[1], filter = Expr.filters[ name ];\r
+\r
+                       if ( filter ) {\r
+                               return filter( elem, i, match, array );\r
+                       } else if ( name === "contains" ) {\r
+                               return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;\r
+                       } else if ( name === "not" ) {\r
+                               var not = match[3];\r
+\r
+                               for ( var j = 0, l = not.length; j < l; j++ ) {\r
+                                       if ( not[j] === elem ) {\r
+                                               return false;\r
+                                       }\r
+                               }\r
+\r
+                               return true;\r
+                       } else {\r
+                               Sizzle.error( "Syntax error, unrecognized expression: " + name );\r
+                       }\r
+               },\r
+               CHILD: function(elem, match){\r
+                       var type = match[1], node = elem;\r
+                       switch (type) {\r
+                               case 'only':\r
+                               case 'first':\r
+                                       while ( (node = node.previousSibling) )  {\r
+                                               if ( node.nodeType === 1 ) { \r
+                                                       return false; \r
+                                               }\r
+                                       }\r
+                                       if ( type === "first" ) { \r
+                                               return true; \r
+                                       }\r
+                                       node = elem;\r
+                               case 'last':\r
+                                       while ( (node = node.nextSibling) )      {\r
+                                               if ( node.nodeType === 1 ) { \r
+                                                       return false; \r
+                                               }\r
+                                       }\r
+                                       return true;\r
+                               case 'nth':\r
+                                       var first = match[2], last = match[3];\r
+\r
+                                       if ( first === 1 && last === 0 ) {\r
+                                               return true;\r
+                                       }\r
+                                       \r
+                                       var doneName = match[0],\r
+                                               parent = elem.parentNode;\r
+       \r
+                                       if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {\r
+                                               var count = 0;\r
+                                               for ( node = parent.firstChild; node; node = node.nextSibling ) {\r
+                                                       if ( node.nodeType === 1 ) {\r
+                                                               node.nodeIndex = ++count;\r
+                                                       }\r
+                                               } \r
+                                               parent.sizcache = doneName;\r
+                                       }\r
+                                       \r
+                                       var diff = elem.nodeIndex - last;\r
+                                       if ( first === 0 ) {\r
+                                               return diff === 0;\r
+                                       } else {\r
+                                               return ( diff % first === 0 && diff / first >= 0 );\r
+                                       }\r
+                       }\r
+               },\r
+               ID: function(elem, match){\r
+                       return elem.nodeType === 1 && elem.getAttribute("id") === match;\r
+               },\r
+               TAG: function(elem, match){\r
+                       return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;\r
+               },\r
+               CLASS: function(elem, match){\r
+                       return (" " + (elem.className || elem.getAttribute("class")) + " ")\r
+                               .indexOf( match ) > -1;\r
+               },\r
+               ATTR: function(elem, match){\r
+                       var name = match[1],\r
+                               result = Expr.attrHandle[ name ] ?\r
+                                       Expr.attrHandle[ name ]( elem ) :\r
+                                       elem[ name ] != null ?\r
+                                               elem[ name ] :\r
+                                               elem.getAttribute( name ),\r
+                               value = result + "",\r
+                               type = match[2],\r
+                               check = match[4];\r
+\r
+                       return result == null ?\r
+                               type === "!=" :\r
+                               type === "=" ?\r
+                               value === check :\r
+                               type === "*=" ?\r
+                               value.indexOf(check) >= 0 :\r
+                               type === "~=" ?\r
+                               (" " + value + " ").indexOf(check) >= 0 :\r
+                               !check ?\r
+                               value && result !== false :\r
+                               type === "!=" ?\r
+                               value !== check :\r
+                               type === "^=" ?\r
+                               value.indexOf(check) === 0 :\r
+                               type === "$=" ?\r
+                               value.substr(value.length - check.length) === check :\r
+                               type === "|=" ?\r
+                               value === check || value.substr(0, check.length + 1) === check + "-" :\r
+                               false;\r
+               },\r
+               POS: function(elem, match, i, array){\r
+                       var name = match[2], filter = Expr.setFilters[ name ];\r
+\r
+                       if ( filter ) {\r
+                               return filter( elem, i, match, array );\r
+                       }\r
+               }\r
+       }\r
+};\r
+\r
+var origPOS = Expr.match.POS,\r
+       fescape = function(all, num){\r
+               return "\\" + (num - 0 + 1);\r
+       };\r
+\r
+for ( var type in Expr.match ) {\r
+       Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );\r
+       Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );\r
+}\r
+\r
+var makeArray = function(array, results) {\r
+       array = Array.prototype.slice.call( array, 0 );\r
+\r
+       if ( results ) {\r
+               results.push.apply( results, array );\r
+               return results;\r
+       }\r
+       \r
+       return array;\r
+};\r
+\r
+// Perform a simple check to determine if the browser is capable of\r
+// converting a NodeList to an array using builtin methods.\r
+// Also verifies that the returned array holds DOM nodes\r
+// (which is not the case in the Blackberry browser)\r
+try {\r
+       Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;\r
+\r
+// Provide a fallback method if it does not work\r
+} catch(e){\r
+       makeArray = function(array, results) {\r
+               var ret = results || [], i = 0;\r
+\r
+               if ( toString.call(array) === "[object Array]" ) {\r
+                       Array.prototype.push.apply( ret, array );\r
+               } else {\r
+                       if ( typeof array.length === "number" ) {\r
+                               for ( var l = array.length; i < l; i++ ) {\r
+                                       ret.push( array[i] );\r
+                               }\r
+                       } else {\r
+                               for ( ; array[i]; i++ ) {\r
+                                       ret.push( array[i] );\r
+                               }\r
+                       }\r
+               }\r
+\r
+               return ret;\r
+       };\r
+}\r
+\r
+var sortOrder;\r
+\r
+if ( document.documentElement.compareDocumentPosition ) {\r
+       sortOrder = function( a, b ) {\r
+               if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {\r
+                       if ( a == b ) {\r
+                               hasDuplicate = true;\r
+                       }\r
+                       return a.compareDocumentPosition ? -1 : 1;\r
+               }\r
+\r
+               var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;\r
+               if ( ret === 0 ) {\r
+                       hasDuplicate = true;\r
+               }\r
+               return ret;\r
+       };\r
+} else if ( "sourceIndex" in document.documentElement ) {\r
+       sortOrder = function( a, b ) {\r
+               if ( !a.sourceIndex || !b.sourceIndex ) {\r
+                       if ( a == b ) {\r
+                               hasDuplicate = true;\r
+                       }\r
+                       return a.sourceIndex ? -1 : 1;\r
+               }\r
+\r
+               var ret = a.sourceIndex - b.sourceIndex;\r
+               if ( ret === 0 ) {\r
+                       hasDuplicate = true;\r
+               }\r
+               return ret;\r
+       };\r
+} else if ( document.createRange ) {\r
+       sortOrder = function( a, b ) {\r
+               if ( !a.ownerDocument || !b.ownerDocument ) {\r
+                       if ( a == b ) {\r
+                               hasDuplicate = true;\r
+                       }\r
+                       return a.ownerDocument ? -1 : 1;\r
+               }\r
+\r
+               var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();\r
+               aRange.setStart(a, 0);\r
+               aRange.setEnd(a, 0);\r
+               bRange.setStart(b, 0);\r
+               bRange.setEnd(b, 0);\r
+               var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);\r
+               if ( ret === 0 ) {\r
+                       hasDuplicate = true;\r
+               }\r
+               return ret;\r
+       };\r
+}\r
+\r
+// Utility function for retreiving the text value of an array of DOM nodes\r
+Sizzle.getText = function( elems ) {\r
+       var ret = "", elem;\r
+\r
+       for ( var i = 0; elems[i]; i++ ) {\r
+               elem = elems[i];\r
+\r
+               // Get the text from text nodes and CDATA nodes\r
+               if ( elem.nodeType === 3 || elem.nodeType === 4 ) {\r
+                       ret += elem.nodeValue;\r
+\r
+               // Traverse everything else, except comment nodes\r
+               } else if ( elem.nodeType !== 8 ) {\r
+                       ret += Sizzle.getText( elem.childNodes );\r
+               }\r
+       }\r
+\r
+       return ret;\r
+};\r
+\r
+// Check to see if the browser returns elements by name when\r
+// querying by getElementById (and provide a workaround)\r
+(function(){\r
+       // We're going to inject a fake input element with a specified name\r
+       var form = document.createElement("div"),\r
+               id = "script" + (new Date()).getTime();\r
+       form.innerHTML = "<a name='" + id + "'/>";\r
+\r
+       // Inject it into the root element, check its status, and remove it quickly\r
+       var root = document.documentElement;\r
+       root.insertBefore( form, root.firstChild );\r
+\r
+       // The workaround has to do additional checks after a getElementById\r
+       // Which slows things down for other browsers (hence the branching)\r
+       if ( document.getElementById( id ) ) {\r
+               Expr.find.ID = function(match, context, isXML){\r
+                       if ( typeof context.getElementById !== "undefined" && !isXML ) {\r
+                               var m = context.getElementById(match[1]);\r
+                               return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];\r
+                       }\r
+               };\r
+\r
+               Expr.filter.ID = function(elem, match){\r
+                       var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");\r
+                       return elem.nodeType === 1 && node && node.nodeValue === match;\r
+               };\r
+       }\r
+\r
+       root.removeChild( form );\r
+       root = form = null; // release memory in IE\r
+})();\r
+\r
+(function(){\r
+       // Check to see if the browser returns only elements\r
+       // when doing getElementsByTagName("*")\r
+\r
+       // Create a fake element\r
+       var div = document.createElement("div");\r
+       div.appendChild( document.createComment("") );\r
+\r
+       // Make sure no comments are found\r
+       if ( div.getElementsByTagName("*").length > 0 ) {\r
+               Expr.find.TAG = function(match, context){\r
+                       var results = context.getElementsByTagName(match[1]);\r
+\r
+                       // Filter out possible comments\r
+                       if ( match[1] === "*" ) {\r
+                               var tmp = [];\r
+\r
+                               for ( var i = 0; results[i]; i++ ) {\r
+                                       if ( results[i].nodeType === 1 ) {\r
+                                               tmp.push( results[i] );\r
+                                       }\r
+                               }\r
+\r
+                               results = tmp;\r
+                       }\r
+\r
+                       return results;\r
+               };\r
+       }\r
+\r
+       // Check to see if an attribute returns normalized href attributes\r
+       div.innerHTML = "<a href='#'></a>";\r
+       if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&\r
+                       div.firstChild.getAttribute("href") !== "#" ) {\r
+               Expr.attrHandle.href = function(elem){\r
+                       return elem.getAttribute("href", 2);\r
+               };\r
+       }\r
+\r
+       div = null; // release memory in IE\r
+})();\r
+\r
+if ( document.querySelectorAll ) {\r
+       (function(){\r
+               var oldSizzle = Sizzle, div = document.createElement("div");\r
+               div.innerHTML = "<p class='TEST'></p>";\r
+\r
+               // Safari can't handle uppercase or unicode characters when\r
+               // in quirks mode.\r
+               if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {\r
+                       return;\r
+               }\r
+       \r
+               Sizzle = function(query, context, extra, seed){\r
+                       context = context || document;\r
+\r
+                       // Only use querySelectorAll on non-XML documents\r
+                       // (ID selectors don't work in non-HTML documents)\r
+                       if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {\r
+                               try {\r
+                                       return makeArray( context.querySelectorAll(query), extra );\r
+                               } catch(e){}\r
+                       }\r
+               \r
+                       return oldSizzle(query, context, extra, seed);\r
+               };\r
+\r
+               for ( var prop in oldSizzle ) {\r
+                       Sizzle[ prop ] = oldSizzle[ prop ];\r
+               }\r
+\r
+               div = null; // release memory in IE\r
+       })();\r
+}\r
+\r
+(function(){\r
+       var div = document.createElement("div");\r
+\r
+       div.innerHTML = "<div class='test e'></div><div class='test'></div>";\r
+\r
+       // Opera can't find a second classname (in 9.6)\r
+       // Also, make sure that getElementsByClassName actually exists\r
+       if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {\r
+               return;\r
+       }\r
+\r
+       // Safari caches class attributes, doesn't catch changes (in 3.2)\r
+       div.lastChild.className = "e";\r
+\r
+       if ( div.getElementsByClassName("e").length === 1 ) {\r
+               return;\r
+       }\r
+       \r
+       Expr.order.splice(1, 0, "CLASS");\r
+       Expr.find.CLASS = function(match, context, isXML) {\r
+               if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {\r
+                       return context.getElementsByClassName(match[1]);\r
+               }\r
+       };\r
+\r
+       div = null; // release memory in IE\r
+})();\r
+\r
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {\r
+       for ( var i = 0, l = checkSet.length; i < l; i++ ) {\r
+               var elem = checkSet[i];\r
+               if ( elem ) {\r
+                       elem = elem[dir];\r
+                       var match = false;\r
+\r
+                       while ( elem ) {\r
+                               if ( elem.sizcache === doneName ) {\r
+                                       match = checkSet[elem.sizset];\r
+                                       break;\r
+                               }\r
+\r
+                               if ( elem.nodeType === 1 && !isXML ){\r
+                                       elem.sizcache = doneName;\r
+                                       elem.sizset = i;\r
+                               }\r
+\r
+                               if ( elem.nodeName.toLowerCase() === cur ) {\r
+                                       match = elem;\r
+                                       break;\r
+                               }\r
+\r
+                               elem = elem[dir];\r
+                       }\r
+\r
+                       checkSet[i] = match;\r
+               }\r
+       }\r
+}\r
+\r
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {\r
+       for ( var i = 0, l = checkSet.length; i < l; i++ ) {\r
+               var elem = checkSet[i];\r
+               if ( elem ) {\r
+                       elem = elem[dir];\r
+                       var match = false;\r
+\r
+                       while ( elem ) {\r
+                               if ( elem.sizcache === doneName ) {\r
+                                       match = checkSet[elem.sizset];\r
+                                       break;\r
+                               }\r
+\r
+                               if ( elem.nodeType === 1 ) {\r
+                                       if ( !isXML ) {\r
+                                               elem.sizcache = doneName;\r
+                                               elem.sizset = i;\r
+                                       }\r
+                                       if ( typeof cur !== "string" ) {\r
+                                               if ( elem === cur ) {\r
+                                                       match = true;\r
+                                                       break;\r
+                                               }\r
+\r
+                                       } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {\r
+                                               match = elem;\r
+                                               break;\r
+                                       }\r
+                               }\r
+\r
+                               elem = elem[dir];\r
+                       }\r
+\r
+                       checkSet[i] = match;\r
+               }\r
+       }\r
+}\r
+\r
+Sizzle.contains = document.compareDocumentPosition ? function(a, b){\r
+       return !!(a.compareDocumentPosition(b) & 16);\r
+} : function(a, b){\r
+       return a !== b && (a.contains ? a.contains(b) : true);\r
+};\r
+\r
+Sizzle.isXML = function(elem){\r
+       // documentElement is verified for cases where it doesn't yet exist\r
+       // (such as loading iframes in IE - #4833) \r
+       var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;\r
+       return documentElement ? documentElement.nodeName !== "HTML" : false;\r
+};\r
+\r
+var posProcess = function(selector, context){\r
+       var tmpSet = [], later = "", match,\r
+               root = context.nodeType ? [context] : context;\r
+\r
+       // Position selectors must be done after the filter\r
+       // And so must :not(positional) so we move all PSEUDOs to the end\r
+       while ( (match = Expr.match.PSEUDO.exec( selector )) ) {\r
+               later += match[0];\r
+               selector = selector.replace( Expr.match.PSEUDO, "" );\r
+       }\r
+\r
+       selector = Expr.relative[selector] ? selector + "*" : selector;\r
+\r
+       for ( var i = 0, l = root.length; i < l; i++ ) {\r
+               Sizzle( selector, root[i], tmpSet );\r
+       }\r
+\r
+       return Sizzle.filter( later, tmpSet );\r
+};\r
+\r
+// EXPOSE\r
+\r
+window.tinymce.dom.Sizzle = Sizzle;\r
+\r
+})();\r
+\r
+\r
+(function(tinymce) {\r
+       // Shorten names\r
+       var each = tinymce.each, DOM = tinymce.DOM, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, Event;\r
+\r
+       tinymce.create('tinymce.dom.EventUtils', {\r
+               EventUtils : function() {\r
+                       this.inits = [];\r
+                       this.events = [];\r
+               },\r
+\r
+               add : function(o, n, f, s) {\r
+                       var cb, t = this, el = t.events, r;\r
+\r
+                       if (n instanceof Array) {\r
+                               r = [];\r
+\r
+                               each(n, function(n) {\r
+                                       r.push(t.add(o, n, f, s));\r
+                               });\r
+\r
+                               return r;\r
+                       }\r
+\r
+                       // Handle array\r
+                       if (o && o.hasOwnProperty && o instanceof Array) {\r
+                               r = [];\r
+\r
+                               each(o, function(o) {\r
+                                       o = DOM.get(o);\r
+                                       r.push(t.add(o, n, f, s));\r
+                               });\r
+\r
+                               return r;\r
+                       }\r
+\r
+                       o = DOM.get(o);\r
+\r
+                       if (!o)\r
+                               return;\r
+\r
+                       // Setup event callback\r
+                       cb = function(e) {\r
+                               // Is all events disabled\r
+                               if (t.disabled)\r
+                                       return;\r
+\r
+                               e = e || window.event;\r
+\r
+                               // Patch in target, preventDefault and stopPropagation in IE it's W3C valid\r
+                               if (e && isIE) {\r
+                                       if (!e.target)\r
+                                               e.target = e.srcElement;\r
+\r
+                                       // Patch in preventDefault, stopPropagation methods for W3C compatibility\r
+                                       tinymce.extend(e, t._stoppers);\r
+                               }\r
+\r
+                               if (!s)\r
+                                       return f(e);\r
+\r
+                               return f.call(s, e);\r
+                       };\r
+\r
+                       if (n == 'unload') {\r
+                               tinymce.unloads.unshift({func : cb});\r
+                               return cb;\r
+                       }\r
+\r
+                       if (n == 'init') {\r
+                               if (t.domLoaded)\r
+                                       cb();\r
+                               else\r
+                                       t.inits.push(cb);\r
+\r
+                               return cb;\r
+                       }\r
+\r
+                       // Store away listener reference\r
+                       el.push({\r
+                               obj : o,\r
+                               name : n,\r
+                               func : f,\r
+                               cfunc : cb,\r
+                               scope : s\r
+                       });\r
+\r
+                       t._add(o, n, cb);\r
+\r
+                       return f;\r
+               },\r
+\r
+               remove : function(o, n, f) {\r
+                       var t = this, a = t.events, s = false, r;\r
+\r
+                       // Handle array\r
+                       if (o && o.hasOwnProperty && o instanceof Array) {\r
+                               r = [];\r
+\r
+                               each(o, function(o) {\r
+                                       o = DOM.get(o);\r
+                                       r.push(t.remove(o, n, f));\r
+                               });\r
+\r
+                               return r;\r
+                       }\r
+\r
+                       o = DOM.get(o);\r
+\r
+                       each(a, function(e, i) {\r
+                               if (e.obj == o && e.name == n && (!f || (e.func == f || e.cfunc == f))) {\r
+                                       a.splice(i, 1);\r
+                                       t._remove(o, n, e.cfunc);\r
+                                       s = true;\r
+                                       return false;\r
+                               }\r
+                       });\r
+\r
+                       return s;\r
+               },\r
+\r
+               clear : function(o) {\r
+                       var t = this, a = t.events, i, e;\r
+\r
+                       if (o) {\r
+                               o = DOM.get(o);\r
+\r
+                               for (i = a.length - 1; i >= 0; i--) {\r
+                                       e = a[i];\r
+\r
+                                       if (e.obj === o) {\r
+                                               t._remove(e.obj, e.name, e.cfunc);\r
+                                               e.obj = e.cfunc = null;\r
+                                               a.splice(i, 1);\r
+                                       }\r
+                               }\r
+                       }\r
+               },\r
+\r
+               cancel : function(e) {\r
+                       if (!e)\r
+                               return false;\r
+\r
+                       this.stop(e);\r
+\r
+                       return this.prevent(e);\r
+               },\r
+\r
+               stop : function(e) {\r
+                       if (e.stopPropagation)\r
+                               e.stopPropagation();\r
+                       else\r
+                               e.cancelBubble = true;\r
+\r
+                       return false;\r
+               },\r
+\r
+               prevent : function(e) {\r
+                       if (e.preventDefault)\r
+                               e.preventDefault();\r
+                       else\r
+                               e.returnValue = false;\r
+\r
+                       return false;\r
+               },\r
+\r
+               destroy : function() {\r
+                       var t = this;\r
+\r
+                       each(t.events, function(e, i) {\r
+                               t._remove(e.obj, e.name, e.cfunc);\r
+                               e.obj = e.cfunc = null;\r
+                       });\r
+\r
+                       t.events = [];\r
+                       t = null;\r
+               },\r
+\r
+               _add : function(o, n, f) {\r
+                       if (o.attachEvent)\r
+                               o.attachEvent('on' + n, f);\r
+                       else if (o.addEventListener)\r
+                               o.addEventListener(n, f, false);\r
+                       else\r
+                               o['on' + n] = f;\r
+               },\r
+\r
+               _remove : function(o, n, f) {\r
+                       if (o) {\r
+                               try {\r
+                                       if (o.detachEvent)\r
+                                               o.detachEvent('on' + n, f);\r
+                                       else if (o.removeEventListener)\r
+                                               o.removeEventListener(n, f, false);\r
+                                       else\r
+                                               o['on' + n] = null;\r
+                               } catch (ex) {\r
+                                       // Might fail with permission denined on IE so we just ignore that\r
+                               }\r
+                       }\r
+               },\r
+\r
+               _pageInit : function(win) {\r
+                       var t = this;\r
+\r
+                       // Keep it from running more than once\r
+                       if (t.domLoaded)\r
+                               return;\r
+\r
+                       t.domLoaded = true;\r
+\r
+                       each(t.inits, function(c) {\r
+                               c();\r
+                       });\r
+\r
+                       t.inits = [];\r
+               },\r
+\r
+               _wait : function(win) {\r
+                       var t = this, doc = win.document;\r
+\r
+                       // No need since the document is already loaded\r
+                       if (win.tinyMCE_GZ && tinyMCE_GZ.loaded) {\r
+                               t.domLoaded = 1;\r
+                               return;\r
+                       }\r
+\r
+                       // Use IE method\r
+                       if (doc.attachEvent) {\r
+                               doc.attachEvent("onreadystatechange", function() {\r
+                                       if (doc.readyState === "complete") {\r
+                                               doc.detachEvent("onreadystatechange", arguments.callee);\r
+                                               t._pageInit(win);\r
+                                       }\r
+                               });\r
+\r
+                               if (doc.documentElement.doScroll && win == win.top) {\r
+                                       (function() {\r
+                                               if (t.domLoaded)\r
+                                                       return;\r
+\r
+                                               try {\r
+                                                       // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author.\r
+                                                       // http://javascript.nwbox.com/IEContentLoaded/\r
+                                                       doc.documentElement.doScroll("left");\r
+                                               } catch (ex) {\r
+                                                       setTimeout(arguments.callee, 0);\r
+                                                       return;\r
+                                               }\r
+\r
+                                               t._pageInit(win);\r
+                                       })();\r
+                               }\r
+                       } else if (doc.addEventListener) {\r
+                               t._add(win, 'DOMContentLoaded', function() {\r
+                                       t._pageInit(win);\r
+                               });\r
+                       }\r
+\r
+                       t._add(win, 'load', function() {\r
+                               t._pageInit(win);\r
+                       });\r
+               },\r
+\r
+               _stoppers : {\r
+                       preventDefault : function() {\r
+                               this.returnValue = false;\r
+                       },\r
+\r
+                       stopPropagation : function() {\r
+                               this.cancelBubble = true;\r
+                       }\r
+               }\r
+       });\r
+\r
+       Event = tinymce.dom.Event = new tinymce.dom.EventUtils();\r
+\r
+       // Dispatch DOM content loaded event for IE and Safari\r
+       Event._wait(window);\r
+\r
+       tinymce.addUnload(function() {\r
+               Event.destroy();\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       tinymce.dom.Element = function(id, settings) {\r
+               var t = this, dom, el;\r
+\r
+               t.settings = settings = settings || {};\r
+               t.id = id;\r
+               t.dom = dom = settings.dom || tinymce.DOM;\r
+\r
+               // Only IE leaks DOM references, this is a lot faster\r
+               if (!tinymce.isIE)\r
+                       el = dom.get(t.id);\r
+\r
+               tinymce.each(\r
+                               ('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' + \r
+                               'setAttrib,setAttribs,getAttrib,addClass,removeClass,' + \r
+                               'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' + \r
+                               'isHidden,setHTML,get').split(/,/)\r
+                       , function(k) {\r
+                               t[k] = function() {\r
+                                       var a = [id], i;\r
+\r
+                                       for (i = 0; i < arguments.length; i++)\r
+                                               a.push(arguments[i]);\r
+\r
+                                       a = dom[k].apply(dom, a);\r
+                                       t.update(k);\r
+\r
+                                       return a;\r
+                               };\r
+               });\r
+\r
+               tinymce.extend(t, {\r
+                       on : function(n, f, s) {\r
+                               return tinymce.dom.Event.add(t.id, n, f, s);\r
+                       },\r
+\r
+                       getXY : function() {\r
+                               return {\r
+                                       x : parseInt(t.getStyle('left')),\r
+                                       y : parseInt(t.getStyle('top'))\r
+                               };\r
+                       },\r
+\r
+                       getSize : function() {\r
+                               var n = dom.get(t.id);\r
+\r
+                               return {\r
+                                       w : parseInt(t.getStyle('width') || n.clientWidth),\r
+                                       h : parseInt(t.getStyle('height') || n.clientHeight)\r
+                               };\r
+                       },\r
+\r
+                       moveTo : function(x, y) {\r
+                               t.setStyles({left : x, top : y});\r
+                       },\r
+\r
+                       moveBy : function(x, y) {\r
+                               var p = t.getXY();\r
+\r
+                               t.moveTo(p.x + x, p.y + y);\r
+                       },\r
+\r
+                       resizeTo : function(w, h) {\r
+                               t.setStyles({width : w, height : h});\r
+                       },\r
+\r
+                       resizeBy : function(w, h) {\r
+                               var s = t.getSize();\r
+\r
+                               t.resizeTo(s.w + w, s.h + h);\r
+                       },\r
+\r
+                       update : function(k) {\r
+                               var b;\r
+\r
+                               if (tinymce.isIE6 && settings.blocker) {\r
+                                       k = k || '';\r
+\r
+                                       // Ignore getters\r
+                                       if (k.indexOf('get') === 0 || k.indexOf('has') === 0 || k.indexOf('is') === 0)\r
+                                               return;\r
+\r
+                                       // Remove blocker on remove\r
+                                       if (k == 'remove') {\r
+                                               dom.remove(t.blocker);\r
+                                               return;\r
+                                       }\r
+\r
+                                       if (!t.blocker) {\r
+                                               t.blocker = dom.uniqueId();\r
+                                               b = dom.add(settings.container || dom.getRoot(), 'iframe', {id : t.blocker, style : 'position:absolute;', frameBorder : 0, src : 'javascript:""'});\r
+                                               dom.setStyle(b, 'opacity', 0);\r
+                                       } else\r
+                                               b = dom.get(t.blocker);\r
+\r
+                                       dom.setStyles(b, {\r
+                                               left : t.getStyle('left', 1),\r
+                                               top : t.getStyle('top', 1),\r
+                                               width : t.getStyle('width', 1),\r
+                                               height : t.getStyle('height', 1),\r
+                                               display : t.getStyle('display', 1),\r
+                                               zIndex : parseInt(t.getStyle('zIndex', 1) || 0) - 1\r
+                                       });\r
+                               }\r
+                       }\r
+               });\r
+       };\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       function trimNl(s) {\r
+               return s.replace(/[\n\r]+/g, '');\r
+       };\r
+\r
+       // Shorten names\r
+       var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each;\r
+\r
+       tinymce.create('tinymce.dom.Selection', {\r
+               Selection : function(dom, win, serializer) {\r
+                       var t = this;\r
+\r
+                       t.dom = dom;\r
+                       t.win = win;\r
+                       t.serializer = serializer;\r
+\r
+                       // Add events\r
+                       each([\r
+                               'onBeforeSetContent',\r
+\r
+                               'onBeforeGetContent',\r
+\r
+                               'onSetContent',\r
+\r
+                               'onGetContent'\r
+                       ], function(e) {\r
+                               t[e] = new tinymce.util.Dispatcher(t);\r
+                       });\r
+\r
+                       // No W3C Range support\r
+                       if (!t.win.getSelection)\r
+                               t.tridentSel = new tinymce.dom.TridentSelection(t);\r
+\r
+                       if (tinymce.isIE && dom.boxModel)\r
+                               this._fixIESelection();\r
+\r
+                       // Prevent leaks\r
+                       tinymce.addUnload(t.destroy, t);\r
+               },\r
+\r
+               setCursorLocation: function(node, offset) {\r
+                       var t = this; var r = t.dom.createRng();\r
+                       r.setStart(node, offset);\r
+                       r.setEnd(node, offset);\r
+                       t.setRng(r);\r
+                       t.collapse(false);\r
+               },\r
+               getContent : function(s) {\r
+                       var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n;\r
+\r
+                       s = s || {};\r
+                       wb = wa = '';\r
+                       s.get = true;\r
+                       s.format = s.format || 'html';\r
+                       s.forced_root_block = '';\r
+                       t.onBeforeGetContent.dispatch(t, s);\r
+\r
+                       if (s.format == 'text')\r
+                               return t.isCollapsed() ? '' : (r.text || (se.toString ? se.toString() : ''));\r
+\r
+                       if (r.cloneContents) {\r
+                               n = r.cloneContents();\r
+\r
+                               if (n)\r
+                                       e.appendChild(n);\r
+                       } else if (is(r.item) || is(r.htmlText)) {\r
+                               // IE will produce invalid markup if elements are present that\r
+                               // it doesn't understand like custom elements or HTML5 elements.\r
+                               // Adding a BR in front of the contents and then remoiving it seems to fix it though.\r
+                               e.innerHTML = '<br>' + (r.item ? r.item(0).outerHTML : r.htmlText);\r
+                               e.removeChild(e.firstChild);\r
+                       } else\r
+                               e.innerHTML = r.toString();\r
+\r
+                       // Keep whitespace before and after\r
+                       if (/^\s/.test(e.innerHTML))\r
+                               wb = ' ';\r
+\r
+                       if (/\s+$/.test(e.innerHTML))\r
+                               wa = ' ';\r
+\r
+                       s.getInner = true;\r
+\r
+                       s.content = t.isCollapsed() ? '' : wb + t.serializer.serialize(e, s) + wa;\r
+                       t.onGetContent.dispatch(t, s);\r
+\r
+                       return s.content;\r
+               },\r
+\r
+               setContent : function(content, args) {\r
+                       var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp;\r
+\r
+                       args = args || {format : 'html'};\r
+                       args.set = true;\r
+                       content = args.content = content;\r
+\r
+                       // Dispatch before set content event\r
+                       if (!args.no_events)\r
+                               self.onBeforeSetContent.dispatch(self, args);\r
+\r
+                       content = args.content;\r
+\r
+                       if (rng.insertNode) {\r
+                               // Make caret marker since insertNode places the caret in the beginning of text after insert\r
+                               content += '<span id="__caret">_</span>';\r
+\r
+                               // Delete and insert new node\r
+                               if (rng.startContainer == doc && rng.endContainer == doc) {\r
+                                       // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents\r
+                                       doc.body.innerHTML = content;\r
+                               } else {\r
+                                       rng.deleteContents();\r
+\r
+                                       if (doc.body.childNodes.length == 0) {\r
+                                               doc.body.innerHTML = content;\r
+                                       } else {\r
+                                               // createContextualFragment doesn't exists in IE 9 DOMRanges\r
+                                               if (rng.createContextualFragment) {\r
+                                                       rng.insertNode(rng.createContextualFragment(content));\r
+                                               } else {\r
+                                                       // Fake createContextualFragment call in IE 9\r
+                                                       frag = doc.createDocumentFragment();\r
+                                                       temp = doc.createElement('div');\r
+\r
+                                                       frag.appendChild(temp);\r
+                                                       temp.outerHTML = content;\r
+\r
+                                                       rng.insertNode(frag);\r
+                                               }\r
+                                       }\r
+                               }\r
+\r
+                               // Move to caret marker\r
+                               caretNode = self.dom.get('__caret');\r
+\r
+                               // Make sure we wrap it compleatly, Opera fails with a simple select call\r
+                               rng = doc.createRange();\r
+                               rng.setStartBefore(caretNode);\r
+                               rng.setEndBefore(caretNode);\r
+                               self.setRng(rng);\r
+\r
+                               // Remove the caret position\r
+                               self.dom.remove('__caret');\r
+\r
+                               try {\r
+                                       self.setRng(rng);\r
+                               } catch (ex) {\r
+                                       // Might fail on Opera for some odd reason\r
+                               }\r
+                       } else {\r
+                               if (rng.item) {\r
+                                       // Delete content and get caret text selection\r
+                                       doc.execCommand('Delete', false, null);\r
+                                       rng = self.getRng();\r
+                               }\r
+\r
+                               // Explorer removes spaces from the beginning of pasted contents\r
+                               if (/^\s+/.test(content)) {\r
+                                       rng.pasteHTML('<span id="__mce_tmp">_</span>' + content);\r
+                                       self.dom.remove('__mce_tmp');\r
+                               } else\r
+                                       rng.pasteHTML(content);\r
+                       }\r
+\r
+                       // Dispatch set content event\r
+                       if (!args.no_events)\r
+                               self.onSetContent.dispatch(self, args);\r
+               },\r
+\r
+               getStart : function() {\r
+                       var rng = this.getRng(), startElement, parentElement, checkRng, node;\r
+\r
+                       if (rng.duplicate || rng.item) {\r
+                               // Control selection, return first item\r
+                               if (rng.item)\r
+                                       return rng.item(0);\r
+\r
+                               // Get start element\r
+                               checkRng = rng.duplicate();\r
+                               checkRng.collapse(1);\r
+                               startElement = checkRng.parentElement();\r
+\r
+                               // Check if range parent is inside the start element, then return the inner parent element\r
+                               // This will fix issues when a single element is selected, IE would otherwise return the wrong start element\r
+                               parentElement = node = rng.parentElement();\r
+                               while (node = node.parentNode) {\r
+                                       if (node == startElement) {\r
+                                               startElement = parentElement;\r
+                                               break;\r
+                                       }\r
+                               }\r
+\r
+                               return startElement;\r
+                       } else {\r
+                               startElement = rng.startContainer;\r
+\r
+                               if (startElement.nodeType == 1 && startElement.hasChildNodes())\r
+                                       startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)];\r
+\r
+                               if (startElement && startElement.nodeType == 3)\r
+                                       return startElement.parentNode;\r
+\r
+                               return startElement;\r
+                       }\r
+               },\r
+\r
+               getEnd : function() {\r
+                       var t = this, r = t.getRng(), e, eo;\r
+\r
+                       if (r.duplicate || r.item) {\r
+                               if (r.item)\r
+                                       return r.item(0);\r
+\r
+                               r = r.duplicate();\r
+                               r.collapse(0);\r
+                               e = r.parentElement();\r
+\r
+                               if (e && e.nodeName == 'BODY')\r
+                                       return e.lastChild || e;\r
+\r
+                               return e;\r
+                       } else {\r
+                               e = r.endContainer;\r
+                               eo = r.endOffset;\r
+\r
+                               if (e.nodeType == 1 && e.hasChildNodes())\r
+                                       e = e.childNodes[eo > 0 ? eo - 1 : eo];\r
+\r
+                               if (e && e.nodeType == 3)\r
+                                       return e.parentNode;\r
+\r
+                               return e;\r
+                       }\r
+               },\r
+\r
+               getBookmark : function(type, normalized) {\r
+                       var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, index, chr = '\uFEFF', styles;\r
+\r
+                       function findIndex(name, element) {\r
+                               var index = 0;\r
+\r
+                               each(dom.select(name), function(node, i) {\r
+                                       if (node == element)\r
+                                               index = i;\r
+                               });\r
+\r
+                               return index;\r
+                       };\r
+\r
+                       if (type == 2) {\r
+                               function getLocation() {\r
+                                       var rng = t.getRng(true), root = dom.getRoot(), bookmark = {};\r
+\r
+                                       function getPoint(rng, start) {\r
+                                               var container = rng[start ? 'startContainer' : 'endContainer'],\r
+                                                       offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;\r
+\r
+                                               if (container.nodeType == 3) {\r
+                                                       if (normalized) {\r
+                                                               for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling)\r
+                                                                       offset += node.nodeValue.length;\r
+                                                       }\r
+\r
+                                                       point.push(offset);\r
+                                               } else {\r
+                                                       childNodes = container.childNodes;\r
+\r
+                                                       if (offset >= childNodes.length && childNodes.length) {\r
+                                                               after = 1;\r
+                                                               offset = Math.max(0, childNodes.length - 1);\r
+                                                       }\r
+\r
+                                                       point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after);\r
+                                               }\r
+\r
+                                               for (; container && container != root; container = container.parentNode)\r
+                                                       point.push(t.dom.nodeIndex(container, normalized));\r
+\r
+                                               return point;\r
+                                       };\r
+\r
+                                       bookmark.start = getPoint(rng, true);\r
+\r
+                                       if (!t.isCollapsed())\r
+                                               bookmark.end = getPoint(rng);\r
+\r
+                                       return bookmark;\r
+                               };\r
+\r
+                               if (t.tridentSel)\r
+                                       return t.tridentSel.getBookmark(type);\r
+\r
+                               return getLocation();\r
+                       }\r
+\r
+                       // Handle simple range\r
+                       if (type)\r
+                               return {rng : t.getRng()};\r
+\r
+                       rng = t.getRng();\r
+                       id = dom.uniqueId();\r
+                       collapsed = tinyMCE.activeEditor.selection.isCollapsed();\r
+                       styles = 'overflow:hidden;line-height:0px';\r
+\r
+                       // Explorer method\r
+                       if (rng.duplicate || rng.item) {\r
+                               // Text selection\r
+                               if (!rng.item) {\r
+                                       rng2 = rng.duplicate();\r
+\r
+                                       try {\r
+                                               // Insert start marker\r
+                                               rng.collapse();\r
+                                               rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>');\r
+\r
+                                               // Insert end marker\r
+                                               if (!collapsed) {\r
+                                                       rng2.collapse(false);\r
+\r
+                                                       // Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p>\r
+                                                       rng.moveToElementText(rng2.parentElement());\r
+                                                       if (rng.compareEndPoints('StartToEnd', rng2) == 0)\r
+                                                               rng2.move('character', -1);\r
+\r
+                                                       rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');\r
+                                               }\r
+                                       } catch (ex) {\r
+                                               // IE might throw unspecified error so lets ignore it\r
+                                               return null;\r
+                                       }\r
+                               } else {\r
+                                       // Control selection\r
+                                       element = rng.item(0);\r
+                                       name = element.nodeName;\r
+\r
+                                       return {name : name, index : findIndex(name, element)};\r
+                               }\r
+                       } else {\r
+                               element = t.getNode();\r
+                               name = element.nodeName;\r
+                               if (name == 'IMG')\r
+                                       return {name : name, index : findIndex(name, element)};\r
+\r
+                               // W3C method\r
+                               rng2 = rng.cloneRange();\r
+\r
+                               // Insert end marker\r
+                               if (!collapsed) {\r
+                                       rng2.collapse(false);\r
+                                       rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr));\r
+                               }\r
+\r
+                               rng.collapse(true);\r
+                               rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr));\r
+                       }\r
+\r
+                       t.moveToBookmark({id : id, keep : 1});\r
+\r
+                       return {id : id};\r
+               },\r
+\r
+               moveToBookmark : function(bookmark) {\r
+                       var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset;\r
+\r
+                       if (bookmark) {\r
+                               if (bookmark.start) {\r
+                                       rng = dom.createRng();\r
+                                       root = dom.getRoot();\r
+\r
+                                       function setEndPoint(start) {\r
+                                               var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;\r
+\r
+                                               if (point) {\r
+                                                       offset = point[0];\r
+\r
+                                                       // Find container node\r
+                                                       for (node = root, i = point.length - 1; i >= 1; i--) {\r
+                                                               children = node.childNodes;\r
+\r
+                                                               if (point[i] > children.length - 1)\r
+                                                                       return;\r
+\r
+                                                               node = children[point[i]];\r
+                                                       }\r
+\r
+                                                       // Move text offset to best suitable location\r
+                                                       if (node.nodeType === 3)\r
+                                                               offset = Math.min(point[0], node.nodeValue.length);\r
+\r
+                                                       // Move element offset to best suitable location\r
+                                                       if (node.nodeType === 1)\r
+                                                               offset = Math.min(point[0], node.childNodes.length);\r
+\r
+                                                       // Set offset within container node\r
+                                                       if (start)\r
+                                                               rng.setStart(node, offset);\r
+                                                       else\r
+                                                               rng.setEnd(node, offset);\r
+                                               }\r
+\r
+                                               return true;\r
+                                       };\r
+\r
+                                       if (t.tridentSel)\r
+                                               return t.tridentSel.moveToBookmark(bookmark);\r
+\r
+                                       if (setEndPoint(true) && setEndPoint()) {\r
+                                               t.setRng(rng);\r
+                                       }\r
+                               } else if (bookmark.id) {\r
+                                       function restoreEndPoint(suffix) {\r
+                                               var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;\r
+\r
+                                               if (marker) {\r
+                                                       node = marker.parentNode;\r
+\r
+                                                       if (suffix == 'start') {\r
+                                                               if (!keep) {\r
+                                                                       idx = dom.nodeIndex(marker);\r
+                                                               } else {\r
+                                                                       node = marker.firstChild;\r
+                                                                       idx = 1;\r
+                                                               }\r
+\r
+                                                               startContainer = endContainer = node;\r
+                                                               startOffset = endOffset = idx;\r
+                                                       } else {\r
+                                                               if (!keep) {\r
+                                                                       idx = dom.nodeIndex(marker);\r
+                                                               } else {\r
+                                                                       node = marker.firstChild;\r
+                                                                       idx = 1;\r
+                                                               }\r
+\r
+                                                               endContainer = node;\r
+                                                               endOffset = idx;\r
+                                                       }\r
+\r
+                                                       if (!keep) {\r
+                                                               prev = marker.previousSibling;\r
+                                                               next = marker.nextSibling;\r
+\r
+                                                               // Remove all marker text nodes\r
+                                                               each(tinymce.grep(marker.childNodes), function(node) {\r
+                                                                       if (node.nodeType == 3)\r
+                                                                               node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');\r
+                                                               });\r
+\r
+                                                               // Remove marker but keep children if for example contents where inserted into the marker\r
+                                                               // Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature\r
+                                                               while (marker = dom.get(bookmark.id + '_' + suffix))\r
+                                                                       dom.remove(marker, 1);\r
+\r
+                                                               // If siblings are text nodes then merge them unless it's Opera since it some how removes the node\r
+                                                               // 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\r
+                                                               if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) {\r
+                                                                       idx = prev.nodeValue.length;\r
+                                                                       prev.appendData(next.nodeValue);\r
+                                                                       dom.remove(next);\r
+\r
+                                                                       if (suffix == 'start') {\r
+                                                                               startContainer = endContainer = prev;\r
+                                                                               startOffset = endOffset = idx;\r
+                                                                       } else {\r
+                                                                               endContainer = prev;\r
+                                                                               endOffset = idx;\r
+                                                                       }\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       };\r
+\r
+                                       function addBogus(node) {\r
+                                               // Adds a bogus BR element for empty block elements or just a space on IE since it renders BR elements incorrectly\r
+                                               if (dom.isBlock(node) && !node.innerHTML)\r
+                                                       node.innerHTML = !isIE ? '<br data-mce-bogus="1" />' : ' ';\r
+\r
+                                               return node;\r
+                                       };\r
+\r
+                                       // Restore start/end points\r
+                                       restoreEndPoint('start');\r
+                                       restoreEndPoint('end');\r
+\r
+                                       if (startContainer) {\r
+                                               rng = dom.createRng();\r
+                                               rng.setStart(addBogus(startContainer), startOffset);\r
+                                               rng.setEnd(addBogus(endContainer), endOffset);\r
+                                               t.setRng(rng);\r
+                                       }\r
+                               } else if (bookmark.name) {\r
+                                       t.select(dom.select(bookmark.name)[bookmark.index]);\r
+                               } else if (bookmark.rng)\r
+                                       t.setRng(bookmark.rng);\r
+                       }\r
+               },\r
+\r
+               select : function(node, content) {\r
+                       var t = this, dom = t.dom, rng = dom.createRng(), idx;\r
+\r
+                       if (node) {\r
+                               idx = dom.nodeIndex(node);\r
+                               rng.setStart(node.parentNode, idx);\r
+                               rng.setEnd(node.parentNode, idx + 1);\r
+\r
+                               // Find first/last text node or BR element\r
+                               if (content) {\r
+                                       function setPoint(node, start) {\r
+                                               var walker = new tinymce.dom.TreeWalker(node, node);\r
+\r
+                                               do {\r
+                                                       // Text node\r
+                                                       if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) {\r
+                                                               if (start)\r
+                                                                       rng.setStart(node, 0);\r
+                                                               else\r
+                                                                       rng.setEnd(node, node.nodeValue.length);\r
+\r
+                                                               return;\r
+                                                       }\r
+\r
+                                                       // BR element\r
+                                                       if (node.nodeName == 'BR') {\r
+                                                               if (start)\r
+                                                                       rng.setStartBefore(node);\r
+                                                               else\r
+                                                                       rng.setEndBefore(node);\r
+\r
+                                                               return;\r
+                                                       }\r
+                                               } while (node = (start ? walker.next() : walker.prev()));\r
+                                       };\r
+\r
+                                       setPoint(node, 1);\r
+                                       setPoint(node);\r
+                               }\r
+\r
+                               t.setRng(rng);\r
+                       }\r
+\r
+                       return node;\r
+               },\r
+\r
+               isCollapsed : function() {\r
+                       var t = this, r = t.getRng(), s = t.getSel();\r
+\r
+                       if (!r || r.item)\r
+                               return false;\r
+\r
+                       if (r.compareEndPoints)\r
+                               return r.compareEndPoints('StartToEnd', r) === 0;\r
+\r
+                       return !s || r.collapsed;\r
+               },\r
+\r
+               collapse : function(to_start) {\r
+                       var self = this, rng = self.getRng(), node;\r
+\r
+                       // Control range on IE\r
+                       if (rng.item) {\r
+                               node = rng.item(0);\r
+                               rng = self.win.document.body.createTextRange();\r
+                               rng.moveToElementText(node);\r
+                       }\r
+\r
+                       rng.collapse(!!to_start);\r
+                       self.setRng(rng);\r
+               },\r
+\r
+               getSel : function() {\r
+                       var t = this, w = this.win;\r
+\r
+                       return w.getSelection ? w.getSelection() : w.document.selection;\r
+               },\r
+\r
+               getRng : function(w3c) {\r
+                       var t = this, s, r, elm, doc = t.win.document;\r
+\r
+                       // Found tridentSel object then we need to use that one\r
+                       if (w3c && t.tridentSel)\r
+                               return t.tridentSel.getRangeAt(0);\r
+\r
+                       try {\r
+                               if (s = t.getSel())\r
+                                       r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange());\r
+                       } catch (ex) {\r
+                               // IE throws unspecified error here if TinyMCE is placed in a frame/iframe\r
+                       }\r
+\r
+                       // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet\r
+                       if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) {\r
+                               elm = doc.selection.createRange().item(0);\r
+                               r = doc.createRange();\r
+                               r.setStartBefore(elm);\r
+                               r.setEndAfter(elm);\r
+                       }\r
+\r
+                       // No range found then create an empty one\r
+                       // This can occur when the editor is placed in a hidden container element on Gecko\r
+                       // Or on IE when there was an exception\r
+                       if (!r)\r
+                               r = doc.createRange ? doc.createRange() : doc.body.createTextRange();\r
+\r
+                       if (t.selectedRange && t.explicitRange) {\r
+                               if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) {\r
+                                       // Safari, Opera and Chrome only ever select text which causes the range to change.\r
+                                       // This lets us use the originally set range if the selection hasn't been changed by the user.\r
+                                       r = t.explicitRange;\r
+                               } else {\r
+                                       t.selectedRange = null;\r
+                                       t.explicitRange = null;\r
+                               }\r
+                       }\r
+\r
+                       return r;\r
+               },\r
+\r
+               setRng : function(r) {\r
+                       var s, t = this;\r
+                       \r
+                       if (!t.tridentSel) {\r
+                               s = t.getSel();\r
+\r
+                               if (s) {\r
+                                       t.explicitRange = r;\r
+\r
+                                       try {\r
+                                               s.removeAllRanges();\r
+                                       } catch (ex) {\r
+                                               // IE9 might throw errors here don't know why\r
+                                       }\r
+\r
+                                       s.addRange(r);\r
+                                       t.selectedRange = s.getRangeAt(0);\r
+                               }\r
+                       } else {\r
+                               // Is W3C Range\r
+                               if (r.cloneRange) {\r
+                                       t.tridentSel.addRange(r);\r
+                                       return;\r
+                               }\r
+\r
+                               // Is IE specific range\r
+                               try {\r
+                                       r.select();\r
+                               } catch (ex) {\r
+                                       // Needed for some odd IE bug #1843306\r
+                               }\r
+                       }\r
+               },\r
+\r
+               setNode : function(n) {\r
+                       var t = this;\r
+\r
+                       t.setContent(t.dom.getOuterHTML(n));\r
+\r
+                       return n;\r
+               },\r
+\r
+               getNode : function() {\r
+                       var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer;\r
+\r
+                       // Range maybe lost after the editor is made visible again\r
+                       if (!rng)\r
+                               return t.dom.getRoot();\r
+\r
+                       if (rng.setStart) {\r
+                               elm = rng.commonAncestorContainer;\r
+\r
+                               // Handle selection a image or other control like element such as anchors\r
+                               if (!rng.collapsed) {\r
+                                       if (rng.startContainer == rng.endContainer) {\r
+                                               if (rng.endOffset - rng.startOffset < 2) {\r
+                                                       if (rng.startContainer.hasChildNodes())\r
+                                                               elm = rng.startContainer.childNodes[rng.startOffset];\r
+                                               }\r
+                                       }\r
+\r
+                                       // If the anchor node is a element instead of a text node then return this element\r
+                                       //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1) \r
+                                       //      return sel.anchorNode.childNodes[sel.anchorOffset];\r
+\r
+                                       // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.\r
+                                       // This happens when you double click an underlined word in FireFox.\r
+                                       if (start.nodeType === 3 && end.nodeType === 3) {\r
+                                               function skipEmptyTextNodes(n, forwards) {\r
+                                                       var orig = n;\r
+                                                       while (n && n.nodeType === 3 && n.length === 0) {\r
+                                                               n = forwards ? n.nextSibling : n.previousSibling;\r
+                                                       }\r
+                                                       return n || orig;\r
+                                               }\r
+                                               if (start.length === rng.startOffset) {\r
+                                                       start = skipEmptyTextNodes(start.nextSibling, true);\r
+                                               } else {\r
+                                                       start = start.parentNode;\r
+                                               }\r
+                                               if (rng.endOffset === 0) {\r
+                                                       end = skipEmptyTextNodes(end.previousSibling, false);\r
+                                               } else {\r
+                                                       end = end.parentNode;\r
+                                               }\r
+\r
+                                               if (start && start === end)\r
+                                                       return start;\r
+                                       }\r
+                               }\r
+\r
+                               if (elm && elm.nodeType == 3)\r
+                                       return elm.parentNode;\r
+\r
+                               return elm;\r
+                       }\r
+\r
+                       return rng.item ? rng.item(0) : rng.parentElement();\r
+               },\r
+\r
+               getSelectedBlocks : function(st, en) {\r
+                       var t = this, dom = t.dom, sb, eb, n, bl = [];\r
+\r
+                       sb = dom.getParent(st || t.getStart(), dom.isBlock);\r
+                       eb = dom.getParent(en || t.getEnd(), dom.isBlock);\r
+\r
+                       if (sb)\r
+                               bl.push(sb);\r
+\r
+                       if (sb && eb && sb != eb) {\r
+                               n = sb;\r
+\r
+                               while ((n = n.nextSibling) && n != eb) {\r
+                                       if (dom.isBlock(n))\r
+                                               bl.push(n);\r
+                               }\r
+                       }\r
+\r
+                       if (eb && sb != eb)\r
+                               bl.push(eb);\r
+\r
+                       return bl;\r
+               },\r
+\r
+               normalize : function() {\r
+                       var self = this, rng, normalized;\r
+\r
+                       // Normalize only on non IE browsers for now\r
+                       if (tinymce.isIE)\r
+                               return;\r
+\r
+                       function normalizeEndPoint(start) {\r
+                               var container, offset, walker, dom = self.dom, body = dom.getRoot(), node;\r
+\r
+                               container = rng[(start ? 'start' : 'end') + 'Container'];\r
+                               offset = rng[(start ? 'start' : 'end') + 'Offset'];\r
+\r
+                               // If the container is a document move it to the body element\r
+                               if (container.nodeType === 9) {\r
+                                       container = container.body;\r
+                                       offset = 0;\r
+                               }\r
+\r
+                               // If the container is body try move it into the closest text node or position\r
+                               // TODO: Add more logic here to handle element selection cases\r
+                               if (container === body) {\r
+                                       // Resolve the index\r
+                                       if (container.hasChildNodes()) {\r
+                                               container = container.childNodes[Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1)];\r
+                                               offset = 0;\r
+\r
+                                               // Don't walk into elements that doesn't have any child nodes like a IMG\r
+                                               if (container.hasChildNodes()) {\r
+                                                       // Walk the DOM to find a text node to place the caret at or a BR\r
+                                                       node = container;\r
+                                                       walker = new tinymce.dom.TreeWalker(container, body);\r
+                                                       do {\r
+                                                               // Found a text node use that position\r
+                                                               if (node.nodeType === 3) {\r
+                                                                       offset = start ? 0 : node.nodeValue.length - 1;\r
+                                                                       container = node;\r
+                                                                       break;\r
+                                                               }\r
+\r
+                                                               // Found a BR element that we can place the caret before\r
+                                                               if (node.nodeName === 'BR') {\r
+                                                                       offset = dom.nodeIndex(node);\r
+                                                                       container = node.parentNode;\r
+                                                                       break;\r
+                                                               }\r
+                                                       } while (node = (start ? walker.next() : walker.prev()));\r
+\r
+                                                       normalized = true;\r
+                                               }\r
+                                       }\r
+                               }\r
+\r
+                               // Set endpoint if it was normalized\r
+                               if (normalized)\r
+                                       rng['set' + (start ? 'Start' : 'End')](container, offset);\r
+                       };\r
+\r
+                       rng = self.getRng();\r
+\r
+                       // Normalize the end points\r
+                       normalizeEndPoint(true);\r
+                       \r
+                       if (rng.collapsed)\r
+                               normalizeEndPoint();\r
+\r
+                       // Set the selection if it was normalized\r
+                       if (normalized) {\r
+                               //console.log(self.dom.dumpRng(rng));\r
+                               self.setRng(rng);\r
+                       }\r
+               },\r
+\r
+               destroy : function(s) {\r
+                       var t = this;\r
+\r
+                       t.win = null;\r
+\r
+                       // Manual destroy then remove unload handler\r
+                       if (!s)\r
+                               tinymce.removeUnload(t.destroy);\r
+               },\r
+\r
+               // IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode\r
+               _fixIESelection : function() {\r
+                       var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm;\r
+\r
+                       // Make HTML element unselectable since we are going to handle selection by hand\r
+                       doc.documentElement.unselectable = true;\r
+\r
+                       // Return range from point or null if it failed\r
+                       function rngFromPoint(x, y) {\r
+                               var rng = body.createTextRange();\r
+\r
+                               try {\r
+                                       rng.moveToPoint(x, y);\r
+                               } catch (ex) {\r
+                                       // IE sometimes throws and exception, so lets just ignore it\r
+                                       rng = null;\r
+                               }\r
+\r
+                               return rng;\r
+                       };\r
+\r
+                       // Fires while the selection is changing\r
+                       function selectionChange(e) {\r
+                               var pointRng;\r
+\r
+                               // Check if the button is down or not\r
+                               if (e.button) {\r
+                                       // Create range from mouse position\r
+                                       pointRng = rngFromPoint(e.x, e.y);\r
+\r
+                                       if (pointRng) {\r
+                                               // Check if pointRange is before/after selection then change the endPoint\r
+                                               if (pointRng.compareEndPoints('StartToStart', startRng) > 0)\r
+                                                       pointRng.setEndPoint('StartToStart', startRng);\r
+                                               else\r
+                                                       pointRng.setEndPoint('EndToEnd', startRng);\r
+\r
+                                               pointRng.select();\r
+                                       }\r
+                               } else\r
+                                       endSelection();\r
+                       }\r
+\r
+                       // Removes listeners\r
+                       function endSelection() {\r
+                               var rng = doc.selection.createRange();\r
+\r
+                               // If the range is collapsed then use the last start range\r
+                               if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0)\r
+                                       startRng.select();\r
+\r
+                               dom.unbind(doc, 'mouseup', endSelection);\r
+                               dom.unbind(doc, 'mousemove', selectionChange);\r
+                               startRng = started = 0;\r
+                       };\r
+\r
+                       // Detect when user selects outside BODY\r
+                       dom.bind(doc, ['mousedown', 'contextmenu'], function(e) {\r
+                               if (e.target.nodeName === 'HTML') {\r
+                                       if (started)\r
+                                               endSelection();\r
+\r
+                                       // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML\r
+                                       htmlElm = doc.documentElement;\r
+                                       if (htmlElm.scrollHeight > htmlElm.clientHeight)\r
+                                               return;\r
+\r
+                                       started = 1;\r
+                                       // Setup start position\r
+                                       startRng = rngFromPoint(e.x, e.y);\r
+                                       if (startRng) {\r
+                                               // Listen for selection change events\r
+                                               dom.bind(doc, 'mouseup', endSelection);\r
+                                               dom.bind(doc, 'mousemove', selectionChange);\r
+\r
+                                               dom.win.focus();\r
+                                               startRng.select();\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       tinymce.dom.Serializer = function(settings, dom, schema) {\r
+               var onPreProcess, onPostProcess, isIE = tinymce.isIE, each = tinymce.each, htmlParser;\r
+\r
+               // Support the old apply_source_formatting option\r
+               if (!settings.apply_source_formatting)\r
+                       settings.indent = false;\r
+\r
+               settings.remove_trailing_brs = true;\r
+\r
+               // Default DOM and Schema if they are undefined\r
+               dom = dom || tinymce.DOM;\r
+               schema = schema || new tinymce.html.Schema(settings);\r
+               settings.entity_encoding = settings.entity_encoding || 'named';\r
+\r
+               onPreProcess = new tinymce.util.Dispatcher(self);\r
+\r
+               onPostProcess = new tinymce.util.Dispatcher(self);\r
+\r
+               htmlParser = new tinymce.html.DomParser(settings, schema);\r
+\r
+               // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed\r
+               htmlParser.addAttributeFilter('src,href,style', function(nodes, name) {\r
+                       var i = nodes.length, node, value, internalName = 'data-mce-' + name, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef;\r
+\r
+                       while (i--) {\r
+                               node = nodes[i];\r
+\r
+                               value = node.attributes.map[internalName];\r
+                               if (value !== undef) {\r
+                                       // Set external name to internal value and remove internal\r
+                                       node.attr(name, value.length > 0 ? value : null);\r
+                                       node.attr(internalName, null);\r
+                               } else {\r
+                                       // No internal attribute found then convert the value we have in the DOM\r
+                                       value = node.attributes.map[name];\r
+\r
+                                       if (name === "style")\r
+                                               value = dom.serializeStyle(dom.parseStyle(value), node.name);\r
+                                       else if (urlConverter)\r
+                                               value = urlConverter.call(urlConverterScope, value, name, node.name);\r
+\r
+                                       node.attr(name, value.length > 0 ? value : null);\r
+                               }\r
+                       }\r
+               });\r
+\r
+               // Remove internal classes mceItem<..>\r
+               htmlParser.addAttributeFilter('class', function(nodes, name) {\r
+                       var i = nodes.length, node, value;\r
+\r
+                       while (i--) {\r
+                               node = nodes[i];\r
+                               value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, '');\r
+                               node.attr('class', value.length > 0 ? value : null);\r
+                       }\r
+               });\r
+\r
+               // Remove bookmark elements\r
+               htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) {\r
+                       var i = nodes.length, node;\r
+\r
+                       while (i--) {\r
+                               node = nodes[i];\r
+\r
+                               if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup)\r
+                                       node.remove();\r
+                       }\r
+               });\r
+\r
+               // Force script into CDATA sections and remove the mce- prefix also add comments around styles\r
+               htmlParser.addNodeFilter('script,style', function(nodes, name) {\r
+                       var i = nodes.length, node, value;\r
+\r
+                       function trim(value) {\r
+                               return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')\r
+                                               .replace(/^[\r\n]*|[\r\n]*$/g, '')\r
+                                               .replace(/^\s*(\/\/\s*<!--|\/\/\s*<!\[CDATA\[|<!--|<!\[CDATA\[)[\r\n]*/g, '')\r
+                                               .replace(/\s*(\/\/\s*\]\]>|\/\/\s*-->|\]\]>|-->|\]\]-->)\s*$/g, '');\r
+                       };\r
+\r
+                       while (i--) {\r
+                               node = nodes[i];\r
+                               value = node.firstChild ? node.firstChild.value : '';\r
+\r
+                               if (name === "script") {\r
+                                       // Remove mce- prefix from script elements\r
+                                       node.attr('type', (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''));\r
+\r
+                                       if (value.length > 0)\r
+                                               node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';\r
+                               } else {\r
+                                       if (value.length > 0)\r
+                                               node.firstChild.value = '<!--\n' + trim(value) + '\n-->';\r
+                               }\r
+                       }\r
+               });\r
+\r
+               // Convert comments to cdata and handle protected comments\r
+               htmlParser.addNodeFilter('#comment', function(nodes, name) {\r
+                       var i = nodes.length, node;\r
+\r
+                       while (i--) {\r
+                               node = nodes[i];\r
+\r
+                               if (node.value.indexOf('[CDATA[') === 0) {\r
+                                       node.name = '#cdata';\r
+                                       node.type = 4;\r
+                                       node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');\r
+                               } else if (node.value.indexOf('mce:protected ') === 0) {\r
+                                       node.name = "#text";\r
+                                       node.type = 3;\r
+                                       node.raw = true;\r
+                                       node.value = unescape(node.value).substr(14);\r
+                               }\r
+                       }\r
+               });\r
+\r
+               htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) {\r
+                       var i = nodes.length, node;\r
+\r
+                       while (i--) {\r
+                               node = nodes[i];\r
+                               if (node.type === 7)\r
+                                       node.remove();\r
+                               else if (node.type === 1) {\r
+                                       if (name === "input" && !("type" in node.attributes.map))\r
+                                               node.attr('type', 'text');\r
+                               }\r
+                       }\r
+               });\r
+\r
+               // Fix list elements, TODO: Replace this later\r
+               if (settings.fix_list_elements) {\r
+                       htmlParser.addNodeFilter('ul,ol', function(nodes, name) {\r
+                               var i = nodes.length, node, parentNode;\r
+\r
+                               while (i--) {\r
+                                       node = nodes[i];\r
+                                       parentNode = node.parent;\r
+\r
+                                       if (parentNode.name === 'ul' || parentNode.name === 'ol') {\r
+                                               if (node.prev && node.prev.name === 'li') {\r
+                                                       node.prev.append(node);\r
+                                               }\r
+                                       }\r
+                               }\r
+                       });\r
+               }\r
+\r
+               // Remove internal data attributes\r
+               htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style', function(nodes, name) {\r
+                       var i = nodes.length;\r
+\r
+                       while (i--) {\r
+                               nodes[i].attr(name, null);\r
+                       }\r
+               });\r
+\r
+               // Return public methods\r
+               return {\r
+                       schema : schema,\r
+\r
+                       addNodeFilter : htmlParser.addNodeFilter,\r
+\r
+                       addAttributeFilter : htmlParser.addAttributeFilter,\r
+\r
+                       onPreProcess : onPreProcess,\r
+\r
+                       onPostProcess : onPostProcess,\r
+\r
+                       serialize : function(node, args) {\r
+                               var impl, doc, oldDoc, htmlSerializer, content;\r
+\r
+                               // Explorer won't clone contents of script and style and the\r
+                               // selected index of select elements are cleared on a clone operation.\r
+                               if (isIE && dom.select('script,style,select,map').length > 0) {\r
+                                       content = node.innerHTML;\r
+                                       node = node.cloneNode(false);\r
+                                       dom.setHTML(node, content);\r
+                               } else\r
+                                       node = node.cloneNode(true);\r
+\r
+                               // Nodes needs to be attached to something in WebKit/Opera\r
+                               // Older builds of Opera crashes if you attach the node to an document created dynamically\r
+                               // and since we can't feature detect a crash we need to sniff the acutal build number\r
+                               // This fix will make DOM ranges and make Sizzle happy!\r
+                               impl = node.ownerDocument.implementation;\r
+                               if (impl.createHTMLDocument) {\r
+                                       // Create an empty HTML document\r
+                                       doc = impl.createHTMLDocument("");\r
+\r
+                                       // Add the element or it's children if it's a body element to the new document\r
+                                       each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) {\r
+                                               doc.body.appendChild(doc.importNode(node, true));\r
+                                       });\r
+\r
+                                       // Grab first child or body element for serialization\r
+                                       if (node.nodeName != 'BODY')\r
+                                               node = doc.body.firstChild;\r
+                                       else\r
+                                               node = doc.body;\r
+\r
+                                       // set the new document in DOMUtils so createElement etc works\r
+                                       oldDoc = dom.doc;\r
+                                       dom.doc = doc;\r
+                               }\r
+\r
+                               args = args || {};\r
+                               args.format = args.format || 'html';\r
+\r
+                               // Pre process\r
+                               if (!args.no_events) {\r
+                                       args.node = node;\r
+                                       onPreProcess.dispatch(self, args);\r
+                               }\r
+\r
+                               // Setup serializer\r
+                               htmlSerializer = new tinymce.html.Serializer(settings, schema);\r
+\r
+                               // Parse and serialize HTML\r
+                               args.content = htmlSerializer.serialize(\r
+                                       htmlParser.parse(args.getInner ? node.innerHTML : tinymce.trim(dom.getOuterHTML(node), args), args)\r
+                               );\r
+\r
+                               // Replace all BOM characters for now until we can find a better solution\r
+                               if (!args.cleanup)\r
+                                       args.content = args.content.replace(/\uFEFF/g, '');\r
+\r
+                               // Post process\r
+                               if (!args.no_events)\r
+                                       onPostProcess.dispatch(self, args);\r
+\r
+                               // Restore the old document if it was changed\r
+                               if (oldDoc)\r
+                                       dom.doc = oldDoc;\r
+\r
+                               args.node = null;\r
+\r
+                               return args.content;\r
+                       },\r
+\r
+                       addRules : function(rules) {\r
+                               schema.addValidElements(rules);\r
+                       },\r
+\r
+                       setRules : function(rules) {\r
+                               schema.setValidElements(rules);\r
+                       }\r
+               };\r
+       };\r
+})(tinymce);\r
+(function(tinymce) {\r
+       tinymce.dom.ScriptLoader = function(settings) {\r
+               var QUEUED = 0,\r
+                       LOADING = 1,\r
+                       LOADED = 2,\r
+                       states = {},\r
+                       queue = [],\r
+                       scriptLoadedCallbacks = {},\r
+                       queueLoadedCallbacks = [],\r
+                       loading = 0,\r
+                       undefined;\r
+\r
+               function loadScript(url, callback) {\r
+                       var t = this, dom = tinymce.DOM, elm, uri, loc, id;\r
+\r
+                       // Execute callback when script is loaded\r
+                       function done() {\r
+                               dom.remove(id);\r
+\r
+                               if (elm)\r
+                                       elm.onreadystatechange = elm.onload = elm = null;\r
+\r
+                               callback();\r
+                       };\r
+                       \r
+                       function error() {\r
+                               // Report the error so it's easier for people to spot loading errors\r
+                               if (typeof(console) !== "undefined" && console.log)\r
+                                       console.log("Failed to load: " + url);\r
+\r
+                               // We can't mark it as done if there is a load error since\r
+                               // A) We don't want to produce 404 errors on the server and\r
+                               // B) the onerror event won't fire on all browsers.\r
+                               // done();\r
+                       };\r
+\r
+                       id = dom.uniqueId();\r
+\r
+                       if (tinymce.isIE6) {\r
+                               uri = new tinymce.util.URI(url);\r
+                               loc = location;\r
+\r
+                               // If script is from same domain and we\r
+                               // use IE 6 then use XHR since it's more reliable\r
+                               if (uri.host == loc.hostname && uri.port == loc.port && (uri.protocol + ':') == loc.protocol && uri.protocol.toLowerCase() != 'file') {\r
+                                       tinymce.util.XHR.send({\r
+                                               url : tinymce._addVer(uri.getURI()),\r
+                                               success : function(content) {\r
+                                                       // Create new temp script element\r
+                                                       var script = dom.create('script', {\r
+                                                               type : 'text/javascript'\r
+                                                       });\r
+\r
+                                                       // Evaluate script in global scope\r
+                                                       script.text = content;\r
+                                                       document.getElementsByTagName('head')[0].appendChild(script);\r
+                                                       dom.remove(script);\r
+\r
+                                                       done();\r
+                                               },\r
+                                               \r
+                                               error : error\r
+                                       });\r
+\r
+                                       return;\r
+                               }\r
+                       }\r
+\r
+                       // Create new script element\r
+                       elm = dom.create('script', {\r
+                               id : id,\r
+                               type : 'text/javascript',\r
+                               src : tinymce._addVer(url)\r
+                       });\r
+\r
+                       // Add onload listener for non IE browsers since IE9\r
+                       // fires onload event before the script is parsed and executed\r
+                       if (!tinymce.isIE)\r
+                               elm.onload = done;\r
+\r
+                       // Add onerror event will get fired on some browsers but not all of them\r
+                       elm.onerror = error;\r
+\r
+                       // Opera 9.60 doesn't seem to fire the onreadystate event at correctly\r
+                       if (!tinymce.isOpera) {\r
+                               elm.onreadystatechange = function() {\r
+                                       var state = elm.readyState;\r
+\r
+                                       // Loaded state is passed on IE 6 however there\r
+                                       // are known issues with this method but we can't use\r
+                                       // XHR in a cross domain loading\r
+                                       if (state == 'complete' || state == 'loaded')\r
+                                               done();\r
+                               };\r
+                       }\r
+\r
+                       // Most browsers support this feature so we report errors\r
+                       // for those at least to help users track their missing plugins etc\r
+                       // todo: Removed since it produced error if the document is unloaded by navigating away, re-add it as an option\r
+                       /*elm.onerror = function() {\r
+                               alert('Failed to load: ' + url);\r
+                       };*/\r
+\r
+                       // Add script to document\r
+                       (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);\r
+               };\r
+\r
+               this.isDone = function(url) {\r
+                       return states[url] == LOADED;\r
+               };\r
+\r
+               this.markDone = function(url) {\r
+                       states[url] = LOADED;\r
+               };\r
+\r
+               this.add = this.load = function(url, callback, scope) {\r
+                       var item, state = states[url];\r
+\r
+                       // Add url to load queue\r
+                       if (state == undefined) {\r
+                               queue.push(url);\r
+                               states[url] = QUEUED;\r
+                       }\r
+\r
+                       if (callback) {\r
+                               // Store away callback for later execution\r
+                               if (!scriptLoadedCallbacks[url])\r
+                                       scriptLoadedCallbacks[url] = [];\r
+\r
+                               scriptLoadedCallbacks[url].push({\r
+                                       func : callback,\r
+                                       scope : scope || this\r
+                               });\r
+                       }\r
+               };\r
+\r
+               this.loadQueue = function(callback, scope) {\r
+                       this.loadScripts(queue, callback, scope);\r
+               };\r
+\r
+               this.loadScripts = function(scripts, callback, scope) {\r
+                       var loadScripts;\r
+\r
+                       function execScriptLoadedCallbacks(url) {\r
+                               // Execute URL callback functions\r
+                               tinymce.each(scriptLoadedCallbacks[url], function(callback) {\r
+                                       callback.func.call(callback.scope);\r
+                               });\r
+\r
+                               scriptLoadedCallbacks[url] = undefined;\r
+                       };\r
+\r
+                       queueLoadedCallbacks.push({\r
+                               func : callback,\r
+                               scope : scope || this\r
+                       });\r
+\r
+                       loadScripts = function() {\r
+                               var loadingScripts = tinymce.grep(scripts);\r
+\r
+                               // Current scripts has been handled\r
+                               scripts.length = 0;\r
+\r
+                               // Load scripts that needs to be loaded\r
+                               tinymce.each(loadingScripts, function(url) {\r
+                                       // Script is already loaded then execute script callbacks directly\r
+                                       if (states[url] == LOADED) {\r
+                                               execScriptLoadedCallbacks(url);\r
+                                               return;\r
+                                       }\r
+\r
+                                       // Is script not loading then start loading it\r
+                                       if (states[url] != LOADING) {\r
+                                               states[url] = LOADING;\r
+                                               loading++;\r
+\r
+                                               loadScript(url, function() {\r
+                                                       states[url] = LOADED;\r
+                                                       loading--;\r
+\r
+                                                       execScriptLoadedCallbacks(url);\r
+\r
+                                                       // Load more scripts if they where added by the recently loaded script\r
+                                                       loadScripts();\r
+                                               });\r
+                                       }\r
+                               });\r
+\r
+                               // No scripts are currently loading then execute all pending queue loaded callbacks\r
+                               if (!loading) {\r
+                                       tinymce.each(queueLoadedCallbacks, function(callback) {\r
+                                               callback.func.call(callback.scope);\r
+                                       });\r
+\r
+                                       queueLoadedCallbacks.length = 0;\r
+                               }\r
+                       };\r
+\r
+                       loadScripts();\r
+               };\r
+       };\r
+\r
+       // Global script loader\r
+       tinymce.ScriptLoader = new tinymce.dom.ScriptLoader();\r
+})(tinymce);\r
+\r
+tinymce.dom.TreeWalker = function(start_node, root_node) {\r
+       var node = start_node;\r
+\r
+       function findSibling(node, start_name, sibling_name, shallow) {\r
+               var sibling, parent;\r
+\r
+               if (node) {\r
+                       // Walk into nodes if it has a start\r
+                       if (!shallow && node[start_name])\r
+                               return node[start_name];\r
+\r
+                       // Return the sibling if it has one\r
+                       if (node != root_node) {\r
+                               sibling = node[sibling_name];\r
+                               if (sibling)\r
+                                       return sibling;\r
+\r
+                               // Walk up the parents to look for siblings\r
+                               for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {\r
+                                       sibling = parent[sibling_name];\r
+                                       if (sibling)\r
+                                               return sibling;\r
+                               }\r
+                       }\r
+               }\r
+       };\r
+\r
+       this.current = function() {\r
+               return node;\r
+       };\r
+\r
+       this.next = function(shallow) {\r
+               return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));\r
+       };\r
+\r
+       this.prev = function(shallow) {\r
+               return (node = findSibling(node, 'lastChild', 'previousSibling', shallow));\r
+       };\r
 };\r
 \r
-TinyMCE.prototype.setStyleAttrib = function(elm, name, value) {\r
-       eval('elm.style.' + name + '=value;');\r
+(function(tinymce) {\r
+       tinymce.dom.RangeUtils = function(dom) {\r
+               var INVISIBLE_CHAR = '\uFEFF';\r
+\r
+               this.walk = function(rng, callback) {\r
+                       var startContainer = rng.startContainer,\r
+                               startOffset = rng.startOffset,\r
+                               endContainer = rng.endContainer,\r
+                               endOffset = rng.endOffset,\r
+                               ancestor, startPoint,\r
+                               endPoint, node, parent, siblings, nodes;\r
+\r
+                       // Handle table cell selection the table plugin enables\r
+                       // you to fake select table cells and perform formatting actions on them\r
+                       nodes = dom.select('td.mceSelected,th.mceSelected');\r
+                       if (nodes.length > 0) {\r
+                               tinymce.each(nodes, function(node) {\r
+                                       callback([node]);\r
+                               });\r
+\r
+                               return;\r
+                       }\r
+\r
+                       function collectSiblings(node, name, end_node) {\r
+                               var siblings = [];\r
+\r
+                               for (; node && node != end_node; node = node[name])\r
+                                       siblings.push(node);\r
+\r
+                               return siblings;\r
+                       };\r
+\r
+                       function findEndPoint(node, root) {\r
+                               do {\r
+                                       if (node.parentNode == root)\r
+                                               return node;\r
+\r
+                                       node = node.parentNode;\r
+                               } while(node);\r
+                       };\r
+\r
+                       function walkBoundary(start_node, end_node, next) {\r
+                               var siblingName = next ? 'nextSibling' : 'previousSibling';\r
+\r
+                               for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) {\r
+                                       parent = node.parentNode;\r
+                                       siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName);\r
+\r
+                                       if (siblings.length) {\r
+                                               if (!next)\r
+                                                       siblings.reverse();\r
+\r
+                                               callback(siblings);\r
+                                       }\r
+                               }\r
+                       };\r
+\r
+                       // If index based start position then resolve it\r
+                       if (startContainer.nodeType == 1 && startContainer.hasChildNodes())\r
+                               startContainer = startContainer.childNodes[startOffset];\r
+\r
+                       // If index based end position then resolve it\r
+                       if (endContainer.nodeType == 1 && endContainer.hasChildNodes())\r
+                               endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)];\r
+\r
+                       // Find common ancestor and end points\r
+                       ancestor = dom.findCommonAncestor(startContainer, endContainer);\r
+\r
+                       // Same container\r
+                       if (startContainer == endContainer)\r
+                               return callback([startContainer]);\r
+\r
+                       // Process left side\r
+                       for (node = startContainer; node; node = node.parentNode) {\r
+                               if (node == endContainer)\r
+                                       return walkBoundary(startContainer, ancestor, true);\r
+\r
+                               if (node == ancestor)\r
+                                       break;\r
+                       }\r
+\r
+                       // Process right side\r
+                       for (node = endContainer; node; node = node.parentNode) {\r
+                               if (node == startContainer)\r
+                                       return walkBoundary(endContainer, ancestor);\r
+\r
+                               if (node == ancestor)\r
+                                       break;\r
+                       }\r
+\r
+                       // Find start/end point\r
+                       startPoint = findEndPoint(startContainer, ancestor) || startContainer;\r
+                       endPoint = findEndPoint(endContainer, ancestor) || endContainer;\r
+\r
+                       // Walk left leaf\r
+                       walkBoundary(startContainer, startPoint, true);\r
+\r
+                       // Walk the middle from start to end point\r
+                       siblings = collectSiblings(\r
+                               startPoint == startContainer ? startPoint : startPoint.nextSibling,\r
+                               'nextSibling',\r
+                               endPoint == endContainer ? endPoint.nextSibling : endPoint\r
+                       );\r
+\r
+                       if (siblings.length)\r
+                               callback(siblings);\r
+\r
+                       // Walk right leaf\r
+                       walkBoundary(endContainer, endPoint);\r
+               };\r
+\r
+               /*              this.split = function(rng) {\r
+                       var startContainer = rng.startContainer,\r
+                               startOffset = rng.startOffset,\r
+                               endContainer = rng.endContainer,\r
+                               endOffset = rng.endOffset;\r
+\r
+                       function splitText(node, offset) {\r
+                               if (offset == node.nodeValue.length)\r
+                                       node.appendData(INVISIBLE_CHAR);\r
+\r
+                               node = node.splitText(offset);\r
+\r
+                               if (node.nodeValue === INVISIBLE_CHAR)\r
+                                       node.nodeValue = '';\r
+\r
+                               return node;\r
+                       };\r
+\r
+                       // Handle single text node\r
+                       if (startContainer == endContainer) {\r
+                               if (startContainer.nodeType == 3) {\r
+                                       if (startOffset != 0)\r
+                                               startContainer = endContainer = splitText(startContainer, startOffset);\r
+\r
+                                       if (endOffset - startOffset != startContainer.nodeValue.length)\r
+                                               splitText(startContainer, endOffset - startOffset);\r
+                               }\r
+                       } else {\r
+                               // Split startContainer text node if needed\r
+                               if (startContainer.nodeType == 3 && startOffset != 0) {\r
+                                       startContainer = splitText(startContainer, startOffset);\r
+                                       startOffset = 0;\r
+                               }\r
+\r
+                               // Split endContainer text node if needed\r
+                               if (endContainer.nodeType == 3 && endOffset != endContainer.nodeValue.length) {\r
+                                       endContainer = splitText(endContainer, endOffset).previousSibling;\r
+                                       endOffset = endContainer.nodeValue.length;\r
+                               }\r
+                       }\r
+\r
+                       return {\r
+                               startContainer : startContainer,\r
+                               startOffset : startOffset,\r
+                               endContainer : endContainer,\r
+                               endOffset : endOffset\r
+                       };\r
+               };\r
+*/\r
+       };\r
+\r
+       tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) {\r
+               if (rng1 && rng2) {\r
+                       // Compare native IE ranges\r
+                       if (rng1.item || rng1.duplicate) {\r
+                               // Both are control ranges and the selected element matches\r
+                               if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0))\r
+                                       return true;\r
+\r
+                               // Both are text ranges and the range matches\r
+                               if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1))\r
+                                       return true;\r
+                       } else {\r
+                               // Compare w3c ranges\r
+                               return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset;\r
+                       }\r
+               }\r
+\r
+               return false;\r
+       };\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var Event = tinymce.dom.Event, each = tinymce.each;\r
+\r
+       tinymce.create('tinymce.ui.KeyboardNavigation', {\r
+               KeyboardNavigation: function(settings, dom) {\r
+                       var t = this, root = settings.root, items = settings.items,\r
+                                       enableUpDown = settings.enableUpDown, enableLeftRight = settings.enableLeftRight || !settings.enableUpDown,\r
+                                       excludeFromTabOrder = settings.excludeFromTabOrder,\r
+                                       itemFocussed, itemBlurred, rootKeydown, rootFocussed, focussedId;\r
+\r
+                       dom = dom || tinymce.DOM;\r
+\r
+                       itemFocussed = function(evt) {\r
+                               focussedId = evt.target.id;\r
+                       };\r
+                       \r
+                       itemBlurred = function(evt) {\r
+                               dom.setAttrib(evt.target.id, 'tabindex', '-1');\r
+                       };\r
+                       \r
+                       rootFocussed = function(evt) {\r
+                               var item = dom.get(focussedId);\r
+                               dom.setAttrib(item, 'tabindex', '0');\r
+                               item.focus();\r
+                       };\r
+                       \r
+                       t.focus = function() {\r
+                               dom.get(focussedId).focus();\r
+                       };\r
+\r
+                       t.destroy = function() {\r
+                               each(items, function(item) {\r
+                                       dom.unbind(dom.get(item.id), 'focus', itemFocussed);\r
+                                       dom.unbind(dom.get(item.id), 'blur', itemBlurred);\r
+                               });\r
+\r
+                               dom.unbind(dom.get(root), 'focus', rootFocussed);\r
+                               dom.unbind(dom.get(root), 'keydown', rootKeydown);\r
+\r
+                               items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null;\r
+                               t.destroy = function() {};\r
+                       };\r
+                       \r
+                       t.moveFocus = function(dir, evt) {\r
+                               var idx = -1, controls = t.controls, newFocus;\r
+\r
+                               if (!focussedId)\r
+                                       return;\r
+\r
+                               each(items, function(item, index) {\r
+                                       if (item.id === focussedId) {\r
+                                               idx = index;\r
+                                               return false;\r
+                                       }\r
+                               });\r
+\r
+                               idx += dir;\r
+                               if (idx < 0) {\r
+                                       idx = items.length - 1;\r
+                               } else if (idx >= items.length) {\r
+                                       idx = 0;\r
+                               }\r
+                               \r
+                               newFocus = items[idx];\r
+                               dom.setAttrib(focussedId, 'tabindex', '-1');\r
+                               dom.setAttrib(newFocus.id, 'tabindex', '0');\r
+                               dom.get(newFocus.id).focus();\r
+\r
+                               if (settings.actOnFocus) {\r
+                                       settings.onAction(newFocus.id);\r
+                               }\r
+\r
+                               if (evt)\r
+                                       Event.cancel(evt);\r
+                       };\r
+                       \r
+                       rootKeydown = function(evt) {\r
+                               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;\r
+                               \r
+                               switch (evt.keyCode) {\r
+                                       case DOM_VK_LEFT:\r
+                                               if (enableLeftRight) t.moveFocus(-1);\r
+                                               break;\r
+       \r
+                                       case DOM_VK_RIGHT:\r
+                                               if (enableLeftRight) t.moveFocus(1);\r
+                                               break;\r
+       \r
+                                       case DOM_VK_UP:\r
+                                               if (enableUpDown) t.moveFocus(-1);\r
+                                               break;\r
+\r
+                                       case DOM_VK_DOWN:\r
+                                               if (enableUpDown) t.moveFocus(1);\r
+                                               break;\r
+\r
+                                       case DOM_VK_ESCAPE:\r
+                                               if (settings.onCancel) {\r
+                                                       settings.onCancel();\r
+                                                       Event.cancel(evt);\r
+                                               }\r
+                                               break;\r
+\r
+                                       case DOM_VK_ENTER:\r
+                                       case DOM_VK_RETURN:\r
+                                       case DOM_VK_SPACE:\r
+                                               if (settings.onAction) {\r
+                                                       settings.onAction(focussedId);\r
+                                                       Event.cancel(evt);\r
+                                               }\r
+                                               break;\r
+                               }\r
+                       };\r
+\r
+                       // Set up state and listeners for each item.\r
+                       each(items, function(item, idx) {\r
+                               var tabindex;\r
+\r
+                               if (!item.id) {\r
+                                       item.id = dom.uniqueId('_mce_item_');\r
+                               }\r
+\r
+                               if (excludeFromTabOrder) {\r
+                                       dom.bind(item.id, 'blur', itemBlurred);\r
+                                       tabindex = '-1';\r
+                               } else {\r
+                                       tabindex = (idx === 0 ? '0' : '-1');\r
+                               }\r
+\r
+                               dom.setAttrib(item.id, 'tabindex', tabindex);\r
+                               dom.bind(dom.get(item.id), 'focus', itemFocussed);\r
+                       });\r
+                       \r
+                       // Setup initial state for root element.\r
+                       if (items[0]){\r
+                               focussedId = items[0].id;\r
+                       }\r
+\r
+                       dom.setAttrib(root, 'tabindex', '-1');\r
+                       \r
+                       // Setup listeners for root element.\r
+                       dom.bind(dom.get(root), 'focus', rootFocussed);\r
+                       dom.bind(dom.get(root), 'keydown', rootKeydown);\r
+               }\r
+       });\r
+})(tinymce);\r
+(function(tinymce) {\r
+       // Shorten class names\r
+       var DOM = tinymce.DOM, is = tinymce.is;\r
+\r
+       tinymce.create('tinymce.ui.Control', {\r
+               Control : function(id, s, editor) {\r
+                       this.id = id;\r
+                       this.settings = s = s || {};\r
+                       this.rendered = false;\r
+                       this.onRender = new tinymce.util.Dispatcher(this);\r
+                       this.classPrefix = '';\r
+                       this.scope = s.scope || this;\r
+                       this.disabled = 0;\r
+                       this.active = 0;\r
+                       this.editor = editor;\r
+               },\r
+               \r
+               setAriaProperty : function(property, value) {\r
+                       var element = DOM.get(this.id + '_aria') || DOM.get(this.id);\r
+                       if (element) {\r
+                               DOM.setAttrib(element, 'aria-' + property, !!value);\r
+                       }\r
+               },\r
+               \r
+               focus : function() {\r
+                       DOM.get(this.id).focus();\r
+               },\r
+\r
+               setDisabled : function(s) {\r
+                       if (s != this.disabled) {\r
+                               this.setAriaProperty('disabled', s);\r
+\r
+                               this.setState('Disabled', s);\r
+                               this.setState('Enabled', !s);\r
+                               this.disabled = s;\r
+                       }\r
+               },\r
+\r
+               isDisabled : function() {\r
+                       return this.disabled;\r
+               },\r
+\r
+               setActive : function(s) {\r
+                       if (s != this.active) {\r
+                               this.setState('Active', s);\r
+                               this.active = s;\r
+                               this.setAriaProperty('pressed', s);\r
+                       }\r
+               },\r
+\r
+               isActive : function() {\r
+                       return this.active;\r
+               },\r
+\r
+               setState : function(c, s) {\r
+                       var n = DOM.get(this.id);\r
+\r
+                       c = this.classPrefix + c;\r
+\r
+                       if (s)\r
+                               DOM.addClass(n, c);\r
+                       else\r
+                               DOM.removeClass(n, c);\r
+               },\r
+\r
+               isRendered : function() {\r
+                       return this.rendered;\r
+               },\r
+\r
+               renderHTML : function() {\r
+               },\r
+\r
+               renderTo : function(n) {\r
+                       DOM.setHTML(n, this.renderHTML());\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, b;\r
+\r
+                       // Set pending states\r
+                       if (is(t.disabled)) {\r
+                               b = t.disabled;\r
+                               t.disabled = -1;\r
+                               t.setDisabled(b);\r
+                       }\r
+\r
+                       if (is(t.active)) {\r
+                               b = t.active;\r
+                               t.active = -1;\r
+                               t.setActive(b);\r
+                       }\r
+               },\r
+\r
+               remove : function() {\r
+                       DOM.remove(this.id);\r
+                       this.destroy();\r
+               },\r
+\r
+               destroy : function() {\r
+                       tinymce.dom.Event.clear(this.id);\r
+               }\r
+       });\r
+})(tinymce);\r
+tinymce.create('tinymce.ui.Container:tinymce.ui.Control', {\r
+       Container : function(id, s, editor) {\r
+               this.parent(id, s, editor);\r
+\r
+               this.controls = [];\r
+\r
+               this.lookup = {};\r
+       },\r
+\r
+       add : function(c) {\r
+               this.lookup[c.id] = c;\r
+               this.controls.push(c);\r
+\r
+               return c;\r
+       },\r
+\r
+       get : function(n) {\r
+               return this.lookup[n];\r
+       }\r
+});\r
+\r
+\r
+tinymce.create('tinymce.ui.Separator:tinymce.ui.Control', {\r
+       Separator : function(id, s) {\r
+               this.parent(id, s);\r
+               this.classPrefix = 'mceSeparator';\r
+               this.setDisabled(true);\r
+       },\r
+\r
+       renderHTML : function() {\r
+               return tinymce.DOM.createHTML('span', {'class' : this.classPrefix, role : 'separator', 'aria-orientation' : 'vertical', tabindex : '-1'});\r
+       }\r
+});\r
+\r
+(function(tinymce) {\r
+       var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;\r
+\r
+       tinymce.create('tinymce.ui.MenuItem:tinymce.ui.Control', {\r
+               MenuItem : function(id, s) {\r
+                       this.parent(id, s);\r
+                       this.classPrefix = 'mceMenuItem';\r
+               },\r
+\r
+               setSelected : function(s) {\r
+                       this.setState('Selected', s);\r
+                       this.setAriaProperty('checked', !!s);\r
+                       this.selected = s;\r
+               },\r
+\r
+               isSelected : function() {\r
+                       return this.selected;\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this;\r
+                       \r
+                       t.parent();\r
+\r
+                       // Set pending state\r
+                       if (is(t.selected))\r
+                               t.setSelected(t.selected);\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk;\r
+\r
+       tinymce.create('tinymce.ui.Menu:tinymce.ui.MenuItem', {\r
+               Menu : function(id, s) {\r
+                       var t = this;\r
+\r
+                       t.parent(id, s);\r
+                       t.items = {};\r
+                       t.collapsed = false;\r
+                       t.menuCount = 0;\r
+                       t.onAddItem = new tinymce.util.Dispatcher(this);\r
+               },\r
+\r
+               expand : function(d) {\r
+                       var t = this;\r
+\r
+                       if (d) {\r
+                               walk(t, function(o) {\r
+                                       if (o.expand)\r
+                                               o.expand();\r
+                               }, 'items', t);\r
+                       }\r
+\r
+                       t.collapsed = false;\r
+               },\r
+\r
+               collapse : function(d) {\r
+                       var t = this;\r
+\r
+                       if (d) {\r
+                               walk(t, function(o) {\r
+                                       if (o.collapse)\r
+                                               o.collapse();\r
+                               }, 'items', t);\r
+                       }\r
+\r
+                       t.collapsed = true;\r
+               },\r
+\r
+               isCollapsed : function() {\r
+                       return this.collapsed;\r
+               },\r
+\r
+               add : function(o) {\r
+                       if (!o.settings)\r
+                               o = new tinymce.ui.MenuItem(o.id || DOM.uniqueId(), o);\r
+\r
+                       this.onAddItem.dispatch(this, o);\r
+\r
+                       return this.items[o.id] = o;\r
+               },\r
+\r
+               addSeparator : function() {\r
+                       return this.add({separator : true});\r
+               },\r
+\r
+               addMenu : function(o) {\r
+                       if (!o.collapse)\r
+                               o = this.createMenu(o);\r
+\r
+                       this.menuCount++;\r
+\r
+                       return this.add(o);\r
+               },\r
+\r
+               hasMenus : function() {\r
+                       return this.menuCount !== 0;\r
+               },\r
+\r
+               remove : function(o) {\r
+                       delete this.items[o.id];\r
+               },\r
+\r
+               removeAll : function() {\r
+                       var t = this;\r
+\r
+                       walk(t, function(o) {\r
+                               if (o.removeAll)\r
+                                       o.removeAll();\r
+                               else\r
+                                       o.remove();\r
+\r
+                               o.destroy();\r
+                       }, 'items', t);\r
+\r
+                       t.items = {};\r
+               },\r
+\r
+               createMenu : function(o) {\r
+                       var m = new tinymce.ui.Menu(o.id || DOM.uniqueId(), o);\r
+\r
+                       m.onAddItem.add(this.onAddItem.dispatch, this.onAddItem);\r
+\r
+                       return m;\r
+               }\r
+       });\r
+})(tinymce);\r
+(function(tinymce) {\r
+       var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event, Element = tinymce.dom.Element;\r
+\r
+       tinymce.create('tinymce.ui.DropMenu:tinymce.ui.Menu', {\r
+               DropMenu : function(id, s) {\r
+                       s = s || {};\r
+                       s.container = s.container || DOM.doc.body;\r
+                       s.offset_x = s.offset_x || 0;\r
+                       s.offset_y = s.offset_y || 0;\r
+                       s.vp_offset_x = s.vp_offset_x || 0;\r
+                       s.vp_offset_y = s.vp_offset_y || 0;\r
+\r
+                       if (is(s.icons) && !s.icons)\r
+                               s['class'] += ' mceNoIcons';\r
+\r
+                       this.parent(id, s);\r
+                       this.onShowMenu = new tinymce.util.Dispatcher(this);\r
+                       this.onHideMenu = new tinymce.util.Dispatcher(this);\r
+                       this.classPrefix = 'mceMenu';\r
+               },\r
+\r
+               createMenu : function(s) {\r
+                       var t = this, cs = t.settings, m;\r
+\r
+                       s.container = s.container || cs.container;\r
+                       s.parent = t;\r
+                       s.constrain = s.constrain || cs.constrain;\r
+                       s['class'] = s['class'] || cs['class'];\r
+                       s.vp_offset_x = s.vp_offset_x || cs.vp_offset_x;\r
+                       s.vp_offset_y = s.vp_offset_y || cs.vp_offset_y;\r
+                       s.keyboard_focus = cs.keyboard_focus;\r
+                       m = new tinymce.ui.DropMenu(s.id || DOM.uniqueId(), s);\r
+\r
+                       m.onAddItem.add(t.onAddItem.dispatch, t.onAddItem);\r
+\r
+                       return m;\r
+               },\r
+               \r
+               focus : function() {\r
+                       var t = this;\r
+                       if (t.keyboardNav) {\r
+                               t.keyboardNav.focus();\r
+                       }\r
+               },\r
+\r
+               update : function() {\r
+                       var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th;\r
+\r
+                       tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth;\r
+                       th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight;\r
+\r
+                       if (!DOM.boxModel)\r
+                               t.element.setStyles({width : tw + 2, height : th + 2});\r
+                       else\r
+                               t.element.setStyles({width : tw, height : th});\r
+\r
+                       if (s.max_width)\r
+                               DOM.setStyle(co, 'width', tw);\r
+\r
+                       if (s.max_height) {\r
+                               DOM.setStyle(co, 'height', th);\r
+\r
+                               if (tb.clientHeight < s.max_height)\r
+                                       DOM.setStyle(co, 'overflow', 'hidden');\r
+                       }\r
+               },\r
+\r
+               showMenu : function(x, y, px) {\r
+                       var t = this, s = t.settings, co, vp = DOM.getViewPort(), w, h, mx, my, ot = 2, dm, tb, cp = t.classPrefix;\r
+\r
+                       t.collapse(1);\r
+\r
+                       if (t.isMenuVisible)\r
+                               return;\r
+\r
+                       if (!t.rendered) {\r
+                               co = DOM.add(t.settings.container, t.renderNode());\r
+\r
+                               each(t.items, function(o) {\r
+                                       o.postRender();\r
+                               });\r
+\r
+                               t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});\r
+                       } else\r
+                               co = DOM.get('menu_' + t.id);\r
+\r
+                       // Move layer out of sight unless it's Opera since it scrolls to top of page due to an bug\r
+                       if (!tinymce.isOpera)\r
+                               DOM.setStyles(co, {left : -0xFFFF , top : -0xFFFF});\r
+\r
+                       DOM.show(co);\r
+                       t.update();\r
+\r
+                       x += s.offset_x || 0;\r
+                       y += s.offset_y || 0;\r
+                       vp.w -= 4;\r
+                       vp.h -= 4;\r
+\r
+                       // Move inside viewport if not submenu\r
+                       if (s.constrain) {\r
+                               w = co.clientWidth - ot;\r
+                               h = co.clientHeight - ot;\r
+                               mx = vp.x + vp.w;\r
+                               my = vp.y + vp.h;\r
+\r
+                               if ((x + s.vp_offset_x + w) > mx)\r
+                                       x = px ? px - w : Math.max(0, (mx - s.vp_offset_x) - w);\r
+\r
+                               if ((y + s.vp_offset_y + h) > my)\r
+                                       y = Math.max(0, (my - s.vp_offset_y) - h);\r
+                       }\r
+\r
+                       DOM.setStyles(co, {left : x , top : y});\r
+                       t.element.update();\r
+\r
+                       t.isMenuVisible = 1;\r
+                       t.mouseClickFunc = Event.add(co, 'click', function(e) {\r
+                               var m;\r
+\r
+                               e = e.target;\r
+\r
+                               if (e && (e = DOM.getParent(e, 'tr')) && !DOM.hasClass(e, cp + 'ItemSub')) {\r
+                                       m = t.items[e.id];\r
+\r
+                                       if (m.isDisabled())\r
+                                               return;\r
+\r
+                                       dm = t;\r
+\r
+                                       while (dm) {\r
+                                               if (dm.hideMenu)\r
+                                                       dm.hideMenu();\r
+\r
+                                               dm = dm.settings.parent;\r
+                                       }\r
+\r
+                                       if (m.settings.onclick)\r
+                                               m.settings.onclick(e);\r
+\r
+                                       return Event.cancel(e); // Cancel to fix onbeforeunload problem\r
+                               }\r
+                       });\r
+\r
+                       if (t.hasMenus()) {\r
+                               t.mouseOverFunc = Event.add(co, 'mouseover', function(e) {\r
+                                       var m, r, mi;\r
+\r
+                                       e = e.target;\r
+                                       if (e && (e = DOM.getParent(e, 'tr'))) {\r
+                                               m = t.items[e.id];\r
+\r
+                                               if (t.lastMenu)\r
+                                                       t.lastMenu.collapse(1);\r
+\r
+                                               if (m.isDisabled())\r
+                                                       return;\r
+\r
+                                               if (e && DOM.hasClass(e, cp + 'ItemSub')) {\r
+                                                       //p = DOM.getPos(s.container);\r
+                                                       r = DOM.getRect(e);\r
+                                                       m.showMenu((r.x + r.w - ot), r.y - ot, r.x);\r
+                                                       t.lastMenu = m;\r
+                                                       DOM.addClass(DOM.get(m.id).firstChild, cp + 'ItemActive');\r
+                                               }\r
+                                       }\r
+                               });\r
+                       }\r
+                       \r
+                       Event.add(co, 'keydown', t._keyHandler, t);\r
+\r
+                       t.onShowMenu.dispatch(t);\r
+\r
+                       if (s.keyboard_focus) { \r
+                               t._setupKeyboardNav(); \r
+                       }\r
+               },\r
+\r
+               hideMenu : function(c) {\r
+                       var t = this, co = DOM.get('menu_' + t.id), e;\r
+\r
+                       if (!t.isMenuVisible)\r
+                               return;\r
+\r
+                       if (t.keyboardNav) t.keyboardNav.destroy();\r
+                       Event.remove(co, 'mouseover', t.mouseOverFunc);\r
+                       Event.remove(co, 'click', t.mouseClickFunc);\r
+                       Event.remove(co, 'keydown', t._keyHandler);\r
+                       DOM.hide(co);\r
+                       t.isMenuVisible = 0;\r
+\r
+                       if (!c)\r
+                               t.collapse(1);\r
+\r
+                       if (t.element)\r
+                               t.element.hide();\r
+\r
+                       if (e = DOM.get(t.id))\r
+                               DOM.removeClass(e.firstChild, t.classPrefix + 'ItemActive');\r
+\r
+                       t.onHideMenu.dispatch(t);\r
+               },\r
+\r
+               add : function(o) {\r
+                       var t = this, co;\r
+\r
+                       o = t.parent(o);\r
+\r
+                       if (t.isRendered && (co = DOM.get('menu_' + t.id)))\r
+                               t._add(DOM.select('tbody', co)[0], o);\r
+\r
+                       return o;\r
+               },\r
+\r
+               collapse : function(d) {\r
+                       this.parent(d);\r
+                       this.hideMenu(1);\r
+               },\r
+\r
+               remove : function(o) {\r
+                       DOM.remove(o.id);\r
+                       this.destroy();\r
+\r
+                       return this.parent(o);\r
+               },\r
+\r
+               destroy : function() {\r
+                       var t = this, co = DOM.get('menu_' + t.id);\r
+\r
+                       if (t.keyboardNav) t.keyboardNav.destroy();\r
+                       Event.remove(co, 'mouseover', t.mouseOverFunc);\r
+                       Event.remove(DOM.select('a', co), 'focus', t.mouseOverFunc);\r
+                       Event.remove(co, 'click', t.mouseClickFunc);\r
+                       Event.remove(co, 'keydown', t._keyHandler);\r
+\r
+                       if (t.element)\r
+                               t.element.remove();\r
+\r
+                       DOM.remove(co);\r
+               },\r
+\r
+               renderNode : function() {\r
+                       var t = this, s = t.settings, n, tb, co, w;\r
+\r
+                       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'});\r
+                       if (t.settings.parent) {\r
+                               DOM.setAttrib(w, 'aria-parent', 'menu_' + t.settings.parent.id);\r
+                       }\r
+                       co = DOM.add(w, 'div', {role: 'presentation', id : 'menu_' + t.id + '_co', 'class' : t.classPrefix + (s['class'] ? ' ' + s['class'] : '')});\r
+                       t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container});\r
+\r
+                       if (s.menu_line)\r
+                               DOM.add(co, 'span', {'class' : t.classPrefix + 'Line'});\r
+\r
+//                     n = DOM.add(co, 'div', {id : 'menu_' + t.id + '_co', 'class' : 'mceMenuContainer'});\r
+                       n = DOM.add(co, 'table', {role: 'presentation', id : 'menu_' + t.id + '_tbl', border : 0, cellPadding : 0, cellSpacing : 0});\r
+                       tb = DOM.add(n, 'tbody');\r
+\r
+                       each(t.items, function(o) {\r
+                               t._add(tb, o);\r
+                       });\r
+\r
+                       t.rendered = true;\r
+\r
+                       return w;\r
+               },\r
+\r
+               // Internal functions\r
+               _setupKeyboardNav : function(){\r
+                       var contextMenu, menuItems, t=this; \r
+                       contextMenu = DOM.select('#menu_' + t.id)[0];\r
+                       menuItems = DOM.select('a[role=option]', 'menu_' + t.id);\r
+                       menuItems.splice(0,0,contextMenu);\r
+                       t.keyboardNav = new tinymce.ui.KeyboardNavigation({\r
+                               root: 'menu_' + t.id,\r
+                               items: menuItems,\r
+                               onCancel: function() {\r
+                                       t.hideMenu();\r
+                               },\r
+                               enableUpDown: true\r
+                       });\r
+                       contextMenu.focus();\r
+               },\r
+\r
+               _keyHandler : function(evt) {\r
+                       var t = this, e;\r
+                       switch (evt.keyCode) {\r
+                               case 37: // Left\r
+                                       if (t.settings.parent) {\r
+                                               t.hideMenu();\r
+                                               t.settings.parent.focus();\r
+                                               Event.cancel(evt);\r
+                                       }\r
+                                       break;\r
+                               case 39: // Right\r
+                                       if (t.mouseOverFunc)\r
+                                               t.mouseOverFunc(evt);\r
+                                       break;\r
+                       }\r
+               },\r
+\r
+               _add : function(tb, o) {\r
+                       var n, s = o.settings, a, ro, it, cp = this.classPrefix, ic;\r
+\r
+                       if (s.separator) {\r
+                               ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'ItemSeparator'});\r
+                               DOM.add(ro, 'td', {'class' : cp + 'ItemSeparator'});\r
+\r
+                               if (n = ro.previousSibling)\r
+                                       DOM.addClass(n, 'mceLast');\r
+\r
+                               return;\r
+                       }\r
+\r
+                       n = ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'Item ' + cp + 'ItemEnabled'});\r
+                       n = it = DOM.add(n, s.titleItem ? 'th' : 'td');\r
+                       n = a = DOM.add(n, 'a', {id: o.id + '_aria',  role: s.titleItem ? 'presentation' : 'option', href : 'javascript:;', onclick : "return false;", onmousedown : 'return false;'});\r
+\r
+                       if (s.parent) {\r
+                               DOM.setAttrib(a, 'aria-haspopup', 'true');\r
+                               DOM.setAttrib(a, 'aria-owns', 'menu_' + o.id);\r
+                       }\r
+\r
+                       DOM.addClass(it, s['class']);\r
+//                     n = DOM.add(n, 'span', {'class' : 'item'});\r
+\r
+                       ic = DOM.add(n, 'span', {'class' : 'mceIcon' + (s.icon ? ' mce_' + s.icon : '')});\r
+\r
+                       if (s.icon_src)\r
+                               DOM.add(ic, 'img', {src : s.icon_src});\r
+\r
+                       n = DOM.add(n, s.element || 'span', {'class' : 'mceText', title : o.settings.title}, o.settings.title);\r
+\r
+                       if (o.settings.style)\r
+                               DOM.setAttrib(n, 'style', o.settings.style);\r
+\r
+                       if (tb.childNodes.length == 1)\r
+                               DOM.addClass(ro, 'mceFirst');\r
+\r
+                       if ((n = ro.previousSibling) && DOM.hasClass(n, cp + 'ItemSeparator'))\r
+                               DOM.addClass(ro, 'mceFirst');\r
+\r
+                       if (o.collapse)\r
+                               DOM.addClass(ro, cp + 'ItemSub');\r
+\r
+                       if (n = ro.previousSibling)\r
+                               DOM.removeClass(n, 'mceLast');\r
+\r
+                       DOM.addClass(ro, 'mceLast');\r
+               }\r
+       });\r
+})(tinymce);\r
+(function(tinymce) {\r
+       var DOM = tinymce.DOM;\r
+\r
+       tinymce.create('tinymce.ui.Button:tinymce.ui.Control', {\r
+               Button : function(id, s, ed) {\r
+                       this.parent(id, s, ed);\r
+                       this.classPrefix = 'mceButton';\r
+               },\r
+\r
+               renderHTML : function() {\r
+                       var cp = this.classPrefix, s = this.settings, h, l;\r
+\r
+                       l = DOM.encode(s.label || '');\r
+                       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) + '">';\r
+                       if (s.image && !(this.editor  &&this.editor.forcedHighContrastMode) )\r
+                               h += '<img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" />' + l;\r
+                       else\r
+                               h += '<span class="mceIcon ' + s['class'] + '"></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : '');\r
+\r
+                       h += '<span class="mceVoiceLabel mceIconOnly" style="display: none;" id="' + this.id + '_voice">' + s.title + '</span>'; \r
+                       h += '</a>';\r
+                       return h;\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, s = t.settings;\r
+\r
+                       tinymce.dom.Event.add(t.id, 'click', function(e) {\r
+                               if (!t.isDisabled())\r
+                                       return s.onclick.call(s.scope, e);\r
+                       });\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;\r
+\r
+       tinymce.create('tinymce.ui.ListBox:tinymce.ui.Control', {\r
+               ListBox : function(id, s, ed) {\r
+                       var t = this;\r
+\r
+                       t.parent(id, s, ed);\r
+\r
+                       t.items = [];\r
+\r
+                       t.onChange = new Dispatcher(t);\r
+\r
+                       t.onPostRender = new Dispatcher(t);\r
+\r
+                       t.onAdd = new Dispatcher(t);\r
+\r
+                       t.onRenderMenu = new tinymce.util.Dispatcher(this);\r
+\r
+                       t.classPrefix = 'mceListBox';\r
+               },\r
+\r
+               select : function(va) {\r
+                       var t = this, fv, f;\r
+\r
+                       if (va == undefined)\r
+                               return t.selectByIndex(-1);\r
+\r
+                       // Is string or number make function selector\r
+                       if (va && va.call)\r
+                               f = va;\r
+                       else {\r
+                               f = function(v) {\r
+                                       return v == va;\r
+                               };\r
+                       }\r
+\r
+                       // Do we need to do something?\r
+                       if (va != t.selectedValue) {\r
+                               // Find item\r
+                               each(t.items, function(o, i) {\r
+                                       if (f(o.value)) {\r
+                                               fv = 1;\r
+                                               t.selectByIndex(i);\r
+                                               return false;\r
+                                       }\r
+                               });\r
+\r
+                               if (!fv)\r
+                                       t.selectByIndex(-1);\r
+                       }\r
+               },\r
+\r
+               selectByIndex : function(idx) {\r
+                       var t = this, e, o;\r
+\r
+                       if (idx != t.selectedIndex) {\r
+                               e = DOM.get(t.id + '_text');\r
+                               o = t.items[idx];\r
+\r
+                               if (o) {\r
+                                       t.selectedValue = o.value;\r
+                                       t.selectedIndex = idx;\r
+                                       DOM.setHTML(e, DOM.encode(o.title));\r
+                                       DOM.removeClass(e, 'mceTitle');\r
+                                       DOM.setAttrib(t.id, 'aria-valuenow', o.title);\r
+                               } else {\r
+                                       DOM.setHTML(e, DOM.encode(t.settings.title));\r
+                                       DOM.addClass(e, 'mceTitle');\r
+                                       t.selectedValue = t.selectedIndex = null;\r
+                                       DOM.setAttrib(t.id, 'aria-valuenow', t.settings.title);\r
+                               }\r
+                               e = 0;\r
+                       }\r
+               },\r
+\r
+               add : function(n, v, o) {\r
+                       var t = this;\r
+\r
+                       o = o || {};\r
+                       o = tinymce.extend(o, {\r
+                               title : n,\r
+                               value : v\r
+                       });\r
+\r
+                       t.items.push(o);\r
+                       t.onAdd.dispatch(t, o);\r
+               },\r
+\r
+               getLength : function() {\r
+                       return this.items.length;\r
+               },\r
+\r
+               renderHTML : function() {\r
+                       var h = '', t = this, s = t.settings, cp = t.classPrefix;\r
+\r
+                       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>';\r
+                       h += '<td>' + DOM.createHTML('span', {id: t.id + '_voiceDesc', 'class': 'voiceLabel', style:'display:none;'}, t.settings.title); \r
+                       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>';\r
+                       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>';\r
+                       h += '</tr></tbody></table></span>';\r
+\r
+                       return h;\r
+               },\r
+\r
+               showMenu : function() {\r
+                       var t = this, p2, e = DOM.get(this.id), m;\r
+\r
+                       if (t.isDisabled() || t.items.length == 0)\r
+                               return;\r
+\r
+                       if (t.menu && t.menu.isMenuVisible)\r
+                               return t.hideMenu();\r
+\r
+                       if (!t.isMenuRendered) {\r
+                               t.renderMenu();\r
+                               t.isMenuRendered = true;\r
+                       }\r
+\r
+                       p2 = DOM.getPos(e);\r
+\r
+                       m = t.menu;\r
+                       m.settings.offset_x = p2.x;\r
+                       m.settings.offset_y = p2.y;\r
+                       m.settings.keyboard_focus = !tinymce.isOpera; // Opera is buggy when it comes to auto focus\r
+\r
+                       // Select in menu\r
+                       if (t.oldID)\r
+                               m.items[t.oldID].setSelected(0);\r
+\r
+                       each(t.items, function(o) {\r
+                               if (o.value === t.selectedValue) {\r
+                                       m.items[o.id].setSelected(1);\r
+                                       t.oldID = o.id;\r
+                               }\r
+                       });\r
+\r
+                       m.showMenu(0, e.clientHeight);\r
+\r
+                       Event.add(DOM.doc, 'mousedown', t.hideMenu, t);\r
+                       DOM.addClass(t.id, t.classPrefix + 'Selected');\r
+\r
+                       //DOM.get(t.id + '_text').focus();\r
+               },\r
+\r
+               hideMenu : function(e) {\r
+                       var t = this;\r
+\r
+                       if (t.menu && t.menu.isMenuVisible) {\r
+                               DOM.removeClass(t.id, t.classPrefix + 'Selected');\r
+\r
+                               // Prevent double toogles by canceling the mouse click event to the button\r
+                               if (e && e.type == "mousedown" && (e.target.id == t.id + '_text' || e.target.id == t.id + '_open'))\r
+                                       return;\r
+\r
+                               if (!e || !DOM.getParent(e.target, '.mceMenu')) {\r
+                                       DOM.removeClass(t.id, t.classPrefix + 'Selected');\r
+                                       Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);\r
+                                       t.menu.hideMenu();\r
+                               }\r
+                       }\r
+               },\r
+\r
+               renderMenu : function() {\r
+                       var t = this, m;\r
+\r
+                       m = t.settings.control_manager.createDropMenu(t.id + '_menu', {\r
+                               menu_line : 1,\r
+                               'class' : t.classPrefix + 'Menu mceNoIcons',\r
+                               max_width : 150,\r
+                               max_height : 150\r
+                       });\r
+\r
+                       m.onHideMenu.add(function() {\r
+                               t.hideMenu();\r
+                               t.focus();\r
+                       });\r
+\r
+                       m.add({\r
+                               title : t.settings.title,\r
+                               'class' : 'mceMenuItemTitle',\r
+                               onclick : function() {\r
+                                       if (t.settings.onselect('') !== false)\r
+                                               t.select(''); // Must be runned after\r
+                               }\r
+                       });\r
+\r
+                       each(t.items, function(o) {\r
+                               // No value then treat it as a title\r
+                               if (o.value === undefined) {\r
+                                       m.add({\r
+                                               title : o.title,\r
+                                               'class' : 'mceMenuItemTitle',\r
+                                               onclick : function() {\r
+                                                       if (t.settings.onselect('') !== false)\r
+                                                               t.select(''); // Must be runned after\r
+                                               }\r
+                                       });\r
+                               } else {\r
+                                       o.id = DOM.uniqueId();\r
+                                       o.onclick = function() {\r
+                                               if (t.settings.onselect(o.value) !== false)\r
+                                                       t.select(o.value); // Must be runned after\r
+                                       };\r
+\r
+                                       m.add(o);\r
+                               }\r
+                       });\r
+\r
+                       t.onRenderMenu.dispatch(t, m);\r
+                       t.menu = m;\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, cp = t.classPrefix;\r
+\r
+                       Event.add(t.id, 'click', t.showMenu, t);\r
+                       Event.add(t.id, 'keydown', function(evt) {\r
+                               if (evt.keyCode == 32) { // Space\r
+                                       t.showMenu(evt);\r
+                                       Event.cancel(evt);\r
+                               }\r
+                       });\r
+                       Event.add(t.id, 'focus', function() {\r
+                               if (!t._focused) {\r
+                                       t.keyDownHandler = Event.add(t.id, 'keydown', function(e) {\r
+                                               if (e.keyCode == 40) {\r
+                                                       t.showMenu();\r
+                                                       Event.cancel(e);\r
+                                               }\r
+                                       });\r
+                                       t.keyPressHandler = Event.add(t.id, 'keypress', function(e) {\r
+                                               var v;\r
+                                               if (e.keyCode == 13) {\r
+                                                       // Fake select on enter\r
+                                                       v = t.selectedValue;\r
+                                                       t.selectedValue = null; // Needs to be null to fake change\r
+                                                       Event.cancel(e);\r
+                                                       t.settings.onselect(v);\r
+                                               }\r
+                                       });\r
+                               }\r
+\r
+                               t._focused = 1;\r
+                       });\r
+                       Event.add(t.id, 'blur', function() {\r
+                               Event.remove(t.id, 'keydown', t.keyDownHandler);\r
+                               Event.remove(t.id, 'keypress', t.keyPressHandler);\r
+                               t._focused = 0;\r
+                       });\r
+\r
+                       // Old IE doesn't have hover on all elements\r
+                       if (tinymce.isIE6 || !DOM.boxModel) {\r
+                               Event.add(t.id, 'mouseover', function() {\r
+                                       if (!DOM.hasClass(t.id, cp + 'Disabled'))\r
+                                               DOM.addClass(t.id, cp + 'Hover');\r
+                               });\r
+\r
+                               Event.add(t.id, 'mouseout', function() {\r
+                                       if (!DOM.hasClass(t.id, cp + 'Disabled'))\r
+                                               DOM.removeClass(t.id, cp + 'Hover');\r
+                               });\r
+                       }\r
+\r
+                       t.onPostRender.dispatch(t, DOM.get(t.id));\r
+               },\r
+\r
+               destroy : function() {\r
+                       this.parent();\r
+\r
+                       Event.clear(this.id + '_text');\r
+                       Event.clear(this.id + '_open');\r
+               }\r
+       });\r
+})(tinymce);\r
+(function(tinymce) {\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;\r
+\r
+       tinymce.create('tinymce.ui.NativeListBox:tinymce.ui.ListBox', {\r
+               NativeListBox : function(id, s) {\r
+                       this.parent(id, s);\r
+                       this.classPrefix = 'mceNativeListBox';\r
+               },\r
+\r
+               setDisabled : function(s) {\r
+                       DOM.get(this.id).disabled = s;\r
+                       this.setAriaProperty('disabled', s);\r
+               },\r
+\r
+               isDisabled : function() {\r
+                       return DOM.get(this.id).disabled;\r
+               },\r
+\r
+               select : function(va) {\r
+                       var t = this, fv, f;\r
+\r
+                       if (va == undefined)\r
+                               return t.selectByIndex(-1);\r
+\r
+                       // Is string or number make function selector\r
+                       if (va && va.call)\r
+                               f = va;\r
+                       else {\r
+                               f = function(v) {\r
+                                       return v == va;\r
+                               };\r
+                       }\r
+\r
+                       // Do we need to do something?\r
+                       if (va != t.selectedValue) {\r
+                               // Find item\r
+                               each(t.items, function(o, i) {\r
+                                       if (f(o.value)) {\r
+                                               fv = 1;\r
+                                               t.selectByIndex(i);\r
+                                               return false;\r
+                                       }\r
+                               });\r
+\r
+                               if (!fv)\r
+                                       t.selectByIndex(-1);\r
+                       }\r
+               },\r
+\r
+               selectByIndex : function(idx) {\r
+                       DOM.get(this.id).selectedIndex = idx + 1;\r
+                       this.selectedValue = this.items[idx] ? this.items[idx].value : null;\r
+               },\r
+\r
+               add : function(n, v, a) {\r
+                       var o, t = this;\r
+\r
+                       a = a || {};\r
+                       a.value = v;\r
+\r
+                       if (t.isRendered())\r
+                               DOM.add(DOM.get(this.id), 'option', a, n);\r
+\r
+                       o = {\r
+                               title : n,\r
+                               value : v,\r
+                               attribs : a\r
+                       };\r
+\r
+                       t.items.push(o);\r
+                       t.onAdd.dispatch(t, o);\r
+               },\r
+\r
+               getLength : function() {\r
+                       return this.items.length;\r
+               },\r
+\r
+               renderHTML : function() {\r
+                       var h, t = this;\r
+\r
+                       h = DOM.createHTML('option', {value : ''}, '-- ' + t.settings.title + ' --');\r
+\r
+                       each(t.items, function(it) {\r
+                               h += DOM.createHTML('option', {value : it.value}, it.title);\r
+                       });\r
+\r
+                       h = DOM.createHTML('select', {id : t.id, 'class' : 'mceNativeListBox', 'aria-labelledby': t.id + '_aria'}, h);\r
+                       h += DOM.createHTML('span', {id : t.id + '_aria', 'style': 'display: none'}, t.settings.title);\r
+                       return h;\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, ch, changeListenerAdded = true;\r
+\r
+                       t.rendered = true;\r
+\r
+                       function onChange(e) {\r
+                               var v = t.items[e.target.selectedIndex - 1];\r
+\r
+                               if (v && (v = v.value)) {\r
+                                       t.onChange.dispatch(t, v);\r
+\r
+                                       if (t.settings.onselect)\r
+                                               t.settings.onselect(v);\r
+                               }\r
+                       };\r
+\r
+                       Event.add(t.id, 'change', onChange);\r
+\r
+                       // Accessibility keyhandler\r
+                       Event.add(t.id, 'keydown', function(e) {\r
+                               var bf;\r
+\r
+                               Event.remove(t.id, 'change', ch);\r
+                               changeListenerAdded = false;\r
+\r
+                               bf = Event.add(t.id, 'blur', function() {\r
+                                       if (changeListenerAdded) return;\r
+                                       changeListenerAdded = true;\r
+                                       Event.add(t.id, 'change', onChange);\r
+                                       Event.remove(t.id, 'blur', bf);\r
+                               });\r
+\r
+                               //prevent default left and right keys on chrome - so that the keyboard navigation is used.\r
+                               if (tinymce.isWebKit && (e.keyCode==37 ||e.keyCode==39)) {\r
+                                       return Event.prevent(e);\r
+                               }\r
+                               \r
+                               if (e.keyCode == 13 || e.keyCode == 32) {\r
+                                       onChange(e);\r
+                                       return Event.cancel(e);\r
+                               }\r
+                       });\r
+\r
+                       t.onPostRender.dispatch(t, DOM.get(t.id));\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;\r
+\r
+       tinymce.create('tinymce.ui.MenuButton:tinymce.ui.Button', {\r
+               MenuButton : function(id, s, ed) {\r
+                       this.parent(id, s, ed);\r
+\r
+                       this.onRenderMenu = new tinymce.util.Dispatcher(this);\r
+\r
+                       s.menu_container = s.menu_container || DOM.doc.body;\r
+               },\r
+\r
+               showMenu : function() {\r
+                       var t = this, p1, p2, e = DOM.get(t.id), m;\r
+\r
+                       if (t.isDisabled())\r
+                               return;\r
+\r
+                       if (!t.isMenuRendered) {\r
+                               t.renderMenu();\r
+                               t.isMenuRendered = true;\r
+                       }\r
+\r
+                       if (t.isMenuVisible)\r
+                               return t.hideMenu();\r
+\r
+                       p1 = DOM.getPos(t.settings.menu_container);\r
+                       p2 = DOM.getPos(e);\r
+\r
+                       m = t.menu;\r
+                       m.settings.offset_x = p2.x;\r
+                       m.settings.offset_y = p2.y;\r
+                       m.settings.vp_offset_x = p2.x;\r
+                       m.settings.vp_offset_y = p2.y;\r
+                       m.settings.keyboard_focus = t._focused;\r
+                       m.showMenu(0, e.clientHeight);\r
+\r
+                       Event.add(DOM.doc, 'mousedown', t.hideMenu, t);\r
+                       t.setState('Selected', 1);\r
+\r
+                       t.isMenuVisible = 1;\r
+               },\r
+\r
+               renderMenu : function() {\r
+                       var t = this, m;\r
+\r
+                       m = t.settings.control_manager.createDropMenu(t.id + '_menu', {\r
+                               menu_line : 1,\r
+                               'class' : this.classPrefix + 'Menu',\r
+                               icons : t.settings.icons\r
+                       });\r
+\r
+                       m.onHideMenu.add(function() {\r
+                               t.hideMenu();\r
+                               t.focus();\r
+                       });\r
+\r
+                       t.onRenderMenu.dispatch(t, m);\r
+                       t.menu = m;\r
+               },\r
+\r
+               hideMenu : function(e) {\r
+                       var t = this;\r
+\r
+                       // Prevent double toogles by canceling the mouse click event to the button\r
+                       if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id || e.id === t.id + '_open';}))\r
+                               return;\r
+\r
+                       if (!e || !DOM.getParent(e.target, '.mceMenu')) {\r
+                               t.setState('Selected', 0);\r
+                               Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);\r
+                               if (t.menu)\r
+                                       t.menu.hideMenu();\r
+                       }\r
+\r
+                       t.isMenuVisible = 0;\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, s = t.settings;\r
+\r
+                       Event.add(t.id, 'click', function() {\r
+                               if (!t.isDisabled()) {\r
+                                       if (s.onclick)\r
+                                               s.onclick(t.value);\r
+\r
+                                       t.showMenu();\r
+                               }\r
+                       });\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;\r
+\r
+       tinymce.create('tinymce.ui.SplitButton:tinymce.ui.MenuButton', {\r
+               SplitButton : function(id, s, ed) {\r
+                       this.parent(id, s, ed);\r
+                       this.classPrefix = 'mceSplitButton';\r
+               },\r
+\r
+               renderHTML : function() {\r
+                       var h, t = this, s = t.settings, h1;\r
+\r
+                       h = '<tbody><tr>';\r
+\r
+                       if (s.image)\r
+                               h1 = DOM.createHTML('img ', {src : s.image, role: 'presentation', 'class' : 'mceAction ' + s['class']});\r
+                       else\r
+                               h1 = DOM.createHTML('span', {'class' : 'mceAction ' + s['class']}, '');\r
+\r
+                       h1 += DOM.createHTML('span', {'class': 'mceVoiceLabel mceIconOnly', id: t.id + '_voice', style: 'display:none;'}, s.title);\r
+                       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>';\r
+       \r
+                       h1 = DOM.createHTML('span', {'class' : 'mceOpen ' + s['class']}, '<span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span>');\r
+                       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>';\r
+\r
+                       h += '</tr></tbody>';\r
+                       h = DOM.createHTML('table', {id : t.id, role: 'presentation', tabindex: '0',  'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h);\r
+                       return DOM.createHTML('span', {role: 'button', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h);\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, s = t.settings, activate;\r
+\r
+                       if (s.onclick) {\r
+                               activate = function(evt) {\r
+                                       if (!t.isDisabled()) {\r
+                                               s.onclick(t.value);\r
+                                               Event.cancel(evt);\r
+                                       }\r
+                               };\r
+                               Event.add(t.id + '_action', 'click', activate);\r
+                               Event.add(t.id, ['click', 'keydown'], function(evt) {\r
+                                       var DOM_VK_SPACE = 32, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_UP = 38, DOM_VK_DOWN = 40;\r
+                                       if ((evt.keyCode === 32 || evt.keyCode === 13 || evt.keyCode === 14) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) {\r
+                                               activate();\r
+                                               Event.cancel(evt);\r
+                                       } else if (evt.type === 'click' || evt.keyCode === DOM_VK_DOWN) {\r
+                                               t.showMenu();\r
+                                               Event.cancel(evt);\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       Event.add(t.id + '_open', 'click', function (evt) {\r
+                               t.showMenu();\r
+                               Event.cancel(evt);\r
+                       });\r
+                       Event.add([t.id, t.id + '_open'], 'focus', function() {t._focused = 1;});\r
+                       Event.add([t.id, t.id + '_open'], 'blur', function() {t._focused = 0;});\r
+\r
+                       // Old IE doesn't have hover on all elements\r
+                       if (tinymce.isIE6 || !DOM.boxModel) {\r
+                               Event.add(t.id, 'mouseover', function() {\r
+                                       if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled'))\r
+                                               DOM.addClass(t.id, 'mceSplitButtonHover');\r
+                               });\r
+\r
+                               Event.add(t.id, 'mouseout', function() {\r
+                                       if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled'))\r
+                                               DOM.removeClass(t.id, 'mceSplitButtonHover');\r
+                               });\r
+                       }\r
+               },\r
+\r
+               destroy : function() {\r
+                       this.parent();\r
+\r
+                       Event.clear(this.id + '_action');\r
+                       Event.clear(this.id + '_open');\r
+                       Event.clear(this.id);\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, is = tinymce.is, each = tinymce.each;\r
+\r
+       tinymce.create('tinymce.ui.ColorSplitButton:tinymce.ui.SplitButton', {\r
+               ColorSplitButton : function(id, s, ed) {\r
+                       var t = this;\r
+\r
+                       t.parent(id, s, ed);\r
+\r
+                       t.settings = s = tinymce.extend({\r
+                               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',\r
+                               grid_width : 8,\r
+                               default_color : '#888888'\r
+                       }, t.settings);\r
+\r
+                       t.onShowMenu = new tinymce.util.Dispatcher(t);\r
+\r
+                       t.onHideMenu = new tinymce.util.Dispatcher(t);\r
+\r
+                       t.value = s.default_color;\r
+               },\r
+\r
+               showMenu : function() {\r
+                       var t = this, r, p, e, p2;\r
+\r
+                       if (t.isDisabled())\r
+                               return;\r
+\r
+                       if (!t.isMenuRendered) {\r
+                               t.renderMenu();\r
+                               t.isMenuRendered = true;\r
+                       }\r
+\r
+                       if (t.isMenuVisible)\r
+                               return t.hideMenu();\r
+\r
+                       e = DOM.get(t.id);\r
+                       DOM.show(t.id + '_menu');\r
+                       DOM.addClass(e, 'mceSplitButtonSelected');\r
+                       p2 = DOM.getPos(e);\r
+                       DOM.setStyles(t.id + '_menu', {\r
+                               left : p2.x,\r
+                               top : p2.y + e.clientHeight,\r
+                               zIndex : 200000\r
+                       });\r
+                       e = 0;\r
+\r
+                       Event.add(DOM.doc, 'mousedown', t.hideMenu, t);\r
+                       t.onShowMenu.dispatch(t);\r
+\r
+                       if (t._focused) {\r
+                               t._keyHandler = Event.add(t.id + '_menu', 'keydown', function(e) {\r
+                                       if (e.keyCode == 27)\r
+                                               t.hideMenu();\r
+                               });\r
+\r
+                               DOM.select('a', t.id + '_menu')[0].focus(); // Select first link\r
+                       }\r
+\r
+                       t.isMenuVisible = 1;\r
+               },\r
+\r
+               hideMenu : function(e) {\r
+                       var t = this;\r
+\r
+                       if (t.isMenuVisible) {\r
+                               // Prevent double toogles by canceling the mouse click event to the button\r
+                               if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';}))\r
+                                       return;\r
+\r
+                               if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) {\r
+                                       DOM.removeClass(t.id, 'mceSplitButtonSelected');\r
+                                       Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);\r
+                                       Event.remove(t.id + '_menu', 'keydown', t._keyHandler);\r
+                                       DOM.hide(t.id + '_menu');\r
+                               }\r
+\r
+                               t.isMenuVisible = 0;\r
+                               t.onHideMenu.dispatch();\r
+                       }\r
+               },\r
+\r
+               renderMenu : function() {\r
+                       var t = this, m, i = 0, s = t.settings, n, tb, tr, w, context;\r
+\r
+                       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;'});\r
+                       m = DOM.add(w, 'div', {'class' : s['class'] + ' mceSplitButtonMenu'});\r
+                       DOM.add(m, 'span', {'class' : 'mceMenuLine'});\r
+\r
+                       n = DOM.add(m, 'table', {role: 'presentation', 'class' : 'mceColorSplitMenu'});\r
+                       tb = DOM.add(n, 'tbody');\r
+\r
+                       // Generate color grid\r
+                       i = 0;\r
+                       each(is(s.colors, 'array') ? s.colors : s.colors.split(','), function(c) {\r
+                               c = c.replace(/^#/, '');\r
+\r
+                               if (!i--) {\r
+                                       tr = DOM.add(tb, 'tr');\r
+                                       i = s.grid_width - 1;\r
+                               }\r
+\r
+                               n = DOM.add(tr, 'td');\r
+                               n = DOM.add(n, 'a', {\r
+                                       role : 'option',\r
+                                       href : 'javascript:;',\r
+                                       style : {\r
+                                               backgroundColor : '#' + c\r
+                                       },\r
+                                       'title': t.editor.getLang('colors.' + c, c),\r
+                                       'data-mce-color' : '#' + c\r
+                               });\r
+\r
+                               if (t.editor.forcedHighContrastMode) {\r
+                                       n = DOM.add(n, 'canvas', { width: 16, height: 16, 'aria-hidden': 'true' });\r
+                                       if (n.getContext && (context = n.getContext("2d"))) {\r
+                                               context.fillStyle = '#' + c;\r
+                                               context.fillRect(0, 0, 16, 16);\r
+                                       } else {\r
+                                               // No point leaving a canvas element around if it's not supported for drawing on anyway.\r
+                                               DOM.remove(n);\r
+                                       }\r
+                               }\r
+                       });\r
+\r
+                       if (s.more_colors_func) {\r
+                               n = DOM.add(tb, 'tr');\r
+                               n = DOM.add(n, 'td', {colspan : s.grid_width, 'class' : 'mceMoreColors'});\r
+                               n = DOM.add(n, 'a', {role: 'option', id : t.id + '_more', href : 'javascript:;', onclick : 'return false;', 'class' : 'mceMoreColors'}, s.more_colors_title);\r
+\r
+                               Event.add(n, 'click', function(e) {\r
+                                       s.more_colors_func.call(s.more_colors_scope || this);\r
+                                       return Event.cancel(e); // Cancel to fix onbeforeunload problem\r
+                               });\r
+                       }\r
+\r
+                       DOM.addClass(m, 'mceColorSplitMenu');\r
+                       \r
+                       new tinymce.ui.KeyboardNavigation({\r
+                               root: t.id + '_menu',\r
+                               items: DOM.select('a', t.id + '_menu'),\r
+                               onCancel: function() {\r
+                                       t.hideMenu();\r
+                                       t.focus();\r
+                               }\r
+                       });\r
+\r
+                       // Prevent IE from scrolling and hindering click to occur #4019\r
+                       Event.add(t.id + '_menu', 'mousedown', function(e) {return Event.cancel(e);});\r
+\r
+                       Event.add(t.id + '_menu', 'click', function(e) {\r
+                               var c;\r
+\r
+                               e = DOM.getParent(e.target, 'a', tb);\r
+\r
+                               if (e && e.nodeName.toLowerCase() == 'a' && (c = e.getAttribute('data-mce-color')))\r
+                                       t.setColor(c);\r
+\r
+                               return Event.cancel(e); // Prevent IE auto save warning\r
+                       });\r
+\r
+                       return w;\r
+               },\r
+\r
+               setColor : function(c) {\r
+                       this.displayColor(c);\r
+                       this.hideMenu();\r
+                       this.settings.onselect(c);\r
+               },\r
+               \r
+               displayColor : function(c) {\r
+                       var t = this;\r
+\r
+                       DOM.setStyle(t.id + '_preview', 'backgroundColor', c);\r
+\r
+                       t.value = c;\r
+               },\r
+\r
+               postRender : function() {\r
+                       var t = this, id = t.id;\r
+\r
+                       t.parent();\r
+                       DOM.add(id + '_action', 'div', {id : id + '_preview', 'class' : 'mceColorPreview'});\r
+                       DOM.setStyle(t.id + '_preview', 'backgroundColor', t.value);\r
+               },\r
+\r
+               destroy : function() {\r
+                       this.parent();\r
+\r
+                       Event.clear(this.id + '_menu');\r
+                       Event.clear(this.id + '_more');\r
+                       DOM.remove(this.id + '_menu');\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+// Shorten class names\r
+var dom = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event;\r
+tinymce.create('tinymce.ui.ToolbarGroup:tinymce.ui.Container', {\r
+       renderHTML : function() {\r
+               var t = this, h = [], controls = t.controls, each = tinymce.each, settings = t.settings;\r
+\r
+               h.push('<div id="' + t.id + '" role="group" aria-labelledby="' + t.id + '_voice">');\r
+               //TODO: ACC test this out - adding a role = application for getting the landmarks working well.\r
+               h.push("<span role='application'>");\r
+               h.push('<span id="' + t.id + '_voice" class="mceVoiceLabel" style="display:none;">' + dom.encode(settings.name) + '</span>');\r
+               each(controls, function(toolbar) {\r
+                       h.push(toolbar.renderHTML());\r
+               });\r
+               h.push("</span>");\r
+               h.push('</div>');\r
+\r
+               return h.join('');\r
+       },\r
+       \r
+       focus : function() {\r
+               this.keyNav.focus();\r
+       },\r
+       \r
+       postRender : function() {\r
+               var t = this, items = [];\r
+\r
+               each(t.controls, function(toolbar) {\r
+                       each (toolbar.controls, function(control) {\r
+                               if (control.id) {\r
+                                       items.push(control);\r
+                               }\r
+                       });\r
+               });\r
+\r
+               t.keyNav = new tinymce.ui.KeyboardNavigation({\r
+                       root: t.id,\r
+                       items: items,\r
+                       onCancel: function() {\r
+                               t.editor.focus();\r
+                       },\r
+                       excludeFromTabOrder: !t.settings.tab_focus_toolbar\r
+               });\r
+       },\r
+       \r
+       destroy : function() {\r
+               var self = this;\r
+\r
+               self.parent();\r
+               self.keyNav.destroy();\r
+               Event.clear(self.id);\r
+       }\r
+});\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+// Shorten class names\r
+var dom = tinymce.DOM, each = tinymce.each;\r
+tinymce.create('tinymce.ui.Toolbar:tinymce.ui.Container', {\r
+       renderHTML : function() {\r
+               var t = this, h = '', c, co, s = t.settings, i, pr, nx, cl;\r
+\r
+               cl = t.controls;\r
+               for (i=0; i<cl.length; i++) {\r
+                       // Get current control, prev control, next control and if the control is a list box or not\r
+                       co = cl[i];\r
+                       pr = cl[i - 1];\r
+                       nx = cl[i + 1];\r
+\r
+                       // Add toolbar start\r
+                       if (i === 0) {\r
+                               c = 'mceToolbarStart';\r
+\r
+                               if (co.Button)\r
+                                       c += ' mceToolbarStartButton';\r
+                               else if (co.SplitButton)\r
+                                       c += ' mceToolbarStartSplitButton';\r
+                               else if (co.ListBox)\r
+                                       c += ' mceToolbarStartListBox';\r
+\r
+                               h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->'));\r
+                       }\r
+\r
+                       // Add toolbar end before list box and after the previous button\r
+                       // This is to fix the o2k7 editor skins\r
+                       if (pr && co.ListBox) {\r
+                               if (pr.Button || pr.SplitButton)\r
+                                       h += dom.createHTML('td', {'class' : 'mceToolbarEnd'}, dom.createHTML('span', null, '<!-- IE -->'));\r
+                       }\r
+\r
+                       // Render control HTML\r
+\r
+                       // IE 8 quick fix, needed to propertly generate a hit area for anchors\r
+                       if (dom.stdMode)\r
+                               h += '<td style="position: relative">' + co.renderHTML() + '</td>';\r
+                       else\r
+                               h += '<td>' + co.renderHTML() + '</td>';\r
+\r
+                       // Add toolbar start after list box and before the next button\r
+                       // This is to fix the o2k7 editor skins\r
+                       if (nx && co.ListBox) {\r
+                               if (nx.Button || nx.SplitButton)\r
+                                       h += dom.createHTML('td', {'class' : 'mceToolbarStart'}, dom.createHTML('span', null, '<!-- IE -->'));\r
+                       }\r
+               }\r
+\r
+               c = 'mceToolbarEnd';\r
+\r
+               if (co.Button)\r
+                       c += ' mceToolbarEndButton';\r
+               else if (co.SplitButton)\r
+                       c += ' mceToolbarEndSplitButton';\r
+               else if (co.ListBox)\r
+                       c += ' mceToolbarEndListBox';\r
+\r
+               h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->'));\r
+\r
+               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>');\r
+       }\r
+});\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each;\r
+\r
+       tinymce.create('tinymce.AddOnManager', {\r
+               AddOnManager : function() {\r
+                       var self = this;\r
+\r
+                       self.items = [];\r
+                       self.urls = {};\r
+                       self.lookup = {};\r
+                       self.onAdd = new Dispatcher(self);\r
+               },\r
+\r
+               get : function(n) {\r
+                       if (this.lookup[n]) {\r
+                               return this.lookup[n].instance;\r
+                       } else {\r
+                               return undefined;\r
+                       }\r
+               },\r
+\r
+               dependencies : function(n) {\r
+                       var result;\r
+                       if (this.lookup[n]) {\r
+                               result = this.lookup[n].dependencies;\r
+                       }\r
+                       return result || [];\r
+               },\r
+\r
+               requireLangPack : function(n) {\r
+                       var s = tinymce.settings;\r
+\r
+                       if (s && s.language && s.language_load !== false)\r
+                               tinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js');\r
+               },\r
+\r
+               add : function(id, o, dependencies) {\r
+                       this.items.push(o);\r
+                       this.lookup[id] = {instance:o, dependencies:dependencies};\r
+                       this.onAdd.dispatch(this, id, o);\r
+\r
+                       return o;\r
+               },\r
+               createUrl: function(baseUrl, dep) {\r
+                       if (typeof dep === "object") {\r
+                               return dep\r
+                       } else {\r
+                               return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix};\r
+                       }\r
+               },\r
+\r
+               addComponents: function(pluginName, scripts) {\r
+                       var pluginUrl = this.urls[pluginName];\r
+                       tinymce.each(scripts, function(script){\r
+                               tinymce.ScriptLoader.add(pluginUrl+"/"+script); \r
+                       });\r
+               },\r
+\r
+               load : function(n, u, cb, s) {\r
+                       var t = this, url = u;\r
+\r
+                       function loadDependencies() {\r
+                               var dependencies = t.dependencies(n);\r
+                               tinymce.each(dependencies, function(dep) {\r
+                                       var newUrl = t.createUrl(u, dep);\r
+                                       t.load(newUrl.resource, newUrl, undefined, undefined);\r
+                               });\r
+                               if (cb) {\r
+                                       if (s) {\r
+                                               cb.call(s);\r
+                                       } else {\r
+                                               cb.call(tinymce.ScriptLoader);\r
+                                       }\r
+                               }\r
+                       }\r
+\r
+                       if (t.urls[n])\r
+                               return;\r
+                       if (typeof u === "object")\r
+                               url = u.prefix + u.resource + u.suffix;\r
+\r
+                       if (url.indexOf('/') != 0 && url.indexOf('://') == -1)\r
+                               url = tinymce.baseURL + '/' + url;\r
+\r
+                       t.urls[n] = url.substring(0, url.lastIndexOf('/'));\r
+\r
+                       if (t.lookup[n]) {\r
+                               loadDependencies();\r
+                       } else {\r
+                               tinymce.ScriptLoader.add(url, loadDependencies, s);\r
+                       }\r
+               }\r
+       });\r
+\r
+       // Create plugin and theme managers\r
+       tinymce.PluginManager = new tinymce.AddOnManager();\r
+       tinymce.ThemeManager = new tinymce.AddOnManager();\r
+}(tinymce));\r
+\r
+(function(tinymce) {\r
+       // Shorten names\r
+       var each = tinymce.each, extend = tinymce.extend,\r
+               DOM = tinymce.DOM, Event = tinymce.dom.Event,\r
+               ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,\r
+               explode = tinymce.explode,\r
+               Dispatcher = tinymce.util.Dispatcher, undefined, instanceCounter = 0;\r
+\r
+       // Setup some URLs where the editor API is located and where the document is\r
+       tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');\r
+       if (!/[\/\\]$/.test(tinymce.documentBaseURL))\r
+               tinymce.documentBaseURL += '/';\r
+\r
+       tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL);\r
+\r
+       tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL);\r
+\r
+       // Add before unload listener\r
+       // This was required since IE was leaking memory if you added and removed beforeunload listeners\r
+       // with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event\r
+       tinymce.onBeforeUnload = new Dispatcher(tinymce);\r
+\r
+       // Must be on window or IE will leak if the editor is placed in frame or iframe\r
+       Event.add(window, 'beforeunload', function(e) {\r
+               tinymce.onBeforeUnload.dispatch(tinymce, e);\r
+       });\r
+\r
+       tinymce.onAddEditor = new Dispatcher(tinymce);\r
+\r
+       tinymce.onRemoveEditor = new Dispatcher(tinymce);\r
+\r
+       tinymce.EditorManager = extend(tinymce, {\r
+               editors : [],\r
+\r
+               i18n : {},\r
+\r
+               activeEditor : null,\r
+\r
+               init : function(s) {\r
+                       var t = this, pl, sl = tinymce.ScriptLoader, e, el = [], ed;\r
+\r
+                       function execCallback(se, n, s) {\r
+                               var f = se[n];\r
+\r
+                               if (!f)\r
+                                       return;\r
+\r
+                               if (tinymce.is(f, 'string')) {\r
+                                       s = f.replace(/\.\w+$/, '');\r
+                                       s = s ? tinymce.resolve(s) : 0;\r
+                                       f = tinymce.resolve(f);\r
+                               }\r
+\r
+                               return f.apply(s || this, Array.prototype.slice.call(arguments, 2));\r
+                       };\r
+\r
+                       s = extend({\r
+                               theme : "simple",\r
+                               language : "en"\r
+                       }, s);\r
+\r
+                       t.settings = s;\r
+\r
+                       // Legacy call\r
+                       Event.add(document, 'init', function() {\r
+                               var l, co;\r
+\r
+                               execCallback(s, 'onpageload');\r
+\r
+                               switch (s.mode) {\r
+                                       case "exact":\r
+                                               l = s.elements || '';\r
+\r
+                                               if(l.length > 0) {\r
+                                                       each(explode(l), function(v) {\r
+                                                               if (DOM.get(v)) {\r
+                                                                       ed = new tinymce.Editor(v, s);\r
+                                                                       el.push(ed);\r
+                                                                       ed.render(1);\r
+                                                               } else {\r
+                                                                       each(document.forms, function(f) {\r
+                                                                               each(f.elements, function(e) {\r
+                                                                                       if (e.name === v) {\r
+                                                                                               v = 'mce_editor_' + instanceCounter++;\r
+                                                                                               DOM.setAttrib(e, 'id', v);\r
+\r
+                                                                                               ed = new tinymce.Editor(v, s);\r
+                                                                                               el.push(ed);\r
+                                                                                               ed.render(1);\r
+                                                                                       }\r
+                                                                               });\r
+                                                                       });\r
+                                                               }\r
+                                                       });\r
+                                               }\r
+                                               break;\r
+\r
+                                       case "textareas":\r
+                                       case "specific_textareas":\r
+                                               function hasClass(n, c) {\r
+                                                       return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);\r
+                                               };\r
+\r
+                                               each(DOM.select('textarea'), function(v) {\r
+                                                       if (s.editor_deselector && hasClass(v, s.editor_deselector))\r
+                                                               return;\r
+\r
+                                                       if (!s.editor_selector || hasClass(v, s.editor_selector)) {\r
+                                                               // Can we use the name\r
+                                                               e = DOM.get(v.name);\r
+                                                               if (!v.id && !e)\r
+                                                                       v.id = v.name;\r
+\r
+                                                               // Generate unique name if missing or already exists\r
+                                                               if (!v.id || t.get(v.id))\r
+                                                                       v.id = DOM.uniqueId();\r
+\r
+                                                               ed = new tinymce.Editor(v.id, s);\r
+                                                               el.push(ed);\r
+                                                               ed.render(1);\r
+                                                       }\r
+                                               });\r
+                                               break;\r
+                               }\r
+\r
+                               // Call onInit when all editors are initialized\r
+                               if (s.oninit) {\r
+                                       l = co = 0;\r
+\r
+                                       each(el, function(ed) {\r
+                                               co++;\r
+\r
+                                               if (!ed.initialized) {\r
+                                                       // Wait for it\r
+                                                       ed.onInit.add(function() {\r
+                                                               l++;\r
+\r
+                                                               // All done\r
+                                                               if (l == co)\r
+                                                                       execCallback(s, 'oninit');\r
+                                                       });\r
+                                               } else\r
+                                                       l++;\r
+\r
+                                               // All done\r
+                                               if (l == co)\r
+                                                       execCallback(s, 'oninit');                                      \r
+                                       });\r
+                               }\r
+                       });\r
+               },\r
+\r
+               get : function(id) {\r
+                       if (id === undefined)\r
+                               return this.editors;\r
+\r
+                       return this.editors[id];\r
+               },\r
+\r
+               getInstanceById : function(id) {\r
+                       return this.get(id);\r
+               },\r
+\r
+               add : function(editor) {\r
+                       var self = this, editors = self.editors;\r
+\r
+                       // Add named and index editor instance\r
+                       editors[editor.id] = editor;\r
+                       editors.push(editor);\r
+\r
+                       self._setActive(editor);\r
+                       self.onAddEditor.dispatch(self, editor);\r
+\r
+\r
+                       return editor;\r
+               },\r
+\r
+               remove : function(editor) {\r
+                       var t = this, i, editors = t.editors;\r
+\r
+                       // Not in the collection\r
+                       if (!editors[editor.id])\r
+                               return null;\r
+\r
+                       delete editors[editor.id];\r
+\r
+                       for (i = 0; i < editors.length; i++) {\r
+                               if (editors[i] == editor) {\r
+                                       editors.splice(i, 1);\r
+                                       break;\r
+                               }\r
+                       }\r
+\r
+                       // Select another editor since the active one was removed\r
+                       if (t.activeEditor == editor)\r
+                               t._setActive(editors[0]);\r
+\r
+                       editor.destroy();\r
+                       t.onRemoveEditor.dispatch(t, editor);\r
+\r
+                       return editor;\r
+               },\r
+\r
+               execCommand : function(c, u, v) {\r
+                       var t = this, ed = t.get(v), w;\r
+\r
+                       // Manager commands\r
+                       switch (c) {\r
+                               case "mceFocus":\r
+                                       ed.focus();\r
+                                       return true;\r
+\r
+                               case "mceAddEditor":\r
+                               case "mceAddControl":\r
+                                       if (!t.get(v))\r
+                                               new tinymce.Editor(v, t.settings).render();\r
+\r
+                                       return true;\r
+\r
+                               case "mceAddFrameControl":\r
+                                       w = v.window;\r
+\r
+                                       // Add tinyMCE global instance and tinymce namespace to specified window\r
+                                       w.tinyMCE = tinyMCE;\r
+                                       w.tinymce = tinymce;\r
+\r
+                                       tinymce.DOM.doc = w.document;\r
+                                       tinymce.DOM.win = w;\r
+\r
+                                       ed = new tinymce.Editor(v.element_id, v);\r
+                                       ed.render();\r
+\r
+                                       // Fix IE memory leaks\r
+                                       if (tinymce.isIE) {\r
+                                               function clr() {\r
+                                                       ed.destroy();\r
+                                                       w.detachEvent('onunload', clr);\r
+                                                       w = w.tinyMCE = w.tinymce = null; // IE leak\r
+                                               };\r
+\r
+                                               w.attachEvent('onunload', clr);\r
+                                       }\r
+\r
+                                       v.page_window = null;\r
+\r
+                                       return true;\r
+\r
+                               case "mceRemoveEditor":\r
+                               case "mceRemoveControl":\r
+                                       if (ed)\r
+                                               ed.remove();\r
+\r
+                                       return true;\r
+\r
+                               case 'mceToggleEditor':\r
+                                       if (!ed) {\r
+                                               t.execCommand('mceAddControl', 0, v);\r
+                                               return true;\r
+                                       }\r
+\r
+                                       if (ed.isHidden())\r
+                                               ed.show();\r
+                                       else\r
+                                               ed.hide();\r
+\r
+                                       return true;\r
+                       }\r
+\r
+                       // Run command on active editor\r
+                       if (t.activeEditor)\r
+                               return t.activeEditor.execCommand(c, u, v);\r
+\r
+                       return false;\r
+               },\r
+\r
+               execInstanceCommand : function(id, c, u, v) {\r
+                       var ed = this.get(id);\r
+\r
+                       if (ed)\r
+                               return ed.execCommand(c, u, v);\r
+\r
+                       return false;\r
+               },\r
+\r
+               triggerSave : function() {\r
+                       each(this.editors, function(e) {\r
+                               e.save();\r
+                       });\r
+               },\r
+\r
+               addI18n : function(p, o) {\r
+                       var lo, i18n = this.i18n;\r
+\r
+                       if (!tinymce.is(p, 'string')) {\r
+                               each(p, function(o, lc) {\r
+                                       each(o, function(o, g) {\r
+                                               each(o, function(o, k) {\r
+                                                       if (g === 'common')\r
+                                                               i18n[lc + '.' + k] = o;\r
+                                                       else\r
+                                                               i18n[lc + '.' + g + '.' + k] = o;\r
+                                               });\r
+                                       });\r
+                               });\r
+                       } else {\r
+                               each(o, function(o, k) {\r
+                                       i18n[p + '.' + k] = o;\r
+                               });\r
+                       }\r
+               },\r
+\r
+               // Private methods\r
+\r
+               _setActive : function(editor) {\r
+                       this.selectedInstance = this.activeEditor = editor;\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       // Shorten these names\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend,\r
+               Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isGecko = tinymce.isGecko,\r
+               isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, is = tinymce.is,\r
+               ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,\r
+               inArray = tinymce.inArray, grep = tinymce.grep, explode = tinymce.explode;\r
+\r
+       tinymce.create('tinymce.Editor', {\r
+               Editor : function(id, s) {\r
+                       var t = this;\r
+\r
+                       t.id = t.editorId = id;\r
+\r
+                       t.execCommands = {};\r
+                       t.queryStateCommands = {};\r
+                       t.queryValueCommands = {};\r
+\r
+                       t.isNotDirty = false;\r
+\r
+                       t.plugins = {};\r
+\r
+                       // Add events to the editor\r
+                       each([\r
+                               'onPreInit',\r
+\r
+                               'onBeforeRenderUI',\r
+\r
+                               'onPostRender',\r
+\r
+                               'onInit',\r
+\r
+                               'onRemove',\r
+\r
+                               'onActivate',\r
+\r
+                               'onDeactivate',\r
+\r
+                               'onClick',\r
+\r
+                               'onEvent',\r
+\r
+                               'onMouseUp',\r
+\r
+                               'onMouseDown',\r
+\r
+                               'onDblClick',\r
+\r
+                               'onKeyDown',\r
+\r
+                               'onKeyUp',\r
+\r
+                               'onKeyPress',\r
+\r
+                               'onContextMenu',\r
+\r
+                               'onSubmit',\r
+\r
+                               'onReset',\r
+\r
+                               'onPaste',\r
+\r
+                               'onPreProcess',\r
+\r
+                               'onPostProcess',\r
+\r
+                               'onBeforeSetContent',\r
+\r
+                               'onBeforeGetContent',\r
+\r
+                               'onSetContent',\r
+\r
+                               'onGetContent',\r
+\r
+                               'onLoadContent',\r
+\r
+                               'onSaveContent',\r
+\r
+                               'onNodeChange',\r
+\r
+                               'onChange',\r
+\r
+                               'onBeforeExecCommand',\r
+\r
+                               'onExecCommand',\r
+\r
+                               'onUndo',\r
+\r
+                               'onRedo',\r
+\r
+                               'onVisualAid',\r
+\r
+                               'onSetProgressState'\r
+                       ], function(e) {\r
+                               t[e] = new Dispatcher(t);\r
+                       });\r
+\r
+                       t.settings = s = extend({\r
+                               id : id,\r
+                               language : 'en',\r
+                               docs_language : 'en',\r
+                               theme : 'simple',\r
+                               skin : 'default',\r
+                               delta_width : 0,\r
+                               delta_height : 0,\r
+                               popup_css : '',\r
+                               plugins : '',\r
+                               document_base_url : tinymce.documentBaseURL,\r
+                               add_form_submit_trigger : 1,\r
+                               submit_patch : 1,\r
+                               add_unload_trigger : 1,\r
+                               convert_urls : 1,\r
+                               relative_urls : 1,\r
+                               remove_script_host : 1,\r
+                               table_inline_editing : 0,\r
+                               object_resizing : 1,\r
+                               cleanup : 1,\r
+                               accessibility_focus : 1,\r
+                               custom_shortcuts : 1,\r
+                               custom_undo_redo_keyboard_shortcuts : 1,\r
+                               custom_undo_redo_restore_selection : 1,\r
+                               custom_undo_redo : 1,\r
+                               doctype : tinymce.isIE6 ? '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' : '<!DOCTYPE>', // Use old doctype on IE 6 to avoid horizontal scroll\r
+                               visual_table_class : 'mceItemTable',\r
+                               visual : 1,\r
+                               font_size_style_values : 'xx-small,x-small,small,medium,large,x-large,xx-large',\r
+                               apply_source_formatting : 1,\r
+                               directionality : 'ltr',\r
+                               forced_root_block : 'p',\r
+                               hidden_input : 1,\r
+                               padd_empty_editor : 1,\r
+                               render_ui : 1,\r
+                               init_theme : 1,\r
+                               force_p_newlines : 1,\r
+                               indentation : '30px',\r
+                               keep_styles : 1,\r
+                               fix_table_elements : 1,\r
+                               inline_styles : 1,\r
+                               convert_fonts_to_spans : true,\r
+                               indent : 'simple',\r
+                               indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',\r
+                               indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',\r
+                               validate : true,\r
+                               entity_encoding : 'named',\r
+                               url_converter : t.convertURL,\r
+                               url_converter_scope : t,\r
+                               ie7_compat : true\r
+                       }, s);\r
+\r
+                       t.documentBaseURI = new tinymce.util.URI(s.document_base_url || tinymce.documentBaseURL, {\r
+                               base_uri : tinyMCE.baseURI\r
+                       });\r
+\r
+                       t.baseURI = tinymce.baseURI;\r
+\r
+                       t.contentCSS = [];\r
+\r
+                       // Call setup\r
+                       t.execCallback('setup', t);\r
+               },\r
+\r
+               render : function(nst) {\r
+                       var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader;\r
+\r
+                       // Page is not loaded yet, wait for it\r
+                       if (!Event.domLoaded) {\r
+                               Event.add(document, 'init', function() {\r
+                                       t.render();\r
+                               });\r
+                               return;\r
+                       }\r
+\r
+                       tinyMCE.settings = s;\r
+\r
+                       // Element not found, then skip initialization\r
+                       if (!t.getElement())\r
+                               return;\r
+\r
+                       // Is a iPad/iPhone and not on iOS5, then skip initialization. We need to sniff \r
+                       // here since the browser says it has contentEditable support but there is no visible\r
+                       // caret We will remove this check ones Apple implements full contentEditable support\r
+                       if (tinymce.isIDevice && !tinymce.isIOS5)\r
+                               return;\r
+\r
+                       // Add hidden input for non input elements inside form elements\r
+                       if (!/TEXTAREA|INPUT/i.test(t.getElement().nodeName) && s.hidden_input && DOM.getParent(id, 'form'))\r
+                               DOM.insertAfter(DOM.create('input', {type : 'hidden', name : id}), id);\r
+\r
+                       if (tinymce.WindowManager)\r
+                               t.windowManager = new tinymce.WindowManager(t);\r
+\r
+                       if (s.encoding == 'xml') {\r
+                               t.onGetContent.add(function(ed, o) {\r
+                                       if (o.save)\r
+                                               o.content = DOM.encode(o.content);\r
+                               });\r
+                       }\r
+\r
+                       if (s.add_form_submit_trigger) {\r
+                               t.onSubmit.addToTop(function() {\r
+                                       if (t.initialized) {\r
+                                               t.save();\r
+                                               t.isNotDirty = 1;\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       if (s.add_unload_trigger) {\r
+                               t._beforeUnload = tinyMCE.onBeforeUnload.add(function() {\r
+                                       if (t.initialized && !t.destroyed && !t.isHidden())\r
+                                               t.save({format : 'raw', no_events : true});\r
+                               });\r
+                       }\r
+\r
+                       tinymce.addUnload(t.destroy, t);\r
+\r
+                       if (s.submit_patch) {\r
+                               t.onBeforeRenderUI.add(function() {\r
+                                       var n = t.getElement().form;\r
+\r
+                                       if (!n)\r
+                                               return;\r
+\r
+                                       // Already patched\r
+                                       if (n._mceOldSubmit)\r
+                                               return;\r
+\r
+                                       // Check page uses id="submit" or name="submit" for it's submit button\r
+                                       if (!n.submit.nodeType && !n.submit.length) {\r
+                                               t.formElement = n;\r
+                                               n._mceOldSubmit = n.submit;\r
+                                               n.submit = function() {\r
+                                                       // Save all instances\r
+                                                       tinymce.triggerSave();\r
+                                                       t.isNotDirty = 1;\r
+\r
+                                                       return t.formElement._mceOldSubmit(t.formElement);\r
+                                               };\r
+                                       }\r
+\r
+                                       n = null;\r
+                               });\r
+                       }\r
+\r
+                       // Load scripts\r
+                       function loadScripts() {\r
+                               if (s.language && s.language_load !== false)\r
+                                       sl.add(tinymce.baseURL + '/langs/' + s.language + '.js');\r
+\r
+                               if (s.theme && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme])\r
+                                       ThemeManager.load(s.theme, 'themes/' + s.theme + '/editor_template' + tinymce.suffix + '.js');\r
+\r
+                               each(explode(s.plugins), function(p) {\r
+                                       if (p &&!PluginManager.urls[p]) {\r
+                                               if (p.charAt(0) == '-') {\r
+                                                       p = p.substr(1, p.length);\r
+                                                       var dependencies = PluginManager.dependencies(p);\r
+                                                       each(dependencies, function(dep) {\r
+                                                               var defaultSettings = {prefix:'plugins/', resource: dep, suffix:'/editor_plugin' + tinymce.suffix + '.js'};\r
+                                                               var dep = PluginManager.createUrl(defaultSettings, dep);\r
+                                                               PluginManager.load(dep.resource, dep);\r
+                                                               \r
+                                                       });\r
+                                               } else {\r
+                                                       // Skip safari plugin, since it is removed as of 3.3b1\r
+                                                       if (p == 'safari') {\r
+                                                               return;\r
+                                                       }\r
+                                                       PluginManager.load(p, {prefix:'plugins/', resource: p, suffix:'/editor_plugin' + tinymce.suffix + '.js'});\r
+                                               }\r
+                                       }\r
+                               });\r
+\r
+                               // Init when que is loaded\r
+                               sl.loadQueue(function() {\r
+                                       if (!t.removed)\r
+                                               t.init();\r
+                               });\r
+                       };\r
+\r
+                       loadScripts();\r
+               },\r
+\r
+               init : function() {\r
+                       var n, t = this, s = t.settings, w, h, e = t.getElement(), o, ti, u, bi, bc, re, i, initializedPlugins = [];\r
+\r
+                       tinymce.add(t);\r
+\r
+                       s.aria_label = s.aria_label || DOM.getAttrib(e, 'aria-label', t.getLang('aria.rich_text_area'));\r
+\r
+                       if (s.theme) {\r
+                               s.theme = s.theme.replace(/-/, '');\r
+                               o = ThemeManager.get(s.theme);\r
+                               t.theme = new o();\r
+\r
+                               if (t.theme.init && s.init_theme)\r
+                                       t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, ''));\r
+                       }\r
+                       function initPlugin(p) {\r
+                               var c = PluginManager.get(p), u = PluginManager.urls[p] || tinymce.documentBaseURL.replace(/\/$/, ''), po;\r
+                               if (c && tinymce.inArray(initializedPlugins,p) === -1) {\r
+                                       each(PluginManager.dependencies(p), function(dep){\r
+                                               initPlugin(dep);\r
+                                       });\r
+                                       po = new c(t, u);\r
+\r
+                                       t.plugins[p] = po;\r
+\r
+                                       if (po.init) {\r
+                                               po.init(t, u);\r
+                                               initializedPlugins.push(p);\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       // Create all plugins\r
+                       each(explode(s.plugins.replace(/\-/g, '')), initPlugin);\r
+\r
+                       // Setup popup CSS path(s)\r
+                       if (s.popup_css !== false) {\r
+                               if (s.popup_css)\r
+                                       s.popup_css = t.documentBaseURI.toAbsolute(s.popup_css);\r
+                               else\r
+                                       s.popup_css = t.baseURI.toAbsolute("themes/" + s.theme + "/skins/" + s.skin + "/dialog.css");\r
+                       }\r
+\r
+                       if (s.popup_css_add)\r
+                               s.popup_css += ',' + t.documentBaseURI.toAbsolute(s.popup_css_add);\r
+\r
+                       t.controlManager = new tinymce.ControlManager(t);\r
+\r
+                       if (s.custom_undo_redo) {\r
+                               t.onBeforeExecCommand.add(function(ed, cmd, ui, val, a) {\r
+                                       if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))\r
+                                               t.undoManager.beforeChange();\r
+                               });\r
+\r
+                               t.onExecCommand.add(function(ed, cmd, ui, val, a) {\r
+                                       if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))\r
+                                               t.undoManager.add();\r
+                               });\r
+                       }\r
+\r
+                       t.onExecCommand.add(function(ed, c) {\r
+                               // Don't refresh the select lists until caret move\r
+                               if (!/^(FontName|FontSize)$/.test(c))\r
+                                       t.nodeChanged();\r
+                       });\r
+\r
+                       // Remove ghost selections on images and tables in Gecko\r
+                       if (isGecko) {\r
+                               function repaint(a, o) {\r
+                                       if (!o || !o.initial)\r
+                                               t.execCommand('mceRepaint');\r
+                               };\r
+\r
+                               t.onUndo.add(repaint);\r
+                               t.onRedo.add(repaint);\r
+                               t.onSetContent.add(repaint);\r
+                       }\r
+\r
+                       // Enables users to override the control factory\r
+                       t.onBeforeRenderUI.dispatch(t, t.controlManager);\r
+\r
+                       // Measure box\r
+                       if (s.render_ui) {\r
+                               w = s.width || e.style.width || e.offsetWidth;\r
+                               h = s.height || e.style.height || e.offsetHeight;\r
+                               t.orgDisplay = e.style.display;\r
+                               re = /^[0-9\.]+(|px)$/i;\r
+\r
+                               if (re.test('' + w))\r
+                                       w = Math.max(parseInt(w) + (o.deltaWidth || 0), 100);\r
+\r
+                               if (re.test('' + h))\r
+                                       h = Math.max(parseInt(h) + (o.deltaHeight || 0), 100);\r
+\r
+                               // Render UI\r
+                               o = t.theme.renderUI({\r
+                                       targetNode : e,\r
+                                       width : w,\r
+                                       height : h,\r
+                                       deltaWidth : s.delta_width,\r
+                                       deltaHeight : s.delta_height\r
+                               });\r
+\r
+                               t.editorContainer = o.editorContainer;\r
+                       }\r
+\r
+\r
+                       // User specified a document.domain value\r
+                       if (document.domain && location.hostname != document.domain)\r
+                               tinymce.relaxedDomain = document.domain;\r
+\r
+                       // Resize editor\r
+                       DOM.setStyles(o.sizeContainer || o.editorContainer, {\r
+                               width : w,\r
+                               height : h\r
+                       });\r
+\r
+                       // Load specified content CSS last\r
+                       if (s.content_css) {\r
+                               tinymce.each(explode(s.content_css), function(u) {\r
+                                       t.contentCSS.push(t.documentBaseURI.toAbsolute(u));\r
+                               });\r
+                       }\r
+\r
+                       h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : '');\r
+                       if (h < 100)\r
+                               h = 100;\r
+\r
+                       t.iframeHTML = s.doctype + '<html><head xmlns="http://www.w3.org/1999/xhtml">';\r
+\r
+                       // We only need to override paths if we have to\r
+                       // IE has a bug where it remove site absolute urls to relative ones if this is specified\r
+                       if (s.document_base_url != tinymce.documentBaseURL)\r
+                               t.iframeHTML += '<base href="' + t.documentBaseURI.getURI() + '" />';\r
+\r
+                       // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode.\r
+                       if (s.ie7_compat)\r
+                               t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />';\r
+                       else\r
+                               t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=edge" />';\r
+\r
+                       t.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';\r
+\r
+                       bi = s.body_id || 'tinymce';\r
+                       if (bi.indexOf('=') != -1) {\r
+                               bi = t.getParam('body_id', '', 'hash');\r
+                               bi = bi[t.id] || bi;\r
+                       }\r
+\r
+                       bc = s.body_class || '';\r
+                       if (bc.indexOf('=') != -1) {\r
+                               bc = t.getParam('body_class', '', 'hash');\r
+                               bc = bc[t.id] || '';\r
+                       }\r
+\r
+                       t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '"><br></body></html>';\r
+\r
+                       // Domain relaxing enabled, then set document domain\r
+                       if (tinymce.relaxedDomain && (isIE || (tinymce.isOpera && parseFloat(opera.version()) < 11))) {\r
+                               // We need to write the contents here in IE since multiple writes messes up refresh button and back button\r
+                               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();})()';                         \r
+                       }\r
+\r
+                       // Create iframe\r
+                       // TODO: ACC add the appropriate description on this.\r
+                       n = DOM.add(o.iframeContainer, 'iframe', { \r
+                               id : t.id + "_ifr",\r
+                               src : u || 'javascript:""', // Workaround for HTTPS warning in IE6/7\r
+                               frameBorder : '0',\r
+                               allowTransparency : "true",\r
+                               title : s.aria_label,\r
+                               style : {\r
+                                       width : '100%',\r
+                                       height : h,\r
+                                       display : 'block' // Important for Gecko to render the iframe correctly\r
+                               }\r
+                       });\r
+\r
+                       t.contentAreaContainer = o.iframeContainer;\r
+                       DOM.get(o.editorContainer).style.display = t.orgDisplay;\r
+                       DOM.get(t.id).style.display = 'none';\r
+                       DOM.setAttrib(t.id, 'aria-hidden', true);\r
+\r
+                       if (!tinymce.relaxedDomain || !u)\r
+                               t.setupIframe();\r
+\r
+                       e = n = o = null; // Cleanup\r
+               },\r
+\r
+               setupIframe : function() {\r
+                       var t = this, s = t.settings, e = DOM.get(t.id), d = t.getDoc(), h, b;\r
+\r
+                       // Setup iframe body\r
+                       if (!isIE || !tinymce.relaxedDomain) {\r
+                               // Fix for a focus bug in FF 3.x where the body element\r
+                               // wouldn't get proper focus if the user clicked on the HTML element\r
+                               if (isGecko && !Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4\r
+                                       t.onMouseDown.add(function(ed, e) {\r
+                                               if (e.target.nodeName === "HTML") {\r
+                                                       var body = t.getBody();\r
+\r
+                                                       // Blur the body it's focused but not correctly focused\r
+                                                       body.blur();\r
+\r
+                                                       // Refocus the body after a little while\r
+                                                       setTimeout(function() {\r
+                                                               body.focus();\r
+                                                       }, 0);\r
+                                               }\r
+                                       });\r
+                               }\r
+\r
+                               d.open();\r
+                               d.write(t.iframeHTML);\r
+                               d.close();\r
+\r
+                               if (tinymce.relaxedDomain)\r
+                                       d.domain = tinymce.relaxedDomain;\r
+                       }\r
+\r
+                       // It will not steal focus while setting contentEditable\r
+                       b = t.getBody();\r
+                       b.disabled = true;\r
+\r
+                       if (!s.readonly)\r
+                               b.contentEditable = true;\r
+\r
+                       b.disabled = false;\r
+\r
+                       t.schema = new tinymce.html.Schema(s);\r
+\r
+                       t.dom = new tinymce.dom.DOMUtils(t.getDoc(), {\r
+                               keep_values : true,\r
+                               url_converter : t.convertURL,\r
+                               url_converter_scope : t,\r
+                               hex_colors : s.force_hex_style_colors,\r
+                               class_filter : s.class_filter,\r
+                               update_styles : 1,\r
+                               fix_ie_paragraphs : 1,\r
+                               schema : t.schema\r
+                       });\r
+\r
+                       t.parser = new tinymce.html.DomParser(s, t.schema);\r
+\r
+                       // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included.\r
+                       if (!t.settings.allow_html_in_named_anchor) {\r
+                               t.parser.addAttributeFilter('name', function(nodes, name) {\r
+                                       var i = nodes.length, sibling, prevSibling, parent, node;\r
+       \r
+                                       while (i--) {\r
+                                               node = nodes[i];\r
+                                               if (node.name === 'a' && node.firstChild) {\r
+                                                       parent = node.parent;\r
+       \r
+                                                       // Move children after current node\r
+                                                       sibling = node.lastChild;\r
+                                                       do {\r
+                                                               prevSibling = sibling.prev;\r
+                                                               parent.insert(sibling, node);\r
+                                                               sibling = prevSibling;\r
+                                                       } while (sibling);\r
+                                               }\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       // Convert src and href into data-mce-src, data-mce-href and data-mce-style\r
+                       t.parser.addAttributeFilter('src,href,style', function(nodes, name) {\r
+                               var i = nodes.length, node, dom = t.dom, value, internalName;\r
+\r
+                               while (i--) {\r
+                                       node = nodes[i];\r
+                                       value = node.attr(name);\r
+                                       internalName = 'data-mce-' + name;\r
+\r
+                                       // Add internal attribute if we need to we don't on a refresh of the document\r
+                                       if (!node.attributes.map[internalName]) {       \r
+                                               if (name === "style")\r
+                                                       node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name));\r
+                                               else\r
+                                                       node.attr(internalName, t.convertURL(value, name, node.name));\r
+                                       }\r
+                               }\r
+                       });\r
+\r
+                       // Keep scripts from executing\r
+                       t.parser.addNodeFilter('script', function(nodes, name) {\r
+                               var i = nodes.length;\r
+\r
+                               while (i--)\r
+                                       nodes[i].attr('type', 'mce-text/javascript');\r
+                       });\r
+\r
+                       t.parser.addNodeFilter('#cdata', function(nodes, name) {\r
+                               var i = nodes.length, node;\r
+\r
+                               while (i--) {\r
+                                       node = nodes[i];\r
+                                       node.type = 8;\r
+                                       node.name = '#comment';\r
+                                       node.value = '[CDATA[' + node.value + ']]';\r
+                               }\r
+                       });\r
+\r
+                       t.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) {\r
+                               var i = nodes.length, node, nonEmptyElements = t.schema.getNonEmptyElements();\r
+\r
+                               while (i--) {\r
+                                       node = nodes[i];\r
+\r
+                                       if (node.isEmpty(nonEmptyElements))\r
+                                               node.empty().append(new tinymce.html.Node('br', 1)).shortEnded = true;\r
+                               }\r
+                       });\r
+\r
+                       t.serializer = new tinymce.dom.Serializer(s, t.dom, t.schema);\r
+\r
+                       t.selection = new tinymce.dom.Selection(t.dom, t.getWin(), t.serializer);\r
+\r
+                       t.formatter = new tinymce.Formatter(this);\r
+\r
+                       // Register default formats\r
+                       t.formatter.register({\r
+                               alignleft : [\r
+                                       {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}},\r
+                                       {selector : 'img,table', collapsed : false, styles : {'float' : 'left'}}\r
+                               ],\r
+\r
+                               aligncenter : [\r
+                                       {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}},\r
+                                       {selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}},\r
+                                       {selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}}\r
+                               ],\r
+\r
+                               alignright : [\r
+                                       {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}},\r
+                                       {selector : 'img,table', collapsed : false, styles : {'float' : 'right'}}\r
+                               ],\r
+\r
+                               alignfull : [\r
+                                       {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}}\r
+                               ],\r
+\r
+                               bold : [\r
+                                       {inline : 'strong', remove : 'all'},\r
+                                       {inline : 'span', styles : {fontWeight : 'bold'}},\r
+                                       {inline : 'b', remove : 'all'}\r
+                               ],\r
+\r
+                               italic : [\r
+                                       {inline : 'em', remove : 'all'},\r
+                                       {inline : 'span', styles : {fontStyle : 'italic'}},\r
+                                       {inline : 'i', remove : 'all'}\r
+                               ],\r
+\r
+                               underline : [\r
+                                       {inline : 'span', styles : {textDecoration : 'underline'}, exact : true},\r
+                                       {inline : 'u', remove : 'all'}\r
+                               ],\r
+\r
+                               strikethrough : [\r
+                                       {inline : 'span', styles : {textDecoration : 'line-through'}, exact : true},\r
+                                       {inline : 'strike', remove : 'all'}\r
+                               ],\r
+\r
+                               forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false},\r
+                               hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false},\r
+                               fontname : {inline : 'span', styles : {fontFamily : '%value'}},\r
+                               fontsize : {inline : 'span', styles : {fontSize : '%value'}},\r
+                               fontsize_class : {inline : 'span', attributes : {'class' : '%value'}},\r
+                               blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'},\r
+                               subscript : {inline : 'sub'},\r
+                               superscript : {inline : 'sup'},\r
+\r
+                               link : {inline : 'a', selector : 'a', remove : 'all', split : true, deep : true,\r
+                                       onmatch : function(node) {\r
+                                               return true;\r
+                                       },\r
+\r
+                                       onformat : function(elm, fmt, vars) {\r
+                                               each(vars, function(value, key) {\r
+                                                       t.dom.setAttrib(elm, key, value);\r
+                                               });\r
+                                       }\r
+                               },\r
+\r
+                               removeformat : [\r
+                                       {selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true},\r
+                                       {selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},\r
+                                       {selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}\r
+                               ]\r
+                       });\r
+\r
+                       // Register default block formats\r
+                       each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) {\r
+                               t.formatter.register(name, {block : name, remove : 'all'});\r
+                       });\r
+\r
+                       // Register user defined formats\r
+                       t.formatter.register(t.settings.formats);\r
+\r
+                       t.undoManager = new tinymce.UndoManager(t);\r
+\r
+                       // Pass through\r
+                       t.undoManager.onAdd.add(function(um, l) {\r
+                               if (um.hasUndo())\r
+                                       return t.onChange.dispatch(t, l, um);\r
+                       });\r
+\r
+                       t.undoManager.onUndo.add(function(um, l) {\r
+                               return t.onUndo.dispatch(t, l, um);\r
+                       });\r
+\r
+                       t.undoManager.onRedo.add(function(um, l) {\r
+                               return t.onRedo.dispatch(t, l, um);\r
+                       });\r
+\r
+                       t.forceBlocks = new tinymce.ForceBlocks(t, {\r
+                               forced_root_block : s.forced_root_block\r
+                       });\r
+\r
+                       t.editorCommands = new tinymce.EditorCommands(t);\r
+\r
+                       // Pass through\r
+                       t.serializer.onPreProcess.add(function(se, o) {\r
+                               return t.onPreProcess.dispatch(t, o, se);\r
+                       });\r
+\r
+                       t.serializer.onPostProcess.add(function(se, o) {\r
+                               return t.onPostProcess.dispatch(t, o, se);\r
+                       });\r
+\r
+                       t.onPreInit.dispatch(t);\r
+\r
+                       if (!s.gecko_spellcheck)\r
+                               t.getBody().spellcheck = 0;\r
+\r
+                       if (!s.readonly)\r
+                               t._addEvents();\r
+\r
+                       t.controlManager.onPostRender.dispatch(t, t.controlManager);\r
+                       t.onPostRender.dispatch(t);\r
+\r
+                       t.quirks = new tinymce.util.Quirks(this);\r
+\r
+                       if (s.directionality)\r
+                               t.getBody().dir = s.directionality;\r
+\r
+                       if (s.nowrap)\r
+                               t.getBody().style.whiteSpace = "nowrap";\r
+\r
+                       if (s.handle_node_change_callback) {\r
+                               t.onNodeChange.add(function(ed, cm, n) {\r
+                                       t.execCallback('handle_node_change_callback', t.id, n, -1, -1, true, t.selection.isCollapsed());\r
+                               });\r
+                       }\r
+\r
+                       if (s.save_callback) {\r
+                               t.onSaveContent.add(function(ed, o) {\r
+                                       var h = t.execCallback('save_callback', t.id, o.content, t.getBody());\r
+\r
+                                       if (h)\r
+                                               o.content = h;\r
+                               });\r
+                       }\r
+\r
+                       if (s.onchange_callback) {\r
+                               t.onChange.add(function(ed, l) {\r
+                                       t.execCallback('onchange_callback', t, l);\r
+                               });\r
+                       }\r
+\r
+                       if (s.protect) {\r
+                               t.onBeforeSetContent.add(function(ed, o) {\r
+                                       if (s.protect) {\r
+                                               each(s.protect, function(pattern) {\r
+                                                       o.content = o.content.replace(pattern, function(str) {\r
+                                                               return '<!--mce:protected ' + escape(str) + '-->';\r
+                                                       });\r
+                                               });\r
+                                       }\r
+                               });\r
+                       }\r
+\r
+                       if (s.convert_newlines_to_brs) {\r
+                               t.onBeforeSetContent.add(function(ed, o) {\r
+                                       if (o.initial)\r
+                                               o.content = o.content.replace(/\r?\n/g, '<br />');\r
+                               });\r
+                       }\r
+\r
+                       if (s.preformatted) {\r
+                               t.onPostProcess.add(function(ed, o) {\r
+                                       o.content = o.content.replace(/^\s*<pre.*?>/, '');\r
+                                       o.content = o.content.replace(/<\/pre>\s*$/, '');\r
+\r
+                                       if (o.set)\r
+                                               o.content = '<pre class="mceItemHidden">' + o.content + '</pre>';\r
+                               });\r
+                       }\r
+\r
+                       if (s.verify_css_classes) {\r
+                               t.serializer.attribValueFilter = function(n, v) {\r
+                                       var s, cl;\r
+\r
+                                       if (n == 'class') {\r
+                                               // Build regexp for classes\r
+                                               if (!t.classesRE) {\r
+                                                       cl = t.dom.getClasses();\r
+\r
+                                                       if (cl.length > 0) {\r
+                                                               s = '';\r
+\r
+                                                               each (cl, function(o) {\r
+                                                                       s += (s ? '|' : '') + o['class'];\r
+                                                               });\r
+\r
+                                                               t.classesRE = new RegExp('(' + s + ')', 'gi');\r
+                                                       }\r
+                                               }\r
+\r
+                                               return !t.classesRE || /(\bmceItem\w+\b|\bmceTemp\w+\b)/g.test(v) || t.classesRE.test(v) ? v : '';\r
+                                       }\r
+\r
+                                       return v;\r
+                               };\r
+                       }\r
+\r
+                       if (s.cleanup_callback) {\r
+                               t.onBeforeSetContent.add(function(ed, o) {\r
+                                       o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);\r
+                               });\r
+\r
+                               t.onPreProcess.add(function(ed, o) {\r
+                                       if (o.set)\r
+                                               t.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o);\r
+\r
+                                       if (o.get)\r
+                                               t.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o);\r
+                               });\r
+\r
+                               t.onPostProcess.add(function(ed, o) {\r
+                                       if (o.set)\r
+                                               o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);\r
+\r
+                                       if (o.get)                                              \r
+                                               o.content = t.execCallback('cleanup_callback', 'get_from_editor', o.content, o);\r
+                               });\r
+                       }\r
+\r
+                       if (s.save_callback) {\r
+                               t.onGetContent.add(function(ed, o) {\r
+                                       if (o.save)\r
+                                               o.content = t.execCallback('save_callback', t.id, o.content, t.getBody());\r
+                               });\r
+                       }\r
+\r
+                       if (s.handle_event_callback) {\r
+                               t.onEvent.add(function(ed, e, o) {\r
+                                       if (t.execCallback('handle_event_callback', e, ed, o) === false)\r
+                                               Event.cancel(e);\r
+                               });\r
+                       }\r
+\r
+                       // Add visual aids when new contents is added\r
+                       t.onSetContent.add(function() {\r
+                               t.addVisual(t.getBody());\r
+                       });\r
+\r
+                       // Remove empty contents\r
+                       if (s.padd_empty_editor) {\r
+                               t.onPostProcess.add(function(ed, o) {\r
+                                       o.content = o.content.replace(/^(<p[^>]*>(&nbsp;|&#160;|\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, '');\r
+                               });\r
+                       }\r
+\r
+                       if (isGecko) {\r
+                               // Fix gecko link bug, when a link is placed at the end of block elements there is\r
+                               // no way to move the caret behind the link. This fix adds a bogus br element after the link\r
+                               function fixLinks(ed, o) {\r
+                                       each(ed.dom.select('a'), function(n) {\r
+                                               var pn = n.parentNode;\r
+\r
+                                               if (ed.dom.isBlock(pn) && pn.lastChild === n)\r
+                                                       ed.dom.add(pn, 'br', {'data-mce-bogus' : 1});\r
+                                       });\r
+                               };\r
+\r
+                               t.onExecCommand.add(function(ed, cmd) {\r
+                                       if (cmd === 'CreateLink')\r
+                                               fixLinks(ed);\r
+                               });\r
+\r
+                               t.onSetContent.add(t.selection.onSetContent.add(fixLinks));\r
+                       }\r
+\r
+                       t.load({initial : true, format : 'html'});\r
+                       t.startContent = t.getContent({format : 'raw'});\r
+                       t.undoManager.add();\r
+                       t.initialized = true;\r
+\r
+                       t.onInit.dispatch(t);\r
+                       t.execCallback('setupcontent_callback', t.id, t.getBody(), t.getDoc());\r
+                       t.execCallback('init_instance_callback', t);\r
+                       t.focus(true);\r
+                       t.nodeChanged({initial : 1});\r
+\r
+                       // Load specified content CSS last\r
+                       each(t.contentCSS, function(u) {\r
+                               t.dom.loadCSS(u);\r
+                       });\r
+\r
+                       // Handle auto focus\r
+                       if (s.auto_focus) {\r
+                               setTimeout(function () {\r
+                                       var ed = tinymce.get(s.auto_focus);\r
+\r
+                                       ed.selection.select(ed.getBody(), 1);\r
+                                       ed.selection.collapse(1);\r
+                                       ed.getBody().focus();\r
+                                       ed.getWin().focus();\r
+                               }, 100);\r
+                       }\r
+\r
+                       e = null;\r
+               },\r
+\r
+\r
+               focus : function(sf) {\r
+                       var oed, t = this, selection = t.selection, ce = t.settings.content_editable, ieRng, controlElm, doc = t.getDoc();\r
+\r
+                       if (!sf) {\r
+                               // Get selected control element\r
+                               ieRng = selection.getRng();\r
+                               if (ieRng.item) {\r
+                                       controlElm = ieRng.item(0);\r
+                               }\r
+\r
+                               t._refreshContentEditable();\r
+                               selection.normalize();\r
+\r
+                               // Is not content editable\r
+                               if (!ce)\r
+                                       t.getWin().focus();\r
+\r
+                               // Focus the body as well since it's contentEditable\r
+                               if (tinymce.isGecko) {\r
+                                       t.getBody().focus();\r
+                               }\r
+\r
+                               // Restore selected control element\r
+                               // This is needed when for example an image is selected within a\r
+                               // layer a call to focus will then remove the control selection\r
+                               if (controlElm && controlElm.ownerDocument == doc) {\r
+                                       ieRng = doc.body.createControlRange();\r
+                                       ieRng.addElement(controlElm);\r
+                                       ieRng.select();\r
+                               }\r
+\r
+                       }\r
+\r
+                       if (tinymce.activeEditor != t) {\r
+                               if ((oed = tinymce.activeEditor) != null)\r
+                                       oed.onDeactivate.dispatch(oed, t);\r
+\r
+                               t.onActivate.dispatch(t, oed);\r
+                       }\r
+\r
+                       tinymce._setActive(t);\r
+               },\r
+\r
+               execCallback : function(n) {\r
+                       var t = this, f = t.settings[n], s;\r
+\r
+                       if (!f)\r
+                               return;\r
+\r
+                       // Look through lookup\r
+                       if (t.callbackLookup && (s = t.callbackLookup[n])) {\r
+                               f = s.func;\r
+                               s = s.scope;\r
+                       }\r
+\r
+                       if (is(f, 'string')) {\r
+                               s = f.replace(/\.\w+$/, '');\r
+                               s = s ? tinymce.resolve(s) : 0;\r
+                               f = tinymce.resolve(f);\r
+                               t.callbackLookup = t.callbackLookup || {};\r
+                               t.callbackLookup[n] = {func : f, scope : s};\r
+                       }\r
+\r
+                       return f.apply(s || t, Array.prototype.slice.call(arguments, 1));\r
+               },\r
+\r
+               translate : function(s) {\r
+                       var c = this.settings.language || 'en', i18n = tinymce.i18n;\r
+\r
+                       if (!s)\r
+                               return '';\r
+\r
+                       return i18n[c + '.' + s] || s.replace(/{\#([^}]+)\}/g, function(a, b) {\r
+                               return i18n[c + '.' + b] || '{#' + b + '}';\r
+                       });\r
+               },\r
+\r
+               getLang : function(n, dv) {\r
+                       return tinymce.i18n[(this.settings.language || 'en') + '.' + n] || (is(dv) ? dv : '{#' + n + '}');\r
+               },\r
+\r
+               getParam : function(n, dv, ty) {\r
+                       var tr = tinymce.trim, v = is(this.settings[n]) ? this.settings[n] : dv, o;\r
+\r
+                       if (ty === 'hash') {\r
+                               o = {};\r
+\r
+                               if (is(v, 'string')) {\r
+                                       each(v.indexOf('=') > 0 ? v.split(/[;,](?![^=;,]*(?:[;,]|$))/) : v.split(','), function(v) {\r
+                                               v = v.split('=');\r
+\r
+                                               if (v.length > 1)\r
+                                                       o[tr(v[0])] = tr(v[1]);\r
+                                               else\r
+                                                       o[tr(v[0])] = tr(v);\r
+                                       });\r
+                               } else\r
+                                       o = v;\r
+\r
+                               return o;\r
+                       }\r
+\r
+                       return v;\r
+               },\r
+\r
+               nodeChanged : function(o) {\r
+                       var t = this, s = t.selection, n = s.getStart() || t.getBody();\r
+\r
+                       // Fix for bug #1896577 it seems that this can not be fired while the editor is loading\r
+                       if (t.initialized) {\r
+                               o = o || {};\r
+                               n = isIE && n.ownerDocument != t.getDoc() ? t.getBody() : n; // Fix for IE initial state\r
+\r
+                               // Get parents and add them to object\r
+                               o.parents = [];\r
+                               t.dom.getParent(n, function(node) {\r
+                                       if (node.nodeName == 'BODY')\r
+                                               return true;\r
+\r
+                                       o.parents.push(node);\r
+                               });\r
+\r
+                               t.onNodeChange.dispatch(\r
+                                       t,\r
+                                       o ? o.controlManager || t.controlManager : t.controlManager,\r
+                                       n,\r
+                                       s.isCollapsed(),\r
+                                       o\r
+                               );\r
+                       }\r
+               },\r
+\r
+               addButton : function(n, s) {\r
+                       var t = this;\r
+\r
+                       t.buttons = t.buttons || {};\r
+                       t.buttons[n] = s;\r
+               },\r
+\r
+               addCommand : function(name, callback, scope) {\r
+                       this.execCommands[name] = {func : callback, scope : scope || this};\r
+               },\r
+\r
+               addQueryStateHandler : function(name, callback, scope) {\r
+                       this.queryStateCommands[name] = {func : callback, scope : scope || this};\r
+               },\r
+\r
+               addQueryValueHandler : function(name, callback, scope) {\r
+                       this.queryValueCommands[name] = {func : callback, scope : scope || this};\r
+               },\r
+\r
+               addShortcut : function(pa, desc, cmd_func, sc) {\r
+                       var t = this, c;\r
+\r
+                       if (!t.settings.custom_shortcuts)\r
+                               return false;\r
+\r
+                       t.shortcuts = t.shortcuts || {};\r
+\r
+                       if (is(cmd_func, 'string')) {\r
+                               c = cmd_func;\r
+\r
+                               cmd_func = function() {\r
+                                       t.execCommand(c, false, null);\r
+                               };\r
+                       }\r
+\r
+                       if (is(cmd_func, 'object')) {\r
+                               c = cmd_func;\r
+\r
+                               cmd_func = function() {\r
+                                       t.execCommand(c[0], c[1], c[2]);\r
+                               };\r
+                       }\r
+\r
+                       each(explode(pa), function(pa) {\r
+                               var o = {\r
+                                       func : cmd_func,\r
+                                       scope : sc || this,\r
+                                       desc : desc,\r
+                                       alt : false,\r
+                                       ctrl : false,\r
+                                       shift : false\r
+                               };\r
+\r
+                               each(explode(pa, '+'), function(v) {\r
+                                       switch (v) {\r
+                                               case 'alt':\r
+                                               case 'ctrl':\r
+                                               case 'shift':\r
+                                                       o[v] = true;\r
+                                                       break;\r
+\r
+                                               default:\r
+                                                       o.charCode = v.charCodeAt(0);\r
+                                                       o.keyCode = v.toUpperCase().charCodeAt(0);\r
+                                       }\r
+                               });\r
+\r
+                               t.shortcuts[(o.ctrl ? 'ctrl' : '') + ',' + (o.alt ? 'alt' : '') + ',' + (o.shift ? 'shift' : '') + ',' + o.keyCode] = o;\r
+                       });\r
+\r
+                       return true;\r
+               },\r
+\r
+               execCommand : function(cmd, ui, val, a) {\r
+                       var t = this, s = 0, o, st;\r
+\r
+                       if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(cmd) && (!a || !a.skip_focus))\r
+                               t.focus();\r
+\r
+                       o = {};\r
+                       t.onBeforeExecCommand.dispatch(t, cmd, ui, val, o);\r
+                       if (o.terminate)\r
+                               return false;\r
+\r
+                       // Command callback\r
+                       if (t.execCallback('execcommand_callback', t.id, t.selection.getNode(), cmd, ui, val)) {\r
+                               t.onExecCommand.dispatch(t, cmd, ui, val, a);\r
+                               return true;\r
+                       }\r
+\r
+                       // Registred commands\r
+                       if (o = t.execCommands[cmd]) {\r
+                               st = o.func.call(o.scope, ui, val);\r
+\r
+                               // Fall through on true\r
+                               if (st !== true) {\r
+                                       t.onExecCommand.dispatch(t, cmd, ui, val, a);\r
+                                       return st;\r
+                               }\r
+                       }\r
+\r
+                       // Plugin commands\r
+                       each(t.plugins, function(p) {\r
+                               if (p.execCommand && p.execCommand(cmd, ui, val)) {\r
+                                       t.onExecCommand.dispatch(t, cmd, ui, val, a);\r
+                                       s = 1;\r
+                                       return false;\r
+                               }\r
+                       });\r
+\r
+                       if (s)\r
+                               return true;\r
+\r
+                       // Theme commands\r
+                       if (t.theme && t.theme.execCommand && t.theme.execCommand(cmd, ui, val)) {\r
+                               t.onExecCommand.dispatch(t, cmd, ui, val, a);\r
+                               return true;\r
+                       }\r
+\r
+                       // Editor commands\r
+                       if (t.editorCommands.execCommand(cmd, ui, val)) {\r
+                               t.onExecCommand.dispatch(t, cmd, ui, val, a);\r
+                               return true;\r
+                       }\r
+\r
+                       // Browser commands\r
+                       t.getDoc().execCommand(cmd, ui, val);\r
+                       t.onExecCommand.dispatch(t, cmd, ui, val, a);\r
+               },\r
+\r
+               queryCommandState : function(cmd) {\r
+                       var t = this, o, s;\r
+\r
+                       // Is hidden then return undefined\r
+                       if (t._isHidden())\r
+                               return;\r
+\r
+                       // Registred commands\r
+                       if (o = t.queryStateCommands[cmd]) {\r
+                               s = o.func.call(o.scope);\r
+\r
+                               // Fall though on true\r
+                               if (s !== true)\r
+                                       return s;\r
+                       }\r
+\r
+                       // Registred commands\r
+                       o = t.editorCommands.queryCommandState(cmd);\r
+                       if (o !== -1)\r
+                               return o;\r
+\r
+                       // Browser commands\r
+                       try {\r
+                               return this.getDoc().queryCommandState(cmd);\r
+                       } catch (ex) {\r
+                               // Fails sometimes see bug: 1896577\r
+                       }\r
+               },\r
+\r
+               queryCommandValue : function(c) {\r
+                       var t = this, o, s;\r
+\r
+                       // Is hidden then return undefined\r
+                       if (t._isHidden())\r
+                               return;\r
+\r
+                       // Registred commands\r
+                       if (o = t.queryValueCommands[c]) {\r
+                               s = o.func.call(o.scope);\r
+\r
+                               // Fall though on true\r
+                               if (s !== true)\r
+                                       return s;\r
+                       }\r
+\r
+                       // Registred commands\r
+                       o = t.editorCommands.queryCommandValue(c);\r
+                       if (is(o))\r
+                               return o;\r
+\r
+                       // Browser commands\r
+                       try {\r
+                               return this.getDoc().queryCommandValue(c);\r
+                       } catch (ex) {\r
+                               // Fails sometimes see bug: 1896577\r
+                       }\r
+               },\r
+\r
+               show : function() {\r
+                       var t = this;\r
+\r
+                       DOM.show(t.getContainer());\r
+                       DOM.hide(t.id);\r
+                       t.load();\r
+               },\r
+\r
+               hide : function() {\r
+                       var t = this, d = t.getDoc();\r
+\r
+                       // Fixed bug where IE has a blinking cursor left from the editor\r
+                       if (isIE && d)\r
+                               d.execCommand('SelectAll');\r
+\r
+                       // We must save before we hide so Safari doesn't crash\r
+                       t.save();\r
+                       DOM.hide(t.getContainer());\r
+                       DOM.setStyle(t.id, 'display', t.orgDisplay);\r
+               },\r
+\r
+               isHidden : function() {\r
+                       return !DOM.isHidden(this.id);\r
+               },\r
+\r
+               setProgressState : function(b, ti, o) {\r
+                       this.onSetProgressState.dispatch(this, b, ti, o);\r
+\r
+                       return b;\r
+               },\r
+\r
+               load : function(o) {\r
+                       var t = this, e = t.getElement(), h;\r
+\r
+                       if (e) {\r
+                               o = o || {};\r
+                               o.load = true;\r
+\r
+                               // Double encode existing entities in the value\r
+                               h = t.setContent(is(e.value) ? e.value : e.innerHTML, o);\r
+                               o.element = e;\r
+\r
+                               if (!o.no_events)\r
+                                       t.onLoadContent.dispatch(t, o);\r
+\r
+                               o.element = e = null;\r
+\r
+                               return h;\r
+                       }\r
+               },\r
+\r
+               save : function(o) {\r
+                       var t = this, e = t.getElement(), h, f;\r
+\r
+                       if (!e || !t.initialized)\r
+                               return;\r
+\r
+                       o = o || {};\r
+                       o.save = true;\r
+\r
+                       // Add undo level will trigger onchange event\r
+                       if (!o.no_events) {\r
+                               t.undoManager.typing = false;\r
+                               t.undoManager.add();\r
+                       }\r
+\r
+                       o.element = e;\r
+                       h = o.content = t.getContent(o);\r
+\r
+                       if (!o.no_events)\r
+                               t.onSaveContent.dispatch(t, o);\r
+\r
+                       h = o.content;\r
+\r
+                       if (!/TEXTAREA|INPUT/i.test(e.nodeName)) {\r
+                               e.innerHTML = h;\r
+\r
+                               // Update hidden form element\r
+                               if (f = DOM.getParent(t.id, 'form')) {\r
+                                       each(f.elements, function(e) {\r
+                                               if (e.name == t.id) {\r
+                                                       e.value = h;\r
+                                                       return false;\r
+                                               }\r
+                                       });\r
+                               }\r
+                       } else\r
+                               e.value = h;\r
+\r
+                       o.element = e = null;\r
+\r
+                       return h;\r
+               },\r
+\r
+               setContent : function(content, args) {\r
+                       var self = this, rootNode, body = self.getBody(), forcedRootBlockName;\r
+\r
+                       // Setup args object\r
+                       args = args || {};\r
+                       args.format = args.format || 'html';\r
+                       args.set = true;\r
+                       args.content = content;\r
+\r
+                       // Do preprocessing\r
+                       if (!args.no_events)\r
+                               self.onBeforeSetContent.dispatch(self, args);\r
+\r
+                       content = args.content;\r
+\r
+                       // Padd empty content in Gecko and Safari. Commands will otherwise fail on the content\r
+                       // It will also be impossible to place the caret in the editor unless there is a BR element present\r
+                       if (!tinymce.isIE && (content.length === 0 || /^\s+$/.test(content))) {\r
+                               forcedRootBlockName = self.settings.forced_root_block;\r
+                               if (forcedRootBlockName)\r
+                                       content = '<' + forcedRootBlockName + '><br data-mce-bogus="1"></' + forcedRootBlockName + '>';\r
+                               else\r
+                                       content = '<br data-mce-bogus="1">';\r
+\r
+                               body.innerHTML = content;\r
+                               self.selection.select(body, true);\r
+                               self.selection.collapse(true);\r
+                               return;\r
+                       }\r
+\r
+                       // Parse and serialize the html\r
+                       if (args.format !== 'raw') {\r
+                               content = new tinymce.html.Serializer({}, self.schema).serialize(\r
+                                       self.parser.parse(content)\r
+                               );\r
+                       }\r
+\r
+                       // Set the new cleaned contents to the editor\r
+                       args.content = tinymce.trim(content);\r
+                       self.dom.setHTML(body, args.content);\r
+\r
+                       // Do post processing\r
+                       if (!args.no_events)\r
+                               self.onSetContent.dispatch(self, args);\r
+\r
+                       self.selection.normalize();\r
+\r
+                       return args.content;\r
+               },\r
+\r
+               getContent : function(args) {\r
+                       var self = this, content;\r
+\r
+                       // Setup args object\r
+                       args = args || {};\r
+                       args.format = args.format || 'html';\r
+                       args.get = true;\r
+\r
+                       // Do preprocessing\r
+                       if (!args.no_events)\r
+                               self.onBeforeGetContent.dispatch(self, args);\r
+\r
+                       // Get raw contents or by default the cleaned contents\r
+                       if (args.format == 'raw')\r
+                               content = self.getBody().innerHTML;\r
+                       else\r
+                               content = self.serializer.serialize(self.getBody(), args);\r
+\r
+                       args.content = tinymce.trim(content);\r
+\r
+                       // Do post processing\r
+                       if (!args.no_events)\r
+                               self.onGetContent.dispatch(self, args);\r
+\r
+                       return args.content;\r
+               },\r
+\r
+               isDirty : function() {\r
+                       var self = this;\r
+\r
+                       return tinymce.trim(self.startContent) != tinymce.trim(self.getContent({format : 'raw', no_events : 1})) && !self.isNotDirty;\r
+               },\r
+\r
+               getContainer : function() {\r
+                       var t = this;\r
+\r
+                       if (!t.container)\r
+                               t.container = DOM.get(t.editorContainer || t.id + '_parent');\r
+\r
+                       return t.container;\r
+               },\r
+\r
+               getContentAreaContainer : function() {\r
+                       return this.contentAreaContainer;\r
+               },\r
+\r
+               getElement : function() {\r
+                       return DOM.get(this.settings.content_element || this.id);\r
+               },\r
+\r
+               getWin : function() {\r
+                       var t = this, e;\r
+\r
+                       if (!t.contentWindow) {\r
+                               e = DOM.get(t.id + "_ifr");\r
+\r
+                               if (e)\r
+                                       t.contentWindow = e.contentWindow;\r
+                       }\r
+\r
+                       return t.contentWindow;\r
+               },\r
+\r
+               getDoc : function() {\r
+                       var t = this, w;\r
+\r
+                       if (!t.contentDocument) {\r
+                               w = t.getWin();\r
+\r
+                               if (w)\r
+                                       t.contentDocument = w.document;\r
+                       }\r
+\r
+                       return t.contentDocument;\r
+               },\r
+\r
+               getBody : function() {\r
+                       return this.bodyElement || this.getDoc().body;\r
+               },\r
+\r
+               convertURL : function(u, n, e) {\r
+                       var t = this, s = t.settings;\r
+\r
+                       // Use callback instead\r
+                       if (s.urlconverter_callback)\r
+                               return t.execCallback('urlconverter_callback', u, e, true, n);\r
+\r
+                       // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs\r
+                       if (!s.convert_urls || (e && e.nodeName == 'LINK') || u.indexOf('file:') === 0)\r
+                               return u;\r
+\r
+                       // Convert to relative\r
+                       if (s.relative_urls)\r
+                               return t.documentBaseURI.toRelative(u);\r
+\r
+                       // Convert to absolute\r
+                       u = t.documentBaseURI.toAbsolute(u, s.remove_script_host);\r
+\r
+                       return u;\r
+               },\r
+\r
+               addVisual : function(e) {\r
+                       var t = this, s = t.settings;\r
+\r
+                       e = e || t.getBody();\r
+\r
+                       if (!is(t.hasVisual))\r
+                               t.hasVisual = s.visual;\r
+\r
+                       each(t.dom.select('table,a', e), function(e) {\r
+                               var v;\r
+\r
+                               switch (e.nodeName) {\r
+                                       case 'TABLE':\r
+                                               v = t.dom.getAttrib(e, 'border');\r
+\r
+                                               if (!v || v == '0') {\r
+                                                       if (t.hasVisual)\r
+                                                               t.dom.addClass(e, s.visual_table_class);\r
+                                                       else\r
+                                                               t.dom.removeClass(e, s.visual_table_class);\r
+                                               }\r
+\r
+                                               return;\r
+\r
+                                       case 'A':\r
+                                               v = t.dom.getAttrib(e, 'name');\r
+\r
+                                               if (v) {\r
+                                                       if (t.hasVisual)\r
+                                                               t.dom.addClass(e, 'mceItemAnchor');\r
+                                                       else\r
+                                                               t.dom.removeClass(e, 'mceItemAnchor');\r
+                                               }\r
+\r
+                                               return;\r
+                               }\r
+                       });\r
+\r
+                       t.onVisualAid.dispatch(t, e, t.hasVisual);\r
+               },\r
+\r
+               remove : function() {\r
+                       var t = this, e = t.getContainer();\r
+\r
+                       t.removed = 1; // Cancels post remove event execution\r
+                       t.hide();\r
+\r
+                       t.execCallback('remove_instance_callback', t);\r
+                       t.onRemove.dispatch(t);\r
+\r
+                       // Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command\r
+                       t.onExecCommand.listeners = [];\r
+\r
+                       tinymce.remove(t);\r
+                       DOM.remove(e);\r
+               },\r
+\r
+               destroy : function(s) {\r
+                       var t = this;\r
+\r
+                       // One time is enough\r
+                       if (t.destroyed)\r
+                               return;\r
+\r
+                       if (!s) {\r
+                               tinymce.removeUnload(t.destroy);\r
+                               tinyMCE.onBeforeUnload.remove(t._beforeUnload);\r
+\r
+                               // Manual destroy\r
+                               if (t.theme && t.theme.destroy)\r
+                                       t.theme.destroy();\r
+\r
+                               // Destroy controls, selection and dom\r
+                               t.controlManager.destroy();\r
+                               t.selection.destroy();\r
+                               t.dom.destroy();\r
+\r
+                               // Remove all events\r
+\r
+                               // Don't clear the window or document if content editable\r
+                               // is enabled since other instances might still be present\r
+                               if (!t.settings.content_editable) {\r
+                                       Event.clear(t.getWin());\r
+                                       Event.clear(t.getDoc());\r
+                               }\r
+\r
+                               Event.clear(t.getBody());\r
+                               Event.clear(t.formElement);\r
+                       }\r
+\r
+                       if (t.formElement) {\r
+                               t.formElement.submit = t.formElement._mceOldSubmit;\r
+                               t.formElement._mceOldSubmit = null;\r
+                       }\r
+\r
+                       t.contentAreaContainer = t.formElement = t.container = t.settings.content_element = t.bodyElement = t.contentDocument = t.contentWindow = null;\r
+\r
+                       if (t.selection)\r
+                               t.selection = t.selection.win = t.selection.dom = t.selection.dom.doc = null;\r
+\r
+                       t.destroyed = 1;\r
+               },\r
+\r
+               // Internal functions\r
+\r
+               _addEvents : function() {\r
+                       // 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset\r
+                       var t = this, i, s = t.settings, dom = t.dom, lo = {\r
+                               mouseup : 'onMouseUp',\r
+                               mousedown : 'onMouseDown',\r
+                               click : 'onClick',\r
+                               keyup : 'onKeyUp',\r
+                               keydown : 'onKeyDown',\r
+                               keypress : 'onKeyPress',\r
+                               submit : 'onSubmit',\r
+                               reset : 'onReset',\r
+                               contextmenu : 'onContextMenu',\r
+                               dblclick : 'onDblClick',\r
+                               paste : 'onPaste' // Doesn't work in all browsers yet\r
+                       };\r
+\r
+                       function eventHandler(e, o) {\r
+                               var ty = e.type;\r
+\r
+                               // Don't fire events when it's removed\r
+                               if (t.removed)\r
+                                       return;\r
+\r
+                               // Generic event handler\r
+                               if (t.onEvent.dispatch(t, e, o) !== false) {\r
+                                       // Specific event handler\r
+                                       t[lo[e.fakeType || e.type]].dispatch(t, e, o);\r
+                               }\r
+                       };\r
+\r
+                       // Add DOM events\r
+                       each(lo, function(v, k) {\r
+                               switch (k) {\r
+                                       case 'contextmenu':\r
+                                               dom.bind(t.getDoc(), k, eventHandler);\r
+                                               break;\r
+\r
+                                       case 'paste':\r
+                                               dom.bind(t.getBody(), k, function(e) {\r
+                                                       eventHandler(e);\r
+                                               });\r
+                                               break;\r
+\r
+                                       case 'submit':\r
+                                       case 'reset':\r
+                                               dom.bind(t.getElement().form || DOM.getParent(t.id, 'form'), k, eventHandler);\r
+                                               break;\r
+\r
+                                       default:\r
+                                               dom.bind(s.content_editable ? t.getBody() : t.getDoc(), k, eventHandler);\r
+                               }\r
+                       });\r
+\r
+                       dom.bind(s.content_editable ? t.getBody() : (isGecko ? t.getDoc() : t.getWin()), 'focus', function(e) {\r
+                               t.focus(true);\r
+                       });\r
 \r
-       // Style attrib deleted\r
-       if (tinyMCE.isMSIE && value == null || value == '') {\r
-               var str = tinyMCE.serializeStyle(tinyMCE.parseStyle(elm.style.cssText));\r
-               elm.style.cssText = str;\r
-               elm.setAttribute("style", str);\r
-       }\r
-};\r
 \r
-TinyMCE.prototype.convertSpansToFonts = function(doc) {\r
-       var sizes = tinyMCE.getParam('font_size_style_values').replace(/\s+/, '').split(',');\r
+                       // Fixes bug where a specified document_base_uri could result in broken images\r
+                       // This will also fix drag drop of images in Gecko\r
+                       if (tinymce.isGecko) {\r
+                               dom.bind(t.getDoc(), 'DOMNodeInserted', function(e) {\r
+                                       var v;\r
 \r
-       var h = doc.body.innerHTML;\r
-       h = h.replace(/<span/gi, '<font');\r
-       h = h.replace(/<\/span/gi, '</font');\r
-       doc.body.innerHTML = h;\r
+                                       e = e.target;\r
 \r
-       var s = doc.getElementsByTagName("font");\r
-       for (var i=0; i<s.length; i++) {\r
-               var size = tinyMCE.trim(s[i].style.fontSize).toLowerCase();\r
-               var fSize = 0;\r
+                                       if (e.nodeType === 1 && e.nodeName === 'IMG' && (v = e.getAttribute('data-mce-src')))\r
+                                               e.src = t.documentBaseURI.toAbsolute(v);\r
+                               });\r
+                       }\r
 \r
-               for (var x=0; x<sizes.length; x++) {\r
-                       if (sizes[x] == size) {\r
-                               fSize = x + 1;\r
-                               break;\r
+                       // Set various midas options in Gecko\r
+                       if (isGecko) {\r
+                               function setOpts() {\r
+                                       var t = this, d = t.getDoc(), s = t.settings;\r
+\r
+                                       if (isGecko && !s.readonly) {\r
+                                               t._refreshContentEditable();\r
+\r
+                                               try {\r
+                                                       // Try new Gecko method\r
+                                                       d.execCommand("styleWithCSS", 0, false);\r
+                                               } catch (ex) {\r
+                                                       // Use old method\r
+                                                       if (!t._isHidden())\r
+                                                               try {d.execCommand("useCSS", 0, true);} catch (ex) {}\r
+                                               }\r
+\r
+                                               if (!s.table_inline_editing)\r
+                                                       try {d.execCommand('enableInlineTableEditing', false, false);} catch (ex) {}\r
+\r
+                                               if (!s.object_resizing)\r
+                                                       try {d.execCommand('enableObjectResizing', false, false);} catch (ex) {}\r
+                                       }\r
+                               };\r
+\r
+                               t.onBeforeExecCommand.add(setOpts);\r
+                               t.onMouseDown.add(setOpts);\r
                        }\r
-               }\r
 \r
-               if (fSize > 0) {\r
-                       tinyMCE.setAttrib(s[i], 'size', fSize);\r
-                       s[i].style.fontSize = '';\r
-               }\r
+                       t.onClick.add(function(ed, e) {\r
+                               e = e.target;\r
 \r
-               var fFace = s[i].style.fontFamily;\r
-               if (fFace != null && fFace != "") {\r
-                       tinyMCE.setAttrib(s[i], 'face', fFace);\r
-                       s[i].style.fontFamily = '';\r
-               }\r
+                               // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250\r
+                               // WebKit can't even do simple things like selecting an image\r
+                               // Needs tobe the setBaseAndExtend or it will fail to select floated images\r
+                               if (tinymce.isWebKit && e.nodeName == 'IMG')\r
+                                       t.selection.getSel().setBaseAndExtent(e, 0, e, 1);\r
 \r
-               var fColor = s[i].style.color;\r
-               if (fColor != null && fColor != "") {\r
-                       tinyMCE.setAttrib(s[i], 'color', tinyMCE.convertRGBToHex(fColor));\r
-                       s[i].style.color = '';\r
-               }\r
-       }\r
-};\r
+                               if (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor'))\r
+                                       t.selection.select(e);\r
+\r
+                               t.nodeChanged();\r
+                       });\r
 \r
-TinyMCE.prototype.convertFontsToSpans = function(doc) {\r
-       var sizes = tinyMCE.getParam('font_size_style_values').replace(/\s+/, '').split(',');\r
+                       // Add node change handlers\r
+                       t.onMouseUp.add(t.nodeChanged);\r
+                       //t.onClick.add(t.nodeChanged);\r
+                       t.onKeyUp.add(function(ed, e) {\r
+                               var c = e.keyCode;\r
 \r
-       var h = doc.body.innerHTML;\r
-       h = h.replace(/<font/gi, '<span');\r
-       h = h.replace(/<\/font/gi, '</span');\r
-       doc.body.innerHTML = h;\r
+                               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)\r
+                                       t.nodeChanged();\r
+                       });\r
 \r
-       var fsClasses = tinyMCE.getParam('font_size_classes');\r
-       if (fsClasses != '')\r
-               fsClasses = fsClasses.replace(/\s+/, '').split(',');\r
-       else\r
-               fsClasses = null;\r
 \r
-       var s = doc.getElementsByTagName("span");\r
-       for (var i=0; i<s.length; i++) {\r
-               var fSize, fFace, fColor;\r
+                       // Add block quote deletion handler\r
+                       t.onKeyDown.add(function(ed, e) {\r
+                               // Was the BACKSPACE key pressed?\r
+                               if (e.keyCode != 8)\r
+                                       return;\r
 \r
-               fSize = tinyMCE.getAttrib(s[i], 'size');\r
-               fFace = tinyMCE.getAttrib(s[i], 'face');\r
-               fColor = tinyMCE.getAttrib(s[i], 'color');\r
+                               var n = ed.selection.getRng().startContainer;\r
+                               var offset = ed.selection.getRng().startOffset;\r
+\r
+                               while (n && n.nodeType && n.nodeType != 1 && n.parentNode)\r
+                                       n = n.parentNode;\r
+                                       \r
+                               // Is the cursor at the beginning of a blockquote?\r
+                               if (n && n.parentNode && n.parentNode.tagName === 'BLOCKQUOTE' && n.parentNode.firstChild == n && offset == 0) {\r
+                                       // Remove the blockquote\r
+                                       ed.formatter.toggle('blockquote', null, n.parentNode);\r
+\r
+                                       // Move the caret to the beginning of n\r
+                                       var rng = ed.selection.getRng();\r
+                                       rng.setStart(n, 0);\r
+                                       rng.setEnd(n, 0);\r
+                                       ed.selection.setRng(rng);\r
+                                       ed.selection.collapse(false);\r
+                               }\r
+                       });\r
\r
 \r
-               if (fSize != "") {\r
-                       fSize = parseInt(fSize);\r
 \r
-                       if (fSize > 0 && fSize < 8) {\r
-                               if (fsClasses != null)\r
-                                       tinyMCE.setAttrib(s[i], 'class', fsClasses[fSize-1]);\r
-                               else\r
-                                       s[i].style.fontSize = sizes[fSize-1];\r
+                       // Add reset handler\r
+                       t.onReset.add(function() {\r
+                               t.setContent(t.startContent, {format : 'raw'});\r
+                       });\r
+\r
+                       // Add shortcuts\r
+                       if (s.custom_shortcuts) {\r
+                               if (s.custom_undo_redo_keyboard_shortcuts) {\r
+                                       t.addShortcut('ctrl+z', t.getLang('undo_desc'), 'Undo');\r
+                                       t.addShortcut('ctrl+y', t.getLang('redo_desc'), 'Redo');\r
+                               }\r
+\r
+                               // Add default shortcuts for gecko\r
+                               t.addShortcut('ctrl+b', t.getLang('bold_desc'), 'Bold');\r
+                               t.addShortcut('ctrl+i', t.getLang('italic_desc'), 'Italic');\r
+                               t.addShortcut('ctrl+u', t.getLang('underline_desc'), 'Underline');\r
+\r
+                               // BlockFormat shortcuts keys\r
+                               for (i=1; i<=6; i++)\r
+                                       t.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);\r
+\r
+                               t.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']);\r
+                               t.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']);\r
+                               t.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']);\r
+\r
+                               function find(e) {\r
+                                       var v = null;\r
+\r
+                                       if (!e.altKey && !e.ctrlKey && !e.metaKey)\r
+                                               return v;\r
+\r
+                                       each(t.shortcuts, function(o) {\r
+                                               if (tinymce.isMac && o.ctrl != e.metaKey)\r
+                                                       return;\r
+                                               else if (!tinymce.isMac && o.ctrl != e.ctrlKey)\r
+                                                       return;\r
+\r
+                                               if (o.alt != e.altKey)\r
+                                                       return;\r
+\r
+                                               if (o.shift != e.shiftKey)\r
+                                                       return;\r
+\r
+                                               if (e.keyCode == o.keyCode || (e.charCode && e.charCode == o.charCode)) {\r
+                                                       v = o;\r
+                                                       return false;\r
+                                               }\r
+                                       });\r
+\r
+                                       return v;\r
+                               };\r
+\r
+                               t.onKeyUp.add(function(ed, e) {\r
+                                       var o = find(e);\r
+\r
+                                       if (o)\r
+                                               return Event.cancel(e);\r
+                               });\r
+\r
+                               t.onKeyPress.add(function(ed, e) {\r
+                                       var o = find(e);\r
+\r
+                                       if (o)\r
+                                               return Event.cancel(e);\r
+                               });\r
+\r
+                               t.onKeyDown.add(function(ed, e) {\r
+                                       var o = find(e);\r
+\r
+                                       if (o) {\r
+                                               o.func.call(o.scope);\r
+                                               return Event.cancel(e);\r
+                                       }\r
+                               });\r
                        }\r
 \r
-                       s[i].removeAttribute('size');\r
-               }\r
+                       if (tinymce.isIE) {\r
+                               // Fix so resize will only update the width and height attributes not the styles of an image\r
+                               // It will also block mceItemNoResize items\r
+                               dom.bind(t.getDoc(), 'controlselect', function(e) {\r
+                                       var re = t.resizeInfo, cb;\r
 \r
-               if (fFace != "") {\r
-                       s[i].style.fontFamily = fFace;\r
-                       s[i].removeAttribute('face');\r
-               }\r
+                                       e = e.target;\r
 \r
-               if (fColor != "") {\r
-                       s[i].style.color = fColor;\r
-                       s[i].removeAttribute('color');\r
-               }\r
-       }\r
-};\r
+                                       // Don't do this action for non image elements\r
+                                       if (e.nodeName !== 'IMG')\r
+                                               return;\r
 \r
-/*\r
-TinyMCE.prototype.applyClassesToFonts = function(doc, size) {\r
-       var f = doc.getElementsByTagName("font");\r
-       for (var i=0; i<f.length; i++) {\r
-               var s = tinyMCE.getAttrib(f[i], "size");\r
+                                       if (re)\r
+                                               dom.unbind(re.node, re.ev, re.cb);\r
 \r
-               if (s != "")\r
-                       tinyMCE.setAttrib(f[i], 'class', "mceItemFont" + s);\r
-       }\r
+                                       if (!dom.hasClass(e, 'mceItemNoResize')) {\r
+                                               ev = 'resizeend';\r
+                                               cb = dom.bind(e, ev, function(e) {\r
+                                                       var v;\r
 \r
-       if (typeof(size) != "undefined") {\r
-               var css = "";\r
+                                                       e = e.target;\r
 \r
-               for (var x=0; x<doc.styleSheets.length; x++) {\r
-                       for (var i=0; i<doc.styleSheets[x].rules.length; i++) {\r
-                               if (doc.styleSheets[x].rules[i].selectorText == '#mceSpanFonts .mceItemFont' + size) {\r
-                                       css = doc.styleSheets[x].rules[i].style.cssText;\r
-                                       break;\r
-                               }\r
+                                                       if (v = dom.getStyle(e, 'width')) {\r
+                                                               dom.setAttrib(e, 'width', v.replace(/[^0-9%]+/g, ''));\r
+                                                               dom.setStyle(e, 'width', '');\r
+                                                       }\r
+\r
+                                                       if (v = dom.getStyle(e, 'height')) {\r
+                                                               dom.setAttrib(e, 'height', v.replace(/[^0-9%]+/g, ''));\r
+                                                               dom.setStyle(e, 'height', '');\r
+                                                       }\r
+                                               });\r
+                                       } else {\r
+                                               ev = 'resizestart';\r
+                                               cb = dom.bind(e, 'resizestart', Event.cancel, Event);\r
+                                       }\r
+\r
+                                       re = t.resizeInfo = {\r
+                                               node : e,\r
+                                               ev : ev,\r
+                                               cb : cb\r
+                                       };\r
+                               });\r
                        }\r
 \r
-                       if (css != "")\r
-                               break;\r
-               }\r
+                       if (tinymce.isOpera) {\r
+                               t.onClick.add(function(ed, e) {\r
+                                       Event.prevent(e);\r
+                               });\r
+                       }\r
 \r
-               if (doc.styleSheets[0].rules[0].selectorText == "FONT")\r
-                       doc.styleSheets[0].removeRule(0);\r
+                       // Add custom undo/redo handlers\r
+                       if (s.custom_undo_redo) {\r
+                               function addUndo() {\r
+                                       t.undoManager.typing = false;\r
+                                       t.undoManager.add();\r
+                               };\r
 \r
-               doc.styleSheets[0].addRule("FONT", css, 0);\r
-       }\r
-};\r
-*/\r
+                               dom.bind(t.getDoc(), 'focusout', function(e) {\r
+                                       if (!t.removed && t.undoManager.typing)\r
+                                               addUndo();\r
+                               });\r
 \r
-TinyMCE.prototype.setInnerHTML = function(e, h) {\r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera) {\r
-               e.innerHTML = tinyMCE.uniqueTag + h;\r
-               e.firstChild.removeNode(true);\r
-       } else {\r
-               h = this.fixGeckoBaseHREFBug(1, e, h);\r
-               e.innerHTML = h;\r
-               this.fixGeckoBaseHREFBug(2, e, h);\r
-       }\r
-};\r
+                               // Add undo level when contents is drag/dropped within the editor\r
+                               t.dom.bind(t.dom.getRoot(), 'dragend', function(e) {\r
+                                       addUndo();\r
+                               });\r
 \r
-TinyMCE.prototype.fixGeckoBaseHREFBug = function(m, e, h) {\r
-       if (tinyMCE.isGecko) {\r
-               if (m == 1) {\r
-                       h = h.replace(/\ssrc=/gi, " xsrc=");\r
-                       h = h.replace(/\shref=/gi, " xhref=");\r
+                               t.onKeyUp.add(function(ed, e) {\r
+                                       var keyCode = e.keyCode;\r
 \r
-                       return h;\r
-               } else {\r
-                       if (h.indexOf(' xsrc') != -1) {\r
-                               var n = e.getElementsByTagName("img");\r
-                               for (var i=0; i<n.length; i++) {\r
-                                       var xsrc = tinyMCE.getAttrib(n[i], "xsrc");\r
+                                       if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45 || e.ctrlKey)\r
+                                               addUndo();\r
+                               });\r
 \r
-                                       if (xsrc != "") {\r
-                                               n[i].src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], xsrc);\r
-                                               n[i].removeAttribute("xsrc");\r
+                               t.onKeyDown.add(function(ed, e) {\r
+                                       var keyCode = e.keyCode, sel;\r
+\r
+                                       if (keyCode == 8) {\r
+                                               sel = t.getDoc().selection;\r
+\r
+                                               // Fix IE control + backspace browser bug\r
+                                               if (sel && sel.createRange && sel.createRange().item) {\r
+                                                       t.undoManager.beforeChange();\r
+                                                       ed.dom.remove(sel.createRange().item(0));\r
+                                                       addUndo();\r
+\r
+                                                       return Event.cancel(e);\r
+                                               }\r
                                        }\r
-                               }\r
 \r
-                               // Select image form fields\r
-                               var n = e.getElementsByTagName("select");\r
-                               for (var i=0; i<n.length; i++) {\r
-                                       var xsrc = tinyMCE.getAttrib(n[i], "xsrc");\r
+                                       // Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter\r
+                                       if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45) {\r
+                                               // Add position before enter key is pressed, used by IE since it still uses the default browser behavior\r
+                                               // Todo: Remove this once we normalize enter behavior on IE\r
+                                               if (tinymce.isIE && keyCode == 13)\r
+                                                       t.undoManager.beforeChange();\r
+\r
+                                               if (t.undoManager.typing)\r
+                                                       addUndo();\r
 \r
-                                       if (xsrc != "") {\r
-                                               n[i].src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], xsrc);\r
-                                               n[i].removeAttribute("xsrc");\r
+                                               return;\r
                                        }\r
-                               }\r
 \r
-                               // iframes\r
-                               var n = e.getElementsByTagName("iframe");\r
-                               for (var i=0; i<n.length; i++) {\r
-                                       var xsrc = tinyMCE.getAttrib(n[i], "xsrc");\r
+                                       // If key isn't shift,ctrl,alt,capslock,metakey\r
+                                       if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !t.undoManager.typing) {\r
+                                               t.undoManager.beforeChange();\r
+                                               t.undoManager.typing = true;\r
+                                               t.undoManager.add();\r
+                                       }\r
+                               });\r
+\r
+                               t.onMouseDown.add(function() {\r
+                                       if (t.undoManager.typing)\r
+                                               addUndo();\r
+                               });\r
+                       }\r
 \r
-                                       if (xsrc != "") {\r
-                                               n[i].src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], xsrc);\r
-                                               n[i].removeAttribute("xsrc");\r
+                       // Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5\r
+                       // It only fires the nodeChange event every 50ms since it would other wise update the UI when you type and it hogs the CPU\r
+                       if (tinymce.isWebKit) {\r
+                               dom.bind(t.getDoc(), 'selectionchange', function() {\r
+                                       if (t.selectionTimer) {\r
+                                               clearTimeout(t.selectionTimer);\r
+                                               t.selectionTimer = 0;\r
                                        }\r
-                               }\r
+\r
+                                       t.selectionTimer = window.setTimeout(function() {\r
+                                               t.nodeChanged();\r
+                                       }, 50);\r
+                               });\r
                        }\r
 \r
-                       if (h.indexOf(' xhref') != -1) {\r
-                               var n = e.getElementsByTagName("a");\r
-                               for (var i=0; i<n.length; i++) {\r
-                                       var xhref = tinyMCE.getAttrib(n[i], "xhref");\r
+                       // Bug fix for FireFox keeping styles from end of selection instead of start.\r
+                       if (tinymce.isGecko) {\r
+                               function getAttributeApplyFunction() {\r
+                                       var template = t.dom.getAttribs(t.selection.getStart().cloneNode(false));\r
 \r
-                                       if (xhref != "") {\r
-                                               n[i].href = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], xhref);\r
-                                               n[i].removeAttribute("xhref");\r
-                                       }\r
+                                       return function() {\r
+                                               var target = t.selection.getStart();\r
+\r
+                                               if (target !== t.getBody()) {\r
+                                                       t.dom.removeAllAttribs(target);\r
+\r
+                                                       each(template, function(attr) {\r
+                                                               target.setAttributeNode(attr.cloneNode(true));\r
+                                                       });\r
+                                               }\r
+                                       };\r
                                }\r
-                       }\r
-               }\r
-       }\r
 \r
-       return h;\r
-};\r
+                               function isSelectionAcrossElements() {\r
+                                       var s = t.selection;\r
 \r
-TinyMCE.prototype.getOuterHTML = function(e) {\r
-       if (tinyMCE.isMSIE)\r
-               return e.outerHTML;\r
+                                       return !s.isCollapsed() && s.getStart() != s.getEnd();\r
+                               }\r
 \r
-       var d = e.ownerDocument.createElement("body");\r
-       d.appendChild(e);\r
-       return d.innerHTML;\r
-};\r
+                               t.onKeyPress.add(function(ed, e) {\r
+                                       var applyAttributes;\r
 \r
-TinyMCE.prototype.setOuterHTML = function(doc, e, h) {\r
-       if (tinyMCE.isMSIE) {\r
-               e.outerHTML = h;\r
-               return;\r
-       }\r
+                                       if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {\r
+                                               applyAttributes = getAttributeApplyFunction();\r
+                                               t.getDoc().execCommand('delete', false, null);\r
+                                               applyAttributes();\r
 \r
-       var d = e.ownerDocument.createElement("body");\r
-       d.innerHTML = h;\r
-       e.parentNode.replaceChild(d.firstChild, e);\r
-};\r
+                                               return Event.cancel(e);\r
+                                       }\r
+                               });\r
 \r
-TinyMCE.prototype.insertAfter = function(nc, rc){\r
-       if (rc.nextSibling)\r
-               rc.parentNode.insertBefore(nc, rc.nextSibling);\r
-       else\r
-               rc.parentNode.appendChild(nc);\r
-};\r
+                               t.dom.bind(t.getDoc(), 'cut', function(e) {\r
+                                       var applyAttributes;\r
 \r
-TinyMCE.prototype.cleanupAnchors = function(doc) {\r
-       var an = doc.getElementsByTagName("a");\r
+                                       if (isSelectionAcrossElements()) {\r
+                                               applyAttributes = getAttributeApplyFunction();\r
+                                               t.onKeyUp.addToTop(Event.cancel, Event);\r
 \r
-       for (var i=0; i<an.length; i++) {\r
-               if (tinyMCE.getAttrib(an[i], "name") != "") {\r
-                       var cn = an[i].childNodes;\r
-                       for (var x=cn.length-1; x>=0; x--)\r
-                               tinyMCE.insertAfter(cn[x], an[i]);\r
-               }\r
-       }\r
-};\r
+                                               setTimeout(function() {\r
+                                                       applyAttributes();\r
+                                                       t.onKeyUp.remove(Event.cancel, Event);\r
+                                               }, 0);\r
+                                       }\r
+                               });\r
+                       }\r
+               },\r
 \r
-TinyMCE.prototype._setHTML = function(doc, html_content) {\r
-       // Force closed anchors open\r
-       //html_content = html_content.replace(new RegExp('<a(.*?)/>', 'gi'), '<a$1></a>');\r
+               _refreshContentEditable : function() {\r
+                       var self = this, body, parent;\r
 \r
-       html_content = tinyMCE.cleanupHTMLCode(html_content);\r
+                       // Check if the editor was hidden and the re-initalize contentEditable mode by removing and adding the body again\r
+                       if (self._isHidden()) {\r
+                               body = self.getBody();\r
+                               parent = body.parentNode;\r
 \r
-       // Try innerHTML if it fails use pasteHTML in MSIE\r
-       try {\r
-               tinyMCE.setInnerHTML(doc.body, html_content);\r
-       } catch (e) {\r
-               if (this.isMSIE)\r
-                       doc.body.createTextRange().pasteHTML(html_content);\r
-       }\r
+                               parent.removeChild(body);\r
+                               parent.appendChild(body);\r
 \r
-       // Content duplication bug fix\r
-       if (tinyMCE.isMSIE && tinyMCE.settings['fix_content_duplication']) {\r
-               // Remove P elements in P elements\r
-               var paras = doc.getElementsByTagName("P");\r
-               for (var i=0; i<paras.length; i++) {\r
-                       var node = paras[i];\r
-                       while ((node = node.parentNode) != null) {\r
-                               if (node.nodeName == "P")\r
-                                       node.outerHTML = node.innerHTML;\r
+                               body.focus();\r
                        }\r
-               }\r
+               },\r
+\r
+               _isHidden : function() {\r
+                       var s;\r
 \r
-               // Content duplication bug fix (Seems to be word crap)\r
-               var html = doc.body.innerHTML;\r
-\r
-               if (html.indexOf('="mso') != -1) {\r
-                       for (var i=0; i<doc.body.all.length; i++) {\r
-                               var el = doc.body.all[i];\r
-                               el.removeAttribute("className","",0);\r
-                               el.removeAttribute("style","",0);\r
-                       }\r
-\r
-                       html = doc.body.innerHTML;\r
-                       html = tinyMCE.regexpReplace(html, "<o:p><\/o:p>", "<br />");\r
-                       html = tinyMCE.regexpReplace(html, "<o:p>&nbsp;<\/o:p>", "");\r
-                       html = tinyMCE.regexpReplace(html, "<st1:.*?>", "");\r
-                       html = tinyMCE.regexpReplace(html, "<p><\/p>", "");\r
-                       html = tinyMCE.regexpReplace(html, "<p><\/p>\r\n<p><\/p>", "");\r
-                       html = tinyMCE.regexpReplace(html, "<p>&nbsp;<\/p>", "<br />");\r
-                       html = tinyMCE.regexpReplace(html, "<p>\s*(<p>\s*)?", "<p>");\r
-                       html = tinyMCE.regexpReplace(html, "<\/p>\s*(<\/p>\s*)?", "</p>");\r
+                       if (!isGecko)\r
+                               return 0;\r
+\r
+                       // Weird, wheres that cursor selection?\r
+                       s = this.selection.getSel();\r
+                       return (!s || !s.rangeCount || s.rangeCount == 0);\r
                }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       // Added for compression purposes\r
+       var each = tinymce.each, undefined, TRUE = true, FALSE = false;\r
+\r
+       tinymce.EditorCommands = function(editor) {\r
+               var dom = editor.dom,\r
+                       selection = editor.selection,\r
+                       commands = {state: {}, exec : {}, value : {}},\r
+                       settings = editor.settings,\r
+                       formatter = editor.formatter,\r
+                       bookmark;\r
+\r
+               function execCommand(command, ui, value) {\r
+                       var func;\r
+\r
+                       command = command.toLowerCase();\r
+                       if (func = commands.exec[command]) {\r
+                               func(command, ui, value);\r
+                               return TRUE;\r
+                       }\r
 \r
-               // Always set the htmlText output\r
-               tinyMCE.setInnerHTML(doc.body, html);\r
-       }\r
+                       return FALSE;\r
+               };\r
 \r
-       tinyMCE.cleanupAnchors(doc);\r
+               function queryCommandState(command) {\r
+                       var func;\r
 \r
-       if (tinyMCE.getParam("convert_fonts_to_spans"))\r
-               tinyMCE.convertSpansToFonts(doc);\r
-};\r
+                       command = command.toLowerCase();\r
+                       if (func = commands.state[command])\r
+                               return func(command);\r
 \r
-TinyMCE.prototype.getImageSrc = function(str) {\r
-       var pos = -1;\r
+                       return -1;\r
+               };\r
 \r
-       if (!str)\r
-               return "";\r
+               function queryCommandValue(command) {\r
+                       var func;\r
 \r
-       if ((pos = str.indexOf('this.src=')) != -1) {\r
-               var src = str.substring(pos + 10);\r
+                       command = command.toLowerCase();\r
+                       if (func = commands.value[command])\r
+                               return func(command);\r
 \r
-               src = src.substring(0, src.indexOf('\''));\r
+                       return FALSE;\r
+               };\r
 \r
-               return src;\r
-       }\r
+               function addCommands(command_list, type) {\r
+                       type = type || 'exec';\r
 \r
-       return "";\r
-};\r
+                       each(command_list, function(callback, command) {\r
+                               each(command.toLowerCase().split(','), function(command) {\r
+                                       commands[type][command] = callback;\r
+                               });\r
+                       });\r
+               };\r
 \r
-TinyMCE.prototype._getElementById = function(element_id) {\r
-       var elm = document.getElementById(element_id);\r
-       if (!elm) {\r
-               // Check for element in forms\r
-               for (var j=0; j<document.forms.length; j++) {\r
-                       for (var k=0; k<document.forms[j].elements.length; k++) {\r
-                               if (document.forms[j].elements[k].name == element_id) {\r
-                                       elm = document.forms[j].elements[k];\r
-                                       break;\r
+               // Expose public methods\r
+               tinymce.extend(this, {\r
+                       execCommand : execCommand,\r
+                       queryCommandState : queryCommandState,\r
+                       queryCommandValue : queryCommandValue,\r
+                       addCommands : addCommands\r
+               });\r
+\r
+               // Private methods\r
+\r
+               function execNativeCommand(command, ui, value) {\r
+                       if (ui === undefined)\r
+                               ui = FALSE;\r
+\r
+                       if (value === undefined)\r
+                               value = null;\r
+\r
+                       return editor.getDoc().execCommand(command, ui, value);\r
+               };\r
+\r
+               function isFormatMatch(name) {\r
+                       return formatter.match(name);\r
+               };\r
+\r
+               function toggleFormat(name, value) {\r
+                       formatter.toggle(name, value ? {value : value} : undefined);\r
+               };\r
+\r
+               function storeSelection(type) {\r
+                       bookmark = selection.getBookmark(type);\r
+               };\r
+\r
+               function restoreSelection() {\r
+                       selection.moveToBookmark(bookmark);\r
+               };\r
+\r
+               // Add execCommand overrides\r
+               addCommands({\r
+                       // Ignore these, added for compatibility\r
+                       'mceResetDesignMode,mceBeginUndoLevel' : function() {},\r
+\r
+                       // Add undo manager logic\r
+                       'mceEndUndoLevel,mceAddUndoLevel' : function() {\r
+                               editor.undoManager.add();\r
+                       },\r
+\r
+                       'Cut,Copy,Paste' : function(command) {\r
+                               var doc = editor.getDoc(), failed;\r
+\r
+                               // Try executing the native command\r
+                               try {\r
+                                       execNativeCommand(command);\r
+                               } catch (ex) {\r
+                                       // Command failed\r
+                                       failed = TRUE;\r
                                }\r
-                       }\r
-               }\r
-       }\r
 \r
-       return elm;\r
-};\r
+                               // Present alert message about clipboard access not being available\r
+                               if (failed || !doc.queryCommandSupported(command)) {\r
+                                       if (tinymce.isGecko) {\r
+                                               editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) {\r
+                                                       if (state)\r
+                                                               open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank');\r
+                                               });\r
+                                       } else\r
+                                               editor.windowManager.alert(editor.getLang('clipboard_no_support'));\r
+                               }\r
+                       },\r
+\r
+                       // Override unlink command\r
+                       unlink : function(command) {\r
+                               if (selection.isCollapsed())\r
+                                       selection.select(selection.getNode());\r
+\r
+                               execNativeCommand(command);\r
+                               selection.collapse(FALSE);\r
+                       },\r
+\r
+                       // Override justify commands to use the text formatter engine\r
+                       'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {\r
+                               var align = command.substring(7);\r
+\r
+                               // Remove all other alignments first\r
+                               each('left,center,right,full'.split(','), function(name) {\r
+                                       if (align != name)\r
+                                               formatter.remove('align' + name);\r
+                               });\r
+\r
+                               toggleFormat('align' + align);\r
+                               execCommand('mceRepaint');\r
+                       },\r
+\r
+                       // Override list commands to fix WebKit bug\r
+                       'InsertUnorderedList,InsertOrderedList' : function(command) {\r
+                               var listElm, listParent;\r
+\r
+                               execNativeCommand(command);\r
+\r
+                               // WebKit produces lists within block elements so we need to split them\r
+                               // we will replace the native list creation logic to custom logic later on\r
+                               // TODO: Remove this when the list creation logic is removed\r
+                               listElm = dom.getParent(selection.getNode(), 'ol,ul');\r
+                               if (listElm) {\r
+                                       listParent = listElm.parentNode;\r
+\r
+                                       // If list is within a text block then split that block\r
+                                       if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {\r
+                                               storeSelection();\r
+                                               dom.split(listParent, listElm);\r
+                                               restoreSelection();\r
+                                       }\r
+                               }\r
+                       },\r
 \r
-TinyMCE.prototype.getEditorId = function(form_element) {\r
-       var inst = this.getInstanceById(form_element);\r
-       if (!inst)\r
-               return null;\r
+                       // Override commands to use the text formatter engine\r
+                       'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {\r
+                               toggleFormat(command);\r
+                       },\r
 \r
-       return inst.editorId;\r
-};\r
+                       // Override commands to use the text formatter engine\r
+                       'ForeColor,HiliteColor,FontName' : function(command, ui, value) {\r
+                               toggleFormat(command, value);\r
+                       },\r
 \r
-TinyMCE.prototype.getInstanceById = function(editor_id) {\r
-       var inst = this.instances[editor_id];\r
-       if (!inst) {\r
-               for (var n in tinyMCE.instances) {\r
-                       var instance = tinyMCE.instances[n];\r
-                       if (!tinyMCE.isInstance(instance))\r
-                               continue;\r
+                       FontSize : function(command, ui, value) {\r
+                               var fontClasses, fontSizes;\r
 \r
-                       if (instance.formTargetElementId == editor_id) {\r
-                               inst = instance;\r
-                               break;\r
-                       }\r
-               }\r
-       }\r
+                               // Convert font size 1-7 to styles\r
+                               if (value >= 1 && value <= 7) {\r
+                                       fontSizes = tinymce.explode(settings.font_size_style_values);\r
+                                       fontClasses = tinymce.explode(settings.font_size_classes);\r
 \r
-       return inst;\r
-};\r
+                                       if (fontClasses)\r
+                                               value = fontClasses[value - 1] || value;\r
+                                       else\r
+                                               value = fontSizes[value - 1] || value;\r
+                               }\r
 \r
-TinyMCE.prototype.queryInstanceCommandValue = function(editor_id, command) {\r
-       var inst = tinyMCE.getInstanceById(editor_id);\r
-       if (inst)\r
-               return inst.queryCommandValue(command);\r
+                               toggleFormat(command, value);\r
+                       },\r
 \r
-       return false;\r
-};\r
+                       RemoveFormat : function(command) {\r
+                               formatter.remove(command);\r
+                       },\r
 \r
-TinyMCE.prototype.queryInstanceCommandState = function(editor_id, command) {\r
-       var inst = tinyMCE.getInstanceById(editor_id);\r
-       if (inst)\r
-               return inst.queryCommandState(command);\r
+                       mceBlockQuote : function(command) {\r
+                               toggleFormat('blockquote');\r
+                       },\r
 \r
-       return null;\r
-};\r
+                       FormatBlock : function(command, ui, value) {\r
+                               return toggleFormat(value || 'p');\r
+                       },\r
 \r
-TinyMCE.prototype.setWindowArg = function(name, value) {\r
-       this.windowArgs[name] = value;\r
-};\r
+                       mceCleanup : function() {\r
+                               var bookmark = selection.getBookmark();\r
 \r
-TinyMCE.prototype.getWindowArg = function(name, default_value) {\r
-       return (typeof(this.windowArgs[name]) == "undefined") ? default_value : this.windowArgs[name];\r
-};\r
+                               editor.setContent(editor.getContent({cleanup : TRUE}), {cleanup : TRUE});\r
 \r
-TinyMCE.prototype.getCSSClasses = function(editor_id, doc) {\r
-       var output = new Array();\r
+                               selection.moveToBookmark(bookmark);\r
+                       },\r
 \r
-       // Is cached, use that\r
-       if (typeof(tinyMCE.cssClasses) != "undefined")\r
-               return tinyMCE.cssClasses;\r
+                       mceRemoveNode : function(command, ui, value) {\r
+                               var node = value || selection.getNode();\r
 \r
-       if (typeof(editor_id) == "undefined" && typeof(doc) == "undefined") {\r
-               var instance;\r
+                               // Make sure that the body node isn't removed\r
+                               if (node != editor.getBody()) {\r
+                                       storeSelection();\r
+                                       editor.dom.remove(node, TRUE);\r
+                                       restoreSelection();\r
+                               }\r
+                       },\r
 \r
-               for (var instanceName in tinyMCE.instances) {\r
-                       instance = tinyMCE.instances[instanceName];\r
-                       if (!tinyMCE.isInstance(instance))\r
-                               continue;\r
+                       mceSelectNodeDepth : function(command, ui, value) {\r
+                               var counter = 0;\r
 \r
-                       break;\r
-               }\r
+                               dom.getParent(selection.getNode(), function(node) {\r
+                                       if (node.nodeType == 1 && counter++ == value) {\r
+                                               selection.select(node);\r
+                                               return FALSE;\r
+                                       }\r
+                               }, editor.getBody());\r
+                       },\r
 \r
-               doc = instance.getDoc();\r
-       }\r
+                       mceSelectNode : function(command, ui, value) {\r
+                               selection.select(value);\r
+                       },\r
 \r
-       if (typeof(doc) == "undefined") {\r
-               var instance = tinyMCE.getInstanceById(editor_id);\r
-               doc = instance.getDoc();\r
-       }\r
+                       mceInsertContent : function(command, ui, value) {\r
+                               var parser, serializer, parentNode, rootNode, fragment, args,\r
+                                       marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement;\r
 \r
-       if (doc) {\r
-               var styles = tinyMCE.isMSIE ? doc.styleSheets : doc.styleSheets;\r
+                               // Setup parser and serializer\r
+                               parser = editor.parser;\r
+                               serializer = new tinymce.html.Serializer({}, editor.schema);\r
+                               bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>';\r
 \r
-               if (styles && styles.length > 0) {\r
-                       for (var x=0; x<styles.length; x++) {\r
-                               var csses = null;\r
+                               // Run beforeSetContent handlers on the HTML to be inserted\r
+                               args = {content: value, format: 'html'};\r
+                               selection.onBeforeSetContent.dispatch(selection, args);\r
+                               value = args.content;\r
 \r
-                               // Just ignore any errors\r
-                               eval("try {var csses = tinyMCE.isMSIE ? doc.styleSheets(" + x + ").rules : doc.styleSheets[" + x + "].cssRules;} catch(e) {}");\r
-                               if (!csses)\r
-                                       return new Array();\r
+                               // Add caret at end of contents if it's missing\r
+                               if (value.indexOf('{$caret}') == -1)\r
+                                       value += '{$caret}';\r
 \r
-                               for (var i=0; i<csses.length; i++) {\r
-                                       var selectorText = csses[i].selectorText;\r
+                               // Replace the caret marker with a span bookmark element\r
+                               value = value.replace(/\{\$caret\}/, bookmarkHtml);\r
 \r
-                                       // Can be multiple rules per selector\r
-                                       if (selectorText) {\r
-                                               var rules = selectorText.split(',');\r
-                                               for (var c=0; c<rules.length; c++) {\r
-                                                       // Invalid rule\r
-                                                       if (rules[c].indexOf(' ') != -1 || rules[c].indexOf(':') != -1 || rules[c].indexOf('mceItem') != -1)\r
-                                                               continue;\r
+                               // Insert node maker where we will insert the new HTML and get it's parent\r
+                               if (!selection.isCollapsed())\r
+                                       editor.getDoc().execCommand('Delete', false, null);\r
 \r
-                                                       if (rules[c] == "." + tinyMCE.settings['visual_table_class'])\r
-                                                               continue;\r
+                               parentNode = selection.getNode();\r
 \r
-                                                       // Is class rule\r
-                                                       if (rules[c].indexOf('.') != -1) {\r
-                                                               //alert(rules[c].substring(rules[c].indexOf('.')));\r
-                                                               output[output.length] = rules[c].substring(rules[c].indexOf('.')+1);\r
-                                                       }\r
+                               // Parse the fragment within the context of the parent node\r
+                               args = {context : parentNode.nodeName.toLowerCase()};\r
+                               fragment = parser.parse(value, args);\r
+\r
+                               // Move the caret to a more suitable location\r
+                               node = fragment.lastChild;\r
+                               if (node.attr('id') == 'mce_marker') {\r
+                                       marker = node;\r
+\r
+                                       for (node = node.prev; node; node = node.walk(true)) {\r
+                                               if (node.type == 3 || !dom.isBlock(node.name)) {\r
+                                                       node.parent.insert(marker, node, node.name === 'br');\r
+                                                       break;\r
                                                }\r
                                        }\r
                                }\r
-                       }\r
-               }\r
-       }\r
 \r
-       // Cache em\r
-       if (output.length > 0)\r
-               tinyMCE.cssClasses = output;\r
+                               // If parser says valid we can insert the contents into that parent\r
+                               if (!args.invalid) {\r
+                                       value = serializer.serialize(fragment);\r
 \r
-       return output;\r
-};\r
+                                       // Check if parent is empty or only has one BR element then set the innerHTML of that parent\r
+                                       node = parentNode.firstChild;\r
+                                       node2 = parentNode.lastChild;\r
+                                       if (!node || (node === node2 && node.nodeName === 'BR'))\r
+                                               dom.setHTML(parentNode, value);\r
+                                       else\r
+                                               selection.setContent(value);\r
+                               } else {\r
+                                       // If the fragment was invalid within that context then we need\r
+                                       // to parse and process the parent it's inserted into\r
 \r
-TinyMCE.prototype.regexpReplace = function(in_str, reg_exp, replace_str, opts) {\r
-       if (in_str == null)\r
-               return in_str;\r
+                                       // Insert bookmark node and get the parent\r
+                                       selection.setContent(bookmarkHtml);\r
+                                       parentNode = editor.selection.getNode();\r
+                                       rootNode = editor.getBody();\r
 \r
-       if (typeof(opts) == "undefined")\r
-               opts = 'g';\r
+                                       // Opera will return the document node when selection is in root\r
+                                       if (parentNode.nodeType == 9)\r
+                                               parentNode = node = rootNode;\r
+                                       else\r
+                                               node = parentNode;\r
 \r
-       var re = new RegExp(reg_exp, opts);\r
-       return in_str.replace(re, replace_str);\r
-};\r
+                                       // Find the ancestor just before the root element\r
+                                       while (node !== rootNode) {\r
+                                               parentNode = node;\r
+                                               node = node.parentNode;\r
+                                       }\r
 \r
-TinyMCE.prototype.trim = function(str) {\r
-       return str.replace(/^\s*|\s*$/g, "");\r
-};\r
+                                       // Get the outer/inner HTML depending on if we are in the root and parser and serialize that\r
+                                       value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);\r
+                                       value = serializer.serialize(\r
+                                               parser.parse(\r
+                                                       // Need to replace by using a function since $ in the contents would otherwise be a problem\r
+                                                       value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {\r
+                                                               return serializer.serialize(fragment);\r
+                                                       })\r
+                                               )\r
+                                       );\r
+\r
+                                       // Set the inner/outer HTML depending on if we are in the root or not\r
+                                       if (parentNode == rootNode)\r
+                                               dom.setHTML(rootNode, value);\r
+                                       else\r
+                                               dom.setOuterHTML(parentNode, value);\r
+                               }\r
 \r
-TinyMCE.prototype.cleanupEventStr = function(str) {\r
-       str = "" + str;\r
-       str = str.replace('function anonymous()\n{\n', '');\r
-       str = str.replace('\n}', '');\r
-       str = str.replace(/^return true;/gi, ''); // Remove event blocker\r
+                               marker = dom.get('mce_marker');\r
 \r
-       return str;\r
-};\r
+                               // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well\r
+                               nodeRect = dom.getRect(marker);\r
+                               viewPortRect = dom.getViewPort(editor.getWin());\r
 \r
-TinyMCE.prototype.getAbsPosition = function(node) {\r
-       var pos = new Object();\r
+                               // Check if node is out side the viewport if it is then scroll to it\r
+                               if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) ||\r
+                                       (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) {\r
+                                       viewportBodyElement = tinymce.isIE ? editor.getDoc().documentElement : editor.getBody();\r
+                                       viewportBodyElement.scrollLeft = nodeRect.x;\r
+                                       viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25;\r
+                               }\r
 \r
-       pos.absLeft = pos.absTop = 0;\r
+                               // Move selection before marker and remove it\r
+                               rng = dom.createRng();\r
 \r
-       var parentNode = node;\r
-       while (parentNode) {\r
-               pos.absLeft += parentNode.offsetLeft;\r
-               pos.absTop += parentNode.offsetTop;\r
+                               // If previous sibling is a text node set the selection to the end of that node\r
+                               node = marker.previousSibling;\r
+                               if (node && node.nodeType == 3) {\r
+                                       rng.setStart(node, node.nodeValue.length);\r
+                               } else {\r
+                                       // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node\r
+                                       rng.setStartBefore(marker);\r
+                                       rng.setEndBefore(marker);\r
+                               }\r
 \r
-               parentNode = parentNode.offsetParent;\r
-       }\r
+                               // Remove the marker node and set the new range\r
+                               dom.remove(marker);\r
+                               selection.setRng(rng);\r
+\r
+                               // Dispatch after event and add any visual elements needed\r
+                               selection.onSetContent.dispatch(selection, args);\r
+                               editor.addVisual();\r
+                       },\r
+\r
+                       mceInsertRawHTML : function(command, ui, value) {\r
+                               selection.setContent('tiny_mce_marker');\r
+                               editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value }));\r
+                       },\r
+\r
+                       mceSetContent : function(command, ui, value) {\r
+                               editor.setContent(value);\r
+                       },\r
+\r
+                       'Indent,Outdent' : function(command) {\r
+                               var intentValue, indentUnit, value;\r
+\r
+                               // Setup indent level\r
+                               intentValue = settings.indentation;\r
+                               indentUnit = /[a-z%]+$/i.exec(intentValue);\r
+                               intentValue = parseInt(intentValue);\r
+\r
+                               if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {\r
+                                       each(selection.getSelectedBlocks(), function(element) {\r
+                                               if (command == 'outdent') {\r
+                                                       value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue);\r
+                                                       dom.setStyle(element, 'paddingLeft', value ? value + indentUnit : '');\r
+                                               } else\r
+                                                       dom.setStyle(element, 'paddingLeft', (parseInt(element.style.paddingLeft || 0) + intentValue) + indentUnit);\r
+                                       });\r
+                               } else\r
+                                       execNativeCommand(command);\r
+                       },\r
 \r
-       return pos;\r
-};\r
+                       mceRepaint : function() {\r
+                               var bookmark;\r
 \r
-TinyMCE.prototype.getControlHTML = function(control_name) {\r
-       var themePlugins = tinyMCE.getParam('plugins', '', true, ',');\r
-       var templateFunction;\r
-\r
-       // Is it defined in any plugins\r
-       for (var i=themePlugins.length; i>=0; i--) {\r
-               templateFunction = 'TinyMCE_' + themePlugins[i] + "_getControlHTML";\r
-               if (eval("typeof(" + templateFunction + ")") != 'undefined') {\r
-                       var html = eval(templateFunction + "('" + control_name + "');");\r
-                       if (html != "")\r
-                               return tinyMCE.replaceVar(html, "pluginurl", tinyMCE.baseURL + "/plugins/" + themePlugins[i]);\r
-               }\r
-       }\r
+                               if (tinymce.isGecko) {\r
+                                       try {\r
+                                               storeSelection(TRUE);\r
 \r
-       return eval('TinyMCE_' + tinyMCE.settings['theme'] + "_getControlHTML" + "('" + control_name + "');");\r
-};\r
+                                               if (selection.getSel())\r
+                                                       selection.getSel().selectAllChildren(editor.getBody());\r
 \r
-TinyMCE.prototype._themeExecCommand = function(editor_id, element, command, user_interface, value) {\r
-       var themePlugins = tinyMCE.getParam('plugins', '', true, ',');\r
-       var templateFunction;\r
+                                               selection.collapse(TRUE);\r
+                                               restoreSelection();\r
+                                       } catch (ex) {\r
+                                               // Ignore\r
+                                       }\r
+                               }\r
+                       },\r
 \r
-       // Is it defined in any plugins\r
-       for (var i=themePlugins.length; i>=0; i--) {\r
-               templateFunction = 'TinyMCE_' + themePlugins[i] + "_execCommand";\r
-               if (eval("typeof(" + templateFunction + ")") != 'undefined') {\r
-                       if (eval(templateFunction + "(editor_id, element, command, user_interface, value);"))\r
-                               return true;\r
-               }\r
-       }\r
+                       mceToggleFormat : function(command, ui, value) {\r
+                               formatter.toggle(value);\r
+                       },\r
 \r
-       // Theme funtion\r
-       templateFunction = 'TinyMCE_' + tinyMCE.settings['theme'] + "_execCommand";\r
-       if (eval("typeof(" + templateFunction + ")") != 'undefined')\r
-               return eval(templateFunction + "(editor_id, element, command, user_interface, value);");\r
+                       InsertHorizontalRule : function() {\r
+                               editor.execCommand('mceInsertContent', false, '<hr />');\r
+                       },\r
 \r
-       // Pass to normal\r
-       return false;\r
-};\r
+                       mceToggleVisualAid : function() {\r
+                               editor.hasVisual = !editor.hasVisual;\r
+                               editor.addVisual();\r
+                       },\r
 \r
-TinyMCE.prototype._getThemeFunction = function(suffix, skip_plugins) {\r
-       if (skip_plugins)\r
-               return 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;\r
+                       mceReplaceContent : function(command, ui, value) {\r
+                               editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'})));\r
+                       },\r
 \r
-       var themePlugins = tinyMCE.getParam('plugins', '', true, ',');\r
-       var templateFunction;\r
+                       mceInsertLink : function(command, ui, value) {\r
+                               var anchor;\r
 \r
-       // Is it defined in any plugins\r
-       for (var i=themePlugins.length; i>=0; i--) {\r
-               templateFunction = 'TinyMCE_' + themePlugins[i] + suffix;\r
-               if (eval("typeof(" + templateFunction + ")") != 'undefined')\r
-                       return templateFunction;\r
-       }\r
+                               if (typeof(value) == 'string')\r
+                                       value = {href : value};\r
 \r
-       return 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;\r
-};\r
+                               anchor = dom.getParent(selection.getNode(), 'a');\r
 \r
+                               // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.\r
+                               value.href = value.href.replace(' ', '%20');\r
 \r
-TinyMCE.prototype.isFunc = function(func_name) {\r
-       if (func_name == null || func_name == "")\r
-               return false;\r
+                               // Remove existing links if there could be child links or that the href isn't specified\r
+                               if (!anchor || !value.href) {\r
+                                       formatter.remove('link');\r
+                               }               \r
 \r
-       return eval("typeof(" + func_name + ")") != "undefined";\r
-};\r
+                               // Apply new link to selection\r
+                               if (value.href) {\r
+                                       formatter.apply('link', value, anchor);\r
+                               }\r
+                       },\r
 \r
-TinyMCE.prototype.exec = function(func_name, args) {\r
-       var str = func_name + '(';\r
+                       selectAll : function() {\r
+                               var root = dom.getRoot(), rng = dom.createRng();\r
 \r
-       // Add all arguments\r
-       for (var i=3; i<args.length; i++) {\r
-               str += 'args[' + i + ']';\r
+                               rng.setStart(root, 0);\r
+                               rng.setEnd(root, root.childNodes.length);\r
 \r
-               if (i < args.length-1)\r
-                       str += ',';\r
-       }\r
+                               editor.selection.setRng(rng);\r
+                       }\r
+               });\r
 \r
-       str += ');';\r
+               // Add queryCommandState overrides\r
+               addCommands({\r
+                       // Override justify commands\r
+                       'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {\r
+                               return isFormatMatch('align' + command.substring(7));\r
+                       },\r
 \r
-       return eval(str);\r
-};\r
+                       'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {\r
+                               return isFormatMatch(command);\r
+                       },\r
+\r
+                       mceBlockQuote : function() {\r
+                               return isFormatMatch('blockquote');\r
+                       },\r
 \r
-TinyMCE.prototype.executeCallback = function(param, suffix, mode) {\r
-       switch (mode) {\r
-               // No chain\r
-               case 0:\r
-                       var state = false;\r
+                       Outdent : function() {\r
+                               var node;\r
 \r
-                       // Execute each plugin callback\r
-                       var plugins = tinyMCE.getParam('plugins', '', true, ',');\r
-                       for (var i=0; i<plugins.length; i++) {\r
-                               var func = "TinyMCE_" + plugins[i] + suffix;\r
-                               if (tinyMCE.isFunc(func)) {\r
-                                       tinyMCE.exec(func, this.executeCallback.arguments);\r
-                                       state = true;\r
+                               if (settings.inline_styles) {\r
+                                       if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0)\r
+                                               return TRUE;\r
+\r
+                                       if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0)\r
+                                               return TRUE;\r
                                }\r
-                       }\r
 \r
-                       // Execute theme callback\r
-                       var func = 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;\r
-                       if (tinyMCE.isFunc(func)) {\r
-                               tinyMCE.exec(func, this.executeCallback.arguments);\r
-                               state = true;\r
-                       }\r
+                               return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE'));\r
+                       },\r
 \r
-                       // Execute settings callback\r
-                       var func = tinyMCE.getParam(param, '');\r
-                       if (tinyMCE.isFunc(func)) {\r
-                               tinyMCE.exec(func, this.executeCallback.arguments);\r
-                               state = true;\r
+                       'InsertUnorderedList,InsertOrderedList' : function(command) {\r
+                               return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL');\r
                        }\r
+               }, 'state');\r
 \r
-                       return state;\r
+               // Add queryCommandValue overrides\r
+               addCommands({\r
+                       'FontSize,FontName' : function(command) {\r
+                               var value = 0, parent;\r
 \r
-               // Chain mode\r
-               case 1:\r
-                       // Execute each plugin callback\r
-                       var plugins = tinyMCE.getParam('plugins', '', true, ',');\r
-                       for (var i=0; i<plugins.length; i++) {\r
-                               var func = "TinyMCE_" + plugins[i] + suffix;\r
-                               if (tinyMCE.isFunc(func)) {\r
-                                       if (tinyMCE.exec(func, this.executeCallback.arguments))\r
-                                               return true;\r
+                               if (parent = dom.getParent(selection.getNode(), 'span')) {\r
+                                       if (command == 'fontsize')\r
+                                               value = parent.style.fontSize;\r
+                                       else\r
+                                               value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase();\r
                                }\r
+\r
+                               return value;\r
                        }\r
+               }, 'value');\r
 \r
-                       // Execute theme callback\r
-                       var func = 'TinyMCE_' + tinyMCE.settings['theme'] + suffix;\r
-                       if (tinyMCE.isFunc(func)) {\r
-                               if (tinyMCE.exec(func, this.executeCallback.arguments))\r
-                                       return true;\r
+               // Add undo manager logic\r
+               if (settings.custom_undo_redo) {\r
+                       addCommands({\r
+                               Undo : function() {\r
+                                       editor.undoManager.undo();\r
+                               },\r
+\r
+                               Redo : function() {\r
+                                       editor.undoManager.redo();\r
+                               }\r
+                       });\r
+               }\r
+       };\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var Dispatcher = tinymce.util.Dispatcher;\r
+\r
+       tinymce.UndoManager = function(editor) {\r
+               var self, index = 0, data = [], beforeBookmark;\r
+\r
+               function getContent() {\r
+                       return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}));\r
+               };\r
+\r
+               return self = {\r
+                       typing : false,\r
+\r
+                       onAdd : new Dispatcher(self),\r
+\r
+                       onUndo : new Dispatcher(self),\r
+\r
+                       onRedo : new Dispatcher(self),\r
+\r
+                       beforeChange : function() {\r
+                               beforeBookmark = editor.selection.getBookmark(2, true);\r
+                       },\r
+\r
+                       add : function(level) {\r
+                               var i, settings = editor.settings, lastLevel;\r
+\r
+                               level = level || {};\r
+                               level.content = getContent();\r
+\r
+                               // Add undo level if needed\r
+                               lastLevel = data[index];\r
+                               if (lastLevel && lastLevel.content == level.content)\r
+                                       return null;\r
+\r
+                               // Set before bookmark on previous level\r
+                               if (data[index])\r
+                                       data[index].beforeBookmark = beforeBookmark;\r
+\r
+                               // Time to compress\r
+                               if (settings.custom_undo_redo_levels) {\r
+                                       if (data.length > settings.custom_undo_redo_levels) {\r
+                                               for (i = 0; i < data.length - 1; i++)\r
+                                                       data[i] = data[i + 1];\r
+\r
+                                               data.length--;\r
+                                               index = data.length;\r
+                                       }\r
+                               }\r
+\r
+                               // Get a non intrusive normalized bookmark\r
+                               level.bookmark = editor.selection.getBookmark(2, true);\r
+\r
+                               // Crop array if needed\r
+                               if (index < data.length - 1)\r
+                                       data.length = index + 1;\r
+\r
+                               data.push(level);\r
+                               index = data.length - 1;\r
+\r
+                               self.onAdd.dispatch(self, level);\r
+                               editor.isNotDirty = 0;\r
+\r
+                               return level;\r
+                       },\r
+\r
+                       undo : function() {\r
+                               var level, i;\r
+\r
+                               if (self.typing) {\r
+                                       self.add();\r
+                                       self.typing = false;\r
+                               }\r
+\r
+                               if (index > 0) {\r
+                                       level = data[--index];\r
+\r
+                                       editor.setContent(level.content, {format : 'raw'});\r
+                                       editor.selection.moveToBookmark(level.beforeBookmark);\r
+\r
+                                       self.onUndo.dispatch(self, level);\r
+                               }\r
+\r
+                               return level;\r
+                       },\r
+\r
+                       redo : function() {\r
+                               var level;\r
+\r
+                               if (index < data.length - 1) {\r
+                                       level = data[++index];\r
+\r
+                                       editor.setContent(level.content, {format : 'raw'});\r
+                                       editor.selection.moveToBookmark(level.bookmark);\r
+\r
+                                       self.onRedo.dispatch(self, level);\r
+                               }\r
+\r
+                               return level;\r
+                       },\r
+\r
+                       clear : function() {\r
+                               data = [];\r
+                               index = 0;\r
+                               self.typing = false;\r
+                       },\r
+\r
+                       hasUndo : function() {\r
+                               return index > 0 || this.typing;\r
+                       },\r
+\r
+                       hasRedo : function() {\r
+                               return index < data.length - 1 && !this.typing;\r
                        }\r
+               };\r
+       };\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       // Shorten names\r
+       var Event = tinymce.dom.Event,\r
+               isIE = tinymce.isIE,\r
+               isGecko = tinymce.isGecko,\r
+               isOpera = tinymce.isOpera,\r
+               each = tinymce.each,\r
+               extend = tinymce.extend,\r
+               TRUE = true,\r
+               FALSE = false;\r
+\r
+       function cloneFormats(node) {\r
+               var clone, temp, inner;\r
+\r
+               do {\r
+                       if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {\r
+                               if (clone) {\r
+                                       temp = node.cloneNode(false);\r
+                                       temp.appendChild(clone);\r
+                                       clone = temp;\r
+                               } else {\r
+                                       clone = inner = node.cloneNode(false);\r
+                               }\r
 \r
-                       // Execute settings callback\r
-                       var func = tinyMCE.getParam(param, '');\r
-                       if (tinyMCE.isFunc(func)) {\r
-                               if (tinyMCE.exec(func, this.executeCallback.arguments))\r
-                                       return true;\r
+                               clone.removeAttribute('id');\r
                        }\r
+               } while (node = node.parentNode);\r
 \r
-                       return false;\r
-       }\r
-};\r
+               if (clone)\r
+                       return {wrapper : clone, inner : inner};\r
+       };\r
+\r
+       // Checks if the selection/caret is at the end of the specified block element\r
+       function isAtEnd(rng, par) {\r
+               var rng2 = par.ownerDocument.createRange();\r
+\r
+               rng2.setStart(rng.endContainer, rng.endOffset);\r
+               rng2.setEndAfter(par);\r
+\r
+               // 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\r
+               return rng2.cloneContents().textContent.length == 0;\r
+       };\r
 \r
-TinyMCE.prototype.debug = function() {\r
-       var msg = "";\r
+       function splitList(selection, dom, li) {\r
+               var listBlock, block;\r
 \r
-       var elm = document.getElementById("tinymce_debug");\r
-       if (!elm) {\r
-               var debugDiv = document.createElement("div");\r
-               debugDiv.setAttribute("className", "debugger");\r
-               debugDiv.className = "debugger";\r
-               debugDiv.innerHTML = '\\r
-                       Debug output:\\r
-                       <textarea id="tinymce_debug" style="width: 100%; height: 300px" wrap="nowrap"></textarea>';\r
+               if (dom.isEmpty(li)) {\r
+                       listBlock = dom.getParent(li, 'ul,ol');\r
 \r
-               document.body.appendChild(debugDiv);\r
-               elm = document.getElementById("tinymce_debug");\r
-       }\r
+                       if (!dom.getParent(listBlock.parentNode, 'ul,ol')) {\r
+                               dom.split(listBlock, li);\r
+                               block = dom.create('p', 0, '<br data-mce-bogus="1" />');\r
+                               dom.replace(block, li);\r
+                               selection.select(block, 1);\r
+                       }\r
 \r
-       var args = this.debug.arguments;\r
-       for (var i=0; i<args.length; i++) {\r
-               msg += args[i];\r
-               if (i<args.length-1)\r
-                       msg += ', ';\r
-       }\r
+                       return FALSE;\r
+               }\r
 \r
-       elm.value += msg + "\n";\r
-};\r
+               return TRUE;\r
+       };\r
 \r
-// TinyMCEControl\r
-function TinyMCEControl(settings) {\r
-       // Undo levels\r
-       this.undoLevels = new Array();\r
-       this.undoIndex = 0;\r
-       this.typingUndoIndex = -1;\r
-       this.undoRedo = true;\r
-       this.isTinyMCEControl = true;\r
-\r
-       // Default settings\r
-       this.settings = settings;\r
-       this.settings['theme'] = tinyMCE.getParam("theme", "default");\r
-       this.settings['width'] = tinyMCE.getParam("width", -1);\r
-       this.settings['height'] = tinyMCE.getParam("height", -1);\r
-};\r
+       tinymce.create('tinymce.ForceBlocks', {\r
+               ForceBlocks : function(ed) {\r
+                       var t = this, s = ed.settings, elm;\r
 \r
-TinyMCEControl.prototype.repaint = function() {\r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera)\r
-               return;\r
+                       t.editor = ed;\r
+                       t.dom = ed.dom;\r
+                       elm = (s.forced_root_block || 'p').toLowerCase();\r
+                       s.element = elm.toUpperCase();\r
 \r
-       // Ugly mozilla hack to remove ghost resize handles\r
-       try {\r
-               this.getBody().style.display = 'none';\r
-               this.getDoc().execCommand('selectall', false, null);\r
-               this.getSel().collapseToStart();\r
-               this.getBody().style.display = 'block';\r
-       } catch (ex) {\r
-               // Could I care less!!\r
-       }\r
-};\r
+                       ed.onPreInit.add(t.setup, t);\r
+               },\r
 \r
-TinyMCEControl.prototype.switchSettings = function() {\r
-       if (tinyMCE.configs.length > 1 && tinyMCE.currentConfig != this.settings['index']) {\r
-               tinyMCE.settings = this.settings;\r
-               tinyMCE.currentConfig = this.settings['index'];\r
-       }\r
-};\r
+               setup : function() {\r
+                       var t = this, ed = t.editor, s = ed.settings, dom = ed.dom, selection = ed.selection, blockElements = ed.schema.getBlockElements();\r
 \r
-TinyMCEControl.prototype.convertAllRelativeURLs = function() {\r
-       var body = this.getBody();\r
+                       // Force root blocks\r
+                       if (s.forced_root_block) {\r
+                               function addRootBlocks() {\r
+                                       var node = selection.getStart(), rootNode = ed.getBody(), rng, startContainer, startOffset, endContainer, endOffset, rootBlockNode, tempNode, offset = -0xFFFFFF;\r
 \r
-       // Convert all image URL:s to absolute URL\r
-       var elms = body.getElementsByTagName("img");\r
-       for (var i=0; i<elms.length; i++) {\r
-               var src = tinyMCE.getAttrib(elms[i], 'src');\r
+                                       if (!node || node.nodeType !== 1)\r
+                                               return;\r
 \r
-               var msrc = tinyMCE.getAttrib(elms[i], 'mce_src');\r
-               if (msrc != "")\r
-                       src = msrc;\r
+                                       // Check if node is wrapped in block\r
+                                       while (node != rootNode) {\r
+                                               if (blockElements[node.nodeName])\r
+                                                       return;\r
 \r
-               if (src != "") {\r
-                       src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], src);\r
-                       elms[i].setAttribute("src", src);\r
-               }\r
-       }\r
+                                               node = node.parentNode;\r
+                                       }\r
 \r
-       // Convert all link URL:s to absolute URL\r
-       var elms = body.getElementsByTagName("a");\r
-       for (var i=0; i<elms.length; i++) {\r
-               var href = tinyMCE.getAttrib(elms[i], 'href');\r
+                                       // Get current selection\r
+                                       rng = selection.getRng();\r
+                                       if (rng.setStart) {\r
+                                               startContainer = rng.startContainer;\r
+                                               startOffset = rng.startOffset;\r
+                                               endContainer = rng.endContainer;\r
+                                               endOffset = rng.endOffset;\r
+                                       } else {\r
+                                               // Force control range into text range\r
+                                               if (rng.item) {\r
+                                                       rng = ed.getDoc().body.createTextRange();\r
+                                                       rng.moveToElementText(rng.item(0));\r
+                                               }\r
 \r
-               var mhref = tinyMCE.getAttrib(elms[i], 'mce_href');\r
-               if (mhref != "")\r
-                       href = mhref;\r
+                                               tmpRng = rng.duplicate();\r
+                                               tmpRng.collapse(true);\r
+                                               startOffset = tmpRng.move('character', offset) * -1;\r
 \r
-               if (href && href != "") {\r
-                       href = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], href);\r
-                       elms[i].setAttribute("href", href);\r
-               }\r
-       }\r
-};\r
+                                               if (!tmpRng.collapsed) {\r
+                                                       tmpRng = rng.duplicate();\r
+                                                       tmpRng.collapse(false);\r
+                                                       endOffset = (tmpRng.move('character', offset) * -1) - startOffset;\r
+                                               }\r
+                                       }\r
 \r
-TinyMCEControl.prototype.getSelectedHTML = function() {\r
-       if (tinyMCE.isSafari) {\r
-               // Not realy perfect!!\r
+                                       // Wrap non block elements and text nodes\r
+                                       for (node = rootNode.firstChild; node; node) {\r
+                                               if (node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName])) {\r
+                                                       if (!rootBlockNode) {\r
+                                                               rootBlockNode = dom.create(s.forced_root_block);\r
+                                                               node.parentNode.insertBefore(rootBlockNode, node);\r
+                                                       }\r
 \r
-               return this.getRng().toString();\r
-       }\r
+                                                       tempNode = node;\r
+                                                       node = node.nextSibling;\r
+                                                       rootBlockNode.appendChild(tempNode);\r
+                                               } else {\r
+                                                       rootBlockNode = null;\r
+                                                       node = node.nextSibling;\r
+                                               }\r
+                                       }\r
 \r
-       var elm = document.createElement("body");\r
+                                       if (rng.setStart) {\r
+                                               rng.setStart(startContainer, startOffset);\r
+                                               rng.setEnd(endContainer, endOffset);\r
+                                               selection.setRng(rng);\r
+                                       } else {\r
+                                               try {\r
+                                                       rng = ed.getDoc().body.createTextRange();\r
+                                                       rng.moveToElementText(rootNode);\r
+                                                       rng.collapse(true);\r
+                                                       rng.moveStart('character', startOffset);\r
+\r
+                                                       if (endOffset > 0)\r
+                                                               rng.moveEnd('character', endOffset);\r
+\r
+                                                       rng.select();\r
+                                               } catch (ex) {\r
+                                                       // Ignore\r
+                                               }\r
+                                       }\r
 \r
-       if (tinyMCE.isGecko)\r
-               elm.appendChild(this.getRng().cloneContents());\r
-       else\r
-               elm.innerHTML = this.getRng().htmlText;\r
+                                       ed.nodeChanged();\r
+                               };\r
 \r
-       return tinyMCE._cleanupHTML(this, this.contentDocument, this.settings, elm, this.visualAid);\r
-};\r
+                               ed.onKeyUp.add(addRootBlocks);\r
+                               ed.onClick.add(addRootBlocks);\r
+                       }\r
 \r
-TinyMCEControl.prototype.getBookmark = function() {\r
-       var rng = this.getRng();\r
+                       if (s.force_br_newlines) {\r
+                               // Force IE to produce BRs on enter\r
+                               if (isIE) {\r
+                                       ed.onKeyPress.add(function(ed, e) {\r
+                                               var n;\r
+\r
+                                               if (e.keyCode == 13 && selection.getNode().nodeName != 'LI') {\r
+                                                       selection.setContent('<br id="__" /> ', {format : 'raw'});\r
+                                                       n = dom.get('__');\r
+                                                       n.removeAttribute('id');\r
+                                                       selection.select(n);\r
+                                                       selection.collapse();\r
+                                                       return Event.cancel(e);\r
+                                               }\r
+                                       });\r
+                               }\r
+                       }\r
 \r
-       if (tinyMCE.isSafari)\r
-               return rng;\r
+                       if (s.force_p_newlines) {\r
+                               if (!isIE) {\r
+                                       ed.onKeyPress.add(function(ed, e) {\r
+                                               if (e.keyCode == 13 && !e.shiftKey && !t.insertPara(e))\r
+                                                       Event.cancel(e);\r
+                                       });\r
+                               } else {\r
+                                       // Ungly hack to for IE to preserve the formatting when you press\r
+                                       // enter at the end of a block element with formatted contents\r
+                                       // This logic overrides the browsers default logic with\r
+                                       // custom logic that enables us to control the output\r
+                                       tinymce.addUnload(function() {\r
+                                               t._previousFormats = 0; // Fix IE leak\r
+                                       });\r
+\r
+                                       ed.onKeyPress.add(function(ed, e) {\r
+                                               t._previousFormats = 0;\r
+\r
+                                               // Clone the current formats, this will later be applied to the new block contents\r
+                                               if (e.keyCode == 13 && !e.shiftKey && ed.selection.isCollapsed() && s.keep_styles)\r
+                                                       t._previousFormats = cloneFormats(ed.selection.getStart());\r
+                                       });\r
+\r
+                                       ed.onKeyUp.add(function(ed, e) {\r
+                                               // Let IE break the element and the wrap the new caret location in the previous formats\r
+                                               if (e.keyCode == 13 && !e.shiftKey) {\r
+                                                       var parent = ed.selection.getStart(), fmt = t._previousFormats;\r
+\r
+                                                       // Parent is an empty block\r
+                                                       if (!parent.hasChildNodes() && fmt) {\r
+                                                               parent = dom.getParent(parent, dom.isBlock);\r
+\r
+                                                               if (parent && parent.nodeName != 'LI') {\r
+                                                                       parent.innerHTML = '';\r
+\r
+                                                                       if (t._previousFormats) {\r
+                                                                               parent.appendChild(fmt.wrapper);\r
+                                                                               fmt.inner.innerHTML = '\uFEFF';\r
+                                                                       } else\r
+                                                                               parent.innerHTML = '\uFEFF';\r
+\r
+                                                                       selection.select(parent, 1);\r
+                                                                       selection.collapse(true);\r
+                                                                       ed.getDoc().execCommand('Delete', false, null);\r
+                                                                       t._previousFormats = 0;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
+                                       });\r
+                               }\r
 \r
-       if (tinyMCE.isMSIE)\r
-               return rng;\r
+                               if (isGecko) {\r
+                                       ed.onKeyDown.add(function(ed, e) {\r
+                                               if ((e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey)\r
+                                                       t.backspaceDelete(e, e.keyCode == 8);\r
+                                       });\r
+                               }\r
+                       }\r
 \r
-       if (tinyMCE.isGecko)\r
-               return rng.cloneRange();\r
+                       // Workaround for missing shift+enter support, http://bugs.webkit.org/show_bug.cgi?id=16973\r
+                       if (tinymce.isWebKit) {\r
+                               function insertBr(ed) {\r
+                                       var rng = selection.getRng(), br, div = dom.create('div', null, ' '), divYPos, vpHeight = dom.getViewPort(ed.getWin()).h;\r
 \r
-       return null;\r
-};\r
+                                       // Insert BR element\r
+                                       rng.insertNode(br = dom.create('br'));\r
 \r
-TinyMCEControl.prototype.moveToBookmark = function(bookmark) {\r
-       if (tinyMCE.isSafari) {\r
-               var sel = this.getSel().realSelection;\r
+                                       // Place caret after BR\r
+                                       rng.setStartAfter(br);\r
+                                       rng.setEndAfter(br);\r
+                                       selection.setRng(rng);\r
 \r
-               sel.setBaseAndExtent(bookmark.startContainer, bookmark.startOffset, bookmark.endContainer, bookmark.endOffset);\r
+                                       // Could not place caret after BR then insert an nbsp entity and move the caret\r
+                                       if (selection.getSel().focusNode == br.previousSibling) {\r
+                                               selection.select(dom.insertAfter(dom.doc.createTextNode('\u00a0'), br));\r
+                                               selection.collapse(TRUE);\r
+                                       }\r
 \r
-               return true;\r
-       }\r
+                                       // Create a temporary DIV after the BR and get the position as it\r
+                                       // seems like getPos() returns 0 for text nodes and BR elements.\r
+                                       dom.insertAfter(div, br);\r
+                                       divYPos = dom.getPos(div).y;\r
+                                       dom.remove(div);\r
+\r
+                                       // Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117\r
+                                       if (divYPos > vpHeight) // It is not necessary to scroll if the DIV is inside the view port.\r
+                                               ed.getWin().scrollTo(0, divYPos);\r
+                               };\r
+\r
+                               ed.onKeyPress.add(function(ed, e) {\r
+                                       if (e.keyCode == 13 && (e.shiftKey || (s.force_br_newlines && !dom.getParent(selection.getNode(), 'h1,h2,h3,h4,h5,h6,ol,ul')))) {\r
+                                               insertBr(ed);\r
+                                               Event.cancel(e);\r
+                                       }\r
+                               });\r
+                       }\r
 \r
-       if (tinyMCE.isMSIE)\r
-               return bookmark.select();\r
+                       // IE specific fixes\r
+                       if (isIE) {\r
+                               // Replaces IE:s auto generated paragraphs with the specified element name\r
+                               if (s.element != 'P') {\r
+                                       ed.onKeyPress.add(function(ed, e) {\r
+                                               t.lastElm = selection.getNode().nodeName;\r
+                                       });\r
+\r
+                                       ed.onKeyUp.add(function(ed, e) {\r
+                                               var bl, n = selection.getNode(), b = ed.getBody();\r
+\r
+                                               if (b.childNodes.length === 1 && n.nodeName == 'P') {\r
+                                                       n = dom.rename(n, s.element);\r
+                                                       selection.select(n);\r
+                                                       selection.collapse();\r
+                                                       ed.nodeChanged();\r
+                                               } else if (e.keyCode == 13 && !e.shiftKey && t.lastElm != 'P') {\r
+                                                       bl = dom.getParent(n, 'p');\r
+\r
+                                                       if (bl) {\r
+                                                               dom.rename(bl, s.element);\r
+                                                               ed.nodeChanged();\r
+                                                       }\r
+                                               }\r
+                                       });\r
+                               }\r
+                       }\r
+               },\r
 \r
-       if (tinyMCE.isGecko) {\r
-               var rng = this.getDoc().createRange();\r
-               var sel = this.getSel();\r
+               getParentBlock : function(n) {\r
+                       var d = this.dom;\r
 \r
-               rng.setStart(bookmark.startContainer, bookmark.startOffset);\r
-               rng.setEnd(bookmark.endContainer, bookmark.endOffset);\r
+                       return d.getParent(n, d.isBlock);\r
+               },\r
 \r
-               sel.removeAllRanges();\r
-               sel.addRange(rng);\r
+               insertPara : function(e) {\r
+                       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;\r
+                       var rb, ra, dir, sn, so, en, eo, sb, eb, bn, bef, aft, sc, ec, n, vp = dom.getViewPort(ed.getWin()), y, ch, car;\r
 \r
-               return true;\r
-       }\r
+                       ed.undoManager.beforeChange();\r
 \r
-       return false;\r
-};\r
+                       // If root blocks are forced then use Operas default behavior since it's really good\r
+// Removed due to bug: #1853816\r
+//                     if (se.forced_root_block && isOpera)\r
+//                             return TRUE;\r
 \r
-TinyMCEControl.prototype.getSelectedText = function() {\r
-       if (tinyMCE.isMSIE) {\r
-               var doc = this.getDoc();\r
+                       // Setup before range\r
+                       rb = d.createRange();\r
 \r
-               if (doc.selection.type == "Text") {\r
-                       var rng = doc.selection.createRange();\r
-                       selectedText = rng.text;\r
-               } else\r
-                       selectedText = '';\r
-       } else {\r
-               var sel = this.getSel();\r
+                       // If is before the first block element and in body, then move it into first block element\r
+                       rb.setStart(s.anchorNode, s.anchorOffset);\r
+                       rb.collapse(TRUE);\r
 \r
-               if (sel && sel.toString)\r
-                       selectedText = sel.toString();\r
-               else\r
-                       selectedText = '';\r
-       }\r
+                       // Setup after range\r
+                       ra = d.createRange();\r
 \r
-       return selectedText;\r
-};\r
+                       // If is before the first block element and in body, then move it into first block element\r
+                       ra.setStart(s.focusNode, s.focusOffset);\r
+                       ra.collapse(TRUE);\r
 \r
-TinyMCEControl.prototype.selectNode = function(node, collapse, select_text_node, to_start) {\r
-       if (!node)\r
-               return;\r
+                       // Setup start/end points\r
+                       dir = rb.compareBoundaryPoints(rb.START_TO_END, ra) < 0;\r
+                       sn = dir ? s.anchorNode : s.focusNode;\r
+                       so = dir ? s.anchorOffset : s.focusOffset;\r
+                       en = dir ? s.focusNode : s.anchorNode;\r
+                       eo = dir ? s.focusOffset : s.anchorOffset;\r
 \r
-       if (typeof(collapse) == "undefined")\r
-               collapse = true;\r
+                       // If selection is in empty table cell\r
+                       if (sn === en && /^(TD|TH)$/.test(sn.nodeName)) {\r
+                               if (sn.firstChild.nodeName == 'BR')\r
+                                       dom.remove(sn.firstChild); // Remove BR\r
 \r
-       if (typeof(select_text_node) == "undefined")\r
-               select_text_node = false;\r
+                               // Create two new block elements\r
+                               if (sn.childNodes.length == 0) {\r
+                                       ed.dom.add(sn, se.element, null, '<br />');\r
+                                       aft = ed.dom.add(sn, se.element, null, '<br />');\r
+                               } else {\r
+                                       n = sn.innerHTML;\r
+                                       sn.innerHTML = '';\r
+                                       ed.dom.add(sn, se.element, null, n);\r
+                                       aft = ed.dom.add(sn, se.element, null, '<br />');\r
+                               }\r
 \r
-       if (typeof(to_start) == "undefined")\r
-               to_start = true;\r
+                               // Move caret into the last one\r
+                               r = d.createRange();\r
+                               r.selectNodeContents(aft);\r
+                               r.collapse(1);\r
+                               ed.selection.setRng(r);\r
 \r
-       if (tinyMCE.isMSIE) {\r
-               var rng = this.getBody().createTextRange();\r
+                               return FALSE;\r
+                       }\r
 \r
-               try {\r
-                       rng.moveToElementText(node);\r
+                       // If the caret is in an invalid location in FF we need to move it into the first block\r
+                       if (sn == b && en == b && b.firstChild && ed.dom.isBlock(b.firstChild)) {\r
+                               sn = en = sn.firstChild;\r
+                               so = eo = 0;\r
+                               rb = d.createRange();\r
+                               rb.setStart(sn, 0);\r
+                               ra = d.createRange();\r
+                               ra.setStart(en, 0);\r
+                       }\r
 \r
-                       if (collapse)\r
-                               rng.collapse(to_start);\r
+                       // If the body is totally empty add a BR element this might happen on webkit\r
+                       if (!d.body.hasChildNodes()) {\r
+                               d.body.appendChild(dom.create('br'));\r
+                       }\r
 \r
-                       rng.select();\r
-               } catch (e) {\r
-                       // Throws illigal agrument in MSIE some times\r
-               }\r
-       } else {\r
-               var sel = this.getSel();\r
+                       // Never use body as start or end node\r
+                       sn = sn.nodeName == "HTML" ? d.body : sn; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes\r
+                       sn = sn.nodeName == "BODY" ? sn.firstChild : sn;\r
+                       en = en.nodeName == "HTML" ? d.body : en; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes\r
+                       en = en.nodeName == "BODY" ? en.firstChild : en;\r
 \r
-               if (!sel)\r
-                       return;\r
+                       // Get start and end blocks\r
+                       sb = t.getParentBlock(sn);\r
+                       eb = t.getParentBlock(en);\r
+                       bn = sb ? sb.nodeName : se.element; // Get block name to create\r
 \r
-               if (tinyMCE.isSafari) {\r
-                       sel.realSelection.setBaseAndExtent(node, 0, node, node.innerText.length);\r
+                       // Return inside list use default browser behavior\r
+                       if (n = t.dom.getParent(sb, 'li,pre')) {\r
+                               if (n.nodeName == 'LI')\r
+                                       return splitList(ed.selection, t.dom, n);\r
 \r
-                       if (collapse) {\r
-                               if (to_start)\r
-                                       sel.realSelection.collapseToStart();\r
-                               else\r
-                                       sel.realSelection.collapseToEnd();\r
+                               return TRUE;\r
                        }\r
 \r
-                       this.scrollToNode(node);\r
-\r
-                       return;\r
-               }\r
+                       // If caption or absolute layers then always generate new blocks within\r
+                       if (sb && (sb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {\r
+                               bn = se.element;\r
+                               sb = null;\r
+                       }\r
 \r
-               var rng = this.getDoc().createRange();\r
+                       // If caption or absolute layers then always generate new blocks within\r
+                       if (eb && (eb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {\r
+                               bn = se.element;\r
+                               eb = null;\r
+                       }\r
 \r
-               if (select_text_node) {\r
-                       // Find first textnode in tree\r
-                       var nodes = tinyMCE.getNodeTree(node, new Array(), 3);\r
-                       if (nodes.length > 0)\r
-                               rng.selectNodeContents(nodes[0]);\r
-                       else\r
-                               rng.selectNodeContents(node);\r
-               } else\r
-                       rng.selectNode(node);\r
+                       // Use P instead\r
+                       if (/(TD|TABLE|TH|CAPTION)/.test(bn) || (sb && bn == "DIV" && /left|right/gi.test(dom.getStyle(sb, 'float', 1)))) {\r
+                               bn = se.element;\r
+                               sb = eb = null;\r
+                       }\r
 \r
-               if (collapse) {\r
-                       // Special treatment of textnode collapse\r
-                       if (!to_start && node.nodeType == 3) {\r
-                               rng.setStart(node, node.nodeValue.length);\r
-                               rng.setEnd(node, node.nodeValue.length);\r
-                       } else\r
-                               rng.collapse(to_start);\r
-               }\r
+                       // Setup new before and after blocks\r
+                       bef = (sb && sb.nodeName == bn) ? sb.cloneNode(0) : ed.dom.create(bn);\r
+                       aft = (eb && eb.nodeName == bn) ? eb.cloneNode(0) : ed.dom.create(bn);\r
 \r
-               sel.removeAllRanges();\r
-               sel.addRange(rng);\r
-       }\r
+                       // Remove id from after clone\r
+                       aft.removeAttribute('id');\r
 \r
-       this.scrollToNode(node);\r
+                       // Is header and cursor is at the end, then force paragraph under\r
+                       if (/^(H[1-6])$/.test(bn) && isAtEnd(r, sb))\r
+                               aft = ed.dom.create(se.element);\r
 \r
-       // Set selected element\r
-       tinyMCE.selectedElement = null;\r
-       if (node.nodeType == 1)\r
-               tinyMCE.selectedElement = node;\r
-};\r
+                       // Find start chop node\r
+                       n = sc = sn;\r
+                       do {\r
+                               if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))\r
+                                       break;\r
 \r
-TinyMCEControl.prototype.scrollToNode = function(node) {\r
-       // Scroll to node position\r
-       var pos = tinyMCE.getAbsPosition(node);\r
-       var doc = this.getDoc();\r
-       var scrollX = doc.body.scrollLeft + doc.documentElement.scrollLeft;\r
-       var scrollY = doc.body.scrollTop + doc.documentElement.scrollTop;\r
-       var height = tinyMCE.isMSIE ? document.getElementById(this.editorId).style.pixelHeight : this.targetElement.clientHeight;\r
-\r
-       // Only scroll if out of visible area\r
-       if (!tinyMCE.settings['auto_resize'] && !(pos.absTop > scrollY && pos.absTop < (scrollY - 25 + height)))\r
-               this.contentWindow.scrollTo(pos.absLeft, pos.absTop - height + 25); \r
-};\r
+                               sc = n;\r
+                       } while ((n = n.previousSibling ? n.previousSibling : n.parentNode));\r
 \r
-TinyMCEControl.prototype.getBody = function() {\r
-       return this.getDoc().body;\r
-};\r
+                       // Find end chop node\r
+                       n = ec = en;\r
+                       do {\r
+                               if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))\r
+                                       break;\r
 \r
-TinyMCEControl.prototype.getDoc = function() {\r
-       return this.contentWindow.document;\r
-};\r
+                               ec = n;\r
+                       } while ((n = n.nextSibling ? n.nextSibling : n.parentNode));\r
 \r
-TinyMCEControl.prototype.getWin = function() {\r
-       return this.contentWindow;\r
-};\r
+                       // Place first chop part into before block element\r
+                       if (sc.nodeName == bn)\r
+                               rb.setStart(sc, 0);\r
+                       else\r
+                               rb.setStartBefore(sc);\r
 \r
-TinyMCEControl.prototype.getSel = function() {\r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera)\r
-               return this.getDoc().selection;\r
+                       rb.setEnd(sn, so);\r
+                       bef.appendChild(rb.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari\r
 \r
-       var sel = this.contentWindow.getSelection();\r
+                       // Place secnd chop part within new block element\r
+                       try {\r
+                               ra.setEndAfter(ec);\r
+                       } catch(ex) {\r
+                               //console.debug(s.focusNode, s.focusOffset);\r
+                       }\r
 \r
-       // Fake getRangeAt\r
-       if (tinyMCE.isSafari && !sel.getRangeAt) {\r
-               var newSel = new Object();\r
-               var doc = this.getDoc();\r
+                       ra.setStart(en, eo);\r
+                       aft.appendChild(ra.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari\r
 \r
-               function getRangeAt(idx) {\r
-                       var rng = new Object();\r
+                       // Create range around everything\r
+                       r = d.createRange();\r
+                       if (!sc.previousSibling && sc.parentNode.nodeName == bn) {\r
+                               r.setStartBefore(sc.parentNode);\r
+                       } else {\r
+                               if (rb.startContainer.nodeName == bn && rb.startOffset == 0)\r
+                                       r.setStartBefore(rb.startContainer);\r
+                               else\r
+                                       r.setStart(rb.startContainer, rb.startOffset);\r
+                       }\r
 \r
-                       rng.startContainer = this.focusNode;\r
-                       rng.endContainer = this.anchorNode;\r
-                       rng.commonAncestorContainer = this.focusNode;\r
-                       rng.createContextualFragment = function (html) {\r
-                               // Seems to be a tag\r
-                               if (html.charAt(0) == '<') {\r
-                                       var elm = doc.createElement("div");\r
+                       if (!ec.nextSibling && ec.parentNode.nodeName == bn)\r
+                               r.setEndAfter(ec.parentNode);\r
+                       else\r
+                               r.setEnd(ra.endContainer, ra.endOffset);\r
 \r
-                                       elm.innerHTML = html;\r
+                       // Delete and replace it with new block elements\r
+                       r.deleteContents();\r
 \r
-                                       return elm.firstChild;\r
-                               }\r
+                       if (isOpera)\r
+                               ed.getWin().scrollTo(0, vp.y);\r
 \r
-                               return doc.createTextNode("UNSUPPORTED, DUE TO LIMITATIONS IN SAFARI!");\r
-                       };\r
+                       // Never wrap blocks in blocks\r
+                       if (bef.firstChild && bef.firstChild.nodeName == bn)\r
+                               bef.innerHTML = bef.firstChild.innerHTML;\r
 \r
-                       rng.deleteContents = function () {\r
-                               doc.execCommand("Delete", false, "");\r
-                       };\r
+                       if (aft.firstChild && aft.firstChild.nodeName == bn)\r
+                               aft.innerHTML = aft.firstChild.innerHTML;\r
 \r
-                       return rng;\r
-               }\r
+                       function appendStyles(e, en) {\r
+                               var nl = [], nn, n, i;\r
 \r
-               // Patch selection\r
+                               e.innerHTML = '';\r
 \r
-               newSel.focusNode = sel.baseNode;\r
-               newSel.focusOffset = sel.baseOffset;\r
-               newSel.anchorNode = sel.extentNode;\r
-               newSel.anchorOffset = sel.extentOffset;\r
-               newSel.getRangeAt = getRangeAt;\r
-               newSel.text = "" + sel;\r
-               newSel.realSelection = sel;\r
+                               // Make clones of style elements\r
+                               if (se.keep_styles) {\r
+                                       n = en;\r
+                                       do {\r
+                                               // We only want style specific elements\r
+                                               if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(n.nodeName)) {\r
+                                                       nn = n.cloneNode(FALSE);\r
+                                                       dom.setAttrib(nn, 'id', ''); // Remove ID since it needs to be unique\r
+                                                       nl.push(nn);\r
+                                               }\r
+                                       } while (n = n.parentNode);\r
+                               }\r
 \r
-               newSel.toString = function () {return this.text;};\r
+                               // Append style elements to aft\r
+                               if (nl.length > 0) {\r
+                                       for (i = nl.length - 1, nn = e; i >= 0; i--)\r
+                                               nn = nn.appendChild(nl[i]);\r
 \r
-               return newSel;\r
-       }\r
+                                       // Padd most inner style element\r
+                                       nl[0].innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there\r
+                                       return nl[0]; // Move caret to most inner element\r
+                               } else\r
+                                       e.innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there\r
+                       };\r
+                               \r
+                       // Padd empty blocks\r
+                       if (dom.isEmpty(bef))\r
+                               appendStyles(bef, sn);\r
+\r
+                       // Fill empty afterblook with current style\r
+                       if (dom.isEmpty(aft))\r
+                               car = appendStyles(aft, en);\r
+\r
+                       // Opera needs this one backwards for older versions\r
+                       if (isOpera && parseFloat(opera.version()) < 9.5) {\r
+                               r.insertNode(bef);\r
+                               r.insertNode(aft);\r
+                       } else {\r
+                               r.insertNode(aft);\r
+                               r.insertNode(bef);\r
+                       }\r
 \r
-       return sel;\r
-};\r
+                       // Normalize\r
+                       aft.normalize();\r
+                       bef.normalize();\r
 \r
-TinyMCEControl.prototype.getRng = function() {\r
-       var sel = this.getSel();\r
-       if (sel == null)\r
-               return null;\r
+                       // Move cursor and scroll into view\r
+                       ed.selection.select(aft, true);\r
+                       ed.selection.collapse(true);\r
 \r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera)\r
-               return sel.createRange();\r
+                       // 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\r
+                       y = ed.dom.getPos(aft).y;\r
+                       //ch = aft.clientHeight;\r
 \r
-       if (tinyMCE.isSafari) {\r
-               var rng = this.getDoc().createRange();\r
-               var sel = this.getSel().realSelection;\r
+                       // Is element within viewport\r
+                       if (y < vp.y || y + 25 > vp.y + vp.h) {\r
+                               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\r
 \r
-               rng.setStart(sel.baseNode, sel.baseOffset);\r
-               rng.setEnd(sel.extentNode, sel.extentOffset);\r
+                               /*console.debug(\r
+                                       'Element: y=' + y + ', h=' + ch + ', ' +\r
+                                       'Viewport: y=' + vp.y + ", h=" + vp.h + ', bottom=' + (vp.y + vp.h)\r
+                               );*/\r
+                       }\r
 \r
-               return rng;\r
-       }\r
+                       ed.undoManager.add();\r
 \r
-       return this.getSel().getRangeAt(0);\r
-};\r
+                       return FALSE;\r
+               },\r
 \r
-TinyMCEControl.prototype._insertPara = function(e) {\r
-       function isEmpty(para) {\r
-               function isEmptyHTML(html) {\r
-                       return html.replace(new RegExp('[ \t\r\n]+', 'g'), '').toLowerCase() == "";\r
-               }\r
+               backspaceDelete : function(e, bs) {\r
+                       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;\r
 \r
-               // Check for images\r
-               if (para.getElementsByTagName("img").length > 0)\r
-                       return false;\r
+                       // Delete when caret is behind a element doesn't work correctly on Gecko see #3011651\r
+                       if (!bs && r.collapsed && sc.nodeType == 1 && r.startOffset == sc.childNodes.length) {\r
+                               walker = new tinymce.dom.TreeWalker(sc.lastChild, sc);\r
 \r
-               // Check for tables\r
-               if (para.getElementsByTagName("table").length > 0)\r
-                       return false;\r
+                               // Walk the dom backwards until we find a text node\r
+                               for (n = sc.lastChild; n; n = walker.prev()) {\r
+                                       if (n.nodeType == 3) {\r
+                                               r.setStart(n, n.nodeValue.length);\r
+                                               r.collapse(true);\r
+                                               se.setRng(r);\r
+                                               return;\r
+                                       }\r
+                               }\r
+                       }\r
 \r
-               // Check for HRs\r
-               if (para.getElementsByTagName("hr").length > 0)\r
-                       return false;\r
+                       // The caret sometimes gets stuck in Gecko if you delete empty paragraphs\r
+                       // This workaround removes the element by hand and moves the caret to the previous element\r
+                       if (sc && ed.dom.isBlock(sc) && !/^(TD|TH)$/.test(sc.nodeName) && bs) {\r
+                               if (sc.childNodes.length == 0 || (sc.childNodes.length == 1 && sc.firstChild.nodeName == 'BR')) {\r
+                                       // Find previous block element\r
+                                       n = sc;\r
+                                       while ((n = n.previousSibling) && !ed.dom.isBlock(n)) ;\r
+\r
+                                       if (n) {\r
+                                               if (sc != b.firstChild) {\r
+                                                       // Find last text node\r
+                                                       w = ed.dom.doc.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE);\r
+                                                       while (tn = w.nextNode())\r
+                                                               n = tn;\r
+\r
+                                                       // Place caret at the end of last text node\r
+                                                       r = ed.getDoc().createRange();\r
+                                                       r.setStart(n, n.nodeValue ? n.nodeValue.length : 0);\r
+                                                       r.setEnd(n, n.nodeValue ? n.nodeValue.length : 0);\r
+                                                       se.setRng(r);\r
+\r
+                                                       // Remove the target container\r
+                                                       ed.dom.remove(sc);\r
+                                               }\r
 \r
-               // Check all textnodes\r
-               var nodes = tinyMCE.getNodeTree(para, new Array(), 3);\r
-               for (var i=0; i<nodes.length; i++) {\r
-                       if (!isEmptyHTML(nodes[i].nodeValue))\r
-                               return false;\r
+                                               return Event.cancel(e);\r
+                                       }\r
+                               }\r
+                       }\r
                }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       // Shorten names\r
+       var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, extend = tinymce.extend;\r
+\r
+       tinymce.create('tinymce.ControlManager', {\r
+               ControlManager : function(ed, s) {\r
+                       var t = this, i;\r
+\r
+                       s = s || {};\r
+                       t.editor = ed;\r
+                       t.controls = {};\r
+                       t.onAdd = new tinymce.util.Dispatcher(t);\r
+                       t.onPostRender = new tinymce.util.Dispatcher(t);\r
+                       t.prefix = s.prefix || ed.id + '_';\r
+                       t._cls = {};\r
+\r
+                       t.onPostRender.add(function() {\r
+                               each(t.controls, function(c) {\r
+                                       c.postRender();\r
+                               });\r
+                       });\r
+               },\r
 \r
-               // No images, no tables, no hrs, no text content then it's empty\r
-               return true;\r
-       }\r
+               get : function(id) {\r
+                       return this.controls[this.prefix + id] || this.controls[id];\r
+               },\r
 \r
-       var doc = this.getDoc();\r
-       var sel = this.getSel();\r
-       var win = this.contentWindow;\r
-       var rng = sel.getRangeAt(0);\r
-       var body = doc.body;\r
-       var rootElm = doc.documentElement;\r
-       var self = this;\r
-       var blockName = "P";\r
+               setActive : function(id, s) {\r
+                       var c = null;\r
 \r
-//     tinyMCE.debug(body.innerHTML);\r
+                       if (c = this.get(id))\r
+                               c.setActive(s);\r
 \r
-//     debug(e.target, sel.anchorNode.nodeName, sel.focusNode.nodeName, rng.startContainer, rng.endContainer, rng.commonAncestorContainer, sel.anchorOffset, sel.focusOffset, rng.toString());\r
+                       return c;\r
+               },\r
 \r
-       // Setup before range\r
-       var rngBefore = doc.createRange();\r
-       rngBefore.setStart(sel.anchorNode, sel.anchorOffset);\r
-       rngBefore.collapse(true);\r
+               setDisabled : function(id, s) {\r
+                       var c = null;\r
 \r
-       // Setup after range\r
-       var rngAfter = doc.createRange();\r
-       rngAfter.setStart(sel.focusNode, sel.focusOffset);\r
-       rngAfter.collapse(true);\r
+                       if (c = this.get(id))\r
+                               c.setDisabled(s);\r
 \r
-       // Setup start/end points\r
-       var direct = rngBefore.compareBoundaryPoints(rngBefore.START_TO_END, rngAfter) < 0;\r
-       var startNode = direct ? sel.anchorNode : sel.focusNode;\r
-       var startOffset = direct ? sel.anchorOffset : sel.focusOffset;\r
-       var endNode = direct ? sel.focusNode : sel.anchorNode;\r
-       var endOffset = direct ? sel.focusOffset : sel.anchorOffset;\r
+                       return c;\r
+               },\r
 \r
-       startNode = startNode.nodeName == "BODY" ? startNode.firstChild : startNode;\r
-       endNode = endNode.nodeName == "BODY" ? endNode.firstChild : endNode;\r
+               add : function(c) {\r
+                       var t = this;\r
 \r
-       // tinyMCE.debug(startNode, endNode);\r
+                       if (c) {\r
+                               t.controls[c.id] = c;\r
+                               t.onAdd.dispatch(c, t);\r
+                       }\r
 \r
-       // Get block elements\r
-       var startBlock = tinyMCE.getParentBlockElement(startNode);\r
-       var endBlock = tinyMCE.getParentBlockElement(endNode);\r
+                       return c;\r
+               },\r
 \r
-       // Use current block name\r
-       if (startBlock != null) {\r
-               blockName = startBlock.nodeName;\r
+               createControl : function(n) {\r
+                       var c, t = this, ed = t.editor;\r
 \r
-               // Use P instead\r
-               if (blockName == "TD" || blockName == "TABLE" || (blockName == "DIV" && new RegExp('left|right', 'gi').test(startBlock.style.cssFloat)))\r
-                       blockName = "P";\r
-       }\r
+                       each(ed.plugins, function(p) {\r
+                               if (p.createControl) {\r
+                                       c = p.createControl(n, t);\r
 \r
-       // Within a list use normal behaviour\r
-       if (tinyMCE.getParentElement(startBlock, "OL,UL") != null)\r
-               return false;\r
+                                       if (c)\r
+                                               return false;\r
+                               }\r
+                       });\r
 \r
-       // Within a table create new paragraphs\r
-       if ((startBlock != null && startBlock.nodeName == "TABLE") || (endBlock != null && endBlock.nodeName == "TABLE"))\r
-               startBlock = endBlock = null;\r
+                       switch (n) {\r
+                               case "|":\r
+                               case "separator":\r
+                                       return t.createSeparator();\r
+                       }\r
 \r
-       // Setup new paragraphs\r
-       var paraBefore = (startBlock != null && startBlock.nodeName == blockName) ? startBlock.cloneNode(false) : doc.createElement(blockName);\r
-       var paraAfter = (endBlock != null && endBlock.nodeName == blockName) ? endBlock.cloneNode(false) : doc.createElement(blockName);\r
+                       if (!c && ed.buttons && (c = ed.buttons[n]))\r
+                               return t.createButton(n, c);\r
 \r
-       // Is header, then force paragraph under\r
-       if (/^(H[1-6])$/.test(blockName))\r
-               paraAfter = doc.createElement("p");\r
+                       return t.add(c);\r
+               },\r
 \r
-       // Setup chop nodes\r
-       var startChop = startNode;\r
-       var endChop = endNode;\r
+               createDropMenu : function(id, s, cc) {\r
+                       var t = this, ed = t.editor, c, bm, v, cls;\r
 \r
-       // Get startChop node\r
-       node = startChop;\r
-       do {\r
-               if (node == body || node.nodeType == 9 || tinyMCE.isBlockElement(node))\r
-                       break;\r
+                       s = extend({\r
+                               'class' : 'mceDropDown',\r
+                               constrain : ed.settings.constrain_menus\r
+                       }, s);\r
 \r
-               startChop = node;\r
-       } while ((node = node.previousSibling ? node.previousSibling : node.parentNode));\r
+                       s['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin';\r
+                       if (v = ed.getParam('skin_variant'))\r
+                               s['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1);\r
 \r
-       // Get endChop node\r
-       node = endChop;\r
-       do {\r
-               if (node == body || node.nodeType == 9 || tinyMCE.isBlockElement(node))\r
-                       break;\r
+                       id = t.prefix + id;\r
+                       cls = cc || t._cls.dropmenu || tinymce.ui.DropMenu;\r
+                       c = t.controls[id] = new cls(id, s);\r
+                       c.onAddItem.add(function(c, o) {\r
+                               var s = o.settings;\r
 \r
-               endChop = node;\r
-       } while ((node = node.nextSibling ? node.nextSibling : node.parentNode));\r
+                               s.title = ed.getLang(s.title, s.title);\r
 \r
-       // Fix when only a image is within the TD\r
-       if (startChop.nodeName == "TD")\r
-               startChop = startChop.firstChild;\r
+                               if (!s.onclick) {\r
+                                       s.onclick = function(v) {\r
+                                               if (s.cmd)\r
+                                                       ed.execCommand(s.cmd, s.ui || false, s.value);\r
+                                       };\r
+                               }\r
+                       });\r
 \r
-       if (endChop.nodeName == "TD")\r
-               endChop = endChop.lastChild;\r
+                       ed.onRemove.add(function() {\r
+                               c.destroy();\r
+                       });\r
 \r
-       // If not in a block element\r
-       if (startBlock == null) {\r
-               // Delete selection\r
-               rng.deleteContents();\r
-               sel.removeAllRanges();\r
+                       // Fix for bug #1897785, #1898007\r
+                       if (tinymce.isIE) {\r
+                               c.onShowMenu.add(function() {\r
+                                       // IE 8 needs focus in order to store away a range with the current collapsed caret location\r
+                                       ed.focus();\r
 \r
-               if (startChop != rootElm && endChop != rootElm) {\r
-                       // Insert paragraph before\r
-                       rngBefore = rng.cloneRange();\r
+                                       bm = ed.selection.getBookmark(1);\r
+                               });\r
 \r
-                       if (startChop == body)\r
-                               rngBefore.setStart(startChop, 0);\r
-                       else\r
-                               rngBefore.setStartBefore(startChop);\r
+                               c.onHideMenu.add(function() {\r
+                                       if (bm) {\r
+                                               ed.selection.moveToBookmark(bm);\r
+                                               bm = 0;\r
+                                       }\r
+                               });\r
+                       }\r
 \r
-                       paraBefore.appendChild(rngBefore.cloneContents());\r
+                       return t.add(c);\r
+               },\r
 \r
-                       // Insert paragraph after\r
-                       if (endChop.parentNode.nodeName == blockName)\r
-                               endChop = endChop.parentNode;\r
+               createListBox : function(id, s, cc) {\r
+                       var t = this, ed = t.editor, cmd, c, cls;\r
 \r
-                       // If not after image\r
-                       //if (rng.startContainer.nodeName != "BODY" && rng.endContainer.nodeName != "BODY")\r
-                               rng.setEndAfter(endChop);\r
+                       if (t.get(id))\r
+                               return null;\r
 \r
-                       if (endChop.nodeName != "#text" && endChop.nodeName != "BODY")\r
-                               rngBefore.setEndAfter(endChop);\r
+                       s.title = ed.translate(s.title);\r
+                       s.scope = s.scope || ed;\r
 \r
-                       var contents = rng.cloneContents();\r
-                       if (contents.firstChild && (contents.firstChild.nodeName == blockName || contents.firstChild.nodeName == "BODY"))\r
-                               paraAfter.innerHTML = contents.firstChild.innerHTML;\r
-                       else\r
-                               paraAfter.appendChild(contents);\r
+                       if (!s.onselect) {\r
+                               s.onselect = function(v) {\r
+                                       ed.execCommand(s.cmd, s.ui || false, v || s.value);\r
+                               };\r
+                       }\r
 \r
-                       // Check if it's a empty paragraph\r
-                       if (isEmpty(paraBefore))\r
-                               paraBefore.innerHTML = "&nbsp;";\r
+                       s = extend({\r
+                               title : s.title,\r
+                               'class' : 'mce_' + id,\r
+                               scope : s.scope,\r
+                               control_manager : t\r
+                       }, s);\r
 \r
-                       // Check if it's a empty paragraph\r
-                       if (isEmpty(paraAfter))\r
-                               paraAfter.innerHTML = "&nbsp;";\r
+                       id = t.prefix + id;\r
 \r
-                       // Delete old contents\r
-                       rng.deleteContents();\r
-                       rngAfter.deleteContents();\r
-                       rngBefore.deleteContents();\r
+                       if (ed.settings.use_native_selects)\r
+                               c = new tinymce.ui.NativeListBox(id, s);\r
+                       else {\r
+                               cls = cc || t._cls.listbox || tinymce.ui.ListBox;\r
+                               c = new cls(id, s, ed);\r
+                       }\r
 \r
-                       // Insert new paragraphs\r
-                       paraAfter.normalize();\r
-                       rngBefore.insertNode(paraAfter);\r
-                       paraBefore.normalize();\r
-                       rngBefore.insertNode(paraBefore);\r
+                       t.controls[id] = c;\r
+\r
+                       // Fix focus problem in Safari\r
+                       if (tinymce.isWebKit) {\r
+                               c.onPostRender.add(function(c, n) {\r
+                                       // Store bookmark on mousedown\r
+                                       Event.add(n, 'mousedown', function() {\r
+                                               ed.bookmark = ed.selection.getBookmark(1);\r
+                                       });\r
+\r
+                                       // Restore on focus, since it might be lost\r
+                                       Event.add(n, 'focus', function() {\r
+                                               ed.selection.moveToBookmark(ed.bookmark);\r
+                                               ed.bookmark = null;\r
+                                       });\r
+                               });\r
+                       }\r
 \r
-                       // tinyMCE.debug("1: ", paraBefore.innerHTML, paraAfter.innerHTML);\r
-               } else {\r
-                       body.innerHTML = "<" + blockName + ">&nbsp;</" + blockName + "><" + blockName + ">&nbsp;</" + blockName + ">";\r
-                       paraAfter = body.childNodes[1];\r
-               }\r
+                       if (c.hideMenu)\r
+                               ed.onMouseDown.add(c.hideMenu, c);\r
 \r
-               this.selectNode(paraAfter, true, true);\r
+                       return t.add(c);\r
+               },\r
 \r
-               return true;\r
-       }\r
+               createButton : function(id, s, cc) {\r
+                       var t = this, ed = t.editor, o, c, cls;\r
 \r
-       // Place first part within new paragraph\r
-       if (startChop.nodeName == blockName)\r
-               rngBefore.setStart(startChop, 0);\r
-       else\r
-               rngBefore.setStartBefore(startChop);\r
-\r
-       rngBefore.setEnd(startNode, startOffset);\r
-       paraBefore.appendChild(rngBefore.cloneContents());\r
-\r
-       // Place secound part within new paragraph\r
-       rngAfter.setEndAfter(endChop);\r
-       rngAfter.setStart(endNode, endOffset);\r
-       var contents = rngAfter.cloneContents();\r
-\r
-       if (contents.firstChild && contents.firstChild.nodeName == blockName) {\r
-/*             var nodes = contents.firstChild.childNodes;\r
-               for (var i=0; i<nodes.length; i++) {\r
-                       //tinyMCE.debug(nodes[i].nodeName);\r
-                       if (nodes[i].nodeName != "BODY")\r
-                               paraAfter.appendChild(nodes[i]);\r
-               }\r
-*/\r
-               paraAfter.innerHTML = contents.firstChild.innerHTML;\r
-       } else\r
-               paraAfter.appendChild(contents);\r
+                       if (t.get(id))\r
+                               return null;\r
 \r
-       // Check if it's a empty paragraph\r
-       if (isEmpty(paraBefore))\r
-               paraBefore.innerHTML = "&nbsp;";\r
+                       s.title = ed.translate(s.title);\r
+                       s.label = ed.translate(s.label);\r
+                       s.scope = s.scope || ed;\r
 \r
-       // Check if it's a empty paragraph\r
-       if (isEmpty(paraAfter))\r
-               paraAfter.innerHTML = "&nbsp;";\r
+                       if (!s.onclick && !s.menu_button) {\r
+                               s.onclick = function() {\r
+                                       ed.execCommand(s.cmd, s.ui || false, s.value);\r
+                               };\r
+                       }\r
 \r
-       // Create a range around everything\r
-       var rng = doc.createRange();\r
+                       s = extend({\r
+                               title : s.title,\r
+                               'class' : 'mce_' + id,\r
+                               unavailable_prefix : ed.getLang('unavailable', ''),\r
+                               scope : s.scope,\r
+                               control_manager : t\r
+                       }, s);\r
 \r
-       if (!startChop.previousSibling && startChop.parentNode.nodeName.toUpperCase() == blockName) {\r
-               rng.setStartBefore(startChop.parentNode);\r
-       } else {\r
-               if (rngBefore.startContainer.nodeName.toUpperCase() == blockName && rngBefore.startOffset == 0)\r
-                       rng.setStartBefore(rngBefore.startContainer);\r
-               else\r
-                       rng.setStart(rngBefore.startContainer, rngBefore.startOffset);\r
-       }\r
+                       id = t.prefix + id;\r
 \r
-       if (!endChop.nextSibling && endChop.parentNode.nodeName.toUpperCase() == blockName)\r
-               rng.setEndAfter(endChop.parentNode);\r
-       else\r
-               rng.setEnd(rngAfter.endContainer, rngAfter.endOffset);\r
+                       if (s.menu_button) {\r
+                               cls = cc || t._cls.menubutton || tinymce.ui.MenuButton;\r
+                               c = new cls(id, s, ed);\r
+                               ed.onMouseDown.add(c.hideMenu, c);\r
+                       } else {\r
+                               cls = t._cls.button || tinymce.ui.Button;\r
+                               c = new cls(id, s, ed);\r
+                       }\r
 \r
-       // Delete all contents and insert new paragraphs\r
-       rng.deleteContents();\r
-       rng.insertNode(paraAfter);\r
-       rng.insertNode(paraBefore);\r
-       //tinyMCE.debug("2", paraBefore.innerHTML, paraAfter.innerHTML);\r
+                       return t.add(c);\r
+               },\r
 \r
-       // Normalize\r
-       paraAfter.normalize();\r
-       paraBefore.normalize();\r
+               createMenuButton : function(id, s, cc) {\r
+                       s = s || {};\r
+                       s.menu_button = 1;\r
 \r
-       this.selectNode(paraAfter, true, true);\r
+                       return this.createButton(id, s, cc);\r
+               },\r
 \r
-       return true;\r
-};\r
+               createSplitButton : function(id, s, cc) {\r
+                       var t = this, ed = t.editor, cmd, c, cls;\r
 \r
-TinyMCEControl.prototype._handleBackSpace = function(evt_type) {\r
-       var doc = this.getDoc();\r
-       var sel = this.getSel();\r
-       if (sel == null)\r
-               return false;\r
+                       if (t.get(id))\r
+                               return null;\r
 \r
-       var rng = sel.getRangeAt(0);\r
-       var node = rng.startContainer;\r
-       var elm = node.nodeType == 3 ? node.parentNode : node;\r
+                       s.title = ed.translate(s.title);\r
+                       s.scope = s.scope || ed;\r
 \r
-       if (node == null)\r
-               return;\r
+                       if (!s.onclick) {\r
+                               s.onclick = function(v) {\r
+                                       ed.execCommand(s.cmd, s.ui || false, v || s.value);\r
+                               };\r
+                       }\r
 \r
-       // Empty node, wrap contents in paragraph\r
-       if (elm && elm.nodeName == "") {\r
-               var para = doc.createElement("p");\r
+                       if (!s.onselect) {\r
+                               s.onselect = function(v) {\r
+                                       ed.execCommand(s.cmd, s.ui || false, v || s.value);\r
+                               };\r
+                       }\r
 \r
-               while (elm.firstChild)\r
-                       para.appendChild(elm.firstChild);\r
+                       s = extend({\r
+                               title : s.title,\r
+                               'class' : 'mce_' + id,\r
+                               scope : s.scope,\r
+                               control_manager : t\r
+                       }, s);\r
 \r
-               elm.parentNode.insertBefore(para, elm);\r
-               elm.parentNode.removeChild(elm);\r
+                       id = t.prefix + id;\r
+                       cls = cc || t._cls.splitbutton || tinymce.ui.SplitButton;\r
+                       c = t.add(new cls(id, s, ed));\r
+                       ed.onMouseDown.add(c.hideMenu, c);\r
 \r
-               var rng = rng.cloneRange();\r
-               rng.setStartBefore(node.nextSibling);\r
-               rng.setEndAfter(node.nextSibling);\r
-               rng.extractContents();\r
+                       return c;\r
+               },\r
 \r
-               this.selectNode(node.nextSibling, true, true);\r
-       }\r
+               createColorSplitButton : function(id, s, cc) {\r
+                       var t = this, ed = t.editor, cmd, c, cls, bm;\r
 \r
-       // Remove empty paragraphs\r
-       var para = tinyMCE.getParentBlockElement(node);\r
-       if (para != null && para.nodeName.toLowerCase() == 'p' && evt_type == "keypress") {\r
-               var htm = para.innerHTML;\r
-               var block = tinyMCE.getParentBlockElement(node);\r
+                       if (t.get(id))\r
+                               return null;\r
 \r
-               // Empty node, we do the killing!!\r
-               if (htm == "" || htm == "&nbsp;" || block.nodeName.toLowerCase() == "li") {\r
-                       var prevElm = para.previousSibling;\r
+                       s.title = ed.translate(s.title);\r
+                       s.scope = s.scope || ed;\r
 \r
-                       while (prevElm != null && prevElm.nodeType != 1)\r
-                               prevElm = prevElm.previousSibling;\r
+                       if (!s.onclick) {\r
+                               s.onclick = function(v) {\r
+                                       if (tinymce.isIE)\r
+                                               bm = ed.selection.getBookmark(1);\r
 \r
-                       if (prevElm == null)\r
-                               return false;\r
+                                       ed.execCommand(s.cmd, s.ui || false, v || s.value);\r
+                               };\r
+                       }\r
 \r
-                       // Get previous elements last text node\r
-                       var nodes = tinyMCE.getNodeTree(prevElm, new Array(), 3);\r
-                       var lastTextNode = nodes.length == 0 ? null : nodes[nodes.length-1];\r
+                       if (!s.onselect) {\r
+                               s.onselect = function(v) {\r
+                                       ed.execCommand(s.cmd, s.ui || false, v || s.value);\r
+                               };\r
+                       }\r
 \r
-                       // Select the last text node and move curstor to end\r
-                       if (lastTextNode != null)\r
-                               this.selectNode(lastTextNode, true, false, false);\r
+                       s = extend({\r
+                               title : s.title,\r
+                               'class' : 'mce_' + id,\r
+                               'menu_class' : ed.getParam('skin') + 'Skin',\r
+                               scope : s.scope,\r
+                               more_colors_title : ed.getLang('more_colors')\r
+                       }, s);\r
+\r
+                       id = t.prefix + id;\r
+                       cls = cc || t._cls.colorsplitbutton || tinymce.ui.ColorSplitButton;\r
+                       c = new cls(id, s, ed);\r
+                       ed.onMouseDown.add(c.hideMenu, c);\r
+\r
+                       // Remove the menu element when the editor is removed\r
+                       ed.onRemove.add(function() {\r
+                               c.destroy();\r
+                       });\r
 \r
-                       // Remove the empty paragrapsh\r
-                       para.parentNode.removeChild(para);\r
+                       // Fix for bug #1897785, #1898007\r
+                       if (tinymce.isIE) {\r
+                               c.onShowMenu.add(function() {\r
+                                       // IE 8 needs focus in order to store away a range with the current collapsed caret location\r
+                                       ed.focus();\r
+                                       bm = ed.selection.getBookmark(1);\r
+                               });\r
+\r
+                               c.onHideMenu.add(function() {\r
+                                       if (bm) {\r
+                                               ed.selection.moveToBookmark(bm);\r
+                                               bm = 0;\r
+                                       }\r
+                               });\r
+                       }\r
 \r
-                       //debug("within p element" + para.innerHTML);\r
-                       //showHTML(this.getBody().innerHTML);\r
-                       return true;\r
-               }\r
-       }\r
+                       return t.add(c);\r
+               },\r
 \r
-       // Remove BR elements\r
-/*     while (node != null && (node = node.nextSibling) != null) {\r
-               if (node.nodeName.toLowerCase() == 'br')\r
-                       node.parentNode.removeChild(node);\r
-               else if (node.nodeType == 1) // Break at other element\r
-                       break;\r
-       }*/\r
+               createToolbar : function(id, s, cc) {\r
+                       var c, t = this, cls;\r
 \r
-       //showHTML(this.getBody().innerHTML);\r
+                       id = t.prefix + id;\r
+                       cls = cc || t._cls.toolbar || tinymce.ui.Toolbar;\r
+                       c = new cls(id, s, t.editor);\r
 \r
-       return false;\r
-};\r
+                       if (t.get(id))\r
+                               return null;\r
 \r
-TinyMCEControl.prototype._insertSpace = function() {\r
-       return true;\r
-};\r
+                       return t.add(c);\r
+               },\r
+               \r
+               createToolbarGroup : function(id, s, cc) {\r
+                       var c, t = this, cls;\r
+                       id = t.prefix + id;\r
+                       cls = cc || this._cls.toolbarGroup || tinymce.ui.ToolbarGroup;\r
+                       c = new cls(id, s, t.editor);\r
+                       \r
+                       if (t.get(id))\r
+                               return null;\r
+                       \r
+                       return t.add(c);\r
+               },\r
 \r
-TinyMCEControl.prototype.autoResetDesignMode = function() {\r
-       // Add fix for tab/style.display none/block problems in Gecko\r
-       if (!tinyMCE.isMSIE && tinyMCE.settings['auto_reset_designmode'] && this.isHidden())\r
-               eval('try { this.getDoc().designMode = "On"; } catch(e) {}');\r
-};\r
+               createSeparator : function(cc) {\r
+                       var cls = cc || this._cls.separator || tinymce.ui.Separator;\r
 \r
-TinyMCEControl.prototype.isHidden = function() {\r
-       if (tinyMCE.isMSIE)\r
-               return false;\r
+                       return new cls();\r
+               },\r
 \r
-       var sel = this.getSel();\r
+               setControlType : function(n, c) {\r
+                       return this._cls[n.toLowerCase()] = c;\r
+               },\r
+       \r
+               destroy : function() {\r
+                       each(this.controls, function(c) {\r
+                               c.destroy();\r
+                       });\r
 \r
-       // Weird, wheres that cursor selection?\r
-       return (!sel || !sel.rangeCount || sel.rangeCount == 0);\r
-};\r
+                       this.controls = null;\r
+               }\r
+       });\r
+})(tinymce);\r
+\r
+(function(tinymce) {\r
+       var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isIE = tinymce.isIE, isOpera = tinymce.isOpera;\r
+\r
+       tinymce.create('tinymce.WindowManager', {\r
+               WindowManager : function(ed) {\r
+                       var t = this;\r
+\r
+                       t.editor = ed;\r
+                       t.onOpen = new Dispatcher(t);\r
+                       t.onClose = new Dispatcher(t);\r
+                       t.params = {};\r
+                       t.features = {};\r
+               },\r
+\r
+               open : function(s, p) {\r
+                       var t = this, f = '', x, y, mo = t.editor.settings.dialog_type == 'modal', w, sw, sh, vp = tinymce.DOM.getViewPort(), u;\r
+\r
+                       // Default some options\r
+                       s = s || {};\r
+                       p = p || {};\r
+                       sw = isOpera ? vp.w : screen.width; // Opera uses windows inside the Opera window\r
+                       sh = isOpera ? vp.h : screen.height;\r
+                       s.name = s.name || 'mc_' + new Date().getTime();\r
+                       s.width = parseInt(s.width || 320);\r
+                       s.height = parseInt(s.height || 240);\r
+                       s.resizable = true;\r
+                       s.left = s.left || parseInt(sw / 2.0) - (s.width / 2.0);\r
+                       s.top = s.top || parseInt(sh / 2.0) - (s.height / 2.0);\r
+                       p.inline = false;\r
+                       p.mce_width = s.width;\r
+                       p.mce_height = s.height;\r
+                       p.mce_auto_focus = s.auto_focus;\r
+\r
+                       if (mo) {\r
+                               if (isIE) {\r
+                                       s.center = true;\r
+                                       s.help = false;\r
+                                       s.dialogWidth = s.width + 'px';\r
+                                       s.dialogHeight = s.height + 'px';\r
+                                       s.scroll = s.scrollbars || false;\r
+                               }\r
+                       }\r
 \r
-TinyMCEControl.prototype.isDirty = function() {\r
-       // Is content modified and not in a submit procedure\r
-       return this.startContent != tinyMCE.trim(this.getBody().innerHTML) && !tinyMCE.isNotDirty;\r
-};\r
+                       // Build features string\r
+                       each(s, function(v, k) {\r
+                               if (tinymce.is(v, 'boolean'))\r
+                                       v = v ? 'yes' : 'no';\r
 \r
-TinyMCEControl.prototype._mergeElements = function(scmd, pa, ch, override) {\r
-       if (scmd == "removeformat") {\r
-               pa.className = "";\r
-               pa.style.cssText = "";\r
-               ch.className = "";\r
-               ch.style.cssText = "";\r
-               return;\r
-       }\r
+                               if (!/^(name|url)$/.test(k)) {\r
+                                       if (isIE && mo)\r
+                                               f += (f ? ';' : '') + k + ':' + v;\r
+                                       else\r
+                                               f += (f ? ',' : '') + k + '=' + v;\r
+                               }\r
+                       });\r
 \r
-       var st = tinyMCE.parseStyle(tinyMCE.getAttrib(pa, "style"));\r
-       var stc = tinyMCE.parseStyle(tinyMCE.getAttrib(ch, "style"));\r
-       var className = tinyMCE.getAttrib(pa, "class");\r
+                       t.features = s;\r
+                       t.params = p;\r
+                       t.onOpen.dispatch(t, s, p);\r
 \r
-       className += " " + tinyMCE.getAttrib(ch, "class");\r
+                       u = s.url || s.file;\r
+                       u = tinymce._addVer(u);\r
 \r
-       if (override) {\r
-               for (var n in st) {\r
-                       if (typeof(st[n]) == 'function')\r
-                               continue;\r
+                       try {\r
+                               if (isIE && mo) {\r
+                                       w = 1;\r
+                                       window.showModalDialog(u, window, f);\r
+                               } else\r
+                                       w = window.open(u, s.name, f);\r
+                       } catch (ex) {\r
+                               // Ignore\r
+                       }\r
 \r
-                       stc[n] = st[n];\r
-               }\r
-       } else {\r
-               for (var n in stc) {\r
-                       if (typeof(stc[n]) == 'function')\r
-                               continue;\r
+                       if (!w)\r
+                               alert(t.editor.getLang('popup_blocked'));\r
+               },\r
 \r
-                       st[n] = stc[n];\r
-               }\r
-       }\r
+               close : function(w) {\r
+                       w.close();\r
+                       this.onClose.dispatch(this);\r
+               },\r
 \r
-       tinyMCE.setAttrib(pa, "style", tinyMCE.serializeStyle(st));\r
-       tinyMCE.setAttrib(pa, "class", tinyMCE.trim(className));\r
-       ch.className = "";\r
-       ch.style.cssText = "";\r
-       ch.removeAttribute("class");\r
-       ch.removeAttribute("style");\r
-};\r
+               createInstance : function(cl, a, b, c, d, e) {\r
+                       var f = tinymce.resolve(cl);\r
 \r
-TinyMCEControl.prototype.setUseCSS = function(b) {\r
-       var doc = this.getDoc();\r
-       try {doc.execCommand("useCSS", false, !b);} catch (ex) {}\r
-       try {doc.execCommand("styleWithCSS", false, b);} catch (ex) {}\r
+                       return new f(a, b, c, d, e);\r
+               },\r
 \r
-       if (!tinyMCE.getParam("table_inline_editing"))\r
-               try {doc.execCommand('enableInlineTableEditing', false, "false");} catch (ex) {}\r
+               confirm : function(t, cb, s, w) {\r
+                       w = w || window;\r
 \r
-       if (!tinyMCE.getParam("object_resizing"))\r
-               try {doc.execCommand('enableObjectResizing', false, "false");} catch (ex) {}\r
-};\r
+                       cb.call(s || this, w.confirm(this._decode(this.editor.getLang(t, t))));\r
+               },\r
 \r
-TinyMCEControl.prototype.execCommand = function(command, user_interface, value) {\r
-       var doc = this.getDoc();\r
-       var win = this.getWin();\r
-       var focusElm = this.getFocusElement();\r
+               alert : function(tx, cb, s, w) {\r
+                       var t = this;\r
 \r
-       if (this.lastSafariSelection && !new RegExp('mceStartTyping|mceEndTyping|mceBeginUndoLevel|mceEndUndoLevel|mceAddUndoLevel', 'gi').test(command)) {\r
-               this.moveToBookmark(this.lastSafariSelection);\r
-               tinyMCE.selectedElement = this.lastSafariSelectedElement;\r
-       }\r
+                       w = w || window;\r
+                       w.alert(t._decode(t.editor.getLang(tx, tx)));\r
 \r
-       // Mozilla issue\r
-       if (!tinyMCE.isMSIE && !this.useCSS) {\r
-               this.setUseCSS(false);\r
-               this.useCSS = true;\r
-       }\r
+                       if (cb)\r
+                               cb.call(s || t);\r
+               },\r
 \r
-       //debug("command: " + command + ", user_interface: " + user_interface + ", value: " + value);\r
-       this.contentDocument = doc; // <-- Strange, unless this is applied Mozilla 1.3 breaks\r
+               resizeBy : function(dw, dh, win) {\r
+                       win.resizeBy(dw, dh);\r
+               },\r
 \r
-       // Call theme execcommand\r
-       if (tinyMCE._themeExecCommand(this.editorId, this.getBody(), command, user_interface, value))\r
-               return;\r
+               // Internal functions\r
 \r
-       // Fix align on images\r
-       if (focusElm && focusElm.nodeName == "IMG") {\r
-               var align = focusElm.getAttribute('align');\r
-               var img = command == "JustifyCenter" ? focusElm.cloneNode(false) : focusElm;\r
+               _decode : function(s) {\r
+                       return tinymce.DOM.decode(s).replace(/\\n/g, '\n');\r
+               }\r
+       });\r
+}(tinymce));\r
+(function(tinymce) {\r
+       tinymce.Formatter = function(ed) {\r
+               var formats = {},\r
+                       each = tinymce.each,\r
+                       dom = ed.dom,\r
+                       selection = ed.selection,\r
+                       TreeWalker = tinymce.dom.TreeWalker,\r
+                       rangeUtils = new tinymce.dom.RangeUtils(dom),\r
+                       isValid = ed.schema.isValidChild,\r
+                       isBlock = dom.isBlock,\r
+                       forcedRootBlock = ed.settings.forced_root_block,\r
+                       nodeIndex = dom.nodeIndex,\r
+                       INVISIBLE_CHAR = '\uFEFF',\r
+                       MCE_ATTR_RE = /^(src|href|style)$/,\r
+                       FALSE = false,\r
+                       TRUE = true,\r
+                       undefined,\r
+                       pendingFormats = {apply : [], remove : []};\r
+\r
+               function isArray(obj) {\r
+                       return obj instanceof Array;\r
+               };\r
+\r
+               function getParents(node, selector) {\r
+                       return dom.getParents(node, selector, dom.getRoot());\r
+               };\r
+\r
+               function isCaretNode(node) {\r
+                       return node.nodeType === 1 && (node.face === 'mceinline' || node.style.fontFamily === 'mceinline');\r
+               };\r
+\r
+               // Public functions\r
+\r
+               function get(name) {\r
+                       return name ? formats[name] : formats;\r
+               };\r
+\r
+               function register(name, format) {\r
+                       if (name) {\r
+                               if (typeof(name) !== 'string') {\r
+                                       each(name, function(format, name) {\r
+                                               register(name, format);\r
+                                       });\r
+                               } else {\r
+                                       // Force format into array and add it to internal collection\r
+                                       format = format.length ? format : [format];\r
+\r
+                                       each(format, function(format) {\r
+                                               // Set deep to false by default on selector formats this to avoid removing\r
+                                               // alignment on images inside paragraphs when alignment is changed on paragraphs\r
+                                               if (format.deep === undefined)\r
+                                                       format.deep = !format.selector;\r
+\r
+                                               // Default to true\r
+                                               if (format.split === undefined)\r
+                                                       format.split = !format.selector || format.inline;\r
+\r
+                                               // Default to true\r
+                                               if (format.remove === undefined && format.selector && !format.inline)\r
+                                                       format.remove = 'none';\r
+\r
+                                               // Mark format as a mixed format inline + block level\r
+                                               if (format.selector && format.inline) {\r
+                                                       format.mixed = true;\r
+                                                       format.block_expand = true;\r
+                                               }\r
 \r
-               switch (command) {\r
-                       case "JustifyLeft":\r
-                               if (align == 'left')\r
-                                       img.removeAttribute('align');\r
-                               else\r
-                                       img.setAttribute('align', 'left');\r
+                                               // Split classes if needed\r
+                                               if (typeof(format.classes) === 'string')\r
+                                                       format.classes = format.classes.split(/\s+/);\r
+                                       });\r
 \r
-                               // Remove the div\r
-                               var div = focusElm.parentNode;\r
-                               if (div && div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)\r
-                                       div.parentNode.replaceChild(img, div);\r
+                                       formats[name] = format;\r
+                               }\r
+                       }\r
+               };\r
 \r
-                               this.selectNode(img);\r
-                               this.repaint();\r
-                               tinyMCE.triggerNodeChange();\r
-                               return;\r
+               var getTextDecoration = function(node) {\r
+                       var decoration;\r
 \r
-                       case "JustifyCenter":\r
-                               img.removeAttribute('align');\r
+                       ed.dom.getParent(node, function(n) {\r
+                               decoration = ed.dom.getStyle(n, 'text-decoration');\r
+                               return decoration && decoration !== 'none';\r
+                       });\r
 \r
-                               // Is centered\r
-                               var div = tinyMCE.getParentElement(focusElm, "div");\r
-                               if (div && div.style.textAlign == "center") {\r
-                                       // Remove div\r
-                                       if (div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)\r
-                                               div.parentNode.replaceChild(img, div);\r
-                               } else {\r
-                                       // Add div\r
-                                       var div = this.getDoc().createElement("div");\r
-                                       div.style.textAlign = 'center';\r
-                                       div.appendChild(img);\r
-                                       focusElm.parentNode.replaceChild(div, focusElm);\r
+                       return decoration;\r
+               };\r
+\r
+               var processUnderlineAndColor = function(node) {\r
+                       var textDecoration;\r
+                       if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {\r
+                               textDecoration = getTextDecoration(node.parentNode);\r
+                               if (ed.dom.getStyle(node, 'color') && textDecoration) {\r
+                                       ed.dom.setStyle(node, 'text-decoration', textDecoration);\r
+                               } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) {\r
+                                       ed.dom.setStyle(node, 'text-decoration', null);\r
+                               }\r
+                       }\r
+               };\r
+\r
+               function apply(name, vars, node) {\r
+                       var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed();\r
+\r
+                       function moveStart(rng) {\r
+                               var container = rng.startContainer,\r
+                                       offset = rng.startOffset,\r
+                                       walker, node;\r
+\r
+                               // Move startContainer/startOffset in to a suitable node\r
+                               if (container.nodeType == 1 || container.nodeValue === "") {\r
+                                       container = container.nodeType == 1 ? container.childNodes[offset] : container;\r
+\r
+                                       // Might fail if the offset is behind the last element in it's container\r
+                                       if (container) {\r
+                                               walker = new TreeWalker(container, container.parentNode);\r
+                                               for (node = walker.current(); node; node = walker.next()) {\r
+                                                       if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {\r
+                                                               rng.setStart(node, 0);\r
+                                                               break;\r
+                                                       }\r
+                                               }\r
+                                       }\r
                                }\r
 \r
-                               this.selectNode(img);\r
-                               this.repaint();\r
-                               tinyMCE.triggerNodeChange();\r
-                               return;\r
-\r
-                       case "JustifyRight":\r
-                               if (align == 'right')\r
-                                       img.removeAttribute('align');\r
-                               else\r
-                                       img.setAttribute('align', 'right');\r
+                               return rng;\r
+                       };\r
 \r
-                               // Remove the div\r
-                               var div = focusElm.parentNode;\r
-                               if (div && div.nodeName == "DIV" && div.childNodes.length == 1 && div.parentNode)\r
-                                       div.parentNode.replaceChild(img, div);\r
+                       function setElementFormat(elm, fmt) {\r
+                               fmt = fmt || format;\r
 \r
-                               this.selectNode(img);\r
-                               this.repaint();\r
-                               tinyMCE.triggerNodeChange();\r
-                               return;\r
-               }\r
-       }\r
+                               if (elm) {\r
+                                       if (fmt.onformat) {\r
+                                               fmt.onformat(elm, fmt, vars, node);\r
+                                       }\r
 \r
-       if (tinyMCE.settings['force_br_newlines']) {\r
-               var alignValue = "";\r
+                                       each(fmt.styles, function(value, name) {\r
+                                               dom.setStyle(elm, name, replaceVars(value, vars));\r
+                                       });\r
 \r
-               if (doc.selection.type != "Control") {\r
-                       switch (command) {\r
-                                       case "JustifyLeft":\r
-                                               alignValue = "left";\r
-                                               break;\r
+                                       each(fmt.attributes, function(value, name) {\r
+                                               dom.setAttrib(elm, name, replaceVars(value, vars));\r
+                                       });\r
 \r
-                                       case "JustifyCenter":\r
-                                               alignValue = "center";\r
-                                               break;\r
+                                       each(fmt.classes, function(value) {\r
+                                               value = replaceVars(value, vars);\r
 \r
-                                       case "JustifyFull":\r
-                                               alignValue = "justify";\r
-                                               break;\r
+                                               if (!dom.hasClass(elm, value))\r
+                                                       dom.addClass(elm, value);\r
+                                       });\r
+                               }\r
+                       };\r
+                       function adjustSelectionToVisibleSelection() {\r
+                               function findSelectionEnd(start, end) {\r
+                                       var walker = new TreeWalker(end);\r
+                                       for (node = walker.current(); node; node = walker.prev()) {\r
+                                               if (node.childNodes.length > 1 || node == start) {\r
+                                                       return node;\r
+                                               }\r
+                                       }\r
+                               };\r
 \r
-                                       case "JustifyRight":\r
-                                               alignValue = "right";\r
-                                               break;\r
-                       }\r
+                               // Adjust selection so that a end container with a end offset of zero is not included in the selection\r
+                               // as this isn't visible to the user.\r
+                               var rng = ed.selection.getRng();\r
+                               var start = rng.startContainer;\r
+                               var end = rng.endContainer;\r
 \r
-                       if (alignValue != "") {\r
-                               var rng = doc.selection.createRange();\r
+                               if (start != end && rng.endOffset == 0) {\r
+                                       var newEnd = findSelectionEnd(start, end);\r
+                                       var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length;\r
 \r
-                               if ((divElm = tinyMCE.getParentElement(rng.parentElement(), "div")) != null)\r
-                                       divElm.setAttribute("align", alignValue);\r
-                               else if (rng.pasteHTML && rng.htmlText.length > 0)\r
-                                       rng.pasteHTML('<div align="' + alignValue + '">' + rng.htmlText + "</div>");\r
+                                       rng.setEnd(newEnd, endOffset);\r
+                               }\r
 \r
-                               tinyMCE.triggerNodeChange();\r
-                               return;\r
+                               return rng;\r
                        }\r
-               }\r
-       }\r
+                       \r
+                       function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){\r
+                               var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm;\r
+                               \r
+                               // find the index of the first child list.\r
+                               each(node.childNodes, function(n, index) {\r
+                                       if (n.nodeName === "UL" || n.nodeName === "OL") {\r
+                                               listIndex = index;\r
+                                               list = n;\r
+                                               return false;\r
+                                       }\r
+                               });\r
+                               \r
+                               // get the index of the bookmarks\r
+                               each(node.childNodes, function(n, index) {\r
+                                       if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") {\r
+                                               if (n.id == bookmark.id + "_start") {\r
+                                                       startIndex = index;\r
+                                               } else if (n.id == bookmark.id + "_end") {\r
+                                                       endIndex = index;\r
+                                               }\r
+                                       }\r
+                               });\r
+                               \r
+                               // if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally\r
+                               if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) {\r
+                                       each(tinymce.grep(node.childNodes), process);\r
+                                       return 0;\r
+                               } else {\r
+                                       currentWrapElm = wrapElm.cloneNode(FALSE);\r
+                                       \r
+                                       // create a list of the nodes on the same side of the list as the selection\r
+                                       each(tinymce.grep(node.childNodes), function(n, index) {\r
+                                               if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) {\r
+                                                       nodes.push(n); \r
+                                                       n.parentNode.removeChild(n);\r
+                                               }\r
+                                       });\r
+                                       \r
+                                       // insert the wrapping element either before or after the list.\r
+                                       if (startIndex < listIndex) {\r
+                                               node.insertBefore(currentWrapElm, list);\r
+                                       } else if (startIndex > listIndex) {\r
+                                               node.insertBefore(currentWrapElm, list.nextSibling);\r
+                                       }\r
+                                       \r
+                                       // add the new nodes to the list.\r
+                                       newWrappers.push(currentWrapElm);\r
 \r
-       switch (command) {\r
-               case "mceRepaint":\r
-                       this.repaint();\r
-                       return true;\r
+                                       each(nodes, function(node) {\r
+                                               currentWrapElm.appendChild(node);\r
+                                       });\r
 \r
-               case "mceStoreSelection":\r
-                       this.selectionBookmark = this.getBookmark();\r
-                       return true;\r
+                                       return currentWrapElm;\r
+                               }\r
+                       };\r
+                       \r
+                       function applyRngStyle(rng, bookmark) {\r
+                               var newWrappers = [], wrapName, wrapElm;\r
 \r
-               case "mceRestoreSelection":\r
-                       this.moveToBookmark(this.selectionBookmark);\r
-                       return true;\r
+                               // Setup wrapper element\r
+                               wrapName = format.inline || format.block;\r
+                               wrapElm = dom.create(wrapName);\r
+                               setElementFormat(wrapElm);\r
 \r
-               case "InsertUnorderedList":\r
-               case "InsertOrderedList":\r
-                       var tag = (command == "InsertUnorderedList") ? "ul" : "ol";\r
+                               rangeUtils.walk(rng, function(nodes) {\r
+                                       var currentWrapElm;\r
 \r
-                       if (tinyMCE.isSafari)\r
-                               this.execCommand("mceInsertContent", false, "<" + tag + "><li>&nbsp;</li><" + tag + ">");\r
-                       else\r
-                               this.getDoc().execCommand(command, user_interface, value);\r
+                                       function process(node) {\r
+                                               var nodeName = node.nodeName.toLowerCase(), parentName = node.parentNode.nodeName.toLowerCase(), found;\r
 \r
-                       tinyMCE.triggerNodeChange();\r
-                       break;\r
+                                               // Stop wrapping on br elements\r
+                                               if (isEq(nodeName, 'br')) {\r
+                                                       currentWrapElm = 0;\r
 \r
-               case "Strikethrough":\r
-                       if (tinyMCE.isSafari)\r
-                               this.execCommand("mceInsertContent", false, "<strike>" + this.getSelectedHTML() + "</strike>");\r
-                       else\r
-                               this.getDoc().execCommand(command, user_interface, value);\r
+                                                       // Remove any br elements when we wrap things\r
+                                                       if (format.block)\r
+                                                               dom.remove(node);\r
+\r
+                                                       return;\r
+                                               }\r
+\r
+                                               // If node is wrapper type\r
+                                               if (format.wrapper && matchNode(node, name, vars)) {\r
+                                                       currentWrapElm = 0;\r
+                                                       return;\r
+                                               }\r
 \r
-                       tinyMCE.triggerNodeChange();\r
-                       break;\r
+                                               // Can we rename the block\r
+                                               if (format.block && !format.wrapper && isTextBlock(nodeName)) {\r
+                                                       node = dom.rename(node, wrapName);\r
+                                                       setElementFormat(node);\r
+                                                       newWrappers.push(node);\r
+                                                       currentWrapElm = 0;\r
+                                                       return;\r
+                                               }\r
 \r
-               case "mceSelectNode":\r
-                       this.selectNode(value);\r
-                       tinyMCE.triggerNodeChange();\r
-                       tinyMCE.selectedNode = value;\r
-                       break;\r
+                                               // Handle selector patterns\r
+                                               if (format.selector) {\r
+                                                       // Look for matching formats\r
+                                                       each(formatList, function(format) {\r
+                                                               // Check collapsed state if it exists\r
+                                                               if ('collapsed' in format && format.collapsed !== isCollapsed) {\r
+                                                                       return;\r
+                                                               }\r
+\r
+                                                               if (dom.is(node, format.selector) && !isCaretNode(node)) {\r
+                                                                       setElementFormat(node, format);\r
+                                                                       found = true;\r
+                                                               }\r
+                                                       });\r
+\r
+                                                       // Continue processing if a selector match wasn't found and a inline element is defined\r
+                                                       if (!format.inline || found) {\r
+                                                               currentWrapElm = 0;\r
+                                                               return;\r
+                                                       }\r
+                                               }\r
 \r
-               case "FormatBlock":\r
-                       if (value == null || value == "") {\r
-                               var elm = tinyMCE.getParentElement(this.getFocusElement(), "p,div,h1,h2,h3,h4,h5,h6,pre,address");\r
+                                               // Is it valid to wrap this item\r
+                                               if (isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&\r
+                                                               !(node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279)) {\r
+                                                       // Start wrapping\r
+                                                       if (!currentWrapElm) {\r
+                                                               // Wrap the node\r
+                                                               currentWrapElm = wrapElm.cloneNode(FALSE);\r
+                                                               node.parentNode.insertBefore(currentWrapElm, node);\r
+                                                               newWrappers.push(currentWrapElm);\r
+                                                       }\r
 \r
-                               if (elm)\r
-                                       this.execCommand("mceRemoveNode", false, elm);\r
-                       } else\r
-                               this.getDoc().execCommand("FormatBlock", false, value);\r
+                                                       currentWrapElm.appendChild(node);\r
+                                               } else if (nodeName == 'li' && bookmark) {\r
+                                                       // Start wrapping - if we are in a list node and have a bookmark, then we will always begin by wrapping in a new element.\r
+                                                       currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process);\r
+                                               } else {\r
+                                                       // Start a new wrapper for possible children\r
+                                                       currentWrapElm = 0;\r
 \r
-                       tinyMCE.triggerNodeChange();\r
+                                                       each(tinymce.grep(node.childNodes), process);\r
 \r
-                       break;\r
+                                                       // End the last wrapper\r
+                                                       currentWrapElm = 0;\r
+                                               }\r
+                                       };\r
 \r
-               case "mceRemoveNode":\r
-                       if (!value)\r
-                               value = tinyMCE.getParentElement(this.getFocusElement());\r
+                                       // Process siblings from range\r
+                                       each(nodes, process);\r
+                               });\r
 \r
-                       if (tinyMCE.isMSIE) {\r
-                               value.outerHTML = value.innerHTML;\r
-                       } else {\r
-                               var rng = value.ownerDocument.createRange();\r
-                               rng.setStartBefore(value);\r
-                               rng.setEndAfter(value);\r
-                               rng.deleteContents();\r
-                               rng.insertNode(rng.createContextualFragment(value.innerHTML));\r
-                       }\r
+                               // Wrap links inside as well, for example color inside a link when the wrapper is around the link\r
+                               if (format.wrap_links === false) {\r
+                                       each(newWrappers, function(node) {\r
+                                               function process(node) {\r
+                                                       var i, currentWrapElm, children;\r
 \r
-                       tinyMCE.triggerNodeChange();\r
+                                                       if (node.nodeName === 'A') {\r
+                                                               currentWrapElm = wrapElm.cloneNode(FALSE);\r
+                                                               newWrappers.push(currentWrapElm);\r
 \r
-                       break;\r
+                                                               children = tinymce.grep(node.childNodes);\r
+                                                               for (i = 0; i < children.length; i++)\r
+                                                                       currentWrapElm.appendChild(children[i]);\r
 \r
-               case "mceSelectNodeDepth":\r
-                       var parentNode = this.getFocusElement();\r
-                       for (var i=0; parentNode; i++) {\r
-                               if (parentNode.nodeName.toLowerCase() == "body")\r
-                                       break;\r
+                                                               node.appendChild(currentWrapElm);\r
+                                                       }\r
 \r
-                               if (parentNode.nodeName.toLowerCase() == "#text") {\r
-                                       i--;\r
-                                       parentNode = parentNode.parentNode;\r
-                                       continue;\r
-                               }\r
+                                                       each(tinymce.grep(node.childNodes), process);\r
+                                               };\r
 \r
-                               if (i == value) {\r
-                                       this.selectNode(parentNode, false);\r
-                                       tinyMCE.triggerNodeChange();\r
-                                       tinyMCE.selectedNode = parentNode;\r
-                                       return;\r
+                                               process(node);\r
+                                       });\r
                                }\r
 \r
-                               parentNode = parentNode.parentNode;\r
-                       }\r
-\r
-                       break;\r
+                               // Cleanup\r
+                               each(newWrappers, function(node) {\r
+                                       var childCount;\r
 \r
-               case "SetStyleInfo":\r
-                       var rng = this.getRng();\r
-                       var sel = this.getSel();\r
-                       var scmd = value['command'];\r
-                       var sname = value['name'];\r
-                       var svalue = value['value'] == null ? '' : value['value'];\r
-                       //var svalue = value['value'] == null ? '' : value['value'];\r
-                       var wrapper = value['wrapper'] ? value['wrapper'] : "span";\r
-                       var parentElm = null;\r
-                       var invalidRe = new RegExp("^BODY|HTML$", "g");\r
-                       var invalidParentsRe = tinyMCE.settings['merge_styles_invalid_parents'] != '' ? new RegExp(tinyMCE.settings['merge_styles_invalid_parents'], "gi") : null;\r
+                                       function getChildCount(node) {\r
+                                               var count = 0;\r
 \r
-                       // Whole element selected check\r
-                       if (tinyMCE.isMSIE) {\r
-                               // Control range\r
-                               if (rng.item)\r
-                                       parentElm = rng.item(0);\r
-                               else {\r
-                                       var pelm = rng.parentElement();\r
-                                       var prng = doc.selection.createRange();\r
-                                       prng.moveToElementText(pelm);\r
+                                               each(node.childNodes, function(node) {\r
+                                                       if (!isWhiteSpaceNode(node) && !isBookmarkNode(node))\r
+                                                               count++;\r
+                                               });\r
 \r
-                                       if (rng.htmlText == prng.htmlText || rng.boundingWidth == 0) {\r
-                                               if (invalidParentsRe == null || !invalidParentsRe.test(pelm.nodeName))\r
-                                                       parentElm = pelm;\r
-                                       }\r
-                               }\r
-                       } else {\r
-                               var felm = this.getFocusElement();\r
-                               if (sel.isCollapsed || (/td|tr|tbody|table/ig.test(felm.nodeName) && sel.anchorNode == felm.parentNode))\r
-                                       parentElm = felm;\r
-                       }\r
+                                               return count;\r
+                                       };\r
 \r
-                       // Whole element selected\r
-                       if (parentElm && !invalidRe.test(parentElm.nodeName)) {\r
-                               if (scmd == "setstyle")\r
-                                       tinyMCE.setStyleAttrib(parentElm, sname, svalue);\r
+                                       function mergeStyles(node) {\r
+                                               var child, clone;\r
 \r
-                               if (scmd == "setattrib")\r
-                                       tinyMCE.setAttrib(parentElm, sname, svalue);\r
+                                               each(node.childNodes, function(node) {\r
+                                                       if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) {\r
+                                                               child = node;\r
+                                                               return FALSE; // break loop\r
+                                                       }\r
+                                               });\r
 \r
-                               if (scmd == "removeformat") {\r
-                                       parentElm.style.cssText = '';\r
-                                       tinyMCE.setAttrib(parentElm, 'class', '');\r
-                               }\r
+                                               // If child was found and of the same type as the current node\r
+                                               if (child && matchName(child, format)) {\r
+                                                       clone = child.cloneNode(FALSE);\r
+                                                       setElementFormat(clone);\r
 \r
-                               // Remove style/attribs from all children\r
-                               var ch = tinyMCE.getNodeTree(parentElm, new Array(), 1);\r
-                               for (var z=0; z<ch.length; z++) {\r
-                                       if (ch[z] == parentElm)\r
-                                               continue;\r
+                                                       dom.replace(clone, node, TRUE);\r
+                                                       dom.remove(child, 1);\r
+                                               }\r
 \r
-                                       if (scmd == "setstyle")\r
-                                               tinyMCE.setStyleAttrib(ch[z], sname, '');\r
+                                               return clone || node;\r
+                                       };\r
 \r
-                                       if (scmd == "setattrib")\r
-                                               tinyMCE.setAttrib(ch[z], sname, '');\r
+                                       childCount = getChildCount(node);\r
 \r
-                                       if (scmd == "removeformat") {\r
-                                               ch[z].style.cssText = '';\r
-                                               tinyMCE.setAttrib(ch[z], 'class', '');\r
+                                       // Remove empty nodes but only if there is multiple wrappers and they are not block\r
+                                       // elements so never remove single <h1></h1> since that would remove the currrent empty block element where the caret is at\r
+                                       if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) {\r
+                                               dom.remove(node, 1);\r
+                                               return;\r
                                        }\r
-                               }\r
-                       } else {\r
-                               doc.execCommand("fontname", false, "#mce_temp_font#");\r
-                               var elementArray = tinyMCE.getElementsByAttributeValue(this.getBody(), "font", "face", "#mce_temp_font#");\r
-\r
-                               // Change them all\r
-                               for (var x=0; x<elementArray.length; x++) {\r
-                                       elm = elementArray[x];\r
-                                       if (elm) {\r
-                                               var spanElm = doc.createElement(wrapper);\r
 \r
-                                               if (scmd == "setstyle")\r
-                                                       tinyMCE.setStyleAttrib(spanElm, sname, svalue);\r
-\r
-                                               if (scmd == "setattrib")\r
-                                                       tinyMCE.setAttrib(spanElm, sname, svalue);\r
+                                       if (format.inline || format.wrapper) {\r
+                                               // Merges the current node with it's children of similar type to reduce the number of elements\r
+                                               if (!format.exact && childCount === 1)\r
+                                                       node = mergeStyles(node);\r
+\r
+                                               // Remove/merge children\r
+                                               each(formatList, function(format) {\r
+                                                       // Merge all children of similar type will move styles from child to parent\r
+                                                       // this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span>\r
+                                                       // will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span>\r
+                                                       each(dom.select(format.inline, node), function(child) {\r
+                                                               var parent;\r
+\r
+                                                               // When wrap_links is set to false we don't want\r
+                                                               // to remove the format on children within links\r
+                                                               if (format.wrap_links === false) {\r
+                                                                       parent = child.parentNode;\r
+\r
+                                                                       do {\r
+                                                                               if (parent.nodeName === 'A')\r
+                                                                                       return;\r
+                                                                       } while (parent = parent.parentNode);\r
+                                                               }\r
+\r
+                                                               removeFormat(format, vars, child, format.exact ? child : null);\r
+                                                       });\r
+                                               });\r
+\r
+                                               // Remove child if direct parent is of same type\r
+                                               if (matchNode(node.parentNode, name, vars)) {\r
+                                                       dom.remove(node, 1);\r
+                                                       node = 0;\r
+                                                       return TRUE;\r
+                                               }\r
 \r
-                                               if (scmd == "removeformat") {\r
-                                                       spanElm.style.cssText = '';\r
-                                                       tinyMCE.setAttrib(spanElm, 'class', '');\r
+                                               // Look for parent with similar style format\r
+                                               if (format.merge_with_parents) {\r
+                                                       dom.getParent(node.parentNode, function(parent) {\r
+                                                               if (matchNode(parent, name, vars)) {\r
+                                                                       dom.remove(node, 1);\r
+                                                                       node = 0;\r
+                                                                       return TRUE;\r
+                                                               }\r
+                                                       });\r
                                                }\r
 \r
-                                               if (elm.hasChildNodes()) {\r
-                                                       for (var i=0; i<elm.childNodes.length; i++)\r
-                                                               spanElm.appendChild(elm.childNodes[i].cloneNode(true));\r
+                                               // Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b>\r
+                                               if (node && format.merge_siblings !== false) {\r
+                                                       node = mergeSiblings(getNonWhiteSpaceSibling(node), node);\r
+                                                       node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));\r
                                                }\r
+                                       }\r
+                               });\r
+                       };\r
 \r
-                                               spanElm.setAttribute("mce_new", "true");\r
-                                               elm.parentNode.replaceChild(spanElm, elm);\r
+                       if (format) {\r
+                               if (node) {\r
+                                       rng = dom.createRng();\r
 \r
-                                               // Remove style/attribs from all children\r
-                                               var ch = tinyMCE.getNodeTree(spanElm, new Array(), 1);\r
-                                               for (var z=0; z<ch.length; z++) {\r
-                                                       if (ch[z] == spanElm)\r
-                                                               continue;\r
+                                       rng.setStartBefore(node);\r
+                                       rng.setEndAfter(node);\r
 \r
-                                                       if (scmd == "setstyle")\r
-                                                               tinyMCE.setStyleAttrib(ch[z], sname, '');\r
+                                       applyRngStyle(expandRng(rng, formatList));\r
+                               } else {\r
+                                       if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {\r
+                                               // Obtain selection node before selection is unselected by applyRngStyle()\r
+                                               var curSelNode = ed.selection.getNode();\r
+\r
+                                               // Apply formatting to selection\r
+                                               ed.selection.setRng(adjustSelectionToVisibleSelection());\r
+                                               bookmark = selection.getBookmark();\r
+                                               applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark);\r
+\r
+                                               // Colored nodes should be underlined so that the color of the underline matches the text color.\r
+                                               if (format.styles && (format.styles.color || format.styles.textDecoration)) {\r
+                                                       tinymce.walk(curSelNode, processUnderlineAndColor, 'childNodes');\r
+                                                       processUnderlineAndColor(curSelNode);\r
+                                               }\r
 \r
-                                                       if (scmd == "setattrib")\r
-                                                               tinyMCE.setAttrib(ch[z], sname, '');\r
+                                               selection.moveToBookmark(bookmark);\r
+                                               selection.setRng(moveStart(selection.getRng(TRUE)));\r
+                                               ed.nodeChanged();\r
+                                       } else\r
+                                               performCaretAction('apply', name, vars);\r
+                               }\r
+                       }\r
+               };\r
+\r
+               function remove(name, vars, node) {\r
+                       var formatList = get(name), format = formatList[0], bookmark, i, rng;\r
+                       function moveStart(rng) {\r
+                               var container = rng.startContainer,\r
+                                       offset = rng.startOffset,\r
+                                       walker, node, nodes, tmpNode;\r
+\r
+                               // Convert text node into index if possible\r
+                               if (container.nodeType == 3 && offset >= container.nodeValue.length - 1) {\r
+                                       container = container.parentNode;\r
+                                       offset = nodeIndex(container) + 1;\r
+                               }\r
 \r
-                                                       if (scmd == "removeformat") {\r
-                                                               ch[z].style.cssText = '';\r
-                                                               tinyMCE.setAttrib(ch[z], 'class', '');\r
-                                                       }\r
+                               // Move startContainer/startOffset in to a suitable node\r
+                               if (container.nodeType == 1) {\r
+                                       nodes = container.childNodes;\r
+                                       container = nodes[Math.min(offset, nodes.length - 1)];\r
+                                       walker = new TreeWalker(container);\r
+\r
+                                       // If offset is at end of the parent node walk to the next one\r
+                                       if (offset > nodes.length - 1)\r
+                                               walker.next();\r
+\r
+                                       for (node = walker.current(); node; node = walker.next()) {\r
+                                               if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {\r
+                                                       // IE has a "neat" feature where it moves the start node into the closest element\r
+                                                       // we can avoid this by inserting an element before it and then remove it after we set the selection\r
+                                                       tmpNode = dom.create('a', null, INVISIBLE_CHAR);\r
+                                                       node.parentNode.insertBefore(tmpNode, node);\r
+\r
+                                                       // Set selection and remove tmpNode\r
+                                                       rng.setStart(node, 0);\r
+                                                       selection.setRng(rng);\r
+                                                       dom.remove(tmpNode);\r
+\r
+                                                       return;\r
                                                }\r
                                        }\r
                                }\r
-                       }\r
+                       };\r
 \r
-                       // Cleaup wrappers\r
-                       var nodes = doc.getElementsByTagName(wrapper);\r
-                       for (var i=nodes.length-1; i>=0; i--) {\r
-                               var elm = nodes[i];\r
-                               var isNew = tinyMCE.getAttrib(elm, "mce_new") == "true";\r
+                       // Merges the styles for each node\r
+                       function process(node) {\r
+                               var children, i, l;\r
 \r
-                               elm.removeAttribute("mce_new");\r
+                               // Grab the children first since the nodelist might be changed\r
+                               children = tinymce.grep(node.childNodes);\r
 \r
-                               // Is only child a element\r
-                               if (elm.childNodes && elm.childNodes.length == 1 && elm.childNodes[0].nodeType == 1) {\r
-                                       //tinyMCE.debug("merge1" + isNew);\r
-                                       this._mergeElements(scmd, elm, elm.childNodes[0], isNew);\r
-                                       continue;\r
+                               // Process current node\r
+                               for (i = 0, l = formatList.length; i < l; i++) {\r
+                                       if (removeFormat(formatList[i], vars, node, node))\r
+                                               break;\r
                                }\r
 \r
-                               // Is I the only child\r
-                               if (elm.parentNode.childNodes.length == 1 && !invalidRe.test(elm.nodeName) && !invalidRe.test(elm.parentNode.nodeName)) {\r
-                                       //tinyMCE.debug("merge2" + isNew + "," + elm.nodeName + "," + elm.parentNode.nodeName);\r
-                                       if (invalidParentsRe == null || !invalidParentsRe.test(elm.parentNode.nodeName))\r
-                                               this._mergeElements(scmd, elm.parentNode, elm, false);\r
+                               // Process the children\r
+                               if (format.deep) {\r
+                                       for (i = 0, l = children.length; i < l; i++)\r
+                                               process(children[i]);\r
                                }\r
-                       }\r
+                       };\r
 \r
-                       // Remove empty wrappers\r
-                       var nodes = doc.getElementsByTagName(wrapper);\r
-                       for (var i=nodes.length-1; i>=0; i--) {\r
-                               var elm = nodes[i];\r
-                               var isEmpty = true;\r
+                       function findFormatRoot(container) {\r
+                               var formatRoot;\r
 \r
-                               // Check if it has any attribs\r
-                               var tmp = doc.createElement("body");\r
-                               tmp.appendChild(elm.cloneNode(false));\r
+                               // Find format root\r
+                               each(getParents(container.parentNode).reverse(), function(parent) {\r
+                                       var format;\r
 \r
-                               // Is empty span, remove it\r
-                               tmp.innerHTML = tmp.innerHTML.replace(new RegExp('style=""|class=""', 'gi'), '');\r
-                               //tinyMCE.debug(tmp.innerHTML);\r
-                               if (new RegExp('<span>', 'gi').test(tmp.innerHTML)) {\r
-                                       for (var x=0; x<elm.childNodes.length; x++) {\r
-                                               if (elm.parentNode != null)\r
-                                                       elm.parentNode.insertBefore(elm.childNodes[x].cloneNode(true), elm);\r
+                                       // Find format root element\r
+                                       if (!formatRoot && parent.id != '_start' && parent.id != '_end') {\r
+                                               // Is the node matching the format we are looking for\r
+                                               format = matchNode(parent, name, vars);\r
+                                               if (format && format.split !== false)\r
+                                                       formatRoot = parent;\r
                                        }\r
+                               });\r
 \r
-                                       elm.parentNode.removeChild(elm);\r
-                               }\r
-                       }\r
+                               return formatRoot;\r
+                       };\r
+\r
+                       function wrapAndSplit(format_root, container, target, split) {\r
+                               var parent, clone, lastClone, firstClone, i, formatRootParent;\r
 \r
-                       // Re add the visual aids\r
-                       if (scmd == "removeformat")\r
-                               tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);\r
+                               // Format root found then clone formats and split it\r
+                               if (format_root) {\r
+                                       formatRootParent = format_root.parentNode;\r
 \r
-                       tinyMCE.triggerNodeChange();\r
+                                       for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {\r
+                                               clone = parent.cloneNode(FALSE);\r
 \r
-                       break;\r
+                                               for (i = 0; i < formatList.length; i++) {\r
+                                                       if (removeFormat(formatList[i], vars, clone, clone)) {\r
+                                                               clone = 0;\r
+                                                               break;\r
+                                                       }\r
+                                               }\r
 \r
-               case "FontName":\r
-                       if (value == null) {\r
-                               var s = this.getSel();\r
+                                               // Build wrapper node\r
+                                               if (clone) {\r
+                                                       if (lastClone)\r
+                                                               clone.appendChild(lastClone);\r
 \r
-                               // Find font and select it\r
-                               if (tinyMCE.isGecko && s.isCollapsed) {\r
-                                       var f = tinyMCE.getParentElement(this.getFocusElement(), "font");\r
+                                                       if (!firstClone)\r
+                                                               firstClone = clone;\r
 \r
-                                       if (f != null)\r
-                                               this.selectNode(f, false);\r
-                               }\r
+                                                       lastClone = clone;\r
+                                               }\r
+                                       }\r
 \r
-                               // Remove format\r
-                               this.getDoc().execCommand("RemoveFormat", false, null);\r
+                                       // Never split block elements if the format is mixed\r
+                                       if (split && (!format.mixed || !isBlock(format_root)))\r
+                                               container = dom.split(format_root, container);\r
 \r
-                               // Collapse range if font was found\r
-                               if (f != null && tinyMCE.isGecko) {\r
-                                       var r = this.getRng().cloneRange();\r
-                                       r.collapse(true);\r
-                                       s.removeAllRanges();\r
-                                       s.addRange(r);\r
+                                       // Wrap container in cloned formats\r
+                                       if (lastClone) {\r
+                                               target.parentNode.insertBefore(lastClone, target);\r
+                                               firstClone.appendChild(target);\r
+                                       }\r
                                }\r
-                       } else\r
-                               this.getDoc().execCommand('FontName', false, value);\r
 \r
-                       if (tinyMCE.isGecko)\r
-                               window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);\r
+                               return container;\r
+                       };\r
 \r
-                       return;\r
+                       function splitToFormatRoot(container) {\r
+                               return wrapAndSplit(findFormatRoot(container), container, container, true);\r
+                       };\r
 \r
-               case "FontSize":\r
-                       this.getDoc().execCommand('FontSize', false, value);\r
+                       function unwrap(start) {\r
+                               var node = dom.get(start ? '_start' : '_end'),\r
+                                       out = node[start ? 'firstChild' : 'lastChild'];\r
 \r
-                       if (tinyMCE.isGecko)\r
-                               window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);\r
+                               // If the end is placed within the start the result will be removed\r
+                               // So this checks if the out node is a bookmark node if it is it\r
+                               // checks for another more suitable node\r
+                               if (isBookmarkNode(out))\r
+                                       out = out[start ? 'firstChild' : 'lastChild'];\r
 \r
-                       return;\r
+                               dom.remove(node, true);\r
 \r
-               case "forecolor":\r
-                       this.getDoc().execCommand('forecolor', false, value);\r
-                       break;\r
+                               return out;\r
+                       };\r
 \r
-               case "HiliteColor":\r
-                       if (tinyMCE.isGecko) {\r
-                               this.setUseCSS(true);\r
-                               this.getDoc().execCommand('hilitecolor', false, value);\r
-                               this.setUseCSS(false);\r
-                       } else\r
-                               this.getDoc().execCommand('BackColor', false, value);\r
-                       break;\r
+                       function removeRngStyle(rng) {\r
+                               var startContainer, endContainer;\r
 \r
-               case "Cut":\r
-               case "Copy":\r
-               case "Paste":\r
-                       var cmdFailed = false;\r
+                               rng = expandRng(rng, formatList, TRUE);\r
 \r
-                       // Try executing command\r
-                       eval('try {this.getDoc().execCommand(command, user_interface, value);} catch (e) {cmdFailed = true;}');\r
+                               if (format.split) {\r
+                                       startContainer = getContainer(rng, TRUE);\r
+                                       endContainer = getContainer(rng);\r
 \r
-                       if (tinyMCE.isOpera && cmdFailed)\r
-                               alert('Currently not supported by your browser, use keyboard shortcuts instead.');\r
+                                       if (startContainer != endContainer) {\r
+                                               // Wrap start/end nodes in span element since these might be cloned/moved\r
+                                               startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'});\r
+                                               endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'});\r
 \r
-                       // Alert error in gecko if command failed\r
-                       if (tinyMCE.isGecko && cmdFailed) {\r
-                               // Confirm more info\r
-                               if (confirm(tinyMCE.getLang('lang_clipboard_msg')))\r
-                                       window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', 'mceExternal');\r
+                                               // Split start/end\r
+                                               splitToFormatRoot(startContainer);\r
+                                               splitToFormatRoot(endContainer);\r
 \r
-                               return;\r
-                       } else\r
-                               tinyMCE.triggerNodeChange();\r
-               break;\r
-\r
-               case "mceSetContent":\r
-                       if (!value)\r
-                               value = "";\r
-\r
-                       // Call custom cleanup code\r
-                       value = tinyMCE.storeAwayURLs(value);\r
-                       value = tinyMCE._customCleanup(this, "insert_to_editor", value);\r
-                       tinyMCE._setHTML(doc, value);\r
-                       tinyMCE.setInnerHTML(doc.body, tinyMCE._cleanupHTML(this, doc, tinyMCE.settings, doc.body));\r
-                       this.convertAllRelativeURLs();\r
-                       tinyMCE.handleVisualAid(doc.body, true, this.visualAid, this);\r
-                       tinyMCE._setEventsEnabled(doc.body, false);\r
-                       return true;\r
+                                               // Unwrap start/end to get real elements again\r
+                                               startContainer = unwrap(TRUE);\r
+                                               endContainer = unwrap();\r
+                                       } else\r
+                                               startContainer = endContainer = splitToFormatRoot(startContainer);\r
 \r
-               case "mceLink":\r
-                       var selectedText = "";\r
+                                       // Update range positions since they might have changed after the split operations\r
+                                       rng.startContainer = startContainer.parentNode;\r
+                                       rng.startOffset = nodeIndex(startContainer);\r
+                                       rng.endContainer = endContainer.parentNode;\r
+                                       rng.endOffset = nodeIndex(endContainer) + 1;\r
+                               }\r
 \r
-                       if (tinyMCE.isMSIE) {\r
-                               var rng = doc.selection.createRange();\r
-                               selectedText = rng.text;\r
-                       } else\r
-                               selectedText = this.getSel().toString();\r
+                               // Remove items between start/end\r
+                               rangeUtils.walk(rng, function(nodes) {\r
+                                       each(nodes, function(node) {\r
+                                               process(node);\r
 \r
-                       if (!tinyMCE.linkElement) {\r
-                               if ((tinyMCE.selectedElement.nodeName.toLowerCase() != "img") && (selectedText.length <= 0))\r
-                                       return;\r
-                       }\r
+                                               // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined.\r
+                                               if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && getTextDecoration(node.parentNode) === 'underline') {\r
+                                                       removeFormat({'deep': false, 'exact': true, 'inline': 'span', 'styles': {'textDecoration' : 'underline'}}, null, node);\r
+                                               }\r
+                                       });\r
+                               });\r
+                       };\r
 \r
-                       var href = "", target = "", title = "", onclick = "", action = "insert", style_class = "";\r
+                       // Handle node\r
+                       if (node) {\r
+                               rng = dom.createRng();\r
+                               rng.setStartBefore(node);\r
+                               rng.setEndAfter(node);\r
+                               removeRngStyle(rng);\r
+                               return;\r
+                       }\r
 \r
-                       if (tinyMCE.selectedElement.nodeName.toLowerCase() == "a")\r
-                               tinyMCE.linkElement = tinyMCE.selectedElement;\r
+                       if (!selection.isCollapsed() || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {\r
+                               bookmark = selection.getBookmark();\r
+                               removeRngStyle(selection.getRng(TRUE));\r
+                               selection.moveToBookmark(bookmark);\r
 \r
-                       // Is anchor not a link\r
-                       if (tinyMCE.linkElement != null && tinyMCE.getAttrib(tinyMCE.linkElement, 'href') == "")\r
-                               tinyMCE.linkElement = null;\r
+                               // 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\r
+                               if (match(name, vars, selection.getStart())) {\r
+                                       moveStart(selection.getRng(true));\r
+                               }\r
 \r
-                       if (tinyMCE.linkElement) {\r
-                               href = tinyMCE.getAttrib(tinyMCE.linkElement, 'href');\r
-                               target = tinyMCE.getAttrib(tinyMCE.linkElement, 'target');\r
-                               title = tinyMCE.getAttrib(tinyMCE.linkElement, 'title');\r
-                onclick = tinyMCE.getAttrib(tinyMCE.linkElement, 'onclick');\r
-                               style_class = tinyMCE.getAttrib(tinyMCE.linkElement, 'class');\r
+                               ed.nodeChanged();\r
+                       } else\r
+                               performCaretAction('remove', name, vars);\r
+               };\r
 \r
-                               // Try old onclick to if copy/pasted content\r
-                               if (onclick == "")\r
-                                       onclick = tinyMCE.getAttrib(tinyMCE.linkElement, 'onclick');\r
+               function toggle(name, vars, node) {\r
+                       var fmt = get(name);\r
 \r
-                               onclick = tinyMCE.cleanupEventStr(onclick);\r
+                       if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0]['toggle']))\r
+                               remove(name, vars, node);\r
+                       else\r
+                               apply(name, vars, node);\r
+               };\r
 \r
-                               href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, tinyMCE.linkElement, true);");\r
+               function matchNode(node, name, vars, similar) {\r
+                       var formatList = get(name), format, i, classes;\r
 \r
-                               // Use mce_href if defined\r
-                               mceRealHref = tinyMCE.getAttrib(tinyMCE.linkElement, 'mce_href');\r
-                               if (mceRealHref != "") {\r
-                                       href = mceRealHref;\r
+                       function matchItems(node, format, item_name) {\r
+                               var key, value, items = format[item_name], i;\r
 \r
-                                       if (tinyMCE.getParam('convert_urls'))\r
-                                               href = eval(tinyMCE.settings['urlconverter_callback'] + "(href, tinyMCE.linkElement, true);");\r
+                               // Custom match\r
+                               if (format.onmatch) {\r
+                                       return format.onmatch(node, format, item_name);\r
                                }\r
 \r
-                               action = "update";\r
-                       }\r
+                               // Check all items\r
+                               if (items) {\r
+                                       // Non indexed object\r
+                                       if (items.length === undefined) {\r
+                                               for (key in items) {\r
+                                                       if (items.hasOwnProperty(key)) {\r
+                                                               if (item_name === 'attributes')\r
+                                                                       value = dom.getAttrib(node, key);\r
+                                                               else\r
+                                                                       value = getStyle(node, key);\r
+\r
+                                                               if (similar && !value && !format.exact)\r
+                                                                       return;\r
+\r
+                                                               if ((!similar || format.exact) && !isEq(value, replaceVars(items[key], vars)))\r
+                                                                       return;\r
+                                                       }\r
+                                               }\r
+                                       } else {\r
+                                               // Only one match needed for indexed arrays\r
+                                               for (i = 0; i < items.length; i++) {\r
+                                                       if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i]))\r
+                                                               return format;\r
+                                               }\r
+                                       }\r
+                               }\r
 \r
-                       if (this.settings['insertlink_callback']) {\r
-                               var returnVal = eval(this.settings['insertlink_callback'] + "(href, target, title, onclick, action, style_class);");\r
-                               if (returnVal && returnVal['href'])\r
-                                       tinyMCE.insertLink(returnVal['href'], returnVal['target'], returnVal['title'], returnVal['onclick'], returnVal['style_class']);\r
-                       } else {\r
-                               tinyMCE.openWindow(this.insertLinkTemplate, {href : href, target : target, title : title, onclick : onclick, action : action, className : style_class, inline : "yes"});\r
-                       }\r
-               break;\r
+                               return format;\r
+                       };\r
 \r
-               case "mceImage":\r
-                       var src = "", alt = "", border = "", hspace = "", vspace = "", width = "", height = "", align = "";\r
-                       var title = "", onmouseover = "", onmouseout = "", action = "insert";\r
-                       var img = tinyMCE.imgElement;\r
+                       if (formatList && node) {\r
+                               // Check each format in list\r
+                               for (i = 0; i < formatList.length; i++) {\r
+                                       format = formatList[i];\r
+\r
+                                       // Name name, attributes, styles and classes\r
+                                       if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) {\r
+                                               // Match classes\r
+                                               if (classes = format.classes) {\r
+                                                       for (i = 0; i < classes.length; i++) {\r
+                                                               if (!dom.hasClass(node, classes[i]))\r
+                                                                       return;\r
+                                                       }\r
+                                               }\r
 \r
-                       if (tinyMCE.selectedElement != null && tinyMCE.selectedElement.nodeName.toLowerCase() == "img") {\r
-                               img = tinyMCE.selectedElement;\r
-                               tinyMCE.imgElement = img;\r
+                                               return format;\r
+                                       }\r
+                               }\r
                        }\r
+               };\r
 \r
-                       if (img) {\r
-                               // Is it a internal MCE visual aid image, then skip this one.\r
-                               if (tinyMCE.getAttrib(img, 'name').indexOf('mce_') == 0)\r
-                                       return;\r
+               function match(name, vars, node) {\r
+                       var startNode, i;\r
 \r
-                               src = tinyMCE.getAttrib(img, 'src');\r
-                               alt = tinyMCE.getAttrib(img, 'alt');\r
+                       function matchParents(node) {\r
+                               // Find first node with similar format settings\r
+                               node = dom.getParent(node, function(node) {\r
+                                       return !!matchNode(node, name, vars, true);\r
+                               });\r
 \r
-                               // Try polling out the title\r
-                               if (alt == "")\r
-                                       alt = tinyMCE.getAttrib(img, 'title');\r
+                               // Do an exact check on the similar format element\r
+                               return matchNode(node, name, vars);\r
+                       };\r
 \r
-                               // Fix width/height attributes if the styles is specified\r
-                               if (tinyMCE.isGecko) {\r
-                                       var w = img.style.width;\r
-                                       if (w != null && w != "")\r
-                                               img.setAttribute("width", w);\r
+                       // Check specified node\r
+                       if (node)\r
+                               return matchParents(node);\r
 \r
-                                       var h = img.style.height;\r
-                                       if (h != null && h != "")\r
-                                               img.setAttribute("height", h);\r
+                       // Check pending formats\r
+                       if (selection.isCollapsed()) {\r
+                               for (i = pendingFormats.apply.length - 1; i >= 0; i--) {\r
+                                       if (pendingFormats.apply[i].name == name)\r
+                                               return true;\r
                                }\r
 \r
-                               border = tinyMCE.getAttrib(img, 'border');\r
-                               hspace = tinyMCE.getAttrib(img, 'hspace');\r
-                               vspace = tinyMCE.getAttrib(img, 'vspace');\r
-                               width = tinyMCE.getAttrib(img, 'width');\r
-                               height = tinyMCE.getAttrib(img, 'height');\r
-                               align = tinyMCE.getAttrib(img, 'align');\r
-                onmouseover = tinyMCE.getAttrib(img, 'onmouseover');\r
-                onmouseout = tinyMCE.getAttrib(img, 'onmouseout');\r
-                title = tinyMCE.getAttrib(img, 'title');\r
-\r
-                               // Is realy specified?\r
-                               if (tinyMCE.isMSIE) {\r
-                                       width = img.attributes['width'].specified ? width : "";\r
-                                       height = img.attributes['height'].specified ? height : "";\r
+                               for (i = pendingFormats.remove.length - 1; i >= 0; i--) {\r
+                                       if (pendingFormats.remove[i].name == name)\r
+                                               return false;\r
                                }\r
 \r
-                               onmouseover = tinyMCE.getImageSrc(tinyMCE.cleanupEventStr(onmouseover));\r
-                               onmouseout = tinyMCE.getImageSrc(tinyMCE.cleanupEventStr(onmouseout));\r
+                               return matchParents(selection.getNode());\r
+                       }\r
 \r
-                               src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, img, true);");\r
+                       // Check selected node\r
+                       node = selection.getNode();\r
+                       if (matchParents(node))\r
+                               return TRUE;\r
 \r
-                               // Use mce_src if defined\r
-                               mceRealSrc = tinyMCE.getAttrib(img, 'mce_src');\r
-                               if (mceRealSrc != "") {\r
-                                       src = mceRealSrc;\r
+                       // Check start node if it's different\r
+                       startNode = selection.getStart();\r
+                       if (startNode != node) {\r
+                               if (matchParents(startNode))\r
+                                       return TRUE;\r
+                       }\r
 \r
-                                       if (tinyMCE.getParam('convert_urls'))\r
-                                               src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, img, true);");\r
-                               }\r
+                       return FALSE;\r
+               };\r
 \r
-                               if (onmouseover != "")\r
-                                       onmouseover = eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseover, img, true);");\r
+               function matchAll(names, vars) {\r
+                       var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name;\r
+\r
+                       // If the selection is collapsed then check pending formats\r
+                       if (selection.isCollapsed()) {\r
+                               for (ni = 0; ni < names.length; ni++) {\r
+                                       // If the name is to be removed, then stop it from being added\r
+                                       for (i = pendingFormats.remove.length - 1; i >= 0; i--) {\r
+                                               name = names[ni];\r
+\r
+                                               if (pendingFormats.remove[i].name == name) {\r
+                                                       checkedMap[name] = true;\r
+                                                       break;\r
+                                               }\r
+                                       }\r
+                               }\r
 \r
-                               if (onmouseout != "")\r
-                                       onmouseout = eval(tinyMCE.settings['urlconverter_callback'] + "(onmouseout, img, true);");\r
+                               // If the format is to be applied\r
+                               for (i = pendingFormats.apply.length - 1; i >= 0; i--) {\r
+                                       for (ni = 0; ni < names.length; ni++) {\r
+                                               name = names[ni];\r
 \r
-                               action = "update";\r
+                                               if (!checkedMap[name] && pendingFormats.apply[i].name == name) {\r
+                                                       checkedMap[name] = true;\r
+                                                       matchedFormatNames.push(name);\r
+                                               }\r
+                                       }\r
+                               }\r
                        }\r
 \r
-                       if (this.settings['insertimage_callback']) {\r
-                               var returnVal = eval(this.settings['insertimage_callback'] + "(src, alt, border, hspace, vspace, width, height, align, title, onmouseover, onmouseout, action);");\r
-                               if (returnVal && returnVal['src'])\r
-                                       tinyMCE.insertImage(returnVal['src'], returnVal['alt'], returnVal['border'], returnVal['hspace'], returnVal['vspace'], returnVal['width'], returnVal['height'], returnVal['align'], returnVal['title'], returnVal['onmouseover'], returnVal['onmouseout']);\r
-                       } else\r
-                               tinyMCE.openWindow(this.insertImageTemplate, {src : src, alt : alt, border : border, hspace : hspace, vspace : vspace, width : width, height : height, align : align, title : title, onmouseover : onmouseover, onmouseout : onmouseout, action : action, inline : "yes"});\r
-               break;\r
+                       // Check start of selection for formats\r
+                       startElement = selection.getStart();\r
+                       dom.getParent(startElement, function(node) {\r
+                               var i, name;\r
 \r
-               case "mceCleanup":\r
-                       tinyMCE._setHTML(this.contentDocument, this.getBody().innerHTML);\r
-                       tinyMCE.setInnerHTML(this.getBody(), tinyMCE._cleanupHTML(this, this.contentDocument, this.settings, this.getBody(), this.visualAid));\r
-                       this.convertAllRelativeURLs();\r
-                       tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);\r
-                       tinyMCE._setEventsEnabled(this.getBody(), false);\r
-                       this.repaint();\r
-                       tinyMCE.triggerNodeChange();\r
-               break;\r
+                               for (i = 0; i < names.length; i++) {\r
+                                       name = names[i];\r
 \r
-               case "mceReplaceContent":\r
-                       this.getWin().focus();\r
+                                       if (!checkedMap[name] && matchNode(node, name, vars)) {\r
+                                               checkedMap[name] = true;\r
+                                               matchedFormatNames.push(name);\r
+                                       }\r
+                               }\r
+                       });\r
 \r
-                       var selectedText = "";\r
+                       return matchedFormatNames;\r
+               };\r
 \r
-                       if (tinyMCE.isMSIE) {\r
-                               var rng = doc.selection.createRange();\r
-                               selectedText = rng.text;\r
-                       } else\r
-                               selectedText = this.getSel().toString();\r
+               function canApply(name) {\r
+                       var formatList = get(name), startNode, parents, i, x, selector;\r
 \r
-                       if (selectedText.length > 0) {\r
-                               value = tinyMCE.replaceVar(value, "selection", selectedText);\r
-                               tinyMCE.execCommand('mceInsertContent', false, value);\r
-                       }\r
+                       if (formatList) {\r
+                               startNode = selection.getStart();\r
+                               parents = getParents(startNode);\r
 \r
-                       tinyMCE.triggerNodeChange();\r
-               break;\r
+                               for (x = formatList.length - 1; x >= 0; x--) {\r
+                                       selector = formatList[x].selector;\r
 \r
-               case "mceSetAttribute":\r
-                       if (typeof(value) == 'object') {\r
-                               var targetElms = (typeof(value['targets']) == "undefined") ? "p,img,span,div,td,h1,h2,h3,h4,h5,h6,pre,address" : value['targets'];\r
-                               var targetNode = tinyMCE.getParentElement(this.getFocusElement(), targetElms);\r
+                                       // Format is not selector based, then always return TRUE\r
+                                       if (!selector)\r
+                                               return TRUE;\r
 \r
-                               if (targetNode) {\r
-                                       targetNode.setAttribute(value['name'], value['value']);\r
-                                       tinyMCE.triggerNodeChange();\r
+                                       for (i = parents.length - 1; i >= 0; i--) {\r
+                                               if (dom.is(parents[i], selector))\r
+                                                       return TRUE;\r
+                                       }\r
                                }\r
                        }\r
-               break;\r
 \r
-               case "mceSetCSSClass":\r
-                       this.execCommand("SetStyleInfo", false, {command : "setattrib", name : "class", value : value});\r
-               break;\r
+                       return FALSE;\r
+               };\r
+\r
+               // Expose to public\r
+               tinymce.extend(this, {\r
+                       get : get,\r
+                       register : register,\r
+                       apply : apply,\r
+                       remove : remove,\r
+                       toggle : toggle,\r
+                       match : match,\r
+                       matchAll : matchAll,\r
+                       matchNode : matchNode,\r
+                       canApply : canApply\r
+               });\r
+\r
+               // Private functions\r
+\r
+               function matchName(node, format) {\r
+                       // Check for inline match\r
+                       if (isEq(node, format.inline))\r
+                               return TRUE;\r
+\r
+                       // Check for block match\r
+                       if (isEq(node, format.block))\r
+                               return TRUE;\r
+\r
+                       // Check for selector match\r
+                       if (format.selector)\r
+                               return dom.is(node, format.selector);\r
+               };\r
+\r
+               function isEq(str1, str2) {\r
+                       str1 = str1 || '';\r
+                       str2 = str2 || '';\r
+\r
+                       str1 = '' + (str1.nodeName || str1);\r
+                       str2 = '' + (str2.nodeName || str2);\r
+\r
+                       return str1.toLowerCase() == str2.toLowerCase();\r
+               };\r
+\r
+               function getStyle(node, name) {\r
+                       var styleVal = dom.getStyle(node, name);\r
+\r
+                       // Force the format to hex\r
+                       if (name == 'color' || name == 'backgroundColor')\r
+                               styleVal = dom.toHex(styleVal);\r
+\r
+                       // Opera will return bold as 700\r
+                       if (name == 'fontWeight' && styleVal == 700)\r
+                               styleVal = 'bold';\r
+\r
+                       return '' + styleVal;\r
+               };\r
+\r
+               function replaceVars(value, vars) {\r
+                       if (typeof(value) != "string")\r
+                               value = value(vars);\r
+                       else if (vars) {\r
+                               value = value.replace(/%(\w+)/g, function(str, name) {\r
+                                       return vars[name] || str;\r
+                               });\r
+                       }\r
 \r
-               case "mceInsertRawHTML":\r
-                       var key = 'tiny_mce_marker';\r
+                       return value;\r
+               };\r
 \r
-                       this.execCommand('mceBeginUndoLevel');\r
+               function isWhiteSpaceNode(node) {\r
+                       return node && node.nodeType === 3 && /^([\s\r\n]+|)$/.test(node.nodeValue);\r
+               };\r
 \r
-                       // Insert marker key\r
-                       this.execCommand('mceInsertContent', false, key);\r
+               function wrap(node, name, attrs) {\r
+                       var wrapper = dom.create(name, attrs);\r
 \r
-                       // Store away scroll pos\r
-                       var scrollX = this.getDoc().body.scrollLeft + this.getDoc().documentElement.scrollLeft;\r
-                       var scrollY = this.getDoc().body.scrollTop + this.getDoc().documentElement.scrollTop;\r
+                       node.parentNode.insertBefore(wrapper, node);\r
+                       wrapper.appendChild(node);\r
 \r
-                       // Find marker and replace with RAW HTML\r
-                       var html = this.getBody().innerHTML;\r
-                       if ((pos = html.indexOf(key)) != -1)\r
-                               tinyMCE.setInnerHTML(this.getBody(), html.substring(0, pos) + value + html.substring(pos + key.length));\r
+                       return wrapper;\r
+               };\r
 \r
-                       // Restore scoll pos\r
-                       this.contentWindow.scrollTo(scrollX, scrollY);\r
+               function expandRng(rng, format, remove) {\r
+                       var startContainer = rng.startContainer,\r
+                               startOffset = rng.startOffset,\r
+                               endContainer = rng.endContainer,\r
+                               endOffset = rng.endOffset, sibling, lastIdx, leaf;\r
 \r
-                       this.execCommand('mceEndUndoLevel');\r
+                       // This function walks up the tree if there is no siblings before/after the node\r
+                       function findParentContainer(container, child_name, sibling_name, root) {\r
+                               var parent, child;\r
 \r
-                       break;\r
+                               root = root || dom.getRoot();\r
 \r
-               case "mceInsertContent":\r
-                       var insertHTMLFailed = false;\r
-                       this.getWin().focus();\r
+                               for (;;) {\r
+                                       // Check if we can move up are we at root level or body level\r
+                                       parent = container.parentNode;\r
 \r
-                       if (tinyMCE.isGecko || tinyMCE.isOpera) {\r
-                               try {\r
-                                       // Is plain text or HTML\r
-                                       if (value.indexOf('<') == -1) {\r
-                                               var r = this.getRng();\r
-                                               var n = this.getDoc().createTextNode(tinyMCE.entityDecode(value));\r
-                                               var s = this.getSel();\r
-                                               var r2 = r.cloneRange();\r
-\r
-                                               // Insert text at cursor position\r
-                                               s.removeAllRanges();\r
-                                               r.deleteContents();\r
-                                               r.insertNode(n);\r
+                                       // Stop expanding on block elements or root depending on format\r
+                                       if (parent == root || (!format[0].block_expand && isBlock(parent)))\r
+                                               return container;\r
 \r
-                                               // Move the cursor to the end of text\r
-                                               r2.selectNode(n);\r
-                                               r2.collapse(false);\r
-                                               s.removeAllRanges();\r
-                                               s.addRange(r2);\r
-                                       } else {\r
-                                               value = tinyMCE.fixGeckoBaseHREFBug(1, this.getDoc(), value);\r
-                                               this.getDoc().execCommand('inserthtml', false, value);\r
-                                               tinyMCE.fixGeckoBaseHREFBug(2, this.getDoc(), value);\r
+                                       for (sibling = parent[child_name]; sibling && sibling != container; sibling = sibling[sibling_name]) {\r
+                                               if (sibling.nodeType == 1 && !isBookmarkNode(sibling))\r
+                                                       return container;\r
+\r
+                                               if (sibling.nodeType == 3 && !isWhiteSpaceNode(sibling))\r
+                                                       return container;\r
                                        }\r
-                               } catch (ex) {\r
-                                       insertHTMLFailed = true;\r
+\r
+                                       container = container.parentNode;\r
                                }\r
 \r
-                               if (!insertHTMLFailed) {\r
-                                       tinyMCE.triggerNodeChange();\r
-                                       return;\r
+                               return container;\r
+                       };\r
+\r
+                       // This function walks down the tree to find the leaf at the selection.\r
+                       // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node.\r
+                       function findLeaf(node, offset) {\r
+                               if (offset === undefined)\r
+                                       offset = node.nodeType === 3 ? node.length : node.childNodes.length;\r
+                               while (node && node.hasChildNodes()) {\r
+                                       node = node.childNodes[offset];\r
+                                       if (node)\r
+                                               offset = node.nodeType === 3 ? node.length : node.childNodes.length;\r
                                }\r
+                               return { node: node, offset: offset };\r
                        }\r
 \r
-                       // Ugly hack in Opera due to non working "inserthtml"\r
-                       if (tinyMCE.isOpera && insertHTMLFailed) {\r
-                               this.getDoc().execCommand("insertimage", false, tinyMCE.uniqueURL);\r
-                               var ar = tinyMCE.getElementsByAttributeValue(this.getBody(), "img", "src", tinyMCE.uniqueURL);\r
-                               ar[0].outerHTML = value;\r
-                               return;\r
+                       // If index based start position then resolve it\r
+                       if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) {\r
+                               lastIdx = startContainer.childNodes.length - 1;\r
+                               startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset];\r
+\r
+                               if (startContainer.nodeType == 3)\r
+                                       startOffset = 0;\r
                        }\r
 \r
-                       if (!tinyMCE.isMSIE) {\r
-                               var isHTML = value.indexOf('<') != -1;\r
-                               var sel = this.getSel();\r
-                               var rng = this.getRng();\r
+                       // If index based end position then resolve it\r
+                       if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) {\r
+                               lastIdx = endContainer.childNodes.length - 1;\r
+                               endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1];\r
 \r
-                               if (isHTML) {\r
-                                       if (tinyMCE.isSafari) {\r
-                                               var tmpRng = this.getDoc().createRange();\r
+                               if (endContainer.nodeType == 3)\r
+                                       endOffset = endContainer.nodeValue.length;\r
+                       }\r
 \r
-                                               tmpRng.setStart(this.getBody(), 0);\r
-                                               tmpRng.setEnd(this.getBody(), 0);\r
+                       // Exclude bookmark nodes if possible\r
+                       if (isBookmarkNode(startContainer.parentNode))\r
+                               startContainer = startContainer.parentNode;\r
 \r
-                                               value = tmpRng.createContextualFragment(value);\r
-                                       } else\r
-                                               value = rng.createContextualFragment(value);\r
-                               } else {\r
-                                       // Setup text node\r
-                                       var el = document.createElement("div");\r
-                                       el.innerHTML = value;\r
-                                       value = el.firstChild.nodeValue;\r
-                                       value = doc.createTextNode(value);\r
-                               }\r
+                       if (isBookmarkNode(startContainer))\r
+                               startContainer = startContainer.nextSibling || startContainer;\r
 \r
-                               // Insert plain text in Safari\r
-                               if (tinyMCE.isSafari && !isHTML) {\r
-                                       this.execCommand('InsertText', false, value.nodeValue);\r
-                                       tinyMCE.triggerNodeChange();\r
-                                       return true;\r
-                               } else if (tinyMCE.isSafari && isHTML) {\r
-                                       rng.deleteContents();\r
-                                       rng.insertNode(value);\r
-                                       tinyMCE.triggerNodeChange();\r
-                                       return true;\r
-                               }\r
+                       if (isBookmarkNode(endContainer.parentNode)) {\r
+                               endOffset = dom.nodeIndex(endContainer);\r
+                               endContainer = endContainer.parentNode;\r
+                       }\r
 \r
-                               rng.deleteContents();\r
+                       if (isBookmarkNode(endContainer) && endContainer.previousSibling) {\r
+                               endContainer = endContainer.previousSibling;\r
+                               endOffset = endContainer.length;\r
+                       }\r
 \r
-                               // If target node is text do special treatment, (Mozilla 1.3 fix)\r
-                               if (rng.startContainer.nodeType == 3) {\r
-                                       var node = rng.startContainer.splitText(rng.startOffset);\r
-                                       node.parentNode.insertBefore(value, node); \r
-                               } else\r
-                                       rng.insertNode(value);\r
+                       if (format[0].inline) {\r
+                               // Avoid applying formatting to a trailing space.\r
+                               leaf = findLeaf(endContainer, endOffset);\r
+                               if (leaf.node) {\r
+                                       while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling)\r
+                                               leaf = findLeaf(leaf.node.previousSibling);\r
+\r
+                                       if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 &&\r
+                                                       leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') {\r
+\r
+                                               if (leaf.offset > 1) {\r
+                                                       endContainer = leaf.node;\r
+                                                       endContainer.splitText(leaf.offset - 1);\r
+                                               } else if (leaf.node.previousSibling) {\r
+                                                       endContainer = leaf.node.previousSibling;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       // Move start/end point up the tree if the leaves are sharp and if we are in different containers\r
+                       // Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!\r
+                       // This will reduce the number of wrapper elements that needs to be created\r
+                       // Move start point up the tree\r
+                       if (format[0].inline || format[0].block_expand) {\r
+                               startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');\r
+                               endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');\r
+                       }\r
 \r
-                               if (!isHTML) {\r
-                                       // Removes weird selection trails\r
-                                       sel.selectAllChildren(doc.body);\r
-                                       sel.removeAllRanges();\r
+                       // Expand start/end container to matching selector\r
+                       if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) {\r
+                               function findSelectorEndPoint(container, sibling_name) {\r
+                                       var parents, i, y, curFormat;\r
 \r
-                                       // Move cursor to end of content\r
-                                       var rng = doc.createRange();\r
+                                       if (container.nodeType == 3 && container.nodeValue.length == 0 && container[sibling_name])\r
+                                               container = container[sibling_name];\r
 \r
-                                       rng.selectNode(value);\r
-                                       rng.collapse(false);\r
+                                       parents = getParents(container);\r
+                                       for (i = 0; i < parents.length; i++) {\r
+                                               for (y = 0; y < format.length; y++) {\r
+                                                       curFormat = format[y];\r
 \r
-                                       sel.addRange(rng);\r
-                               } else\r
-                                       rng.collapse(false);\r
-                       } else {\r
-                               var rng = doc.selection.createRange();\r
-                               var c = value.indexOf('<!--') != -1;\r
+                                                       // If collapsed state is set then skip formats that doesn't match that\r
+                                                       if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed)\r
+                                                               continue;\r
 \r
-                               // Fix comment bug, add tag before comments\r
-                               if (c)\r
-                                       value = tinyMCE.uniqueTag + value;\r
+                                                       if (dom.is(parents[i], curFormat.selector))\r
+                                                               return parents[i];\r
+                                               }\r
+                                       }\r
 \r
-                               if (rng.item)\r
-                                       rng.item(0).outerHTML = value;\r
-                               else\r
-                                       rng.pasteHTML(value);\r
+                                       return container;\r
+                               };\r
 \r
-                               // Remove unique tag\r
-                               if (c) {\r
-                                       var e = this.getDoc().getElementById('mceTMPElement');\r
-                                       e.parentNode.removeChild(e);\r
-                               }\r
+                               // Find new startContainer/endContainer if there is better one\r
+                               startContainer = findSelectorEndPoint(startContainer, 'previousSibling');\r
+                               endContainer = findSelectorEndPoint(endContainer, 'nextSibling');\r
                        }\r
 \r
-                       tinyMCE.triggerNodeChange();\r
-               break;\r
+                       // Expand start/end container to matching block element or text node\r
+                       if (format[0].block || format[0].selector) {\r
+                               function findBlockEndPoint(container, sibling_name, sibling_name2) {\r
+                                       var node;\r
 \r
-               case "mceStartTyping":\r
-                       if (tinyMCE.settings['custom_undo_redo'] && this.typingUndoIndex == -1) {\r
-                               this.typingUndoIndex = this.undoIndex;\r
-                               this.execCommand('mceAddUndoLevel');\r
-                               //tinyMCE.debug("mceStartTyping");\r
-                       }\r
-                       break;\r
+                                       // Expand to block of similar type\r
+                                       if (!format[0].wrapper)\r
+                                               node = dom.getParent(container, format[0].block);\r
 \r
-               case "mceEndTyping":\r
-                       if (tinyMCE.settings['custom_undo_redo'] && this.typingUndoIndex != -1) {\r
-                               this.execCommand('mceAddUndoLevel');\r
-                               this.typingUndoIndex = -1;\r
-                               //tinyMCE.debug("mceEndTyping");\r
-                       }\r
-                       break;\r
+                                       // Expand to first wrappable block element or any block element\r
+                                       if (!node)\r
+                                               node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock);\r
+\r
+                                       // Exclude inner lists from wrapping\r
+                                       if (node && format[0].wrapper)\r
+                                               node = getParents(node, 'ul,ol').reverse()[0] || node;\r
+\r
+                                       // Didn't find a block element look for first/last wrappable element\r
+                                       if (!node) {\r
+                                               node = container;\r
+\r
+                                               while (node[sibling_name] && !isBlock(node[sibling_name])) {\r
+                                                       node = node[sibling_name];\r
+\r
+                                                       // Break on BR but include it will be removed later on\r
+                                                       // we can't remove it now since we need to check if it can be wrapped\r
+                                                       if (isEq(node, 'br'))\r
+                                                               break;\r
+                                               }\r
+                                       }\r
 \r
-               case "mceBeginUndoLevel":\r
-                       this.undoRedo = false;\r
-                       break;\r
+                                       return node || container;\r
+                               };\r
 \r
-               case "mceEndUndoLevel":\r
-                       this.undoRedo = true;\r
-                       this.execCommand('mceAddUndoLevel');\r
-                       break;\r
+                               // Find new startContainer/endContainer if there is better one\r
+                               startContainer = findBlockEndPoint(startContainer, 'previousSibling');\r
+                               endContainer = findBlockEndPoint(endContainer, 'nextSibling');\r
 \r
-               case "mceAddUndoLevel":\r
-                       if (tinyMCE.settings['custom_undo_redo'] && this.undoRedo) {\r
-                               // tinyMCE.debug("add level");\r
+                               // Non block element then try to expand up the leaf\r
+                               if (format[0].block) {\r
+                                       if (!isBlock(startContainer))\r
+                                               startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');\r
 \r
-                               if (this.typingUndoIndex != -1) {\r
-                                       this.undoIndex = this.typingUndoIndex;\r
-                                       // tinyMCE.debug("Override: " + this.undoIndex);\r
+                                       if (!isBlock(endContainer))\r
+                                               endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');\r
                                }\r
+                       }\r
+\r
+                       // Setup index for startContainer\r
+                       if (startContainer.nodeType == 1) {\r
+                               startOffset = nodeIndex(startContainer);\r
+                               startContainer = startContainer.parentNode;\r
+                       }\r
 \r
-                               var newHTML = tinyMCE.trim(this.getBody().innerHTML);\r
-                               if (newHTML != this.undoLevels[this.undoIndex]) {\r
-                                       tinyMCE.executeCallback('onchange_callback', '_onchange', 0, this);\r
+                       // Setup index for endContainer\r
+                       if (endContainer.nodeType == 1) {\r
+                               endOffset = nodeIndex(endContainer) + 1;\r
+                               endContainer = endContainer.parentNode;\r
+                       }\r
 \r
-                                       // Time to compress\r
-                                       var customUndoLevels = tinyMCE.settings['custom_undo_redo_levels'];\r
-                                       if (customUndoLevels != -1 && this.undoLevels.length > customUndoLevels) {\r
-                                               for (var i=0; i<this.undoLevels.length-1; i++) {\r
-                                                       //tinyMCE.debug(this.undoLevels[i] + "=" + this.undoLevels[i+1]);\r
-                                                       this.undoLevels[i] = this.undoLevels[i+1];\r
-                                               }\r
+                       // Return new range like object\r
+                       return {\r
+                               startContainer : startContainer,\r
+                               startOffset : startOffset,\r
+                               endContainer : endContainer,\r
+                               endOffset : endOffset\r
+                       };\r
+               }\r
+\r
+               function removeFormat(format, vars, node, compare_node) {\r
+                       var i, attrs, stylesModified;\r
+\r
+                       // Check if node matches format\r
+                       if (!matchName(node, format))\r
+                               return FALSE;\r
+\r
+                       // Should we compare with format attribs and styles\r
+                       if (format.remove != 'all') {\r
+                               // Remove styles\r
+                               each(format.styles, function(value, name) {\r
+                                       value = replaceVars(value, vars);\r
 \r
-                                               this.undoLevels.length--;\r
-                                               this.undoIndex--;\r
+                                       // Indexed array\r
+                                       if (typeof(name) === 'number') {\r
+                                               name = value;\r
+                                               compare_node = 0;\r
                                        }\r
 \r
-                                       this.undoIndex++;\r
-                                       this.undoLevels[this.undoIndex] = newHTML;\r
-                                       this.undoLevels.length = this.undoIndex + 1;\r
+                                       if (!compare_node || isEq(getStyle(compare_node, name), value))\r
+                                               dom.setStyle(node, name, '');\r
 \r
-                                       // tinyMCE.debug("level added" + this.undoIndex);\r
-                                       tinyMCE.triggerNodeChange(false);\r
+                                       stylesModified = 1;\r
+                               });\r
 \r
-                                       // tinyMCE.debug(this.undoIndex + "," + (this.undoLevels.length-1));\r
+                               // Remove style attribute if it's empty\r
+                               if (stylesModified && dom.getAttrib(node, 'style') == '') {\r
+                                       node.removeAttribute('style');\r
+                                       node.removeAttribute('data-mce-style');\r
                                }\r
-                       }\r
-                       break;\r
 \r
-               case "Undo":\r
-                       if (tinyMCE.settings['custom_undo_redo']) {\r
-                               tinyMCE.execCommand("mceEndTyping");\r
+                               // Remove attributes\r
+                               each(format.attributes, function(value, name) {\r
+                                       var valueOut;\r
 \r
-                               // Do undo\r
-                               if (this.undoIndex > 0) {\r
-                                       this.undoIndex--;\r
-                                       tinyMCE.setInnerHTML(this.getBody(), this.undoLevels[this.undoIndex]);\r
-                                       this.repaint();\r
-                               }\r
+                                       value = replaceVars(value, vars);\r
 \r
-                               // tinyMCE.debug("Undo - undo levels:" + this.undoLevels.length + ", undo index: " + this.undoIndex);\r
-                               tinyMCE.triggerNodeChange();\r
-                       } else\r
-                               this.getDoc().execCommand(command, user_interface, value);\r
-                       break;\r
+                                       // Indexed array\r
+                                       if (typeof(name) === 'number') {\r
+                                               name = value;\r
+                                               compare_node = 0;\r
+                                       }\r
 \r
-               case "Redo":\r
-                       if (tinyMCE.settings['custom_undo_redo']) {\r
-                               tinyMCE.execCommand("mceEndTyping");\r
+                                       if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) {\r
+                                               // Keep internal classes\r
+                                               if (name == 'class') {\r
+                                                       value = dom.getAttrib(node, name);\r
+                                                       if (value) {\r
+                                                               // Build new class value where everything is removed except the internal prefixed classes\r
+                                                               valueOut = '';\r
+                                                               each(value.split(/\s+/), function(cls) {\r
+                                                                       if (/mce\w+/.test(cls))\r
+                                                                               valueOut += (valueOut ? ' ' : '') + cls;\r
+                                                               });\r
+\r
+                                                               // We got some internal classes left\r
+                                                               if (valueOut) {\r
+                                                                       dom.setAttrib(node, name, valueOut);\r
+                                                                       return;\r
+                                                               }\r
+                                                       }\r
+                                               }\r
 \r
-                               if (this.undoIndex < (this.undoLevels.length-1)) {\r
-                                       this.undoIndex++;\r
-                                       tinyMCE.setInnerHTML(this.getBody(), this.undoLevels[this.undoIndex]);\r
-                                       this.repaint();\r
-                                       // tinyMCE.debug("Redo - undo levels:" + this.undoLevels.length + ", undo index: " + this.undoIndex);\r
-                               }\r
+                                               // IE6 has a bug where the attribute doesn't get removed correctly\r
+                                               if (name == "class")\r
+                                                       node.removeAttribute('className');\r
 \r
-                               tinyMCE.triggerNodeChange();\r
-                       } else\r
-                               this.getDoc().execCommand(command, user_interface, value);\r
-                       break;\r
-\r
-               case "mceToggleVisualAid":\r
-                       this.visualAid = !this.visualAid;\r
-                       tinyMCE.handleVisualAid(this.getBody(), true, this.visualAid, this);\r
-                       tinyMCE.triggerNodeChange();\r
-                       break;\r
-\r
-               case "Indent":\r
-                       this.getDoc().execCommand(command, user_interface, value);\r
-                       tinyMCE.triggerNodeChange();\r
-                       if (tinyMCE.isMSIE) {\r
-                               var n = tinyMCE.getParentElement(this.getFocusElement(), "blockquote");\r
-                               do {\r
-                                       if (n && n.nodeName == "BLOCKQUOTE") {\r
-                                               n.removeAttribute("dir");\r
-                                               n.removeAttribute("style");\r
+                                               // Remove mce prefixed attributes\r
+                                               if (MCE_ATTR_RE.test(name))\r
+                                                       node.removeAttribute('data-mce-' + name);\r
+\r
+                                               node.removeAttribute(name);\r
                                        }\r
-                               } while (n != null && (n = n.parentNode) != null);\r
-                       }\r
-                       break;\r
+                               });\r
 \r
-               case "removeformat":\r
-                       var text = this.getSelectedText();\r
+                               // Remove classes\r
+                               each(format.classes, function(value) {\r
+                                       value = replaceVars(value, vars);\r
 \r
-                       if (tinyMCE.isOpera) {\r
-                               this.getDoc().execCommand("RemoveFormat", false, null);\r
-                               return;\r
-                       }\r
+                                       if (!compare_node || dom.hasClass(compare_node, value))\r
+                                               dom.removeClass(node, value);\r
+                               });\r
 \r
-                       if (tinyMCE.isMSIE) {\r
-                               try {\r
-                                       var rng = doc.selection.createRange();\r
-                                       rng.execCommand("RemoveFormat", false, null);\r
-                               } catch (e) {\r
-                                       // Do nothing\r
+                               // Check for non internal attributes\r
+                               attrs = dom.getAttribs(node);\r
+                               for (i = 0; i < attrs.length; i++) {\r
+                                       if (attrs[i].nodeName.indexOf('_') !== 0)\r
+                                               return FALSE;\r
                                }\r
+                       }\r
 \r
-                               this.execCommand("SetStyleInfo", false, {command : "removeformat"});\r
-                       } else {\r
-                               this.getDoc().execCommand(command, user_interface, value);\r
-\r
-                               this.execCommand("SetStyleInfo", false, {command : "removeformat"});\r
+                       // Remove the inline child if it's empty for example <b> or <span>\r
+                       if (format.remove != 'none') {\r
+                               removeNode(node, format);\r
+                               return TRUE;\r
                        }\r
+               };\r
 \r
-                       // Remove class\r
-                       if (text.length == 0)\r
-                               this.execCommand("mceSetCSSClass", false, "");\r
+               function removeNode(node, format) {\r
+                       var parentNode = node.parentNode, rootBlockElm;\r
 \r
-                       tinyMCE.triggerNodeChange();\r
-                       break;\r
+                       if (format.block) {\r
+                               if (!forcedRootBlock) {\r
+                                       function find(node, next, inc) {\r
+                                               node = getNonWhiteSpaceSibling(node, next, inc);\r
 \r
-               default:\r
-                       this.getDoc().execCommand(command, user_interface, value);\r
+                                               return !node || (node.nodeName == 'BR' || isBlock(node));\r
+                                       };\r
 \r
-                       if (tinyMCE.isGecko)\r
-                               window.setTimeout('tinyMCE.triggerNodeChange(false);', 1);\r
-                       else\r
-                               tinyMCE.triggerNodeChange();\r
-       }\r
+                                       // Append BR elements if needed before we remove the block\r
+                                       if (isBlock(node) && !isBlock(parentNode)) {\r
+                                               if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1))\r
+                                                       node.insertBefore(dom.create('br'), node.firstChild);\r
 \r
-       // Add undo level after modification\r
-       if (command != "mceAddUndoLevel" && command != "Undo" && command != "Redo" && command != "mceStartTyping" && command != "mceEndTyping")\r
-               tinyMCE.execCommand("mceAddUndoLevel");\r
-};\r
+                                               if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1))\r
+                                                       node.appendChild(dom.create('br'));\r
+                                       }\r
+                               } else {\r
+                                       // Wrap the block in a forcedRootBlock if we are at the root of document\r
+                                       if (parentNode == dom.getRoot()) {\r
+                                               if (!format.list_block || !isEq(node, format.list_block)) {\r
+                                                       each(tinymce.grep(node.childNodes), function(node) {\r
+                                                               if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) {\r
+                                                                       if (!rootBlockElm)\r
+                                                                               rootBlockElm = wrap(node, forcedRootBlock);\r
+                                                                       else\r
+                                                                               rootBlockElm.appendChild(node);\r
+                                                               } else\r
+                                                                       rootBlockElm = 0;\r
+                                                       });\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
 \r
-TinyMCEControl.prototype.queryCommandValue = function(command) {\r
-       try {\r
-               return this.getDoc().queryCommandValue(command);\r
-       } catch (ex) {\r
-               return null;\r
-       }\r
-};\r
+                       // Never remove nodes that isn't the specified inline element if a selector is specified too\r
+                       if (format.selector && format.inline && !isEq(format.inline, node))\r
+                               return;\r
 \r
-TinyMCEControl.prototype.queryCommandState = function(command) {\r
-       return this.getDoc().queryCommandState(command);\r
-};\r
+                       dom.remove(node, 1);\r
+               };\r
 \r
-TinyMCEControl.prototype.onAdd = function(replace_element, form_element_name, target_document) {\r
-       var targetDoc = target_document ? target_document : document;\r
+               function getNonWhiteSpaceSibling(node, next, inc) {\r
+                       if (node) {\r
+                               next = next ? 'nextSibling' : 'previousSibling';\r
 \r
-       this.targetDoc = targetDoc;\r
+                               for (node = inc ? node : node[next]; node; node = node[next]) {\r
+                                       if (node.nodeType == 1 || !isWhiteSpaceNode(node))\r
+                                               return node;\r
+                               }\r
+                       }\r
+               };\r
 \r
-       tinyMCE.themeURL = tinyMCE.baseURL + "/themes/" + this.settings['theme'];\r
-       this.settings['themeurl'] = tinyMCE.themeURL;\r
+               function isBookmarkNode(node) {\r
+                       return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark';\r
+               };\r
 \r
-       if (!replace_element) {\r
-               alert("Error: Could not find the target element.");\r
-               return false;\r
-       }\r
+               function mergeSiblings(prev, next) {\r
+                       var marker, sibling, tmpSibling;\r
 \r
-       var templateFunction = tinyMCE._getThemeFunction('_getInsertLinkTemplate');\r
-       if (eval("typeof(" + templateFunction + ")") != 'undefined')\r
-               this.insertLinkTemplate = eval(templateFunction + '(this.settings);');\r
+                       function compareElements(node1, node2) {\r
+                               // Not the same name\r
+                               if (node1.nodeName != node2.nodeName)\r
+                                       return FALSE;\r
 \r
-       var templateFunction = tinyMCE._getThemeFunction('_getInsertImageTemplate');\r
-       if (eval("typeof(" + templateFunction + ")") != 'undefined')\r
-               this.insertImageTemplate = eval(templateFunction + '(this.settings);');\r
+                               function getAttribs(node) {\r
+                                       var attribs = {};\r
 \r
-       var templateFunction = tinyMCE._getThemeFunction('_getEditorTemplate');\r
-       if (eval("typeof(" + templateFunction + ")") == 'undefined') {\r
-               alert("Error: Could not find the template function: " + templateFunction);\r
-               return false;\r
-       }\r
+                                       each(dom.getAttribs(node), function(attr) {\r
+                                               var name = attr.nodeName.toLowerCase();\r
 \r
-       var editorTemplate = eval(templateFunction + '(this.settings, this.editorId);');\r
+                                               // Don't compare internal attributes or style\r
+                                               if (name.indexOf('_') !== 0 && name !== 'style')\r
+                                                       attribs[name] = dom.getAttrib(node, name);\r
+                                       });\r
 \r
-       var deltaWidth = editorTemplate['delta_width'] ? editorTemplate['delta_width'] : 0;\r
-       var deltaHeight = editorTemplate['delta_height'] ? editorTemplate['delta_height'] : 0;\r
-       var html = '<span id="' + this.editorId + '_parent">' + editorTemplate['html'];\r
+                                       return attribs;\r
+                               };\r
 \r
-       var templateFunction = tinyMCE._getThemeFunction('_handleNodeChange', true);\r
-       if (eval("typeof(" + templateFunction + ")") != 'undefined')\r
-               this.settings['handleNodeChangeCallback'] = templateFunction;\r
+                               function compareObjects(obj1, obj2) {\r
+                                       var value, name;\r
 \r
-       html = tinyMCE.replaceVar(html, "editor_id", this.editorId);\r
-       this.settings['default_document'] = tinyMCE.baseURL + "/blank.htm";\r
+                                       for (name in obj1) {\r
+                                               // Obj1 has item obj2 doesn't have\r
+                                               if (obj1.hasOwnProperty(name)) {\r
+                                                       value = obj2[name];\r
 \r
-       this.settings['old_width'] = this.settings['width'];\r
-       this.settings['old_height'] = this.settings['height'];\r
+                                                       // Obj2 doesn't have obj1 item\r
+                                                       if (value === undefined)\r
+                                                               return FALSE;\r
 \r
-       // Set default width, height\r
-       if (this.settings['width'] == -1)\r
-               this.settings['width'] = replace_element.offsetWidth;\r
+                                                       // Obj2 item has a different value\r
+                                                       if (obj1[name] != value)\r
+                                                               return FALSE;\r
 \r
-       if (this.settings['height'] == -1)\r
-               this.settings['height'] = replace_element.offsetHeight;\r
+                                                       // Delete similar value\r
+                                                       delete obj2[name];\r
+                                               }\r
+                                       }\r
 \r
-       // Try the style width\r
-       if (this.settings['width'] == 0)\r
-               this.settings['width'] = replace_element.style.width;\r
+                                       // Check if obj 2 has something obj 1 doesn't have\r
+                                       for (name in obj2) {\r
+                                               // Obj2 has item obj1 doesn't have\r
+                                               if (obj2.hasOwnProperty(name))\r
+                                                       return FALSE;\r
+                                       }\r
 \r
-       // Try the style height\r
-       if (this.settings['height'] == 0)\r
-               this.settings['height'] = replace_element.style.height; \r
+                                       return TRUE;\r
+                               };\r
 \r
-       // If no width/height then default to 320x240, better than nothing\r
-       if (this.settings['width'] == 0)\r
-               this.settings['width'] = 320;\r
+                               // Attribs are not the same\r
+                               if (!compareObjects(getAttribs(node1), getAttribs(node2)))\r
+                                       return FALSE;\r
 \r
-       if (this.settings['height'] == 0)\r
-               this.settings['height'] = 240;\r
+                               // Styles are not the same\r
+                               if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style'))))\r
+                                       return FALSE;\r
 \r
-       this.settings['area_width'] = parseInt(this.settings['width']);\r
-       this.settings['area_height'] = parseInt(this.settings['height']);\r
-       this.settings['area_width'] += deltaWidth;\r
-       this.settings['area_height'] += deltaHeight;\r
+                               return TRUE;\r
+                       };\r
 \r
-       // Special % handling\r
-       if (("" + this.settings['width']).indexOf('%') != -1)\r
-               this.settings['area_width'] = "100%";\r
+                       // Check if next/prev exists and that they are elements\r
+                       if (prev && next) {\r
+                               function findElementSibling(node, sibling_name) {\r
+                                       for (sibling = node; sibling; sibling = sibling[sibling_name]) {\r
+                                               if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0)\r
+                                                       return node;\r
 \r
-       if (("" + this.settings['height']).indexOf('%') != -1)\r
-               this.settings['area_height'] = "100%";\r
+                                               if (sibling.nodeType == 1 && !isBookmarkNode(sibling))\r
+                                                       return sibling;\r
+                                       }\r
 \r
-       if (("" + replace_element.style.width).indexOf('%') != -1) {\r
-               this.settings['width'] = replace_element.style.width;\r
-               this.settings['area_width'] = "100%";\r
-       }\r
+                                       return node;\r
+                               };\r
+\r
+                               // If previous sibling is empty then jump over it\r
+                               prev = findElementSibling(prev, 'previousSibling');\r
+                               next = findElementSibling(next, 'nextSibling');\r
+\r
+                               // Compare next and previous nodes\r
+                               if (compareElements(prev, next)) {\r
+                                       // Append nodes between\r
+                                       for (sibling = prev.nextSibling; sibling && sibling != next;) {\r
+                                               tmpSibling = sibling;\r
+                                               sibling = sibling.nextSibling;\r
+                                               prev.appendChild(tmpSibling);\r
+                                       }\r
 \r
-       if (("" + replace_element.style.height).indexOf('%') != -1) {\r
-               this.settings['height'] = replace_element.style.height;\r
-               this.settings['area_height'] = "100%";\r
-       }\r
+                                       // Remove next node\r
+                                       dom.remove(next);\r
 \r
-       html = tinyMCE.applyTemplate(html);\r
+                                       // Move children into prev node\r
+                                       each(tinymce.grep(next.childNodes), function(node) {\r
+                                               prev.appendChild(node);\r
+                                       });\r
 \r
-       this.settings['width'] = this.settings['old_width'];\r
-       this.settings['height'] = this.settings['old_height'];\r
+                                       return prev;\r
+                               }\r
+                       }\r
 \r
-       this.visualAid = this.settings['visual'];\r
-       this.formTargetElementId = form_element_name;\r
+                       return next;\r
+               };\r
 \r
-       // Get replace_element contents\r
-       if (replace_element.nodeName == "TEXTAREA" || replace_element.nodeName == "INPUT")\r
-               this.startContent = replace_element.value;\r
-       else\r
-               this.startContent = replace_element.innerHTML;\r
+               function isTextBlock(name) {\r
+                       return /^(h[1-6]|p|div|pre|address|dl|dt|dd)$/.test(name);\r
+               };\r
 \r
-       // If not text area\r
-       if (replace_element.nodeName.toLowerCase() != "textarea") {\r
-               this.oldTargetElement = replace_element.cloneNode(true);\r
+               function getContainer(rng, start) {\r
+                       var container, offset, lastIdx;\r
 \r
-               // Debug mode\r
-               if (tinyMCE.settings['debug'])\r
-                       html += '<textarea wrap="off" id="' + form_element_name + '" name="' + form_element_name + '" cols="100" rows="15"></textarea>';\r
-               else\r
-                       html += '<input type="hidden" type="text" id="' + form_element_name + '" name="' + form_element_name + '" />';\r
+                       container = rng[start ? 'startContainer' : 'endContainer'];\r
+                       offset = rng[start ? 'startOffset' : 'endOffset'];\r
 \r
-               html += '</span>';\r
+                       if (container.nodeType == 1) {\r
+                               lastIdx = container.childNodes.length - 1;\r
 \r
-               // Output HTML and set editable\r
-               if (!tinyMCE.isMSIE) {\r
-                       var rng = replace_element.ownerDocument.createRange();\r
-                       rng.setStartBefore(replace_element);\r
+                               if (!start && offset)\r
+                                       offset--;\r
 \r
-                       var fragment = rng.createContextualFragment(html);\r
-                       replace_element.parentNode.replaceChild(fragment, replace_element);\r
-               } else\r
-                       replace_element.outerHTML = html;\r
-       } else {\r
-               html += '</span>';\r
+                               container = container.childNodes[offset > lastIdx ? lastIdx : offset];\r
+                       }\r
 \r
-               // Just hide the textarea element\r
-               this.oldTargetElement = replace_element;\r
+                       return container;\r
+               };\r
 \r
-               if (!tinyMCE.settings['debug'])\r
-                       this.oldTargetElement.style.display = "none";\r
+               function performCaretAction(type, name, vars) {\r
+                       var i, currentPendingFormats = pendingFormats[type],\r
+                               otherPendingFormats = pendingFormats[type == 'apply' ? 'remove' : 'apply'];\r
 \r
-               // Output HTML and set editable\r
-               if (!tinyMCE.isMSIE) {\r
-                       var rng = replace_element.ownerDocument.createRange();\r
-                       rng.setStartBefore(replace_element);\r
+                       function hasPending() {\r
+                               return pendingFormats.apply.length || pendingFormats.remove.length;\r
+                       };\r
 \r
-                       var fragment = rng.createContextualFragment(html);\r
+                       function resetPending() {\r
+                               pendingFormats.apply = [];\r
+                               pendingFormats.remove = [];\r
+                       };\r
 \r
-                       if (tinyMCE.isGecko)\r
-                               tinyMCE.insertAfter(fragment, replace_element);\r
-                       else\r
-                               replace_element.parentNode.insertBefore(fragment, replace_element);\r
-               } else\r
-                       replace_element.insertAdjacentHTML("beforeBegin", html);\r
-       }\r
+                       function perform(caret_node) {\r
+                               // Apply pending formats\r
+                               each(pendingFormats.apply.reverse(), function(item) {\r
+                                       apply(item.name, item.vars, caret_node);\r
 \r
-       // Setup iframe\r
-       var dynamicIFrame = false;\r
-       var tElm = targetDoc.getElementById(this.editorId);\r
+                                       // Colored nodes should be underlined so that the color of the underline matches the text color.\r
+                                       if (item.name === 'forecolor' && item.vars.value)\r
+                                               processUnderlineAndColor(caret_node.parentNode);\r
+                               });\r
 \r
-       if (!tinyMCE.isMSIE) {\r
-               if (tElm && tElm.nodeName.toLowerCase() == "span") {\r
-                       tElm = tinyMCE._createIFrame(tElm);\r
-                       dynamicIFrame = true;\r
-               }\r
+                               // Remove pending formats\r
+                               each(pendingFormats.remove.reverse(), function(item) {\r
+                                       remove(item.name, item.vars, caret_node);\r
+                               });\r
 \r
-               this.targetElement = tElm;\r
-               this.iframeElement = tElm;\r
-               this.contentDocument = tElm.contentDocument;\r
-               this.contentWindow = tElm.contentWindow;\r
+                               dom.remove(caret_node, 1);\r
+                               resetPending();\r
+                       };\r
 \r
-               //this.getDoc().designMode = "on";\r
-       } else {\r
-               if (tElm && tElm.nodeName.toLowerCase() == "span")\r
-                       tElm = tinyMCE._createIFrame(tElm);\r
-               else\r
-                       tElm = targetDoc.frames[this.editorId];\r
-\r
-               this.targetElement = tElm;\r
-               this.iframeElement = targetDoc.getElementById(this.editorId);\r
-\r
-               if (tinyMCE.isOpera) {\r
-                       this.contentDocument = this.iframeElement.contentDocument;\r
-                       this.contentWindow = this.iframeElement.contentWindow;\r
-                       dynamicIFrame = true;\r
-               } else {\r
-                       this.contentDocument = tElm.window.document;\r
-                       this.contentWindow = tElm.window;\r
-               }\r
+                       // Check if it already exists then ignore it\r
+                       for (i = currentPendingFormats.length - 1; i >= 0; i--) {\r
+                               if (currentPendingFormats[i].name == name)\r
+                                       return;\r
+                       }\r
 \r
-               this.getDoc().designMode = "on";\r
-       }\r
+                       currentPendingFormats.push({name : name, vars : vars});\r
 \r
-       // Setup base HTML\r
-       var doc = this.contentDocument;\r
-       if (dynamicIFrame) {\r
-               var html = tinyMCE.getParam('doctype') + '<html><head xmlns="http://www.w3.org/1999/xhtml"><base href="' + tinyMCE.settings['base_href'] + '" /><title>blank_page</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body class="mceContentBody"></body></html>';\r
-\r
-               try {\r
-                       if (!this.isHidden())\r
-                               this.getDoc().designMode = "on";\r
-\r
-                       doc.open();\r
-                       doc.write(html);\r
-                       doc.close();\r
-               } catch (e) {\r
-                       // Failed Mozilla 1.3\r
-                       this.getDoc().location.href = tinyMCE.baseURL + "/blank.htm";\r
-               }\r
-       }\r
+                       // Check if it's in the other type, then remove it\r
+                       for (i = otherPendingFormats.length - 1; i >= 0; i--) {\r
+                               if (otherPendingFormats[i].name == name)\r
+                                       otherPendingFormats.splice(i, 1);\r
+                       }\r
 \r
-       // This timeout is needed in MSIE 5.5 for some odd reason\r
-       // it seems that the document.frames isn't initialized yet?\r
-       if (tinyMCE.isMSIE)\r
-               window.setTimeout("TinyMCE.prototype.addEventHandlers('" + this.editorId + "');", 1);\r
+                       // Pending apply or remove formats\r
+                       if (hasPending()) {\r
+                               ed.getDoc().execCommand('FontName', false, 'mceinline');\r
+                               pendingFormats.lastRng = selection.getRng();\r
 \r
-       tinyMCE.setupContent(this.editorId, true);\r
+                               // IE will convert the current word\r
+                               each(dom.select('font,span'), function(node) {\r
+                                       var bookmark;\r
 \r
-       return true;\r
-};\r
+                                       if (isCaretNode(node)) {\r
+                                               bookmark = selection.getBookmark();\r
+                                               perform(node);\r
+                                               selection.moveToBookmark(bookmark);\r
+                                               ed.nodeChanged();\r
+                                       }\r
+                               });\r
+\r
+                               // Only register listeners once if we need to\r
+                               if (!pendingFormats.isListening && hasPending()) {\r
+                                       pendingFormats.isListening = true;\r
+                                       function performPendingFormat(node, textNode) {\r
+                                               var rng = dom.createRng();\r
+                                               perform(node);\r
+\r
+                                               rng.setStart(textNode, textNode.nodeValue.length);\r
+                                               rng.setEnd(textNode, textNode.nodeValue.length);\r
+                                               selection.setRng(rng);\r
+                                               ed.nodeChanged();\r
+                                       }\r
+                                       var enterKeyPressed = false;\r
+\r
+                                       each('onKeyDown,onKeyUp,onKeyPress,onMouseUp'.split(','), function(event) {\r
+                                               ed[event].addToTop(function(ed, e) {\r
+                                                       if (e.keyCode==13 && !e.shiftKey) {\r
+                                                               enterKeyPressed = true;\r
+                                                               return;\r
+                                                       }\r
+                                                       // Do we have pending formats and is the selection moved has moved\r
+                                                       if (hasPending() && !tinymce.dom.RangeUtils.compareRanges(pendingFormats.lastRng, selection.getRng())) {\r
+                                                               var foundCaret = false;\r
+                                                               each(dom.select('font,span'), function(node) {\r
+                                                                       var textNode, rng;\r
+\r
+                                                                       // Look for marker\r
+                                                                       if (isCaretNode(node)) {\r
+                                                                               foundCaret = true;\r
+                                                                               textNode = node.firstChild;\r
+\r
+                                                                               // Find the first text node within node\r
+                                                                               while (textNode && textNode.nodeType != 3)\r
+                                                                                       textNode = textNode.firstChild;\r
+\r
+                                                                               if (textNode) \r
+                                                                                       performPendingFormat(node, textNode);\r
+                                                                               else\r
+                                                                                       dom.remove(node);\r
+                                                                       }\r
+                                                               });\r
+                                                               \r
+                                                               // no caret - so we are \r
+                                                               if (enterKeyPressed && !foundCaret) {\r
+                                                                       var node = selection.getNode();\r
+                                                                       var textNode = node;\r
+\r
+                                                                       // Find the first text node within node\r
+                                                                       while (textNode && textNode.nodeType != 3)\r
+                                                                               textNode = textNode.firstChild;\r
+                                                                       if (textNode) {\r
+                                                                               node=textNode.parentNode;\r
+                                                                               while (!isBlock(node)){\r
+                                                                                       node=node.parentNode;\r
+                                                                               }\r
+                                                                               performPendingFormat(node, textNode);\r
+                                                                       }\r
+                                                               }\r
+\r
+                                                               // Always unbind and clear pending styles on keyup\r
+                                                               if (e.type == 'keyup' || e.type == 'mouseup') {\r
+                                                                       resetPending();\r
+                                                                       enterKeyPressed=false;\r
+                                                               }\r
+                                                       }\r
+                                               });\r
+                                       });\r
+                               }\r
+                       }\r
+               };\r
+       };\r
+})(tinymce);\r
 \r
-TinyMCEControl.prototype.getFocusElement = function() {\r
-       if (tinyMCE.isMSIE && !tinyMCE.isOpera) {\r
-               var doc = this.getDoc();\r
-               var rng = doc.selection.createRange();\r
+tinymce.onAddEditor.add(function(tinymce, ed) {\r
+       var filters, fontSizes, dom, settings = ed.settings;\r
 \r
-//             if (rng.collapse)\r
-//                     rng.collapse(true);\r
+       if (settings.inline_styles) {\r
+               fontSizes = tinymce.explode(settings.font_size_style_values);\r
 \r
-               var elm = rng.item ? rng.item(0) : rng.parentElement();\r
-       } else {\r
-               if (this.isHidden())\r
-                       return this.getBody();\r
+               function replaceWithSpan(node, styles) {\r
+                       tinymce.each(styles, function(value, name) {\r
+                               if (value)\r
+                                       dom.setStyle(node, name, value);\r
+                       });\r
 \r
-               var sel = this.getSel();\r
-               var rng = this.getRng();\r
+                       dom.rename(node, 'span');\r
+               };\r
+\r
+               filters = {\r
+                       font : function(dom, node) {\r
+                               replaceWithSpan(node, {\r
+                                       backgroundColor : node.style.backgroundColor,\r
+                                       color : node.color,\r
+                                       fontFamily : node.face,\r
+                                       fontSize : fontSizes[parseInt(node.size) - 1]\r
+                               });\r
+                       },\r
+\r
+                       u : function(dom, node) {\r
+                               replaceWithSpan(node, {\r
+                                       textDecoration : 'underline'\r
+                               });\r
+                       },\r
+\r
+                       strike : function(dom, node) {\r
+                               replaceWithSpan(node, {\r
+                                       textDecoration : 'line-through'\r
+                               });\r
+                       }\r
+               };\r
 \r
-               var elm = rng.commonAncestorContainer;\r
-               //var elm = (sel && sel.anchorNode) ? sel.anchorNode : null;\r
+               function convert(editor, params) {\r
+                       dom = editor.dom;\r
 \r
-               // Handle selection a image or other control like element such as anchors\r
-               if (!rng.collapsed) {\r
-                       // Is selection small\r
-                       if (rng.startContainer == rng.endContainer) {\r
-                               if (rng.startOffset - rng.endOffset < 2) {\r
-                                       if (rng.startContainer.hasChildNodes())\r
-                                               elm = rng.startContainer.childNodes[rng.startOffset];\r
-                               }\r
+                       if (settings.convert_fonts_to_spans) {\r
+                               tinymce.each(dom.select('font,u,strike', params.node), function(node) {\r
+                                       filters[node.nodeName.toLowerCase()](ed.dom, node);\r
+                               });\r
                        }\r
-               }\r
+               };\r
 \r
-               // Get the element parent of the node\r
-               elm = tinyMCE.getParentElement(elm);\r
+               ed.onPreProcess.add(convert);\r
+               ed.onSetContent.add(convert);\r
 \r
-               //if (tinyMCE.selectedElement != null && tinyMCE.selectedElement.nodeName.toLowerCase() == "img")\r
-               //      elm = tinyMCE.selectedElement;\r
+               ed.onInit.add(function() {\r
+                       ed.selection.onSetContent.add(convert);\r
+               });\r
        }\r
+});\r
 \r
-       return elm;\r
-};\r
-\r
-// Global instances\r
-var tinyMCE = new TinyMCE();\r
-var tinyMCELang = new Array();\r