From 8eefbb2158c43b51a8c33e6c480cbe61539b9535 Mon Sep 17 00:00:00 2001
From: Aleksander Machniak <alec@alec.pl>
Date: Mon, 27 Aug 2012 04:16:04 -0400
Subject: [PATCH] Add option to enable HTML editor on forwarding (#1488517)

---
 program/js/tiny_mce/tiny_mce_src.js | 11069 ++++++++++++++++++++++++++++++++++++++---------------------
 1 files changed, 7,088 insertions(+), 3,981 deletions(-)

diff --git a/program/js/tiny_mce/tiny_mce_src.js b/program/js/tiny_mce/tiny_mce_src.js
index b28a65a..e38fb7e 100644
--- a/program/js/tiny_mce/tiny_mce_src.js
+++ b/program/js/tiny_mce/tiny_mce_src.js
@@ -1,13 +1,14 @@
+// FILE IS GENERATED BY COMBINING THE SOURCES IN THE "classes" DIRECTORY SO DON'T MODIFY THIS FILE DIRECTLY
 (function(win) {
 	var whiteSpaceRe = /^\s*|\s*$/g,
-		undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
+		undef, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
 
 	var tinymce = {
 		majorVersion : '3',
 
-		minorVersion : '4.1',
+		minorVersion : '5.6',
 
-		releaseDate : '2011-03-24',
+		releaseDate : '2012-07-26',
 
 		_init : function() {
 			var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v;
@@ -20,6 +21,12 @@
 
 			t.isIE6 = t.isIE && /MSIE [56]/.test(ua);
 
+			t.isIE7 = t.isIE && /MSIE [7]/.test(ua);
+
+			t.isIE8 = t.isIE && /MSIE [8]/.test(ua);
+
+			t.isIE9 = t.isIE && /MSIE [9]/.test(ua);
+
 			t.isGecko = !t.isWebKit && /Gecko/.test(ua);
 
 			t.isMac = ua.indexOf('Mac') != -1;
@@ -27,6 +34,8 @@
 			t.isAir = /adobeair/i.test(ua);
 
 			t.isIDevice = /(iPad|iPhone)/.test(ua);
+			
+			t.isIOS5 = t.isIDevice && ua.match(/AppleWebKit\/(\d*)/)[1]>=534;
 
 			// TinyMCE .NET webcontrol might be setting the values for TinyMCE
 			if (win.tinyMCEPreInit) {
@@ -42,7 +51,8 @@
 			// If base element found, add that infront of baseURL
 			nl = d.getElementsByTagName('base');
 			for (i=0; i<nl.length; i++) {
-				if (v = nl[i].href) {
+				v = nl[i].href;
+				if (v) {
 					// Host only value like http://site.com or http://site.com:8008
 					if (/^https?:\/\/[^\/]+$/.test(v))
 						v += '/';
@@ -95,7 +105,7 @@
 
 		is : function(o, t) {
 			if (!t)
-				return o !== undefined;
+				return o !== undef;
 
 			if (t == 'array' && (o.hasOwnProperty && o instanceof Array))
 				return true;
@@ -129,7 +139,7 @@
 
 			s = s || o;
 
-			if (o.length !== undefined) {
+			if (o.length !== undef) {
 				// Indexed arrays, needed for Safari
 				for (n=0, l = o.length; n < l; n++) {
 					if (cb.call(s, o[n], n, o) === false)
@@ -183,19 +193,23 @@
 			return -1;
 		},
 
-		extend : function(o, e) {
-			var i, l, a = arguments;
+		extend : function(obj, ext) {
+			var i, l, name, args = arguments, value;
 
-			for (i = 1, l = a.length; i < l; i++) {
-				e = a[i];
+			for (i = 1, l = args.length; i < l; i++) {
+				ext = args[i];
+				for (name in ext) {
+					if (ext.hasOwnProperty(name)) {
+						value = ext[name];
 
-				tinymce.each(e, function(v, n) {
-					if (v !== undefined)
-						o[n] = v;
-				});
+						if (value !== undef) {
+							obj[name] = value;
+						}
+					}
+				}
 			}
 
-			return o;
+			return obj;
 		},
 
 
@@ -338,69 +352,69 @@
 		},
 
 		addUnload : function(f, s) {
-			var t = this;
+			var t = this, unload;
+
+			unload = function() {
+				var li = t.unloads, o, n;
+
+				if (li) {
+					// Call unload handlers
+					for (n in li) {
+						o = li[n];
+
+						if (o && o.func)
+							o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
+					}
+
+					// Detach unload function
+					if (win.detachEvent) {
+						win.detachEvent('onbeforeunload', fakeUnload);
+						win.detachEvent('onunload', unload);
+					} else if (win.removeEventListener)
+						win.removeEventListener('unload', unload, false);
+
+					// Destroy references
+					t.unloads = o = li = w = unload = 0;
+
+					// Run garbarge collector on IE
+					if (win.CollectGarbage)
+						CollectGarbage();
+				}
+			};
+
+			function fakeUnload() {
+				var d = document;
+
+				function stop() {
+					// Prevent memory leak
+					d.detachEvent('onstop', stop);
+
+					// Call unload handler
+					if (unload)
+						unload();
+
+					d = 0;
+				};
+
+				// Is there things still loading, then do some magic
+				if (d.readyState == 'interactive') {
+					// Fire unload when the currently loading page is stopped
+					if (d)
+						d.attachEvent('onstop', stop);
+
+					// Remove onstop listener after a while to prevent the unload function
+					// to execute if the user presses cancel in an onbeforeunload
+					// confirm dialog and then presses the browser stop button
+					win.setTimeout(function() {
+						if (d)
+							d.detachEvent('onstop', stop);
+					}, 0);
+				}
+			};
 
 			f = {func : f, scope : s || this};
 
 			if (!t.unloads) {
-				function unload() {
-					var li = t.unloads, o, n;
-
-					if (li) {
-						// Call unload handlers
-						for (n in li) {
-							o = li[n];
-
-							if (o && o.func)
-								o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
-						}
-
-						// Detach unload function
-						if (win.detachEvent) {
-							win.detachEvent('onbeforeunload', fakeUnload);
-							win.detachEvent('onunload', unload);
-						} else if (win.removeEventListener)
-							win.removeEventListener('unload', unload, false);
-
-						// Destroy references
-						t.unloads = o = li = w = unload = 0;
-
-						// Run garbarge collector on IE
-						if (win.CollectGarbage)
-							CollectGarbage();
-					}
-				};
-
-				function fakeUnload() {
-					var d = document;
-
-					// Is there things still loading, then do some magic
-					if (d.readyState == 'interactive') {
-						function stop() {
-							// Prevent memory leak
-							d.detachEvent('onstop', stop);
-
-							// Call unload handler
-							if (unload)
-								unload();
-
-							d = 0;
-						};
-
-						// Fire unload when the currently loading page is stopped
-						if (d)
-							d.attachEvent('onstop', stop);
-
-						// Remove onstop listener after a while to prevent the unload function
-						// to execute if the user presses cancel in an onbeforeunload
-						// confirm dialog and then presses the browser stop button
-						win.setTimeout(function() {
-							if (d)
-								d.detachEvent('onstop', stop);
-						}, 0);
-					}
-				};
-
 				// Attach unload handler
 				if (win.attachEvent) {
 					win.attachEvent('onunload', unload);
@@ -431,7 +445,11 @@
 		},
 
 		explode : function(s, d) {
-			return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;
+			if (!s || tinymce.is(s, 'array')) {
+				return s;
+			}
+
+			return tinymce.map(s.split(d || ','), tinymce.trim);
 		},
 
 		_addVer : function(u) {
@@ -457,7 +475,7 @@
 					var val = replace, args = arguments, i;
 
 					for (i = 0; i < args.length - 2; i++) {
-						if (args[i] === undefined) {
+						if (args[i] === undef) {
 							val = val.replace(new RegExp('\\$' + i, 'g'), '');
 						} else {
 							val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);
@@ -484,55 +502,68 @@
 	})(window);
 
 
+
 tinymce.create('tinymce.util.Dispatcher', {
 	scope : null,
 	listeners : null,
+	inDispatch: false,
 
-	Dispatcher : function(s) {
-		this.scope = s || this;
+	Dispatcher : function(scope) {
+		this.scope = scope || this;
 		this.listeners = [];
 	},
 
-	add : function(cb, s) {
-		this.listeners.push({cb : cb, scope : s || this.scope});
+	add : function(callback, scope) {
+		this.listeners.push({cb : callback, scope : scope || this.scope});
 
-		return cb;
+		return callback;
 	},
 
-	addToTop : function(cb, s) {
-		this.listeners.unshift({cb : cb, scope : s || this.scope});
+	addToTop : function(callback, scope) {
+		var self = this, listener = {cb : callback, scope : scope || self.scope};
 
-		return cb;
+		// Create new listeners if addToTop is executed in a dispatch loop
+		if (self.inDispatch) {
+			self.listeners = [listener].concat(self.listeners);
+		} else {
+			self.listeners.unshift(listener);
+		}
+
+		return callback;
 	},
 
-	remove : function(cb) {
-		var l = this.listeners, o = null;
+	remove : function(callback) {
+		var listeners = this.listeners, output = null;
 
-		tinymce.each(l, function(c, i) {
-			if (cb == c.cb) {
-				o = cb;
-				l.splice(i, 1);
+		tinymce.each(listeners, function(listener, i) {
+			if (callback == listener.cb) {
+				output = listener;
+				listeners.splice(i, 1);
 				return false;
 			}
 		});
 
-		return o;
+		return output;
 	},
 
 	dispatch : function() {
-		var s, a = arguments, i, li = this.listeners, c;
+		var self = this, returnValue, args = arguments, i, listeners = self.listeners, listener;
 
+		self.inDispatch = true;
+		
 		// Needs to be a real loop since the listener count might change while looping
 		// And this is also more efficient
-		for (i = 0; i<li.length; i++) {
-			c = li[i];
-			s = c.cb.apply(c.scope, a);
+		for (i = 0; i < listeners.length; i++) {
+			listener = listeners[i];
+			returnValue = listener.cb.apply(listener.scope, args.length > 0 ? args : [listener.scope]);
 
-			if (s === false)
+			if (returnValue === false)
 				break;
 		}
 
-		return s;
+		self.inDispatch = false;
+
+		return returnValue;
 	}
 
 	});
@@ -542,7 +573,7 @@
 
 	tinymce.create('tinymce.util.URI', {
 		URI : function(u, s) {
-			var t = this, o, a, b;
+			var t = this, o, a, b, base_url;
 
 			// Trim whitespace
 			u = tinymce.trim(u);
@@ -550,8 +581,9 @@
 			// Default settings
 			s = t.settings = s || {};
 
-			// Strange app protocol or local anchor
-			if (/^(mailto|tel|news|javascript|about|data):/i.test(u) || /^\s*#/.test(u)) {
+			// Strange app protocol that isn't http/https or local anchor
+			// For example: mailto,skype,tel etc.
+			if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) {
 				t.source = u;
 				return;
 			}
@@ -561,12 +593,14 @@
 				u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;
 
 			// Relative path http:// or protocol relative //path
-			if (!/^\w*:?\/\//.test(u))
-				u = (s.base_uri.protocol || 'http') + '://mce_host' + t.toAbsPath(s.base_uri.path, u);
+			if (!/^[\w\-]*:?\/\//.test(u)) {
+				base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory;
+				u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u);
+			}
 
 			// Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
 			u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
-			u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
+			u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
 			each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
 				var s = u[i];
 
@@ -577,17 +611,18 @@
 				t[v] = s;
 			});
 
-			if (b = s.base_uri) {
+			b = s.base_uri;
+			if (b) {
 				if (!t.protocol)
 					t.protocol = b.protocol;
 
 				if (!t.userInfo)
 					t.userInfo = b.userInfo;
 
-				if (!t.port && t.host == 'mce_host')
+				if (!t.port && t.host === 'mce_host')
 					t.port = b.port;
 
-				if (!t.host || t.host == 'mce_host')
+				if (!t.host || t.host === 'mce_host')
 					t.host = b.host;
 
 				t.source = '';
@@ -623,6 +658,12 @@
 			if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
 				return u.getURI();
 
+			var tu = t.getURI(), uu = u.getURI();
+			
+			// Allow usage of the base_uri when relative_urls = true
+			if(tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu))
+				return tu;
+
 			o = t.toRelPath(t.path, u.path);
 
 			// Add query
@@ -637,7 +678,7 @@
 		},
 	
 		toAbsolute : function(u, nh) {
-			var u = new tinymce.util.URI(u, {base_uri : this});
+			u = new tinymce.util.URI(u, {base_uri : this});
 
 			return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
 		},
@@ -668,7 +709,7 @@
 				}
 			}
 
-			if (bp == 1)
+			if (bp === 1)
 				return path;
 
 			for (i = 0, l = base.length - (bp - 1); i < l; i++)
@@ -703,11 +744,11 @@
 			// Merge relURLParts chunks
 			for (i = path.length - 1, o = []; i >= 0; i--) {
 				// Ignore empty or .
-				if (path[i].length == 0 || path[i] == ".")
+				if (path[i].length === 0 || path[i] === ".")
 					continue;
 
 				// Is parent
-				if (path[i] == '..') {
+				if (path[i] === '..') {
 					nb++;
 					continue;
 				}
@@ -818,7 +859,7 @@
 			if (b == -1) {
 				b = c.indexOf(p);
 
-				if (b != 0)
+				if (b !== 0)
 					return null;
 			} else
 				b += 2;
@@ -839,19 +880,19 @@
 				((s) ? "; secure" : "");
 		},
 
-		remove : function(n, p) {
-			var d = new Date();
+		remove : function(name, path, domain) {
+			var date = new Date();
 
-			d.setTime(d.getTime() - 1000);
+			date.setTime(date.getTime() - 1000);
 
-			this.set(n, '', d, p, d);
+			this.set(name, '', date, path, domain);
 		}
 	});
 })();
 
 (function() {
 	function serialize(o, quote) {
-		var i, v, t;
+		var i, v, t, name;
 
 		quote = quote || '"';
 
@@ -889,8 +930,11 @@
 
 				v = '{';
 
-				for (i in o)
-					v += typeof o[i] != 'function' ? (v.length > 1 ? ',' + quote : quote) + i + quote +':' + serialize(o[i], quote) : '';
+				for (name in o) {
+					if (o.hasOwnProperty(name)) {
+						v += typeof o[name] != 'function' ? (v.length > 1 ? ',' + quote : quote) + name + quote +':' + serialize(o[name], quote) : '';
+					}
+				}
 
 				return v + '}';
 		}
@@ -911,9 +955,22 @@
 
 		};
 })();
+
 tinymce.create('static tinymce.util.XHR', {
 	send : function(o) {
 		var x, t, w = window, c = 0;
+
+		function ready() {
+			if (!o.async || x.readyState == 4 || c++ > 10000) {
+				if (o.success && c < 10000 && x.status == 200)
+					o.success.call(o.success_scope, '' + x.responseText, x, o);
+				else if (o.error)
+					o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);
+
+				x = null;
+			} else
+				w.setTimeout(ready, 10);
+		};
 
 		// Default settings
 		o.scope = o.scope || this;
@@ -947,18 +1004,6 @@
 			x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
 
 			x.send(o.data);
-
-			function ready() {
-				if (!o.async || x.readyState == 4 || c++ > 10000) {
-					if (o.success && c < 10000 && x.status == 200)
-						o.success.call(o.success_scope, '' + x.responseText, x, o);
-					else if (o.error)
-						o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o);
-
-					x = null;
-				} else
-					w.setTimeout(ready, 10);
-			};
 
 			// Syncronous request
 			if (!o.async)
@@ -1024,12 +1069,855 @@
 		}
 	});
 }());
+(function(tinymce){
+	tinymce.VK = {
+		BACKSPACE: 8,
+		DELETE: 46,
+		DOWN: 40,
+		ENTER: 13,
+		LEFT: 37,
+		RIGHT: 39,
+		SPACEBAR: 32,
+		TAB: 9,
+		UP: 38,
+
+		modifierPressed: function (e) {
+			return e.shiftKey || e.ctrlKey || e.altKey;
+		},
+
+		metaKeyPressed: function(e) {
+			// Check if ctrl or meta key is pressed also check if alt is false for Polish users
+			return tinymce.isMac ? e.metaKey : e.ctrlKey && !e.altKey;
+		}
+	};
+})(tinymce);
+
+tinymce.util.Quirks = function(editor) {
+	var VK = tinymce.VK, BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, settings = editor.settings;
+
+	function setEditorCommandState(cmd, state) {
+		try {
+			editor.getDoc().execCommand(cmd, false, state);
+		} catch (ex) {
+			// Ignore
+		}
+	}
+
+	function getDocumentMode() {
+		var documentMode = editor.getDoc().documentMode;
+
+		return documentMode ? documentMode : 6;
+	};
+
+	function cleanupStylesWhenDeleting() {
+		function removeMergedFormatSpans(isDelete) {
+			var rng, blockElm, node, clonedSpan;
+
+			rng = selection.getRng();
+
+			// Find root block
+			blockElm = dom.getParent(rng.startContainer, dom.isBlock);
+
+			// On delete clone the root span of the next block element
+			if (isDelete)
+				blockElm = dom.getNext(blockElm, dom.isBlock);
+
+			// Locate root span element and clone it since it would otherwise get merged by the "apple-style-span" on delete/backspace
+			if (blockElm) {
+				node = blockElm.firstChild;
+
+				// Ignore empty text nodes
+				while (node && node.nodeType == 3 && node.nodeValue.length === 0)
+					node = node.nextSibling;
+
+				if (node && node.nodeName === 'SPAN') {
+					clonedSpan = node.cloneNode(false);
+				}
+			}
+
+			// Do the backspace/delete action
+			editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null);
+
+			// Find all odd apple-style-spans
+			blockElm = dom.getParent(rng.startContainer, dom.isBlock);
+			tinymce.each(dom.select('span.Apple-style-span,font.Apple-style-span', blockElm), function(span) {
+				var bm = selection.getBookmark();
+
+				if (clonedSpan) {
+					dom.replace(clonedSpan.cloneNode(false), span, true);
+				} else {
+					dom.remove(span, true);
+				}
+
+				// Restore the selection
+				selection.moveToBookmark(bm);
+			});
+		};
+
+		editor.onKeyDown.add(function(editor, e) {
+			var isDelete;
+
+			isDelete = e.keyCode == DELETE;
+			if (!e.isDefaultPrevented() && (isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) {
+				e.preventDefault();
+				removeMergedFormatSpans(isDelete);
+			}
+		});
+
+		editor.addCommand('Delete', function() {removeMergedFormatSpans();});
+	};
+	
+	function emptyEditorWhenDeleting() {
+		function serializeRng(rng) {
+			var body = dom.create("body");
+			var contents = rng.cloneContents();
+			body.appendChild(contents);
+			return selection.serializer.serialize(body, {format: 'html'});
+		}
+
+		function allContentsSelected(rng) {
+			var selection = serializeRng(rng);
+
+			var allRng = dom.createRng();
+			allRng.selectNode(editor.getBody());
+
+			var allSelection = serializeRng(allRng);
+			return selection === allSelection;
+		}
+
+		editor.onKeyDown.add(function(editor, e) {
+			var keyCode = e.keyCode, isCollapsed;
+
+			// Empty the editor if it's needed for example backspace at <p><b>|</b></p>
+			if (!e.isDefaultPrevented() && (keyCode == DELETE || keyCode == BACKSPACE)) {
+				isCollapsed = editor.selection.isCollapsed();
+
+				// Selection is collapsed but the editor isn't empty
+				if (isCollapsed && !dom.isEmpty(editor.getBody())) {
+					return;
+				}
+
+				// IE deletes all contents correctly when everything is selected
+				if (tinymce.isIE && !isCollapsed) {
+					return;
+				}
+
+				// Selection isn't collapsed but not all the contents is selected
+				if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
+					return;
+				}
+
+				// Manually empty the editor
+				editor.setContent('');
+				editor.selection.setCursorLocation(editor.getBody(), 0);
+				editor.nodeChanged();
+			}
+		});
+	};
+
+	function selectAll() {
+		editor.onKeyDown.add(function(editor, e) {
+			if (e.keyCode == 65 && VK.metaKeyPressed(e)) {
+				e.preventDefault();
+				editor.execCommand('SelectAll');
+			}
+		});
+	};
+
+	function inputMethodFocus() {
+		if (!editor.settings.content_editable) {
+			// Case 1 IME doesn't initialize if you focus the document
+			dom.bind(editor.getDoc(), 'focusin', function(e) {
+				selection.setRng(selection.getRng());
+			});
+
+			// Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event
+			dom.bind(editor.getDoc(), 'mousedown', function(e) {
+				if (e.target == editor.getDoc().documentElement) {
+					editor.getWin().focus();
+					selection.setRng(selection.getRng());
+				}
+			});
+		}
+	};
+
+	function removeHrOnBackspace() {
+		editor.onKeyDown.add(function(editor, e) {
+			if (!e.isDefaultPrevented() && e.keyCode === BACKSPACE) {
+				if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) {
+					var node = selection.getNode();
+					var previousSibling = node.previousSibling;
+
+					if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") {
+						dom.remove(previousSibling);
+						tinymce.dom.Event.cancel(e);
+					}
+				}
+			}
+		})
+	}
+
+	function focusBody() {
+		// Fix for a focus bug in FF 3.x where the body element
+		// wouldn't get proper focus if the user clicked on the HTML element
+		if (!Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4
+			editor.onMouseDown.add(function(editor, e) {
+				if (e.target.nodeName === "HTML") {
+					var body = editor.getBody();
+
+					// Blur the body it's focused but not correctly focused
+					body.blur();
+
+					// Refocus the body after a little while
+					setTimeout(function() {
+						body.focus();
+					}, 0);
+				}
+			});
+		}
+	};
+
+	function selectControlElements() {
+		editor.onClick.add(function(editor, e) {
+			e = e.target;
+
+			// Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
+			// WebKit can't even do simple things like selecting an image
+			// Needs tobe the setBaseAndExtend or it will fail to select floated images
+			if (/^(IMG|HR)$/.test(e.nodeName)) {
+				selection.getSel().setBaseAndExtent(e, 0, e, 1);
+			}
+
+			if (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor')) {
+				selection.select(e);
+			}
+
+			editor.nodeChanged();
+		});
+	};
+
+	function removeStylesWhenDeletingAccrossBlockElements() {
+		function getAttributeApplyFunction() {
+			var template = dom.getAttribs(selection.getStart().cloneNode(false));
+
+			return function() {
+				var target = selection.getStart();
+
+				if (target !== editor.getBody()) {
+					dom.setAttrib(target, "style", null);
+
+					tinymce.each(template, function(attr) {
+						target.setAttributeNode(attr.cloneNode(true));
+					});
+				}
+			};
+		}
+
+		function isSelectionAcrossElements() {
+			return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock);
+		}
+
+		function blockEvent(editor, e) {
+			e.preventDefault();
+			return false;
+		}
+
+		editor.onKeyPress.add(function(editor, e) {
+			var applyAttributes;
+
+			if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {
+				applyAttributes = getAttributeApplyFunction();
+				editor.getDoc().execCommand('delete', false, null);
+				applyAttributes();
+				e.preventDefault();
+				return false;
+			}
+		});
+
+		dom.bind(editor.getDoc(), 'cut', function(e) {
+			var applyAttributes;
+
+			if (isSelectionAcrossElements()) {
+				applyAttributes = getAttributeApplyFunction();
+				editor.onKeyUp.addToTop(blockEvent);
+
+				setTimeout(function() {
+					applyAttributes();
+					editor.onKeyUp.remove(blockEvent);
+				}, 0);
+			}
+		});
+	}
+
+	function selectionChangeNodeChanged() {
+		var lastRng, selectionTimer;
+
+		dom.bind(editor.getDoc(), 'selectionchange', function() {
+			if (selectionTimer) {
+				clearTimeout(selectionTimer);
+				selectionTimer = 0;
+			}
+
+			selectionTimer = window.setTimeout(function() {
+				var rng = selection.getRng();
+
+				// Compare the ranges to see if it was a real change or not
+				if (!lastRng || !tinymce.dom.RangeUtils.compareRanges(rng, lastRng)) {
+					editor.nodeChanged();
+					lastRng = rng;
+				}
+			}, 50);
+		});
+	}
+
+	function ensureBodyHasRoleApplication() {
+		document.body.setAttribute("role", "application");
+	}
+
+	function disableBackspaceIntoATable() {
+		editor.onKeyDown.add(function(editor, e) {
+			if (!e.isDefaultPrevented() && e.keyCode === BACKSPACE) {
+				if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) {
+					var previousSibling = selection.getNode().previousSibling;
+					if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") {
+						return tinymce.dom.Event.cancel(e);
+					}
+				}
+			}
+		})
+	}
+
+	function addNewLinesBeforeBrInPre() {
+		// IE8+ rendering mode does the right thing with BR in PRE
+		if (getDocumentMode() > 7) {
+			return;
+		}
+
+		 // Enable display: none in area and add a specific class that hides all BR elements in PRE to
+		 // avoid the caret from getting stuck at the BR elements while pressing the right arrow key
+		setEditorCommandState('RespectVisibilityInDesign', true);
+		editor.contentStyles.push('.mceHideBrInPre pre br {display: none}');
+		dom.addClass(editor.getBody(), 'mceHideBrInPre');
+
+		// Adds a \n before all BR elements in PRE to get them visual
+		editor.parser.addNodeFilter('pre', function(nodes, name) {
+			var i = nodes.length, brNodes, j, brElm, sibling;
+
+			while (i--) {
+				brNodes = nodes[i].getAll('br');
+				j = brNodes.length;
+				while (j--) {
+					brElm = brNodes[j];
+
+					// Add \n before BR in PRE elements on older IE:s so the new lines get rendered
+					sibling = brElm.prev;
+					if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') {
+						sibling.value += '\n';
+					} else {
+						brElm.parent.insert(new tinymce.html.Node('#text', 3), brElm, true).value = '\n';
+					}
+				}
+			}
+		});
+
+		// Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible
+		editor.serializer.addNodeFilter('pre', function(nodes, name) {
+			var i = nodes.length, brNodes, j, brElm, sibling;
+
+			while (i--) {
+				brNodes = nodes[i].getAll('br');
+				j = brNodes.length;
+				while (j--) {
+					brElm = brNodes[j];
+					sibling = brElm.prev;
+					if (sibling && sibling.type == 3) {
+						sibling.value = sibling.value.replace(/\r?\n$/, '');
+					}
+				}
+			}
+		});
+	}
+
+	function removePreSerializedStylesWhenSelectingControls() {
+		dom.bind(editor.getBody(), 'mouseup', function(e) {
+			var value, node = selection.getNode();
+
+			// Moved styles to attributes on IMG eements
+			if (node.nodeName == 'IMG') {
+				// Convert style width to width attribute
+				if (value = dom.getStyle(node, 'width')) {
+					dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, ''));
+					dom.setStyle(node, 'width', '');
+				}
+
+				// Convert style height to height attribute
+				if (value = dom.getStyle(node, 'height')) {
+					dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, ''));
+					dom.setStyle(node, 'height', '');
+				}
+			}
+		});
+	}
+
+	function keepInlineElementOnDeleteBackspace() {
+		editor.onKeyDown.add(function(editor, e) {
+			var isDelete, rng, container, offset, brElm, sibling, collapsed;
+
+			isDelete = e.keyCode == DELETE;
+			if (!e.isDefaultPrevented() && (isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) {
+				rng = selection.getRng();
+				container = rng.startContainer;
+				offset = rng.startOffset;
+				collapsed = rng.collapsed;
+
+				// Override delete if the start container is a text node and is at the beginning of text or
+				// just before/after the last character to be deleted in collapsed mode
+				if (container.nodeType == 3 && container.nodeValue.length > 0 && ((offset === 0 && !collapsed) || (collapsed && offset === (isDelete ? 0 : 1)))) {
+					nonEmptyElements = editor.schema.getNonEmptyElements();
+
+					// Prevent default logic since it's broken
+					e.preventDefault();
+
+					// Insert a BR before the text node this will prevent the containing element from being deleted/converted
+					brElm = dom.create('br', {id: '__tmp'});
+					container.parentNode.insertBefore(brElm, container);
+
+					// Do the browser delete
+					editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null);
+
+					// Check if the previous sibling is empty after deleting for example: <p><b></b>|</p>
+					container = selection.getRng().startContainer;
+					sibling = container.previousSibling;
+					if (sibling && sibling.nodeType == 1 && !dom.isBlock(sibling) && dom.isEmpty(sibling) && !nonEmptyElements[sibling.nodeName.toLowerCase()]) {
+						dom.remove(sibling);
+					}
+
+					// Remove the temp element we inserted
+					dom.remove('__tmp');
+				}
+			}
+		});
+	}
+
+	function removeBlockQuoteOnBackSpace() {
+		// Add block quote deletion handler
+		editor.onKeyDown.add(function(editor, e) {
+			var rng, container, offset, root, parent;
+
+			if (e.isDefaultPrevented() || e.keyCode != VK.BACKSPACE) {
+				return;
+			}
+
+			rng = selection.getRng();
+			container = rng.startContainer;
+			offset = rng.startOffset;
+			root = dom.getRoot();
+			parent = container;
+
+			if (!rng.collapsed || offset !== 0) {
+				return;
+			}
+
+			while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) {
+				parent = parent.parentNode;
+			}
+
+			// Is the cursor at the beginning of a blockquote?
+			if (parent.tagName === 'BLOCKQUOTE') {
+				// Remove the blockquote
+				editor.formatter.toggle('blockquote', null, parent);
+
+				// Move the caret to the beginning of container
+				rng.setStart(container, 0);
+				rng.setEnd(container, 0);
+				selection.setRng(rng);
+				selection.collapse(false);
+			}
+		});
+	};
+
+	function setGeckoEditingOptions() {
+		function setOpts() {
+			editor._refreshContentEditable();
+
+			setEditorCommandState("StyleWithCSS", false);
+			setEditorCommandState("enableInlineTableEditing", false);
+
+			if (!settings.object_resizing) {
+				setEditorCommandState("enableObjectResizing", false);
+			}
+		};
+
+		if (!settings.readonly) {
+			editor.onBeforeExecCommand.add(setOpts);
+			editor.onMouseDown.add(setOpts);
+		}
+	};
+
+	function addBrAfterLastLinks() {
+		function fixLinks(editor, o) {
+			tinymce.each(dom.select('a'), function(node) {
+				var parentNode = node.parentNode, root = dom.getRoot();
+
+				if (parentNode.lastChild === node) {
+					while (parentNode && !dom.isBlock(parentNode)) {
+						if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
+							return;
+						}
+
+						parentNode = parentNode.parentNode;
+					}
+
+					dom.add(parentNode, 'br', {'data-mce-bogus' : 1});
+				}
+			});
+		};
+
+		editor.onExecCommand.add(function(editor, cmd) {
+			if (cmd === 'CreateLink') {
+				fixLinks(editor);
+			}
+		});
+
+		editor.onSetContent.add(selection.onSetContent.add(fixLinks));
+	};
+
+	function setDefaultBlockType() {
+		if (settings.forced_root_block) {
+			editor.onInit.add(function() {
+				setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block);
+			});
+		}
+	}
+
+	function removeGhostSelection() {
+		function repaint(sender, args) {
+			if (!sender || !args.initial) {
+				editor.execCommand('mceRepaint');
+			}
+		};
+
+		editor.onUndo.add(repaint);
+		editor.onRedo.add(repaint);
+		editor.onSetContent.add(repaint);
+	};
+
+	function deleteControlItemOnBackSpace() {
+		editor.onKeyDown.add(function(editor, e) {
+			var rng;
+
+			if (!e.isDefaultPrevented() && e.keyCode == BACKSPACE) {
+				rng = editor.getDoc().selection.createRange();
+				if (rng && rng.item) {
+					e.preventDefault();
+					editor.undoManager.beforeChange();
+					dom.remove(rng.item(0));
+					editor.undoManager.add();
+				}
+			}
+		});
+	};
+
+	function renderEmptyBlocksFix() {
+		var emptyBlocksCSS;
+
+		// IE10+
+		if (getDocumentMode() >= 10) {
+			emptyBlocksCSS = '';
+			tinymce.each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) {
+				emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty';
+			});
+
+			editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}');
+		}
+	};
+
+	function fakeImageResize() {
+		var selectedElmX, selectedElmY, selectedElm, selectedElmGhost, selectedHandle, startX, startY, startW, startH, ratio,
+			resizeHandles, width, height, rootDocument = document, editableDoc = editor.getDoc();
+
+		if (!settings.object_resizing || settings.webkit_fake_resize === false) {
+			return;
+		}
+
+		// Try disabling object resizing if WebKit implements resizing in the future
+		setEditorCommandState("enableObjectResizing", false);
+
+		// Details about each resize handle how to scale etc
+		resizeHandles = {
+			// Name: x multiplier, y multiplier, delta size x, delta size y
+			n: [.5, 0, 0, -1],
+			e: [1, .5, 1, 0],
+			s: [.5, 1, 0, 1],
+			w: [0, .5, -1, 0],
+			nw: [0, 0, -1, -1],
+			ne: [1, 0, 1, -1],
+			se: [1, 1, 1, 1],
+			sw : [0, 1, -1, 1]
+		};
+
+		function resizeElement(e) {
+			var deltaX, deltaY;
+
+			// Calc new width/height
+			deltaX = e.screenX - startX;
+			deltaY = e.screenY - startY;
+
+			// Calc new size
+			width = deltaX * selectedHandle[2] + startW;
+			height = deltaY * selectedHandle[3] + startH;
+
+			// Never scale down lower than 5 pixels
+			width = width < 5 ? 5 : width;
+			height = height < 5 ? 5 : height;
+
+			// Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image
+			if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) {
+				width = Math.round(height / ratio);
+				height = Math.round(width * ratio);
+			}
+
+			// Update ghost size
+			dom.setStyles(selectedElmGhost, {
+				width: width,
+				height: height
+			});
+
+			// Update ghost X position if needed
+			if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
+				dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
+			}
+
+			// Update ghost Y position if needed
+			if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
+				dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
+			}
+		}
+
+		function endResize() {
+			function setSizeProp(name, value) {
+				if (value) {
+					// Resize by using style or attribute
+					if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
+						dom.setStyle(selectedElm, name, value);
+					} else {
+						dom.setAttrib(selectedElm, name, value);
+					}
+				}
+			}
+
+			// Set width/height properties
+			setSizeProp('width', width);
+			setSizeProp('height', height);
+
+			dom.unbind(editableDoc, 'mousemove', resizeElement);
+			dom.unbind(editableDoc, 'mouseup', endResize);
+
+			if (rootDocument != editableDoc) {
+				dom.unbind(rootDocument, 'mousemove', resizeElement);
+				dom.unbind(rootDocument, 'mouseup', endResize);
+			}
+
+			// Remove ghost and update resize handle positions
+			dom.remove(selectedElmGhost);
+			showResizeRect(selectedElm);
+		}
+
+		function showResizeRect(targetElm) {
+			var position, targetWidth, targetHeight;
+
+			hideResizeRect();
+
+			// Get position and size of target
+			position = dom.getPos(targetElm);
+			selectedElmX = position.x;
+			selectedElmY = position.y;
+			targetWidth = targetElm.offsetWidth;
+			targetHeight = targetElm.offsetHeight;
+
+			// Reset width/height if user selects a new image/table
+			if (selectedElm != targetElm) {
+				selectedElm = targetElm;
+				width = height = 0;
+			}
+
+			tinymce.each(resizeHandles, function(handle, name) {
+				var handleElm;
+
+				// Get existing or render resize handle
+				handleElm = dom.get('mceResizeHandle' + name);
+				if (!handleElm) {
+					handleElm = dom.add(editableDoc.documentElement, 'div', {
+						id: 'mceResizeHandle' + name,
+						'class': 'mceResizeHandle',
+						style: 'cursor:' + name + '-resize; margin:0; padding:0'
+					});
+
+					dom.bind(handleElm, 'mousedown', function(e) {
+						e.preventDefault();
+
+						endResize();
+
+						startX = e.screenX;
+						startY = e.screenY;
+						startW = selectedElm.clientWidth;
+						startH = selectedElm.clientHeight;
+						ratio = startH / startW;
+						selectedHandle = handle;
+
+						selectedElmGhost = selectedElm.cloneNode(true);
+						dom.addClass(selectedElmGhost, 'mceClonedResizable');
+						dom.setStyles(selectedElmGhost, {
+							left: selectedElmX,
+							top: selectedElmY,
+							margin: 0
+						});
+
+						editableDoc.documentElement.appendChild(selectedElmGhost);
+
+						dom.bind(editableDoc, 'mousemove', resizeElement);
+						dom.bind(editableDoc, 'mouseup', endResize);
+
+						if (rootDocument != editableDoc) {
+							dom.bind(rootDocument, 'mousemove', resizeElement);
+							dom.bind(rootDocument, 'mouseup', endResize);
+						}
+					});
+				} else {
+					dom.show(handleElm);
+				}
+
+				// Position element
+				dom.setStyles(handleElm, {
+					left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2),
+					top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2)
+				});
+			});
+
+			// Only add resize rectangle on WebKit and only on images
+			if (!tinymce.isOpera && selectedElm.nodeName == "IMG") {
+				selectedElm.setAttribute('data-mce-selected', '1');
+			}
+		}
+
+		function hideResizeRect() {
+			if (selectedElm) {
+				selectedElm.removeAttribute('data-mce-selected');
+			}
+
+			for (var name in resizeHandles) {
+				dom.hide('mceResizeHandle' + name);
+			}
+		}
+
+		// Add CSS for resize handles, cloned element and selected
+		editor.contentStyles.push(
+			'.mceResizeHandle {' +
+				'position: absolute;' +
+				'border: 1px solid black;' +
+				'background: #FFF;' +
+				'width: 5px;' +
+				'height: 5px;' +
+				'z-index: 10000' +
+			'}' +
+			'.mceResizeHandle:hover {' +
+				'background: #000' +
+			'}' +
+			'img[data-mce-selected] {' +
+				'outline: 1px solid black' +
+			'}' +
+			'img.mceClonedResizable, table.mceClonedResizable {' +
+				'position: absolute;' +
+				'outline: 1px dashed black;' +
+				'opacity: .5;' +
+				'z-index: 10000' +
+			'}'
+		);
+
+		function updateResizeRect() {
+			var controlElm = dom.getParent(selection.getNode(), 'table,img');
+
+			// Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v
+			tinymce.each(dom.select('img[data-mce-selected]'), function(img) {
+				img.removeAttribute('data-mce-selected');
+			});
+
+			if (controlElm) {
+				showResizeRect(controlElm);
+			} else {
+				hideResizeRect();
+			}
+		}
+
+		// Show/hide resize rect when image is selected
+		editor.onNodeChange.add(updateResizeRect);
+
+		// Fixes WebKit quirk where it returns IMG on getNode if caret is after last image in container
+		dom.bind(editableDoc, 'selectionchange', updateResizeRect);
+
+		// Remove the internal attribute when serializing the DOM
+		editor.serializer.addAttributeFilter('data-mce-selected', function(nodes, name) {
+			var i = nodes.length;
+
+			while (i--) {
+				nodes[i].attr(name, null);
+			}
+		});
+	}
+
+	// All browsers
+	disableBackspaceIntoATable();
+	removeBlockQuoteOnBackSpace();
+	emptyEditorWhenDeleting();
+
+	// WebKit
+	if (tinymce.isWebKit) {
+		keepInlineElementOnDeleteBackspace();
+		cleanupStylesWhenDeleting();
+		inputMethodFocus();
+		selectControlElements();
+		setDefaultBlockType();
+
+		// iOS
+		if (tinymce.isIDevice) {
+			selectionChangeNodeChanged();
+		} else {
+			fakeImageResize();
+			selectAll();
+		}
+	}
+
+	// IE
+	if (tinymce.isIE) {
+		removeHrOnBackspace();
+		ensureBodyHasRoleApplication();
+		addNewLinesBeforeBrInPre();
+		removePreSerializedStylesWhenSelectingControls();
+		deleteControlItemOnBackSpace();
+		renderEmptyBlocksFix();
+	}
+
+	// Gecko
+	if (tinymce.isGecko) {
+		removeHrOnBackspace();
+		focusBody();
+		removeStylesWhenDeletingAccrossBlockElements();
+		setGeckoEditingOptions();
+		addBrAfterLastLinks();
+		removeGhostSelection();
+	}
+
+	// Opera
+	if (tinymce.isOpera) {
+		fakeImageResize();
+	}
+};
 (function(tinymce) {
 	var namedEntities, baseEntities, reverseEntities,
-		attrsCharsRegExp = /[&\"\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
-		textCharsRegExp = /[<>&\u007E-\uD7FF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
+		attrsCharsRegExp = /[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
+		textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
 		rawCharsRegExp = /[<>&\"\']/g,
-		entityRegExp = /&(#)?([\w]+);/g,
+		entityRegExp = /&(#x|#)?([\w]+);/g,
 		asciiMap = {
 				128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020",
 				135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152",
@@ -1040,7 +1928,7 @@
 
 	// Raw entities
 	baseEntities = {
-		'"' : '&quot;',
+		'\"' : '&quot;', // Needs to be escaped since the YUI compressor would otherwise break the code
 		"'" : '&#39;',
 		'<' : '&lt;',
 		'>' : '&gt;',
@@ -1116,8 +2004,7 @@
 		'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
 		'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
 		'80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
-		'811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro'
-	, 32);
+		'811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);
 
 	tinymce.html = tinymce.html || {};
 
@@ -1194,7 +2081,7 @@
 		decode : function(text) {
 			return text.replace(entityRegExp, function(all, numeric, value) {
 				if (numeric) {
-					value = parseInt(value);
+					value = parseInt(value, numeric.length === 2 ? 16 : 10);
 
 					// Support upper UTF
 					if (value > 0xFFFF) {
@@ -1221,10 +2108,10 @@
 
 	settings = settings || {};
 
-	encodingItems = '\\" \\\' \\; \\: ; : _'.split(' ');
+	encodingItems = '\\" \\\' \\; \\: ; : \uFEFF'.split(' ');
 	for (i = 0; i < encodingItems.length; i++) {
-		encodingLookup[encodingItems[i]] = '_' + i;
-		encodingLookup['_' + i] = encodingItems[i];
+		encodingLookup[encodingItems[i]] = '\uFEFF' + i;
+		encodingLookup['\uFEFF' + i] = encodingItems[i];
 	}
 
 	function toHex(match, r, g, b) {
@@ -1319,7 +2206,7 @@
 			// It will also decode the \" \' if keep_slashes is set to fale or omitted
 			function decode(str, keep_slashes) {
 				if (isEncoded) {
-					str = str.replace(/_[0-9]/g, function(str) {
+					str = str.replace(/\uFEFF[0-9]/g, function(str) {
 						return encodingLookup[str];
 					});
 				}
@@ -1328,11 +2215,31 @@
 					str = str.replace(/\\([\'\";:])/g, "$1");
 
 				return str;
-			}
+			};
+
+			function processUrl(match, url, url2, url3, str, str2) {
+				str = str || str2;
+
+				if (str) {
+					str = decode(str);
+
+					// Force strings into single quote format
+					return "'" + str.replace(/\'/g, "\\'") + "'";
+				}
+
+				url = decode(url || url2 || url3);
+
+				// Convert the URL to relative/absolute depending on config
+				if (urlConverter)
+					url = urlConverter.call(urlConverterScope, url, 'style');
+
+				// Output new URL format
+				return "url('" + url.replace(/\'/g, "\\'") + "')";
+			};
 
 			if (css) {
 				// Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing
-				css = css.replace(/\\[\"\';:_]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
+				css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
 					return str.replace(/[;:]/g, encode);
 				});
 
@@ -1352,26 +2259,7 @@
 						value = value.replace(rgbRegExp, toHex);
 
 						// Convert URLs and force them into url('value') format
-						value = value.replace(urlOrStrRegExp, function(match, url, url2, url3, str, str2) {
-							str = str || str2;
-
-							if (str) {
-								str = decode(str);
-
-								// Force strings into single quote format
-								return "'" + str.replace(/\'/g, "\\'") + "'";
-							}
-
-							url = decode(url || url2 || url3);
-
-							// Convert the URL to relative/absolute depending on config
-							if (urlConverter)
-								url = urlConverter.call(urlConverterScope, url, 'style');
-
-							// Output new URL format
-							return "url('" + url.replace(/\'/g, "\\'") + "')";
-						});
-
+						value = value.replace(urlOrStrRegExp, processUrl);
 						styles[name] = isEncoded ? decode(value, true) : value;
 					}
 
@@ -1399,7 +2287,7 @@
 			var css = '', name, value;
 
 			function serializeStyles(name) {
-				var styleList, i, l, name, value;
+				var styleList, i, l, value;
 
 				styleList = schema.styles[name];
 				if (styleList) {
@@ -1407,7 +2295,7 @@
 						name = styleList[i];
 						value = styles[name];
 
-						if (value !== undef)
+						if (value !== undef && value.length > 0)
 							css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
 					}
 				}
@@ -1417,13 +2305,13 @@
 			if (element_name && schema && schema.styles) {
 				// Serialize global styles and element specific styles
 				serializeStyles('*');
-				serializeStyles(name);
+				serializeStyles(element_name);
 			} else {
 				// Output the styles in the order they are inside the object
 				for (name in styles) {
 					value = styles[name];
 
-					if (value !== undef)
+					if (value !== undef && value.length > 0)
 						css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
 				}
 			}
@@ -1434,8 +2322,7 @@
 };
 
 (function(tinymce) {
-	var transitional = {}, boolAttrMap, blockElementsMap, shortEndedElementsMap, nonEmptyElementsMap,
-		whiteSpaceElementsMap, selfClosingElementsMap, makeMap = tinymce.makeMap, each = tinymce.each;
+	var mapCache = {}, makeMap = tinymce.makeMap, each = tinymce.each;
 
 	function split(str, delim) {
 		return str.split(delim || ',');
@@ -1470,142 +2357,286 @@
 		return elements;
 	};
 
-	// Build a lookup table for block elements both lowercase and uppercase
-	blockElementsMap = 'h1,h2,h3,h4,h5,h6,hr,p,div,address,pre,form,table,tbody,thead,tfoot,' + 
-						'th,tr,td,li,ol,ul,caption,blockquote,center,dl,dt,dd,dir,fieldset,' + 
-						'noscript,menu,isindex,samp,header,footer,article,section,hgroup';
-	blockElementsMap = makeMap(blockElementsMap, ',', makeMap(blockElementsMap.toUpperCase()));
+	function getHTML5() {
+		var html5 = mapCache.html5;
 
-	// This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size
-	transitional = unpack({
-		Z : 'H|K|N|O|P',
-		Y : 'X|form|R|Q',
-		ZG : 'E|span|width|align|char|charoff|valign',
-		X : 'p|T|div|U|W|isindex|fieldset|table',
-		ZF : 'E|align|char|charoff|valign',
-		W : 'pre|hr|blockquote|address|center|noframes',
-		ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',
-		ZD : '[E][S]',
-		U : 'ul|ol|dl|menu|dir',
-		ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',
-		T : 'h1|h2|h3|h4|h5|h6',
-		ZB : 'X|S|Q',
-		S : 'R|P',
-		ZA : 'a|G|J|M|O|P',
-		R : 'a|H|K|N|O',
-		Q : 'noscript|P',
-		P : 'ins|del|script',
-		O : 'input|select|textarea|label|button',
-		N : 'M|L',
-		M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',
-		L : 'sub|sup',
-		K : 'J|I',
-		J : 'tt|i|b|u|s|strike',
-		I : 'big|small|font|basefont',
-		H : 'G|F',
-		G : 'br|span|bdo',
-		F : 'object|applet|img|map|iframe',
-		E : 'A|B|C',
-		D : 'accesskey|tabindex|onfocus|onblur',
-		C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
-		B : 'lang|xml:lang|dir',
-		A : 'id|class|style|title'
-	}, 'script[id|charset|type|language|src|defer|xml:space][]' + 
-		'style[B|id|type|media|title|xml:space][]' + 
-		'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 
-		'param[id|name|value|valuetype|type][]' + 
-		'p[E|align][#|S]' + 
-		'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 
-		'br[A|clear][]' + 
-		'span[E][#|S]' + 
-		'bdo[A|C|B][#|S]' + 
-		'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 
-		'h1[E|align][#|S]' + 
-		'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 
-		'map[B|C|A|name][X|form|Q|area]' + 
-		'h2[E|align][#|S]' + 
-		'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 
-		'h3[E|align][#|S]' + 
-		'tt[E][#|S]' + 
-		'i[E][#|S]' + 
-		'b[E][#|S]' + 
-		'u[E][#|S]' + 
-		's[E][#|S]' + 
-		'strike[E][#|S]' + 
-		'big[E][#|S]' + 
-		'small[E][#|S]' + 
-		'font[A|B|size|color|face][#|S]' + 
-		'basefont[id|size|color|face][]' + 
-		'em[E][#|S]' + 
-		'strong[E][#|S]' + 
-		'dfn[E][#|S]' + 
-		'code[E][#|S]' + 
-		'q[E|cite][#|S]' + 
-		'samp[E][#|S]' + 
-		'kbd[E][#|S]' + 
-		'var[E][#|S]' + 
-		'cite[E][#|S]' + 
-		'abbr[E][#|S]' + 
-		'acronym[E][#|S]' + 
-		'sub[E][#|S]' + 
-		'sup[E][#|S]' + 
-		'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 
-		'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 
-		'optgroup[E|disabled|label][option]' + 
-		'option[E|selected|disabled|label|value][]' + 
-		'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 
-		'label[E|for|accesskey|onfocus|onblur][#|S]' + 
-		'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 
-		'h4[E|align][#|S]' + 
-		'ins[E|cite|datetime][#|Y]' + 
-		'h5[E|align][#|S]' + 
-		'del[E|cite|datetime][#|Y]' + 
-		'h6[E|align][#|S]' + 
-		'div[E|align][#|Y]' + 
-		'ul[E|type|compact][li]' + 
-		'li[E|type|value][#|Y]' + 
-		'ol[E|type|compact|start][li]' + 
-		'dl[E|compact][dt|dd]' + 
-		'dt[E][#|S]' + 
-		'dd[E][#|Y]' + 
-		'menu[E|compact][li]' + 
-		'dir[E|compact][li]' + 
-		'pre[E|width|xml:space][#|ZA]' + 
-		'hr[E|align|noshade|size|width][]' + 
-		'blockquote[E|cite][#|Y]' + 
-		'address[E][#|S|p]' + 
-		'center[E][#|Y]' + 
-		'noframes[E][#|Y]' + 
-		'isindex[A|B|prompt][]' + 
-		'fieldset[E][#|legend|Y]' + 
-		'legend[E|accesskey|align][#|S]' + 
-		'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 
-		'caption[E|align][#|S]' + 
-		'col[ZG][]' + 
-		'colgroup[ZG][col]' + 
-		'thead[ZF][tr]' + 
-		'tr[ZF|bgcolor][th|td]' + 
-		'th[E|ZE][#|Y]' + 
-		'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 
-		'noscript[E][#|Y]' + 
-		'td[E|ZE][#|Y]' + 
-		'tfoot[ZF][tr]' + 
-		'tbody[ZF][tr]' + 
-		'area[E|D|shape|coords|href|nohref|alt|target][]' + 
-		'base[id|href|target][]' + 
-		'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'
-	);
+		if (!html5) {
+			html5 = mapCache.html5 = unpack({
+					A : 'id|accesskey|class|dir|draggable|item|hidden|itemprop|role|spellcheck|style|subject|title|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
+					B : '#|a|abbr|area|audio|b|bdo|br|button|canvas|cite|code|command|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|meta|' +
+						'meter|noscript|object|output|progress|q|ruby|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|var|video|wbr',
+					C : '#|a|abbr|area|address|article|aside|audio|b|bdo|blockquote|br|button|canvas|cite|code|command|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|' +
+						'figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|menu|meta|meter|nav|noscript|ol|object|output|' +
+						'p|pre|progress|q|ruby|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|ul|var|video'
+				}, 'html[A|manifest][body|head]' +
+					'head[A][base|command|link|meta|noscript|script|style|title]' +
+					'title[A][#]' +
+					'base[A|href|target][]' +
+					'link[A|href|rel|media|type|sizes][]' +
+					'meta[A|http-equiv|name|content|charset][]' +
+					'style[A|type|media|scoped][#]' +
+					'script[A|charset|type|src|defer|async][#]' +
+					'noscript[A][C]' +
+					'body[A][C]' +
+					'section[A][C]' +
+					'nav[A][C]' +
+					'article[A][C]' +
+					'aside[A][C]' +
+					'h1[A][B]' +
+					'h2[A][B]' +
+					'h3[A][B]' +
+					'h4[A][B]' +
+					'h5[A][B]' +
+					'h6[A][B]' +
+					'hgroup[A][h1|h2|h3|h4|h5|h6]' +
+					'header[A][C]' +
+					'footer[A][C]' +
+					'address[A][C]' +
+					'p[A][B]' +
+					'br[A][]' +
+					'pre[A][B]' +
+					'dialog[A][dd|dt]' +
+					'blockquote[A|cite][C]' +
+					'ol[A|start|reversed][li]' +
+					'ul[A][li]' +
+					'li[A|value][C]' +
+					'dl[A][dd|dt]' +
+					'dt[A][B]' +
+					'dd[A][C]' +
+					'a[A|href|target|ping|rel|media|type][B]' +
+					'em[A][B]' +
+					'strong[A][B]' +
+					'small[A][B]' +
+					'cite[A][B]' +
+					'q[A|cite][B]' +
+					'dfn[A][B]' +
+					'abbr[A][B]' +
+					'code[A][B]' +
+					'var[A][B]' +
+					'samp[A][B]' +
+					'kbd[A][B]' +
+					'sub[A][B]' +
+					'sup[A][B]' +
+					'i[A][B]' +
+					'b[A][B]' +
+					'mark[A][B]' +
+					'progress[A|value|max][B]' +
+					'meter[A|value|min|max|low|high|optimum][B]' +
+					'time[A|datetime][B]' +
+					'ruby[A][B|rt|rp]' +
+					'rt[A][B]' +
+					'rp[A][B]' +
+					'bdo[A][B]' +
+					'span[A][B]' +
+					'ins[A|cite|datetime][B]' +
+					'del[A|cite|datetime][B]' +
+					'figure[A][C|legend|figcaption]' +
+					'figcaption[A][C]' +
+					'img[A|alt|src|height|width|usemap|ismap][]' +
+					'iframe[A|name|src|height|width|sandbox|seamless][]' +
+					'embed[A|src|height|width|type][]' +
+					'object[A|data|type|height|width|usemap|name|form|classid][param]' +
+					'param[A|name|value][]' +
+					'details[A|open][C|legend]' +
+					'command[A|type|label|icon|disabled|checked|radiogroup][]' +
+					'menu[A|type|label][C|li]' +
+					'legend[A][C|B]' +
+					'div[A][C]' +
+					'source[A|src|type|media][]' +
+					'audio[A|src|autobuffer|autoplay|loop|controls][source]' +
+					'video[A|src|autobuffer|autoplay|loop|controls|width|height|poster][source]' +
+					'hr[A][]' +
+					'form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]' +
+					'fieldset[A|disabled|form|name][C|legend]' +
+					'label[A|form|for][B]' +
+					'input[A|type|accept|alt|autocomplete|checked|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|list|max|maxlength|min|' +
+						'multiple|pattern|placeholder|readonly|required|size|src|step|width|files|value|name][]' +
+					'button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|value|type][B]' +
+					'select[A|autofocus|disabled|form|multiple|name|size][option|optgroup]' +
+					'datalist[A][B|option]' +
+					'optgroup[A|disabled|label][option]' +
+					'option[A|disabled|selected|label|value][]' +
+					'textarea[A|autofocus|disabled|form|maxlength|name|placeholder|readonly|required|rows|cols|wrap][]' +
+					'keygen[A|autofocus|challenge|disabled|form|keytype|name][]' +
+					'output[A|for|form|name][B]' +
+					'canvas[A|width|height][]' +
+					'map[A|name][B|C]' +
+					'area[A|shape|coords|href|alt|target|media|rel|ping|type][]' +
+					'mathml[A][]' +
+					'svg[A][]' +
+					'table[A|border][caption|colgroup|thead|tfoot|tbody|tr]' +
+					'caption[A][C]' +
+					'colgroup[A|span][col]' +
+					'col[A|span][]' +
+					'thead[A][tr]' +
+					'tfoot[A][tr]' +
+					'tbody[A][tr]' +
+					'tr[A][th|td]' +
+					'th[A|headers|rowspan|colspan|scope][B]' +
+					'td[A|headers|rowspan|colspan][C]' +
+					'wbr[A][]'
+			);
+		}
 
-	boolAttrMap = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected,preload,autoplay,loop,controls');
-	shortEndedElementsMap = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,source');
-	nonEmptyElementsMap = tinymce.extend(makeMap('td,th,iframe,video,object'), shortEndedElementsMap);
-	whiteSpaceElementsMap = makeMap('pre,script,style');
-	selfClosingElementsMap = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
+		return html5;
+	};
+
+	function getHTML4() {
+		var html4 = mapCache.html4;
+
+		if (!html4) {
+			// This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size
+			html4 = mapCache.html4 = unpack({
+				Z : 'H|K|N|O|P',
+				Y : 'X|form|R|Q',
+				ZG : 'E|span|width|align|char|charoff|valign',
+				X : 'p|T|div|U|W|isindex|fieldset|table',
+				ZF : 'E|align|char|charoff|valign',
+				W : 'pre|hr|blockquote|address|center|noframes',
+				ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height',
+				ZD : '[E][S]',
+				U : 'ul|ol|dl|menu|dir',
+				ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q',
+				T : 'h1|h2|h3|h4|h5|h6',
+				ZB : 'X|S|Q',
+				S : 'R|P',
+				ZA : 'a|G|J|M|O|P',
+				R : 'a|H|K|N|O',
+				Q : 'noscript|P',
+				P : 'ins|del|script',
+				O : 'input|select|textarea|label|button',
+				N : 'M|L',
+				M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym',
+				L : 'sub|sup',
+				K : 'J|I',
+				J : 'tt|i|b|u|s|strike',
+				I : 'big|small|font|basefont',
+				H : 'G|F',
+				G : 'br|span|bdo',
+				F : 'object|applet|img|map|iframe',
+				E : 'A|B|C',
+				D : 'accesskey|tabindex|onfocus|onblur',
+				C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup',
+				B : 'lang|xml:lang|dir',
+				A : 'id|class|style|title'
+			}, 'script[id|charset|type|language|src|defer|xml:space][]' + 
+				'style[B|id|type|media|title|xml:space][]' + 
+				'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 
+				'param[id|name|value|valuetype|type][]' + 
+				'p[E|align][#|S]' + 
+				'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 
+				'br[A|clear][]' + 
+				'span[E][#|S]' + 
+				'bdo[A|C|B][#|S]' + 
+				'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 
+				'h1[E|align][#|S]' + 
+				'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 
+				'map[B|C|A|name][X|form|Q|area]' + 
+				'h2[E|align][#|S]' + 
+				'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 
+				'h3[E|align][#|S]' + 
+				'tt[E][#|S]' + 
+				'i[E][#|S]' + 
+				'b[E][#|S]' + 
+				'u[E][#|S]' + 
+				's[E][#|S]' + 
+				'strike[E][#|S]' + 
+				'big[E][#|S]' + 
+				'small[E][#|S]' + 
+				'font[A|B|size|color|face][#|S]' + 
+				'basefont[id|size|color|face][]' + 
+				'em[E][#|S]' + 
+				'strong[E][#|S]' + 
+				'dfn[E][#|S]' + 
+				'code[E][#|S]' + 
+				'q[E|cite][#|S]' + 
+				'samp[E][#|S]' + 
+				'kbd[E][#|S]' + 
+				'var[E][#|S]' + 
+				'cite[E][#|S]' + 
+				'abbr[E][#|S]' + 
+				'acronym[E][#|S]' + 
+				'sub[E][#|S]' + 
+				'sup[E][#|S]' + 
+				'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 
+				'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 
+				'optgroup[E|disabled|label][option]' + 
+				'option[E|selected|disabled|label|value][]' + 
+				'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 
+				'label[E|for|accesskey|onfocus|onblur][#|S]' + 
+				'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 
+				'h4[E|align][#|S]' + 
+				'ins[E|cite|datetime][#|Y]' + 
+				'h5[E|align][#|S]' + 
+				'del[E|cite|datetime][#|Y]' + 
+				'h6[E|align][#|S]' + 
+				'div[E|align][#|Y]' + 
+				'ul[E|type|compact][li]' + 
+				'li[E|type|value][#|Y]' + 
+				'ol[E|type|compact|start][li]' + 
+				'dl[E|compact][dt|dd]' + 
+				'dt[E][#|S]' + 
+				'dd[E][#|Y]' + 
+				'menu[E|compact][li]' + 
+				'dir[E|compact][li]' + 
+				'pre[E|width|xml:space][#|ZA]' + 
+				'hr[E|align|noshade|size|width][]' + 
+				'blockquote[E|cite][#|Y]' + 
+				'address[E][#|S|p]' + 
+				'center[E][#|Y]' + 
+				'noframes[E][#|Y]' + 
+				'isindex[A|B|prompt][]' + 
+				'fieldset[E][#|legend|Y]' + 
+				'legend[E|accesskey|align][#|S]' + 
+				'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 
+				'caption[E|align][#|S]' + 
+				'col[ZG][]' + 
+				'colgroup[ZG][col]' + 
+				'thead[ZF][tr]' + 
+				'tr[ZF|bgcolor][th|td]' + 
+				'th[E|ZE][#|Y]' + 
+				'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 
+				'noscript[E][#|Y]' + 
+				'td[E|ZE][#|Y]' + 
+				'tfoot[ZF][tr]' + 
+				'tbody[ZF][tr]' + 
+				'area[E|D|shape|coords|href|nohref|alt|target][]' + 
+				'base[id|href|target][]' + 
+				'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]'
+			);
+		}
+
+		return html4;
+	};
 
 	tinymce.html.Schema = function(settings) {
-		var self = this, elements = {}, children = {}, patternElements = [], validStyles;
+		var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems;
+		var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, blockElementsMap, nonEmptyElementsMap, customElementsMap = {};
+
+		// Creates an lookup table map object for the specified option or the default value
+		function createLookupTable(option, default_value, extend) {
+			var value = settings[option];
+
+			if (!value) {
+				// Get cached default map or make it if needed
+				value = mapCache[option];
+
+				if (!value) {
+					value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' '));
+					value = tinymce.extend(value, extend);
+
+					mapCache[option] = value;
+				}
+			} else {
+				// Create custom map
+				value = makeMap(value, ',', makeMap(value.toUpperCase(), ' '));
+			}
+
+			return value;
+		};
 
 		settings = settings || {};
+		schemaItems = settings.schema == "html5" ? getHTML5() : getHTML4();
 
 		// Allow all elements and attributes if verify_html is set to false
 		if (settings.verify_html === false)
@@ -1621,6 +2652,16 @@
 			});
 		}
 
+		// Setup map objects
+		whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script style textarea');
+		selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
+		shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link meta param embed source wbr');
+		boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls');
+		nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap);
+		blockElementsMap = createLookupTable('block_elements', 'h1 h2 h3 h4 h5 h6 hr p div address pre form table tbody thead tfoot ' + 
+						'th tr td li ol ul caption blockquote center dl dt dd dir fieldset ' + 
+						'noscript menu isindex samp header footer article section hgroup aside nav figure option datalist select optgroup');
+
 		// Converts a wildcard expression string to a regexp for example *a will become /.*a/.
 		function patternToRegExp(str) {
 			return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
@@ -1631,7 +2672,7 @@
 		function addValidElements(valid_elements) {
 			var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
 				prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value,
-				elementRuleRegExp = /^([#+-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,
+				elementRuleRegExp = /^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,
 				attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
 				hasPatternsRegExp = /[*?+]/;
 
@@ -1773,7 +2814,7 @@
 
 			addValidElements(valid_elements);
 
-			each(transitional, function(element, name) {
+			each(schemaItems, function(element, name) {
 				children[name] = element.children;
 			});
 		};
@@ -1785,10 +2826,16 @@
 			if (custom_elements) {
 				each(split(custom_elements), function(rule) {
 					var matches = customElementRegExp.exec(rule),
-						cloneName = matches[1] === '~' ? 'span' : 'div',
+						inline = matches[1] === '~',
+						cloneName = inline ? 'span' : 'div',
 						name = matches[2];
 
 					children[name] = children[cloneName];
+					customElementsMap[name] = cloneName;
+
+					// If it's not marked as inline then add it to valid block elements
+					if (!inline)
+						blockElementsMap[name] = {};
 
 					// Add custom elements at span/div positions
 					each(children, function(element, child) {
@@ -1827,11 +2874,28 @@
 					}
 				});
 			}
-		}
+		};
+
+		function getElementRule(name) {
+			var element = elements[name], i;
+
+			// Exact match found
+			if (element)
+				return element;
+
+			// No exact match then try the patterns
+			i = patternElements.length;
+			while (i--) {
+				element = patternElements[i];
+
+				if (element.pattern.test(name))
+					return element;
+			}
+		};
 
 		if (!settings.valid_elements) {
-			// No valid elements defined then clone the elements from the transitional spec
-			each(transitional, function(element, name) {
+			// No valid elements defined then clone the elements from the schema spec
+			each(schemaItems, function(element, name) {
 				elements[name] = {
 					attributes : element.attributes,
 					attributesOrder : element.attributesOrder
@@ -1840,18 +2904,22 @@
 				children[name] = element.children;
 			});
 
-			// Switch these
-			each(split('strong/b,em/i'), function(item) {
-				item = split(item, '/');
-				elements[item[1]].outputName = item[0];
-			});
+			// Switch these on HTML4
+			if (settings.schema != "html5") {
+				each(split('strong/b,em/i'), function(item) {
+					item = split(item, '/');
+					elements[item[1]].outputName = item[0];
+				});
+			}
 
 			// Add default alt attribute for images
 			elements.img.attributesDefault = [{name: 'alt', value: ''}];
 
 			// Remove these if they are empty by default
-			each(split('ol,ul,li,sub,sup,blockquote,tr,div,span,font,a,table,tbody'), function(name) {
-				elements[name].removeEmpty = true;
+			each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr,strong,em,b,i'), function(name) {
+				if (elements[name]) {
+					elements[name].removeEmpty = true;
+				}
 			});
 
 			// Padd these by default
@@ -1875,6 +2943,10 @@
 					delete elements[item];
 			});
 		}
+
+		// If the user didn't allow span only allow internal spans
+		if (!getElementRule('span'))
+			addValidElements('span[!data-mce-type|*]');
 
 		self.children = children;
 
@@ -1910,21 +2982,40 @@
 			return !!(parent && parent[child]);
 		};
 
-		self.getElementRule = function(name) {
-			var element = elements[name], i;
+		self.isValid = function(name, attr) {
+			var attrPatterns, i, rule = getElementRule(name);
 
-			// Exact match found
-			if (element)
-				return element;
+			// Check if it's a valid element
+			if (rule) {
+				if (attr) {
+					// Check if attribute name exists
+					if (rule.attributes[attr]) {
+						return true;
+					}
 
-			// No exact match then try the patterns
-			i = patternElements.length;
-			while (i--) {
-				element = patternElements[i];
-
-				if (element.pattern.test(name))
-					return element;
+					// Check if attribute matches a regexp pattern
+					attrPatterns = rule.attributePatterns;
+					if (attrPatterns) {
+						i = attrPatterns.length;
+						while (i--) {
+							if (attrPatterns[i].pattern.test(name)) {
+								return true;
+							}
+						}
+					}
+				} else {
+					return true;
+				}
 			}
+
+			// No match
+			return false;
+		};
+		
+		self.getElementRule = getElementRule;
+
+		self.getCustomElements = function() {
+			return customElementsMap;
 		};
 
 		self.addValidElements = addValidElements;
@@ -1935,10 +3026,6 @@
 
 		self.addValidChildren = addValidChildren;
 	};
-
-	// Expose boolMap and blockElementMap as static properties for usage in DOMUtils
-	tinymce.html.Schema.boolAttrMap = boolAttrMap;
-	tinymce.html.Schema.blockElementsMap = blockElementsMap;
 })(tinymce);
 
 (function(tinymce) {
@@ -1958,10 +3045,10 @@
 		});
 
 		self.parse = function(html) {
-			var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name,
-				shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue,
+			var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name, isInternalElement, removeInternalElements,
+				shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue, invalidPrefixRegExp,
 				validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing,
-				tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing;
+				tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing, isIE;
 
 			function processEndTag(name) {
 				var pos, i;
@@ -1988,6 +3075,47 @@
 				}
 			};
 
+			function parseAttribute(match, name, value, val2, val3) {
+				var attrRule, i;
+
+				name = name.toLowerCase();
+				value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
+
+				// Validate name and value
+				if (validate && !isInternalElement && name.indexOf('data-') !== 0) {
+					attrRule = validAttributesMap[name];
+
+					// Find rule by pattern matching
+					if (!attrRule && validAttributePatterns) {
+						i = validAttributePatterns.length;
+						while (i--) {
+							attrRule = validAttributePatterns[i];
+							if (attrRule.pattern.test(name))
+								break;
+						}
+
+						// No rule matched
+						if (i === -1)
+							attrRule = null;
+					}
+
+					// No attribute rule found
+					if (!attrRule)
+						return;
+
+					// Validate value
+					if (attrRule.validValues && !(value in attrRule.validValues))
+						return;
+				}
+
+				// Add attribute to list and map
+				attrList.map[name] = value;
+				attrList.push({
+					name: name,
+					value: value
+				});
+			};
+
 			// Precompile RegExps and map objects
 			tokenRegExp = new RegExp('<(?:' +
 				'(?:!--([\\w\\W]*?)-->)|' + // Comment
@@ -1995,7 +3123,7 @@
 				'(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
 				'(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
 				'(?:\\/([^>]+)>)|' + // End element
-				'(?:([^\\s\\/<>]+)\\s*((?:[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*)>)' + // Start element
+				'(?:([A-Za-z0-9\\-\\:]+)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + // Start element
 			')', 'g');
 
 			attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g;
@@ -2007,10 +3135,13 @@
 
 			// Setup lookup tables for empty elements and boolean attributes
 			shortEndedElements = schema.getShortEndedElements();
-			selfClosing = schema.getSelfClosingElements();
+			selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
 			fillAttrsMap = schema.getBoolAttrs();
 			validate = settings.validate;
+			removeInternalElements = settings.remove_internals;
 			fixSelfClosing = settings.fix_self_closing;
+			isIE = tinymce.isIE;
+			invalidPrefixRegExp = /^:/;
 
 			while (matches = tokenRegExp.exec(html)) {
 				// Text
@@ -2018,9 +3149,20 @@
 					self.text(decode(html.substr(index, matches.index - index)));
 
 				if (value = matches[6]) { // End element
-					processEndTag(value.toLowerCase());
+					value = value.toLowerCase();
+
+					// IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
+					if (isIE && invalidPrefixRegExp.test(value))
+						value = value.substr(1);
+
+					processEndTag(value);
 				} else if (value = matches[7]) { // Start element
 					value = value.toLowerCase();
+
+					// IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
+					if (isIE && invalidPrefixRegExp.test(value))
+						value = value.substr(1);
+
 					isShortEnded = value in shortEndedElements;
 
 					// Is self closing tag for example an <li> after an open <li>
@@ -2039,56 +3181,23 @@
 
 						// Parse attributes
 						if (attribsValue = matches[8]) {
+							isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element
+
+							// If the element has internal attributes then remove it if we are told to do so
+							if (isInternalElement && removeInternalElements)
+								isValidElement = false;
+
 							attrList = [];
 							attrList.map = {};
 
-							attribsValue.replace(attrRegExp, function(match, name, value, val2, val3) {
-								var attrRule, i;
-
-								name = name.toLowerCase();
-								value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
-
-								// Validate name and value
-								if (validate && name.indexOf('data-') !== 0) {
-									attrRule = validAttributesMap[name];
-
-									// Find rule by pattern matching
-									if (!attrRule && validAttributePatterns) {
-										i = validAttributePatterns.length;
-										while (i--) {
-											attrRule = validAttributePatterns[i];
-											if (attrRule.pattern.test(name))
-												break;
-										}
-
-										// No rule matched
-										if (i === -1)
-											attrRule = null;
-									}
-
-									// No attribute rule found
-									if (!attrRule)
-										return;
-
-									// Validate value
-									if (attrRule.validValues && !(value in attrRule.validValues))
-										return;
-								}
-
-								// Add attribute to list and map
-								attrList.map[name] = value;
-								attrList.push({
-									name: name,
-									value: value
-								});
-							});
+							attribsValue.replace(attrRegExp, parseAttribute);
 						} else {
 							attrList = [];
 							attrList.map = {};
 						}
 
 						// Process attributes if validation is enabled
-						if (validate) {
+						if (validate && !isInternalElement) {
 							attributesRequired = elementRule.attributesRequired;
 							attributesDefault = elementRule.attributesDefault;
 							attributesForced = elementRule.attributesForced;
@@ -2483,11 +3592,12 @@
 		},
 
 		isEmpty : function(elements) {
-			var self = this, node = self.firstChild, i;
+			var self = this, node = self.firstChild, i, name;
 
 			if (node) {
 				do {
 					if (node.type === 1) {
+						// Ignore bogus elements
 						if (node.attributes.map['data-mce-bogus'])
 							continue;
 
@@ -2495,14 +3605,19 @@
 						if (elements[node.name])
 							return false;
 
-						// Keep elements with data attributes
+						// Keep elements with data attributes or name attribute like <a name="1"></a>
 						i = node.attributes.length;
 						while (i--) {
-							if (node.attributes[i].name.indexOf('data-') === 0)
+							name = node.attributes[i].name;
+							if (name === "name" || name.indexOf('data-') === 0)
 								return false;
 						}
 					}
 
+					// Keep comments
+					if (node.type === 8)
+						return false;
+					
 					// Keep non whitespace text nodes
 					if ((node.type === 3 && !whiteSpaceRegExp.test(node.value)))
 						return false;
@@ -2510,6 +3625,10 @@
 			}
 
 			return true;
+		},
+
+		walk : function(prev) {
+			return walk(this, null, prev);
 		}
 	});
 
@@ -2540,6 +3659,7 @@
 		var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};
 
 		settings = settings || {};
+		settings.validate = "validate" in settings ? settings.validate : true;
 		settings.root_name = settings.root_name || 'body';
 		self.schema = schema = schema || new tinymce.html.Schema();
 
@@ -2690,21 +3810,46 @@
 		};
 
 		self.parse = function(html, args) {
-			var parser, rootNode, node, nodes, i, l, fi, fl, list, name,
-				blockElements, startWhiteSpaceRegExp, invalidChildren = [],
-				endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements;
+			var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate,
+				blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement,
+				endWhiteSpaceRegExp, allWhiteSpaceRegExp, isAllWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements, rootBlockName;
 
 			args = args || {};
 			matchedNodes = {};
 			matchedAttributes = {};
-			blockElements = tinymce.extend(tinymce.makeMap('script,style,head,title,meta,param'), schema.getBlockElements());
+			blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
 			nonEmptyElements = schema.getNonEmptyElements();
 			children = schema.children;
+			validate = settings.validate;
+			rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
 
 			whiteSpaceElements = schema.getWhiteSpaceElements();
 			startWhiteSpaceRegExp = /^[ \t\r\n]+/;
 			endWhiteSpaceRegExp = /[ \t\r\n]+$/;
 			allWhiteSpaceRegExp = /[ \t\r\n]+/g;
+			isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
+
+			function addRootBlocks() {
+				var node = rootNode.firstChild, next, rootBlockNode;
+
+				while (node) {
+					next = node.next;
+
+					if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) {
+						if (!rootBlockNode) {
+							// Create a new root block element
+							rootBlockNode = createNode(rootBlockName, 1);
+							rootNode.insert(rootBlockNode, node);
+							rootBlockNode.append(node);
+						} else
+							rootBlockNode.append(node);
+					} else {
+						rootBlockNode = null;
+					}
+
+					node = next;
+				};
+			};
 
 			function createNode(name, type) {
 				var node = new Node(name, type), list;
@@ -2721,9 +3866,40 @@
 				return node;
 			};
 
+			function removeWhitespaceBefore(node) {
+				var textNode, textVal, sibling;
+
+				for (textNode = node.prev; textNode && textNode.type === 3; ) {
+					textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
+
+					if (textVal.length > 0) {
+						textNode.value = textVal;
+						textNode = textNode.prev;
+					} else {
+						sibling = textNode.prev;
+						textNode.remove();
+						textNode = sibling;
+					}
+				}
+			};
+
+			function cloneAndExcludeBlocks(input) {
+				var name, output = {};
+
+				for (name in input) {
+					if (name !== 'li' && name != 'p') {
+						output[name] = input[name];
+					}
+				}
+
+				return output;
+			};
+
 			parser = new tinymce.html.SaxParser({
-				validate : settings.validate,
-				fix_self_closing : false, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results
+				validate : validate,
+
+				// Exclude P and LI from DOM parsing since it's treated better by the DOM parser
+				self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
 
 				cdata: function(text) {
 					node.append(createNode('#cdata', 4)).value = text;
@@ -2733,7 +3909,7 @@
 					var textNode;
 
 					// Trim all redundant whitespace on non white space elements
-					if (!whiteSpaceElements[node.name]) {
+					if (!isInWhiteSpacePreservedElement) {
 						text = text.replace(allWhiteSpaceRegExp, ' ');
 
 						if (node.lastChild && blockElements[node.lastChild.name])
@@ -2754,16 +3930,21 @@
 
 				pi: function(name, text) {
 					node.append(createNode(name, 7)).value = text;
+					removeWhitespaceBefore(node);
 				},
 
 				doctype: function(text) {
-					node.append(createNode('#doctype', 10)).value = text;
+					var newNode;
+		
+					newNode = node.append(createNode('#doctype', 10));
+					newNode.value = text;
+					removeWhitespaceBefore(node);
 				},
 
 				start: function(name, attrs, empty) {
 					var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent;
 
-					elementRule = schema.getElementRule(name);
+					elementRule = validate ? schema.getElementRule(name) : {};
 					if (elementRule) {
 						newNode = createNode(elementRule.outputName || name, 1);
 						newNode.attributes = attrs;
@@ -2792,38 +3973,33 @@
 						}
 
 						// Trim whitespace before block
-						if (blockElements[name]) {
-							for (textNode = newNode.prev; textNode && textNode.type === 3; ) {
-								text = textNode.value.replace(endWhiteSpaceRegExp, '');
-
-								if (text.length > 0) {
-									textNode.value = text;
-									textNode = textNode.prev;
-								} else {
-									sibling = textNode.prev;
-									textNode.remove();
-									textNode = sibling;
-								}
-							}
-						}
+						if (blockElements[name])
+							removeWhitespaceBefore(newNode);
 
 						// Change current node if the element wasn't empty i.e not <br /> or <img />
 						if (!empty)
 							node = newNode;
+
+						// Check if we are inside a whitespace preserved element
+						if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
+							isInWhiteSpacePreservedElement = true;
+						}
 					}
 				},
 
 				end: function(name) {
 					var textNode, elementRule, text, sibling, tempNode;
 
-					elementRule = schema.getElementRule(name);
+					elementRule = validate ? schema.getElementRule(name) : {};
 					if (elementRule) {
 						if (blockElements[name]) {
-							if (!whiteSpaceElements[node.name]) {
-								// Trim whitespace at beginning of block
-								for (textNode = node.firstChild; textNode && textNode.type === 3; ) {
+							if (!isInWhiteSpacePreservedElement) {
+								// Trim whitespace of the first node in a block
+								textNode = node.firstChild;
+								if (textNode && textNode.type === 3) {
 									text = textNode.value.replace(startWhiteSpaceRegExp, '');
 
+									// Any characters left after trim or should we remove it
 									if (text.length > 0) {
 										textNode.value = text;
 										textNode = textNode.next;
@@ -2832,18 +4008,46 @@
 										textNode.remove();
 										textNode = sibling;
 									}
+
+									// Remove any pure whitespace siblings
+									while (textNode && textNode.type === 3) {
+										text = textNode.value;
+										sibling = textNode.next;
+
+										if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
+											textNode.remove();
+											textNode = sibling;
+										}
+
+										textNode = sibling;
+									}
 								}
 
-								// Trim whitespace at end of block
-								for (textNode = node.lastChild; textNode && textNode.type === 3; ) {
+								// Trim whitespace of the last node in a block
+								textNode = node.lastChild;
+								if (textNode && textNode.type === 3) {
 									text = textNode.value.replace(endWhiteSpaceRegExp, '');
 
+									// Any characters left after trim or should we remove it
 									if (text.length > 0) {
 										textNode.value = text;
 										textNode = textNode.prev;
 									} else {
 										sibling = textNode.prev;
 										textNode.remove();
+										textNode = sibling;
+									}
+
+									// Remove any pure whitespace siblings
+									while (textNode && textNode.type === 3) {
+										text = textNode.value;
+										sibling = textNode.prev;
+
+										if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
+											textNode.remove();
+											textNode = sibling;
+										}
+
 										textNode = sibling;
 									}
 								}
@@ -2861,6 +4065,11 @@
 							}
 						}
 
+						// Check if we exited a whitespace preserved element
+						if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
+							isInWhiteSpacePreservedElement = false;
+						}
+
 						// Handle empty nodes
 						if (elementRule.removeEmpty || elementRule.paddEmpty) {
 							if (node.isEmpty(nonEmptyElements)) {
@@ -2868,7 +4077,7 @@
 									node.empty().append(new Node('#text', '3')).value = '\u00a0';
 								else {
 									// Leave nodes that have a name like <a name="name">
-									if (!node.attributes.map.name) {
+									if (!node.attributes.map.name && !node.attributes.map.id) {
 										tempNode = node.parent;
 										node.empty().remove();
 										node = tempNode;
@@ -2883,34 +4092,28 @@
 				}
 			}, schema);
 
-			rootNode = node = new Node(settings.root_name, 11);
+			rootNode = node = new Node(args.context || settings.root_name, 11);
 
 			parser.parse(html);
 
-			fixInvalidChildren(invalidChildren);
-
-			// Run node filters
-			for (name in matchedNodes) {
-				list = nodeFilters[name];
-				nodes = matchedNodes[name];
-
-				// Remove already removed children
-				fi = nodes.length;
-				while (fi--) {
-					if (!nodes[fi].parent)
-						nodes.splice(fi, 1);
-				}
-
-				for (i = 0, l = list.length; i < l; i++)
-					list[i](nodes, name, args);
+			// Fix invalid children or report invalid children in a contextual parsing
+			if (validate && invalidChildren.length) {
+				if (!args.context)
+					fixInvalidChildren(invalidChildren);
+				else
+					args.invalid = true;
 			}
 
-			// Run attribute filters
-			for (i = 0, l = attributeFilters.length; i < l; i++) {
-				list = attributeFilters[i];
+			// Wrap nodes in the root into block elements if the root is body
+			if (rootBlockName && rootNode.name == 'body')
+				addRootBlocks();
 
-				if (list.name in matchedAttributes) {
-					nodes = matchedAttributes[list.name];
+			// Run filters only when the contents is valid
+			if (!args.invalid) {
+				// Run node filters
+				for (name in matchedNodes) {
+					list = nodeFilters[name];
+					nodes = matchedNodes[name];
 
 					// Remove already removed children
 					fi = nodes.length;
@@ -2919,8 +4122,27 @@
 							nodes.splice(fi, 1);
 					}
 
-					for (fi = 0, fl = list.callbacks.length; fi < fl; fi++)
-						list.callbacks[fi](nodes, list.name, args);
+					for (i = 0, l = list.length; i < l; i++)
+						list[i](nodes, name, args);
+				}
+
+				// Run attribute filters
+				for (i = 0, l = attributeFilters.length; i < l; i++) {
+					list = attributeFilters[i];
+
+					if (list.name in matchedAttributes) {
+						nodes = matchedAttributes[list.name];
+
+						// Remove already removed children
+						fi = nodes.length;
+						while (fi--) {
+							if (!nodes[fi].parent)
+								nodes.splice(fi, 1);
+						}
+
+						for (fi = 0, fl = list.callbacks.length; fi < fl; fi++)
+							list.callbacks[fi](nodes, list.name, args);
+					}
 				}
 			}
 
@@ -2932,8 +4154,11 @@
 		// these elements and keep br elements that where intended to be there intact
 		if (settings.remove_trailing_brs) {
 			self.addNodeFilter('br', function(nodes, name) {
-				var i, l = nodes.length, node, blockElements = schema.getBlockElements(),
-					nonEmptyElements = schema.getNonEmptyElements(), parent, prev, prevName;
+				var i, l = nodes.length, node, blockElements = tinymce.extend({}, schema.getBlockElements()),
+					nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName;
+
+				// Remove brs from body element as well
+				blockElements.body = 1;
 
 				// Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p>
 				for (i = 0; i < l; i++) {
@@ -2941,7 +4166,7 @@
 					parent = node.parent;
 
 					if (blockElements[node.parent.name] && node === parent.lastChild) {
-						// Loop all nodes to the right of the current node and check for other BR elements
+						// Loop all nodes to the left of the current node and check for other BR elements
 						// excluding bookmarks since they are invisible
 						prev = node.prev;
 						while (prev) {
@@ -2971,12 +4196,54 @@
 								elementRule = schema.getElementRule(parent.name);
 
 								// Remove or padd the element depending on schema rule
-								if (elementRule.removeEmpty)
-									parent.remove();
-								else if (elementRule.paddEmpty) 
-									parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0';
+								if (elementRule) {
+									if (elementRule.removeEmpty)
+										parent.remove();
+									else if (elementRule.paddEmpty)
+										parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0';
+								}
 							}
 						}
+					} else {
+						// Replaces BR elements inside inline elements like <p><b><i><br></i></b></p> so they become <p><b><i>&nbsp;</i></b></p> 
+						lastParent = node;
+						while (parent.firstChild === lastParent && parent.lastChild === lastParent) {
+							lastParent = parent;
+
+							if (blockElements[parent.name]) {
+								break;
+							}
+
+							parent = parent.parent;
+						}
+
+						if (lastParent === parent) {
+							textNode = new tinymce.html.Node('#text', 3);
+							textNode.value = '\u00a0';
+							node.replace(textNode);
+						}
+					}
+				}
+			});
+		}
+
+		// Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included.
+		if (!settings.allow_html_in_named_anchor) {
+			self.addAttributeFilter('id,name', function(nodes, name) {
+				var i = nodes.length, sibling, prevSibling, parent, node;
+
+				while (i--) {
+					node = nodes[i];
+					if (node.name === 'a' && node.firstChild && !node.attr('href')) {
+						parent = node.parent;
+
+						// Move children after current node
+						sibling = node.lastChild;
+						do {
+							prevSibling = sibling.prev;
+							parent.insert(sibling, node);
+							sibling = prevSibling;
+						} while (sibling);
 					}
 				}
 			});
@@ -3019,8 +4286,12 @@
 			else
 				html[html.length] = ' />';
 
-			/*if (indent && indentAfter[name])
-				html.push('\n');*/
+			if (empty && indent && indentAfter[name] && html.length > 0) {
+				value = html[html.length - 1];
+
+				if (value.length > 0 && value !== '\n')
+					html.push('\n');
+			}
 		},
 
 		end: function(name) {
@@ -3061,10 +4332,13 @@
 				html.push('<?', name, ' ', text, '?>');
 			else
 				html.push('<?', name, '?>');
+
+			if (indent)
+				html.push('\n');
 		},
 
 		doctype: function(text) {
-			html.push('<!DOCTYPE', text, '>');
+			html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
 		},
 
 		reset: function() {
@@ -3118,7 +4392,7 @@
 					writer.cdata(node.value);
 				},
 
- 				// Document fragment
+				// Document fragment
 				11: function(node) {
 					if ((node = node.firstChild)) {
 						do {
@@ -3193,6 +4467,586 @@
 	}
 })(tinymce);
 
+// JSLint defined globals
+/*global tinymce:false, window:false */
+
+tinymce.dom = {};
+
+(function(namespace, expando) {
+	var w3cEventModel = !!document.addEventListener;
+
+	function addEvent(target, name, callback, capture) {
+		if (target.addEventListener) {
+			target.addEventListener(name, callback, capture || false);
+		} else if (target.attachEvent) {
+			target.attachEvent('on' + name, callback);
+		}
+	}
+
+	function removeEvent(target, name, callback, capture) {
+		if (target.removeEventListener) {
+			target.removeEventListener(name, callback, capture || false);
+		} else if (target.detachEvent) {
+			target.detachEvent('on' + name, callback);
+		}
+	}
+
+	function fix(original_event, data) {
+		var name, event = data || {};
+
+		// Dummy function that gets replaced on the delegation state functions
+		function returnFalse() {
+			return false;
+		}
+
+		// Dummy function that gets replaced on the delegation state functions
+		function returnTrue() {
+			return true;
+		}
+
+		// Copy all properties from the original event
+		for (name in original_event) {
+			// layerX/layerY is deprecated in Chrome and produces a warning
+			if (name !== "layerX" && name !== "layerY") {
+				event[name] = original_event[name];
+			}
+		}
+
+		// Normalize target IE uses srcElement
+		if (!event.target) {
+			event.target = event.srcElement || document;
+		}
+
+		// Add preventDefault method
+		event.preventDefault = function() {
+			event.isDefaultPrevented = returnTrue;
+
+			// Execute preventDefault on the original event object
+			if (original_event) {
+				if (original_event.preventDefault) {
+					original_event.preventDefault();
+				} else {
+					original_event.returnValue = false; // IE
+				}
+			}
+		};
+
+		// Add stopPropagation
+		event.stopPropagation = function() {
+			event.isPropagationStopped = returnTrue;
+
+			// Execute stopPropagation on the original event object
+			if (original_event) {
+				if (original_event.stopPropagation) {
+					original_event.stopPropagation();
+				} else {
+					original_event.cancelBubble = true; // IE
+				}
+			 }
+		};
+
+		// Add stopImmediatePropagation
+		event.stopImmediatePropagation = function() {
+			event.isImmediatePropagationStopped = returnTrue;
+			event.stopPropagation();
+		};
+
+		// Add event delegation states
+		if (!event.isDefaultPrevented) {
+			event.isDefaultPrevented = returnFalse;
+			event.isPropagationStopped = returnFalse;
+			event.isImmediatePropagationStopped = returnFalse;
+		}
+
+		return event;
+	}
+
+	function bindOnReady(win, callback, event_utils) {
+		var doc = win.document, event = {type: 'ready'};
+
+		// Gets called when the DOM is ready
+		function readyHandler() {
+			if (!event_utils.domLoaded) {
+				event_utils.domLoaded = true;
+				callback(event);
+			}
+		}
+
+		// Use W3C method
+		if (w3cEventModel) {
+			addEvent(win, 'DOMContentLoaded', readyHandler);
+		} else {
+			// Use IE method
+			addEvent(doc, "readystatechange", function() {
+				if (doc.readyState === "complete") {
+					removeEvent(doc, "readystatechange", arguments.callee);
+					readyHandler();
+				}
+			});
+
+			// Wait until we can scroll, when we can the DOM is initialized
+			if (doc.documentElement.doScroll && win === win.top) {
+				(function() {
+					try {
+						// If IE is used, use the trick by Diego Perini licensed under MIT by request to the author.
+						// http://javascript.nwbox.com/IEContentLoaded/
+						doc.documentElement.doScroll("left");
+					} catch (ex) {
+						setTimeout(arguments.callee, 0);
+						return;
+					}
+
+					readyHandler();
+				})();
+			}
+		}
+
+		// Fallback if any of the above methods should fail for some odd reason
+		addEvent(win, 'load', readyHandler);
+	}
+
+	function EventUtils(proxy) {
+		var self = this, events = {}, count, isFocusBlurBound, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave;
+
+		hasMouseEnterLeave = "onmouseenter" in document.documentElement;
+		hasFocusIn = "onfocusin" in document.documentElement;
+		mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'};
+		count = 1;
+
+		// State if the DOMContentLoaded was executed or not
+		self.domLoaded = false;
+		self.events = events;
+
+		function executeHandlers(evt, id) {
+			var callbackList, i, l, callback;
+
+			callbackList = events[id][evt.type];
+			if (callbackList) {
+				for (i = 0, l = callbackList.length; i < l; i++) {
+					callback = callbackList[i];
+					
+					// Check if callback exists might be removed if a unbind is called inside the callback
+					if (callback && callback.func.call(callback.scope, evt) === false) {
+						evt.preventDefault();
+					}
+
+					// Should we stop propagation to immediate listeners
+					if (evt.isImmediatePropagationStopped()) {
+						return;
+					}
+				}
+			}
+		}
+
+		self.bind = function(target, names, callback, scope) {
+			var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window;
+
+			// Native event handler function patches the event and executes the callbacks for the expando
+			function defaultNativeHandler(evt) {
+				executeHandlers(fix(evt || win.event), id);
+			}
+
+			// Don't bind to text nodes or comments
+			if (!target || target.nodeType === 3 || target.nodeType === 8) {
+				return;
+			}
+
+			// Create or get events id for the target
+			if (!target[expando]) {
+				id = count++;
+				target[expando] = id;
+				events[id] = {};
+			} else {
+				id = target[expando];
+
+				if (!events[id]) {
+					events[id] = {};
+				}
+			}
+
+			// Setup the specified scope or use the target as a default
+			scope = scope || target;
+
+			// Split names and bind each event, enables you to bind multiple events with one call
+			names = names.split(' ');
+			i = names.length;
+			while (i--) {
+				name = names[i];
+				nativeHandler = defaultNativeHandler;
+				fakeName = capture = false;
+
+				// Use ready instead of DOMContentLoaded
+				if (name === "DOMContentLoaded") {
+					name = "ready";
+				}
+
+				// DOM is already ready
+				if ((self.domLoaded || target.readyState == 'complete') && name === "ready") {
+					self.domLoaded = true;
+					callback.call(scope, fix({type: name}));
+					continue;
+				}
+
+				// Handle mouseenter/mouseleaver
+				if (!hasMouseEnterLeave) {
+					fakeName = mouseEnterLeave[name];
+
+					if (fakeName) {
+						nativeHandler = function(evt) {
+							var current, related;
+
+							current = evt.currentTarget;
+							related = evt.relatedTarget;
+
+							// Check if related is inside the current target if it's not then the event should be ignored since it's a mouseover/mouseout inside the element
+							if (related && current.contains) {
+								// Use contains for performance
+								related = current.contains(related);
+							} else {
+								while (related && related !== current) {
+									related = related.parentNode;
+								}
+							}
+
+							// Fire fake event
+							if (!related) {
+								evt = fix(evt || win.event);
+								evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
+								evt.target = current;
+								executeHandlers(evt, id);
+							}
+						};
+					}
+				}
+
+				// Fake bubbeling of focusin/focusout
+				if (!hasFocusIn && (name === "focusin" || name === "focusout")) {
+					capture = true;
+					fakeName = name === "focusin" ? "focus" : "blur";
+					nativeHandler = function(evt) {
+						evt = fix(evt || win.event);
+						evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
+						executeHandlers(evt, id);
+					};
+				}
+
+				// Setup callback list and bind native event
+				callbackList = events[id][name];
+				if (!callbackList) {
+					events[id][name] = callbackList = [{func: callback, scope: scope}];
+					callbackList.fakeName = fakeName;
+					callbackList.capture = capture;
+
+					// Add the nativeHandler to the callback list so that we can later unbind it
+					callbackList.nativeHandler = nativeHandler;
+					if (!w3cEventModel) {
+						callbackList.proxyHandler = proxy(id);
+					}
+
+					// Check if the target has native events support
+					if (name === "ready") {
+						bindOnReady(target, nativeHandler, self);
+					} else {
+						addEvent(target, fakeName || name, w3cEventModel ? nativeHandler : callbackList.proxyHandler, capture);
+					}
+				} else {
+					// If it already has an native handler then just push the callback
+					callbackList.push({func: callback, scope: scope});
+				}
+			}
+
+			target = callbackList = 0; // Clean memory for IE
+
+			return callback;
+		};
+
+		self.unbind = function(target, names, callback) {
+			var id, callbackList, i, ci, name, eventMap;
+
+			// Don't bind to text nodes or comments
+			if (!target || target.nodeType === 3 || target.nodeType === 8) {
+				return self;
+			}
+
+			// Unbind event or events if the target has the expando
+			id = target[expando];
+			if (id) {
+				eventMap = events[id];
+
+				// Specific callback
+				if (names) {
+					names = names.split(' ');
+					i = names.length;
+					while (i--) {
+						name = names[i];
+						callbackList = eventMap[name];
+
+						// Unbind the event if it exists in the map
+						if (callbackList) {
+							// Remove specified callback
+							if (callback) {
+								ci = callbackList.length;
+								while (ci--) {
+									if (callbackList[ci].func === callback) {
+										callbackList.splice(ci, 1);
+									}
+								}
+							}
+
+							// Remove all callbacks if there isn't a specified callback or there is no callbacks left
+							if (!callback || callbackList.length === 0) {
+								delete eventMap[name];
+								removeEvent(target, callbackList.fakeName || name, w3cEventModel ? callbackList.nativeHandler : callbackList.proxyHandler, callbackList.capture);
+							}
+						}
+					}
+				} else {
+					// All events for a specific element
+					for (name in eventMap) {
+						callbackList = eventMap[name];
+						removeEvent(target, callbackList.fakeName || name, w3cEventModel ? callbackList.nativeHandler : callbackList.proxyHandler, callbackList.capture);
+					}
+
+					eventMap = {};
+				}
+
+				// Check if object is empty, if it isn't then we won't remove the expando map
+				for (name in eventMap) {
+					return self;
+				}
+
+				// Delete event object
+				delete events[id];
+
+				// Remove expando from target
+				try {
+					// IE will fail here since it can't delete properties from window
+					delete target[expando];
+				} catch (ex) {
+					// IE will set it to null
+					target[expando] = null;
+				}
+			}
+
+			return self;
+		};
+
+		self.fire = function(target, name, args) {
+			var id, event;
+
+			// Don't bind to text nodes or comments
+			if (!target || target.nodeType === 3 || target.nodeType === 8) {
+				return self;
+			}
+
+			// Build event object by patching the args
+			event = fix(null, args);
+			event.type = name;
+
+			do {
+				// Found an expando that means there is listeners to execute
+				id = target[expando];
+				if (id) {
+					executeHandlers(event, id);
+				}
+
+				// Walk up the DOM
+				target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
+			} while (target && !event.isPropagationStopped());
+
+			return self;
+		};
+
+		self.clean = function(target) {
+			var i, children, unbind = self.unbind;
+	
+			// Don't bind to text nodes or comments
+			if (!target || target.nodeType === 3 || target.nodeType === 8) {
+				return self;
+			}
+
+			// Unbind any element on the specificed target
+			if (target[expando]) {
+				unbind(target);
+			}
+
+			// Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children
+			if (!target.getElementsByTagName) {
+				target = target.document;
+			}
+
+			// Remove events from each child element
+			if (target && target.getElementsByTagName) {
+				unbind(target);
+
+				children = target.getElementsByTagName('*');
+				i = children.length;
+				while (i--) {
+					target = children[i];
+
+					if (target[expando]) {
+						unbind(target);
+					}
+				}
+			}
+
+			return self;
+		};
+
+		self.callNativeHandler = function(id, evt) {
+			if (events) {
+				events[id][evt.type].nativeHandler(evt);
+			}
+		};
+
+		self.destory = function() {
+			events = {};
+		};
+
+		// Legacy function calls
+
+		self.add = function(target, events, func, scope) {
+			// Old API supported direct ID assignment
+			if (typeof(target) === "string") {
+				target = document.getElementById(target);
+			}
+
+			// Old API supported multiple targets
+			if (target && target instanceof Array) {
+				var i = target.length;
+
+				while (i--) {
+					self.add(target[i], events, func, scope);
+				}
+
+				return;
+			}
+
+			// Old API called ready init
+			if (events === "init") {
+				events = "ready";
+			}
+
+			return self.bind(target, events instanceof Array ? events.join(' ') : events, func, scope);
+		};
+
+		self.remove = function(target, events, func, scope) {
+			if (!target) {
+				return self;
+			}
+
+			// Old API supported direct ID assignment
+			if (typeof(target) === "string") {
+				target = document.getElementById(target);
+			}
+
+			// Old API supported multiple targets
+			if (target instanceof Array) {
+				var i = target.length;
+
+				while (i--) {
+					self.remove(target[i], events, func, scope);
+				}
+
+				return self;
+			}
+
+			return self.unbind(target, events instanceof Array ? events.join(' ') : events, func);
+		};
+
+		self.clear = function(target) {
+			// Old API supported direct ID assignment
+			if (typeof(target) === "string") {
+				target = document.getElementById(target);
+			}
+
+			return self.clean(target);
+		};
+
+		self.cancel = function(e) {
+			if (e) {
+				self.prevent(e);
+				self.stop(e);
+			}
+
+			return false;
+		};
+
+		self.prevent = function(e) {
+			if (!e.preventDefault) {
+				e = fix(e);
+			}
+
+			e.preventDefault();
+
+			return false;
+		};
+
+		self.stop = function(e) {
+			if (!e.stopPropagation) {
+				e = fix(e);
+			}
+
+			e.stopPropagation();
+
+			return false;
+		};
+	}
+
+	namespace.EventUtils = EventUtils;
+
+	namespace.Event = new EventUtils(function(id) {
+		return function(evt) {
+			tinymce.dom.Event.callNativeHandler(id, evt);
+		};
+	});
+
+	// Bind ready event when tinymce script is loaded
+	namespace.Event.bind(window, 'ready', function() {});
+
+	namespace = 0;
+})(tinymce.dom, 'data-mce-expando'); // Namespace and expando
+
+tinymce.dom.TreeWalker = function(start_node, root_node) {
+	var node = start_node;
+
+	function findSibling(node, start_name, sibling_name, shallow) {
+		var sibling, parent;
+
+		if (node) {
+			// Walk into nodes if it has a start
+			if (!shallow && node[start_name])
+				return node[start_name];
+
+			// Return the sibling if it has one
+			if (node != root_node) {
+				sibling = node[sibling_name];
+				if (sibling)
+					return sibling;
+
+				// Walk up the parents to look for siblings
+				for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
+					sibling = parent[sibling_name];
+					if (sibling)
+						return sibling;
+				}
+			}
+		}
+	};
+
+	this.current = function() {
+		return node;
+	};
+
+	this.next = function(shallow) {
+		return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));
+	};
+
+	this.prev = function(shallow) {
+		return (node = findSibling(node, 'lastChild', 'previousSibling', shallow));
+	};
+};
+
 (function(tinymce) {
 	// Shorten names
 	var each = tinymce.each,
@@ -3201,7 +5055,7 @@
 		isIE = tinymce.isIE,
 		Entities = tinymce.html.Entities,
 		simpleSelectorRe = /^([a-z0-9],?)+$/i,
-		blockElementsMap = tinymce.html.Schema.blockElementsMap;
+		whiteSpaceRegExp = /^[ \t\r\n]*$/;
 
 	tinymce.create('tinymce.dom.DOMUtils', {
 		doc : null,
@@ -3224,7 +5078,7 @@
 		},
 
 		DOMUtils : function(d, s) {
-			var t = this, globalStyle;
+			var t = this, globalStyle, name, blockElementsMap;
 
 			t.doc = d;
 			t.win = window;
@@ -3239,7 +5093,8 @@
 				keep_values : false,
 				hex_colors : 1
 			}, s);
-
+			
+			t.schema = s.schema;
 			t.styles = new tinymce.html.Styles({
 				url_converter : s.url_converter,
 				url_converter_scope : s.url_converter_scope
@@ -3254,18 +5109,78 @@
 				}
 			}
 
-			if (isIE) {
+			t.fixDoc(d);
+			t.events = s.ownEvents ? new tinymce.dom.EventUtils(s.proxy) : tinymce.dom.Event;
+			tinymce.addUnload(t.destroy, t);
+			blockElementsMap = s.schema ? s.schema.getBlockElements() : {};
+
+			t.isBlock = function(node) {
+				// This function is called in module pattern style since it might be executed with the wrong this scope
+				var type = node.nodeType;
+
+				// If it's a node then check the type and use the nodeName
+				if (type)
+					return !!(type === 1 && blockElementsMap[node.nodeName]);
+
+				return !!blockElementsMap[node];
+			};
+		},
+
+		fixDoc: function(doc) {
+			var settings = this.settings, name;
+
+			if (isIE && settings.schema) {
 				// Add missing HTML 4/5 elements to IE
 				('abbr article aside audio canvas ' +
 				'details figcaption figure footer ' +
 				'header hgroup mark menu meter nav ' +
 				'output progress section summary ' +
 				'time video').replace(/\w+/g, function(name) {
-					d.createElement(name);
+					doc.createElement(name);
 				});
+
+				// Create all custom elements
+				for (name in settings.schema.getCustomElements()) {
+					doc.createElement(name);
+				}
+			}
+		},
+
+		clone: function(node, deep) {
+			var self = this, clone, doc;
+
+			// TODO: Add feature detection here in the future
+			if (!isIE || node.nodeType !== 1 || deep) {
+				return node.cloneNode(deep);
 			}
 
-			tinymce.addUnload(t.destroy, t);
+			doc = self.doc;
+
+			// Make a HTML5 safe shallow copy
+			if (!deep) {
+				clone = doc.createElement(node.nodeName);
+
+				// Copy attribs
+				each(self.getAttribs(node), function(attr) {
+					self.setAttrib(clone, attr.nodeName, self.getAttrib(node, attr.nodeName));
+				});
+
+				return clone;
+			}
+/*
+			// Setup HTML5 patched document fragment
+			if (!self.frag) {
+				self.frag = doc.createDocumentFragment();
+				self.fixDoc(self.frag);
+			}
+
+			// Make a deep copy by adding it to the document fragment then removing it this removed the :section
+			clone = doc.createElement('div');
+			self.frag.appendChild(clone);
+			clone.innerHTML = node.outerHTML;
+			self.frag.removeChild(clone);
+*/
+			return clone.firstChild;
 		},
 
 		getRoot : function() {
@@ -3321,8 +5236,8 @@
 				h = 0;
 
 			return {
-				w : parseInt(w) || e.offsetWidth || e.clientWidth,
-				h : parseInt(h) || e.offsetHeight || e.clientHeight
+				w : parseInt(w, 10) || e.offsetWidth || e.clientWidth,
+				h : parseInt(h, 10) || e.offsetHeight || e.clientHeight
 			};
 		},
 
@@ -3469,9 +5384,7 @@
 
 		remove : function(node, keep_children) {
 			return this.run(node, function(node) {
-				var parent, child;
-
-				parent = node.parentNode;
+				var child, parent = node.parentNode;
 
 				if (!parent)
 					return null;
@@ -3539,7 +5452,7 @@
 			n = this.get(n);
 
 			if (!n)
-				return false;
+				return;
 
 			// Gecko
 			if (this.doc.defaultView && c) {
@@ -3568,7 +5481,7 @@
 			if (n.currentStyle && c)
 				return n.currentStyle[na];
 
-			return n.style[na];
+			return n.style ? n.style[na] : undefined;
 		},
 
 		setStyles : function(e, o) {
@@ -3589,8 +5502,8 @@
 
 		removeAllAttribs: function(e) {
 			return this.run(e, function(e) {
-				var attrs = e.attributes;
-				for (var i = attrs.length - 1; i >= 0; i--) {
+				var i, attrs = e.attributes;
+				for (i = attrs.length - 1; i >= 0; i--) {
 					e.removeAttributeNode(attrs.item(i));
 				}
 			});
@@ -3609,52 +5522,59 @@
 
 			return this.run(e, function(e) {
 				var s = t.settings;
+				var originalValue = e.getAttribute(n);
+				if (v !== null) {
+					switch (n) {
+						case "style":
+							if (!is(v, 'string')) {
+								each(v, function(v, n) {
+									t.setStyle(e, n, v);
+								});
 
-				switch (n) {
-					case "style":
-						if (!is(v, 'string')) {
-							each(v, function(v, n) {
-								t.setStyle(e, n, v);
-							});
+								return;
+							}
 
-							return;
-						}
+							// No mce_style for elements with these since they might get resized by the user
+							if (s.keep_values) {
+								if (v && !t._isRes(v))
+									e.setAttribute('data-mce-style', v, 2);
+								else
+									e.removeAttribute('data-mce-style', 2);
+							}
 
-						// No mce_style for elements with these since they might get resized by the user
-						if (s.keep_values) {
-							if (v && !t._isRes(v))
-								e.setAttribute('data-mce-style', v, 2);
-							else
-								e.removeAttribute('data-mce-style', 2);
-						}
+							e.style.cssText = v;
+							break;
 
-						e.style.cssText = v;
-						break;
+						case "class":
+							e.className = v || ''; // Fix IE null bug
+							break;
 
-					case "class":
-						e.className = v || ''; // Fix IE null bug
-						break;
+						case "src":
+						case "href":
+							if (s.keep_values) {
+								if (s.url_converter)
+									v = s.url_converter.call(s.url_converter_scope || t, v, n, e);
 
-					case "src":
-					case "href":
-						if (s.keep_values) {
-							if (s.url_converter)
-								v = s.url_converter.call(s.url_converter_scope || t, v, n, e);
+								t.setAttrib(e, 'data-mce-' + n, v, 2);
+							}
 
-							t.setAttrib(e, 'data-mce-' + n, v, 2);
-						}
+							break;
 
-						break;
-					
-					case "shape":
-						e.setAttribute('data-mce-style', v);
-						break;
+						case "shape":
+							e.setAttribute('data-mce-style', v);
+							break;
+					}
 				}
-
 				if (is(v) && v !== null && v.length !== 0)
 					e.setAttribute(n, '' + v, 2);
 				else
 					e.removeAttribute(n, 2);
+
+				// fire onChangeAttrib event for attributes that have changed
+				if (tinyMCE.activeEditor && originalValue != v) {
+					var ed = tinyMCE.activeEditor;
+					ed.onSetAttrib.dispatch(ed, e, n, v);
+				}
 			});
 		},
 
@@ -3669,12 +5589,12 @@
 		},
 
 		getAttrib : function(e, n, dv) {
-			var v, t = this;
+			var v, t = this, undef;
 
 			e = t.get(e);
 
 			if (!e || e.nodeType !== 1)
-				return false;
+				return dv === undef ? false : dv;
 
 			if (!is(dv))
 				dv = '';
@@ -3786,7 +5706,7 @@
 				}
 			}
 
-			return (v !== undefined && v !== null && v !== '') ? '' + v : dv;
+			return (v !== undef && v !== null && v !== '') ? '' + v : dv;
 		},
 
 		getPos : function(n, ro) {
@@ -3796,14 +5716,17 @@
 			ro = ro || d.body;
 
 			if (n) {
-				// Use getBoundingClientRect on IE, Opera has it but it's not perfect
-				if (isIE && !t.stdMode) {
+				// Use getBoundingClientRect if it exists since it's faster than looping offset nodes
+				if (n.getBoundingClientRect) {
 					n = n.getBoundingClientRect();
 					e = t.boxModel ? d.documentElement : d.body;
-					x = t.getStyle(t.select('html')[0], 'borderWidth'); // Remove border
-					x = (x == 'medium' || t.boxModel && !t.isIE6) && 2 || x;
 
-					return {x : n.left + e.scrollLeft - x, y : n.top + e.scrollTop - x};
+					// Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit
+					// Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position
+					x = n.left + (d.documentElement.scrollLeft || d.body.scrollLeft) - e.clientTop;
+					y = n.top + (d.documentElement.scrollTop || d.body.scrollTop) - e.clientLeft;
+
+					return {x : x, y : y};
 				}
 
 				r = n;
@@ -3832,13 +5755,39 @@
 			return this.styles.serialize(o, name);
 		},
 
+		addStyle: function(cssText) {
+			var doc = this.doc, head;
+
+			// Create style element if needed
+			styleElm = doc.getElementById('mceDefaultStyles');
+			if (!styleElm) {
+				styleElm = doc.createElement('style'),
+				styleElm.id = 'mceDefaultStyles';
+				styleElm.type = 'text/css';
+
+				head = doc.getElementsByTagName('head')[0];
+				if (head.firstChild) {
+					head.insertBefore(styleElm, head.firstChild);
+				} else {
+					head.appendChild(styleElm);
+				}
+			}
+
+			// Append style data to old or new style element
+			if (styleElm.styleSheet) {
+				styleElm.styleSheet.cssText += cssText;
+			} else {
+				styleElm.appendChild(doc.createTextNode(cssText));
+			}
+		},
+
 		loadCSS : function(u) {
 			var t = this, d = t.doc, head;
 
 			if (!u)
 				u = '';
 
-			head = t.select('head')[0];
+			head = d.getElementsByTagName('head')[0];
 
 			each(u.split(','), function(u) {
 				var link;
@@ -3955,13 +5904,13 @@
 						// This seems to fix this problem
 
 						// Create new div with HTML contents and a BR infront to keep comments
-						element = self.create('div');
-						element.innerHTML = '<br />' + html;
+						var newElement = self.create('div');
+						newElement.innerHTML = '<br />' + html;
 
 						// Add all children from div to target
-						each (element.childNodes, function(node, i) {
+						each (tinymce.grep(newElement.childNodes), function(node, i) {
 							// Skip br element
-							if (i)
+							if (i && element.canHaveHTML)
 								element.appendChild(node);
 						});
 					}
@@ -4053,16 +6002,6 @@
 			});
 		},
 
-		isBlock : function(node) {
-			var type = node.nodeType;
-
-			// If it's a node then check the type and use the nodeName
-			if (type)
-				return !!(type === 1 && blockElementsMap[node.nodeName]);
-
-			return !!blockElementsMap[node];
-		},
-
 		replace : function(n, o, k) {
 			var t = this;
 
@@ -4124,7 +6063,7 @@
 			var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s);
 
 			function hex(s) {
-				s = parseInt(s).toString(16);
+				s = parseInt(s, 10).toString(16);
 
 				return s.length > 1 ? s : '0' + s; // 0 -> 00
 			};
@@ -4257,13 +6196,61 @@
 			return n.attributes;
 		},
 
+		isEmpty : function(node, elements) {
+			var self = this, i, attributes, type, walker, name, brCount = 0;
+
+			node = node.firstChild;
+			if (node) {
+				walker = new tinymce.dom.TreeWalker(node, node.parentNode);
+				elements = elements || self.schema ? self.schema.getNonEmptyElements() : null;
+
+				do {
+					type = node.nodeType;
+
+					if (type === 1) {
+						// Ignore bogus elements
+						if (node.getAttribute('data-mce-bogus'))
+							continue;
+
+						// Keep empty elements like <img />
+						name = node.nodeName.toLowerCase();
+						if (elements && elements[name]) {
+							// Ignore single BR elements in blocks like <p><br /></p> or <p><span><br /></span></p>
+							if (name === 'br') {
+								brCount++;
+								continue;
+							}
+
+							return false;
+						}
+
+						// Keep elements with data-bookmark attributes or name attribute like <a name="1"></a>
+						attributes = self.getAttribs(node);
+						i = node.attributes.length;
+						while (i--) {
+							name = node.attributes[i].nodeName;
+							if (name === "name" || name === 'data-mce-bookmark')
+								return false;
+						}
+					}
+
+					// Keep comment nodes
+					if (type == 8)
+						return false;
+
+					// Keep non whitespace text nodes
+					if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue)))
+						return false;
+				} while (node = walker.next());
+			}
+
+			return brCount <= 1;
+		},
+
 		destroy : function(s) {
 			var t = this;
 
-			if (t.events)
-				t.events.destroy();
-
-			t.win = t.doc = t.root = t.events = null;
+			t.win = t.doc = t.root = t.events = t.frag = null;
 
 			// Manual destroy then remove unload handler
 			if (!s)
@@ -4277,7 +6264,7 @@
 		},
 
 		nodeIndex : function(node, normalized) {
-			var idx = 0, lastNodeType, lastNode, nodeType, nodeValueExists;
+			var idx = 0, lastNodeType, lastNode, nodeType;
 
 			if (node) {
 				for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) {
@@ -4285,11 +6272,7 @@
 
 					// Normalize text nodes
 					if (normalized && nodeType == 3) {
-						// ensure that text nodes that have been removed are handled correctly in Internet Explorer.
-						// (the nodeValue attribute will not exist, and will error here).
-						nodeValueExists = false;
-						try {nodeValueExists = node.nodeValue.length} catch (c) {}
-						if (nodeType == lastNodeType || !nodeValueExists)
+						if (nodeType == lastNodeType || !node.nodeValue.length)
 							continue;
 					}
 					idx++;
@@ -4312,23 +6295,30 @@
 			// this function will then trim of empty edges and produce:
 			//   <p>text 1</p><b>CHOP</b><p>text 2</p>
 			function trim(node) {
-				var i, children = node.childNodes;
+				var i, children = node.childNodes, type = node.nodeType;
 
-				if (node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark')
+				function surroundedBySpans(node) {
+					var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN';
+					var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN';
+					return previousIsSpan && nextIsSpan;
+				}
+
+				if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark')
 					return;
 
 				for (i = children.length - 1; i >= 0; i--)
 					trim(children[i]);
 
-				if (node.nodeType != 9) {
+				if (type != 9) {
 					// Keep non whitespace text nodes
-					if (node.nodeType == 3 && node.nodeValue.length > 0) {
+					if (type == 3 && node.nodeValue.length > 0) {
 						// If parent element isn't a block or there isn't any useful contents for example "<p>   </p>"
-						if (!t.isBlock(node.parentNode) || tinymce.trim(node.nodeValue).length > 0)
+						// Also keep text nodes with only spaces if surrounded by spans.
+						// eg. "<p><span>a</span> <span>b</span></p>" should keep space between a and b
+						var trimmedLength = tinymce.trim(node.nodeValue).length;
+						if (!t.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node))
 							return;
-					}
-
-					if (node.nodeType == 1) {
+					} else if (type == 1) {
 						// If the only child is a bookmark then move it up
 						children = node.childNodes;
 						if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark')
@@ -4363,9 +6353,9 @@
 
 				// Insert middle chunk
 				if (re)
-					pa.replaceChild(re, e);
-				else
-					pa.insertBefore(e, pe);
+				pa.replaceChild(re, e);
+			else
+				pa.insertBefore(e, pe);
 
 				// Insert after chunk
 				pa.insertBefore(trim(aft), pe);
@@ -4376,21 +6366,34 @@
 		},
 
 		bind : function(target, name, func, scope) {
-			var t = this;
-
-			if (!t.events)
-				t.events = new tinymce.dom.EventUtils();
-
-			return t.events.add(target, name, func, scope || this);
+			return this.events.add(target, name, func, scope || this);
 		},
 
 		unbind : function(target, name, func) {
-			var t = this;
+			return this.events.remove(target, name, func);
+		},
 
-			if (!t.events)
-				t.events = new tinymce.dom.EventUtils();
+		fire : function(target, name, evt) {
+			return this.events.fire(target, name, evt);
+		},
 
-			return t.events.remove(target, name, func);
+		// Returns the content editable state of a node
+		getContentEditable: function(node) {
+			var contentEditable;
+
+			// Check type
+			if (node.nodeType != 1) {
+				return null;
+			}
+
+			// Check for fake content editable
+			contentEditable = node.getAttribute("data-mce-contenteditable");
+			if (contentEditable && contentEditable !== "inherit") {
+				return contentEditable;
+			}
+
+			// Check for real content editable
+			return node.contentEditable !== "inherit" ? node.contentEditable : null;
 		},
 
 
@@ -4502,8 +6505,13 @@
 			cloneContents : cloneContents,
 			insertNode : insertNode,
 			surroundContents : surroundContents,
-			cloneRange : cloneRange
+			cloneRange : cloneRange,
+			toStringIE : toStringIE
 		});
+
+		function createDocumentFragment() {
+			return doc.createDocumentFragment();
+		};
 
 		function setStart(n, o) {
 			_setEndPoint(TRUE, n, o);
@@ -4837,10 +6845,10 @@
 		};
 
 		 function _traverseSameContainer(how) {
-			var frag, s, sub, n, cnt, sibling, xferNode;
+			var frag, s, sub, n, cnt, sibling, xferNode, start, len;
 
 			if (how != DELETE)
-				frag = doc.createDocumentFragment();
+				frag = createDocumentFragment();
 
 			// If selection is empty, just return the fragment
 			if (t[START_OFFSET] == t[END_OFFSET])
@@ -4854,7 +6862,15 @@
 
 				// set the original text node to its new value
 				if (how != CLONE) {
-					t[START_CONTAINER].deleteData(t[START_OFFSET], t[END_OFFSET] - t[START_OFFSET]);
+					n = t[START_CONTAINER];
+					start = t[START_OFFSET];
+					len = t[END_OFFSET] - t[START_OFFSET];
+
+					if (start === 0 && len >= n.nodeValue.length - 1) {
+						n.parentNode.removeChild(n);
+					} else {
+						n.deleteData(start, len);
+					}
 
 					// Nothing is partially selected, so collapse to start point
 					t.collapse(TRUE);
@@ -4863,7 +6879,10 @@
 				if (how == DELETE)
 					return;
 
-				frag.appendChild(doc.createTextNode(sub));
+				if (sub.length > 0) {
+					frag.appendChild(doc.createTextNode(sub));
+				}
+
 				return frag;
 			}
 
@@ -4871,7 +6890,7 @@
 			n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]);
 			cnt = t[END_OFFSET] - t[START_OFFSET];
 
-			while (cnt > 0) {
+			while (n && cnt > 0) {
 				sibling = n.nextSibling;
 				xferNode = _traverseFullySelected(n, how);
 
@@ -4893,7 +6912,7 @@
 			var frag, n, endIdx, cnt, sibling, xferNode;
 
 			if (how != DELETE)
-				frag = doc.createDocumentFragment();
+				frag = createDocumentFragment();
 
 			n = _traverseRightBoundary(endAncestor, how);
 
@@ -4940,7 +6959,7 @@
 			var frag, startIdx, n, cnt, sibling, xferNode;
 
 			if (how != DELETE)
-				frag = doc.createDocumentFragment();
+				frag = createDocumentFragment();
 
 			n = _traverseLeftBoundary(startAncestor, how);
 			if (frag)
@@ -4951,7 +6970,7 @@
 
 			cnt = t[END_OFFSET] - startIdx;
 			n = startAncestor.nextSibling;
-			while (cnt > 0) {
+			while (n && cnt > 0) {
 				sibling = n.nextSibling;
 				xferNode = _traverseFullySelected(n, how);
 
@@ -4974,7 +6993,7 @@
 			var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling;
 
 			if (how != DELETE)
-				frag = doc.createDocumentFragment();
+				frag = createDocumentFragment();
 
 			n = _traverseLeftBoundary(startAncestor, how);
 			if (frag)
@@ -5109,7 +7128,7 @@
 				if (how == DELETE)
 					return;
 
-				newNode = n.cloneNode(FALSE);
+				newNode = dom.clone(n, FALSE);
 				newNode.nodeValue = newNodeValue;
 
 				return newNode;
@@ -5118,27 +7137,123 @@
 			if (how == DELETE)
 				return;
 
-			return n.cloneNode(FALSE);
+			return dom.clone(n, FALSE);
 		};
 
 		function _traverseFullySelected(n, how) {
 			if (how != DELETE)
-				return how == CLONE ? n.cloneNode(TRUE) : n;
+				return how == CLONE ? dom.clone(n, TRUE) : n;
 
 			n.parentNode.removeChild(n);
 		};
+
+		function toStringIE() {
+			return dom.create('body', null, cloneContents()).outerText;
+		}
+		
+		return t;
 	};
 
 	ns.Range = Range;
+
+	// Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype
+	Range.prototype.toString = function() {
+		return this.toStringIE();
+	};
 })(tinymce.dom);
 
 (function() {
 	function Selection(selection) {
-		var t = this, invisibleChar = '\uFEFF', range, lastIERng, dom = selection.dom, TRUE = true, FALSE = false;
+		var self = this, dom = selection.dom, TRUE = true, FALSE = false;
+
+		function getPosition(rng, start) {
+			var checkRng, startIndex = 0, endIndex, inside,
+				children, child, offset, index, position = -1, parent;
+
+			// Setup test range, collapse it and get the parent
+			checkRng = rng.duplicate();
+			checkRng.collapse(start);
+			parent = checkRng.parentElement();
+
+			// Check if the selection is within the right document
+			if (parent.ownerDocument !== selection.dom.doc)
+				return;
+
+			// IE will report non editable elements as it's parent so look for an editable one
+			while (parent.contentEditable === "false") {
+				parent = parent.parentNode;
+			}
+
+			// If parent doesn't have any children then return that we are inside the element
+			if (!parent.hasChildNodes()) {
+				return {node : parent, inside : 1};
+			}
+
+			// Setup node list and endIndex
+			children = parent.children;
+			endIndex = children.length - 1;
+
+			// Perform a binary search for the position
+			while (startIndex <= endIndex) {
+				index = Math.floor((startIndex + endIndex) / 2);
+
+				// Move selection to node and compare the ranges
+				child = children[index];
+				checkRng.moveToElementText(child);
+				position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng);
+
+				// Before/after or an exact match
+				if (position > 0) {
+					endIndex = index - 1;
+				} else if (position < 0) {
+					startIndex = index + 1;
+				} else {
+					return {node : child};
+				}
+			}
+
+			// Check if child position is before or we didn't find a position
+			if (position < 0) {
+				// No element child was found use the parent element and the offset inside that
+				if (!child) {
+					checkRng.moveToElementText(parent);
+					checkRng.collapse(true);
+					child = parent;
+					inside = true;
+				} else
+					checkRng.collapse(false);
+
+				// Walk character by character in text node until we hit the selected range endpoint, hit the end of document or parent isn't the right one
+				// We need to walk char by char since rng.text or rng.htmlText will trim line endings
+				offset = 0;
+				while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) {
+					if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) {
+						break;
+					}
+
+					offset++;
+				}
+			} else {
+				// Child position is after the selection endpoint
+				checkRng.collapse(true);
+
+				// Walk character by character in text node until we hit the selected range endpoint, hit the end of document or parent isn't the right one
+				offset = 0;
+				while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) {
+					if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) {
+						break;
+					}
+
+					offset++;
+				}
+			}
+
+			return {node : child, position : position, offset : offset, inside : inside};
+		};
 
 		// Returns a W3C DOM compatible range object by using the IE Range API
 		function getRange() {
-			var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed;
+			var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark, fail;
 
 			// If selection is outside the current document just return an empty range
 			element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
@@ -5147,113 +7262,261 @@
 
 			collapsed = selection.isCollapsed();
 
-			// Handle control selection or text selection of a image
-			if (ieRange.item || !element.hasChildNodes()) {
-				if (collapsed) {
-					domRange.setStart(element, 0);
-					domRange.setEnd(element, 0);
-				} else {
-					domRange.setStart(element.parentNode, dom.nodeIndex(element));
-					domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
-				}
+			// Handle control selection
+			if (ieRange.item) {
+				domRange.setStart(element.parentNode, dom.nodeIndex(element));
+				domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
 
 				return domRange;
 			}
 
 			function findEndPoint(start) {
-				var marker, container, offset, nodes, startIndex = 0, endIndex, index, parent, checkRng, position;
+				var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue;
 
-				// Setup temp range and collapse it
-				checkRng = ieRange.duplicate();
-				checkRng.collapse(start);
+				container = endPoint.node;
+				offset = endPoint.offset;
 
-				// Create marker and insert it at the end of the endpoints parent
-				marker = dom.create('a');
-				parent = checkRng.parentElement();
-
-				// If parent doesn't have any children then set the container to that parent and the index to 0
-				if (!parent.hasChildNodes()) {
-					domRange[start ? 'setStart' : 'setEnd'](parent, 0);
+				if (endPoint.inside && !container.hasChildNodes()) {
+					domRange[start ? 'setStart' : 'setEnd'](container, 0);
 					return;
 				}
 
-				parent.appendChild(marker);
-				checkRng.moveToElementText(marker);
-				position = ieRange.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', checkRng);
-				if (position > 0) {
-					// The position is after the end of the parent element.
-					// This is the case where IE puts the caret to the left edge of a table.
-					domRange[start ? 'setStartAfter' : 'setEndAfter'](parent);
-					dom.remove(marker);
+				if (offset === undef) {
+					domRange[start ? 'setStartBefore' : 'setEndAfter'](container);
 					return;
 				}
 
-				// Setup node list and endIndex
-				nodes = tinymce.grep(parent.childNodes);
-				endIndex = nodes.length - 1;
-				// Perform a binary search for the position
-				while (startIndex <= endIndex) {
-					index = Math.floor((startIndex + endIndex) / 2);
+				if (endPoint.position < 0) {
+					sibling = endPoint.inside ? container.firstChild : container.nextSibling;
 
-					// Insert marker and check it's position relative to the selection
-					parent.insertBefore(marker, nodes[index]);
-					checkRng.moveToElementText(marker);
-					position = ieRange.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', checkRng);
-					if (position > 0) {
-						// Marker is to the right
-						startIndex = index + 1;
-					} else if (position < 0) {
-						// Marker is to the left
-						endIndex = index - 1;
-					} else {
-						// Maker is where we are
-						found = true;
-						break;
+					if (!sibling) {
+						domRange[start ? 'setStartAfter' : 'setEndAfter'](container);
+						return;
 					}
-				}
 
-				// Setup container
-				container = position > 0 || index == 0 ? marker.nextSibling : marker.previousSibling;
+					if (!offset) {
+						if (sibling.nodeType == 3)
+							domRange[start ? 'setStart' : 'setEnd'](sibling, 0);
+						else
+							domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling);
 
-				// Handle element selection
-				if (container.nodeType == 1) {
-					dom.remove(marker);
+						return;
+					}
 
-					// Find offset and container
-					offset = dom.nodeIndex(container);
-					container = container.parentNode;
+					// Find the text node and offset
+					while (sibling) {
+						nodeValue = sibling.nodeValue;
+						textNodeOffset += nodeValue.length;
 
-					// Move the offset if we are setting the end or the position is after an element
-					if (!start || index > 0)
-						offset++;
+						// We are at or passed the position we where looking for
+						if (textNodeOffset >= offset) {
+							container = sibling;
+							textNodeOffset -= offset;
+							textNodeOffset = nodeValue.length - textNodeOffset;
+							break;
+						}
+
+						sibling = sibling.nextSibling;
+					}
 				} else {
-					// Calculate offset within text node
-					if (position > 0 || index == 0) {
-						checkRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', ieRange);
-						offset = checkRng.text.length;
-					} else {
-						checkRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', ieRange);
-						offset = container.nodeValue.length - checkRng.text.length;
+					// Find the text node and offset
+					sibling = container.previousSibling;
+
+					if (!sibling)
+						return domRange[start ? 'setStartBefore' : 'setEndBefore'](container);
+
+					// If there isn't any text to loop then use the first position
+					if (!offset) {
+						if (container.nodeType == 3)
+							domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length);
+						else
+							domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling);
+
+						return;
 					}
 
-					dom.remove(marker);
+					while (sibling) {
+						textNodeOffset += sibling.nodeValue.length;
+
+						// We are at or passed the position we where looking for
+						if (textNodeOffset >= offset) {
+							container = sibling;
+							textNodeOffset -= offset;
+							break;
+						}
+
+						sibling = sibling.previousSibling;
+					}
 				}
 
-				domRange[start ? 'setStart' : 'setEnd'](container, offset);
+				domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset);
 			};
 
-			// Find start point
-			findEndPoint(true);
+			try {
+				// Find start point
+				findEndPoint(true);
 
-			// Find end point if needed
-			if (!collapsed)
-				findEndPoint();
+				// Find end point if needed
+				if (!collapsed)
+					findEndPoint();
+			} catch (ex) {
+				// IE has a nasty bug where text nodes might throw "invalid argument" when you
+				// access the nodeValue or other properties of text nodes. This seems to happend when
+				// text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it.
+				if (ex.number == -2147024809) {
+					// Get the current selection
+					bookmark = self.getBookmark(2);
+
+					// Get start element
+					tmpRange = ieRange.duplicate();
+					tmpRange.collapse(true);
+					element = tmpRange.parentElement();
+
+					// Get end element
+					if (!collapsed) {
+						tmpRange = ieRange.duplicate();
+						tmpRange.collapse(false);
+						element2 = tmpRange.parentElement();
+						element2.innerHTML = element2.innerHTML;
+					}
+
+					// Remove the broken elements
+					element.innerHTML = element.innerHTML;
+
+					// Restore the selection
+					self.moveToBookmark(bookmark);
+
+					// Since the range has moved we need to re-get it
+					ieRange = selection.getRng();
+
+					// Find start point
+					findEndPoint(true);
+
+					// Find end point if needed
+					if (!collapsed)
+						findEndPoint();
+				} else
+					throw ex; // Throw other errors
+			}
 
 			return domRange;
 		};
 
+		this.getBookmark = function(type) {
+			var rng = selection.getRng(), start, end, bookmark = {};
+
+			function getIndexes(node) {
+				var parent, root, children, i, indexes = [];
+
+				parent = node.parentNode;
+				root = dom.getRoot().parentNode;
+
+				while (parent != root && parent.nodeType !== 9) {
+					children = parent.children;
+
+					i = children.length;
+					while (i--) {
+						if (node === children[i]) {
+							indexes.push(i);
+							break;
+						}
+					}
+
+					node = parent;
+					parent = parent.parentNode;
+				}
+
+				return indexes;
+			};
+
+			function getBookmarkEndPoint(start) {
+				var position;
+
+				position = getPosition(rng, start);
+				if (position) {
+					return {
+						position : position.position,
+						offset : position.offset,
+						indexes : getIndexes(position.node),
+						inside : position.inside
+					};
+				}
+			};
+
+			// Non ubstructive bookmark
+			if (type === 2) {
+				// Handle text selection
+				if (!rng.item) {
+					bookmark.start = getBookmarkEndPoint(true);
+
+					if (!selection.isCollapsed())
+						bookmark.end = getBookmarkEndPoint();
+				} else
+					bookmark.start = {ctrl : true, indexes : getIndexes(rng.item(0))};
+			}
+
+			return bookmark;
+		};
+
+		this.moveToBookmark = function(bookmark) {
+			var rng, body = dom.doc.body;
+
+			function resolveIndexes(indexes) {
+				var node, i, idx, children;
+
+				node = dom.getRoot();
+				for (i = indexes.length - 1; i >= 0; i--) {
+					children = node.children;
+					idx = indexes[i];
+
+					if (idx <= children.length - 1) {
+						node = children[idx];
+					}
+				}
+
+				return node;
+			};
+			
+			function setBookmarkEndPoint(start) {
+				var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef;
+
+				if (endPoint) {
+					moveLeft = endPoint.position > 0;
+
+					moveRng = body.createTextRange();
+					moveRng.moveToElementText(resolveIndexes(endPoint.indexes));
+
+					offset = endPoint.offset;
+					if (offset !== undef) {
+						moveRng.collapse(endPoint.inside || moveLeft);
+						moveRng.moveStart('character', moveLeft ? -offset : offset);
+					} else
+						moveRng.collapse(start);
+
+					rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng);
+
+					if (start)
+						rng.collapse(true);
+				}
+			};
+
+			if (bookmark.start) {
+				if (bookmark.start.ctrl) {
+					rng = body.createControlRange();
+					rng.addElement(resolveIndexes(bookmark.start.indexes));
+					rng.select();
+				} else {
+					rng = body.createTextRange();
+					setBookmarkEndPoint(true);
+					setBookmarkEndPoint();
+					rng.select();
+				}
+			}
+		};
+
 		this.addRange = function(rng) {
-			var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body;
+			var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling,
+				doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm;
 
 			function setEndPoint(start) {
 				var container, offset, marker, tmpRng, nodes;
@@ -5285,21 +7548,19 @@
 						}
 
 						tmpRng.moveToElementText(marker);
-					} else {
+					} else if (container.canHaveHTML) {
 						// Empty node selection for example <div>|</div>
-						marker = doc.createTextNode(invisibleChar);
-						container.appendChild(marker);
-						tmpRng.moveToElementText(marker.parentNode);
-						tmpRng.collapse(TRUE);
+						// Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open
+						container.innerHTML = '<span>\uFEFF</span>';
+						marker = container.firstChild;
+						tmpRng.moveToElementText(marker);
+						tmpRng.collapse(FALSE); // Collapse false works better than true for some odd reason
 					}
 
 					ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
 					dom.remove(marker);
 				}
 			}
-
-			// Destroy cached range
-			this.destroy();
 
 			// Setup some shorter versions
 			startContainer = rng.startContainer;
@@ -5309,13 +7570,49 @@
 			ieRng = body.createTextRange();
 
 			// If single element selection then try making a control selection out of it
-			if (startContainer == endContainer && startContainer.nodeType == 1 && startOffset == endOffset - 1) {
+			if (startContainer == endContainer && startContainer.nodeType == 1) {
+				// Trick to place the caret inside an empty block element like <p></p>
+				if (startOffset == endOffset && !startContainer.hasChildNodes()) {
+					if (startContainer.canHaveHTML) {
+						// Check if previous sibling is an empty block if it is then we need to render it
+						// IE would otherwise move the caret into the sibling instead of the empty startContainer see: #5236
+						// Example this: <p></p><p>|</p> would become this: <p>|</p><p></p>
+						sibling = startContainer.previousSibling;
+						if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) {
+							sibling.innerHTML = '\uFEFF';
+						} else {
+							sibling = null;
+						}
+
+						startContainer.innerHTML = '<span>\uFEFF</span><span>\uFEFF</span>';
+						ieRng.moveToElementText(startContainer.lastChild);
+						ieRng.select();
+						dom.doc.selection.clear();
+						startContainer.innerHTML = '';
+
+						if (sibling) {
+							sibling.innerHTML = '';
+						}
+						return;
+					} else {
+						startOffset = dom.nodeIndex(startContainer);
+						startContainer = startContainer.parentNode;
+					}
+				}
+
 				if (startOffset == endOffset - 1) {
 					try {
+						ctrlElm = startContainer.childNodes[startOffset];
 						ctrlRng = body.createControlRange();
-						ctrlRng.addElement(startContainer.childNodes[startOffset]);
+						ctrlRng.addElement(ctrlElm);
 						ctrlRng.select();
-						return;
+
+						// Check if the range produced is on the correct element and is a control range
+						// On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398
+						nativeRng = selection.getRng();
+						if (nativeRng.item && ctrlElm === nativeRng.item(0)) {
+							return;
+						}
 					} catch (ex) {
 						// Ignore
 					}
@@ -5330,33 +7627,8 @@
 			ieRng.select();
 		};
 
-		this.getRangeAt = function() {
-			// Setup new range if the cache is empty
-			if (!range || !tinymce.dom.RangeUtils.compareRanges(lastIERng, selection.getRng())) {
-				range = getRange();
-
-				// Store away text range for next call
-				lastIERng = selection.getRng();
-			}
-
-			// IE will say that the range is equal then produce an invalid argument exception
-			// if you perform specific operations in a keyup event. For example Ctrl+Del.
-			// This hack will invalidate the range cache if the exception occurs
-			try {
-				range.startContainer.nextSibling;
-			} catch (ex) {
-				range = getRange();
-				lastIERng = null;
-			}
-
-			// Return cached range
-			return range;
-		};
-
-		this.destroy = function() {
-			// Destroy cached range and last IE range to avoid memory leaks
-			lastIERng = range = null;
-		};
+		// Expose range method
+		this.getRangeAt = getRange;
 	};
 
 	// Expose the selection object
@@ -5365,29 +7637,33 @@
 
 
 /*
- * Sizzle CSS Selector Engine - v1.0
- *  Copyright 2009, The Dojo Foundation
+ * Sizzle CSS Selector Engine
+ *  Copyright, The Dojo Foundation
  *  Released under the MIT, BSD, and GPL Licenses.
  *  More information: http://sizzlejs.com/
  */
 (function(){
 
 var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+	expando = "sizcache",
 	done = 0,
 	toString = Object.prototype.toString,
 	hasDuplicate = false,
-	baseHasDuplicate = true;
+	baseHasDuplicate = true,
+	rBackslash = /\\/g,
+	rReturn = /\r\n/g,
+	rNonWord = /\W/;
 
 // Here we check if the JavaScript engine is using some sort of
 // optimization where it does not always call our comparision
 // function. If that is the case, discard the hasDuplicate value.
 //   Thus far that includes Google Chrome.
-[0, 0].sort(function(){
+[0, 0].sort(function() {
 	baseHasDuplicate = false;
 	return 0;
 });
 
-var Sizzle = function(selector, context, results, seed) {
+var Sizzle = function( selector, context, results, seed ) {
 	results = results || [];
 	context = context || document;
 
@@ -5396,24 +7672,27 @@
 	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
 		return [];
 	}
-	
+
 	if ( !selector || typeof selector !== "string" ) {
 		return results;
 	}
 
-	var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
-		soFar = selector, ret, cur, pop, i;
-	
+	var m, set, checkSet, extra, ret, cur, pop, i,
+		prune = true,
+		contextXML = Sizzle.isXML( context ),
+		parts = [],
+		soFar = selector;
+
 	// Reset the position of the chunker regexp (start from head)
 	do {
-		chunker.exec("");
-		m = chunker.exec(soFar);
+		chunker.exec( "" );
+		m = chunker.exec( soFar );
 
 		if ( m ) {
 			soFar = m[3];
-		
+
 			parts.push( m[1] );
-		
+
 			if ( m[2] ) {
 				extra = m[3];
 				break;
@@ -5422,8 +7701,10 @@
 	} while ( m );
 
 	if ( parts.length > 1 && origPOS.exec( selector ) ) {
+
 		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
-			set = posProcess( parts[0] + parts[1], context );
+			set = posProcess( parts[0] + parts[1], context, seed );
+
 		} else {
 			set = Expr.relative[ parts[0] ] ?
 				[ context ] :
@@ -5435,27 +7716,35 @@
 				if ( Expr.relative[ selector ] ) {
 					selector += parts.shift();
 				}
-				
-				set = posProcess( selector, set );
+
+				set = posProcess( selector, set, seed );
 			}
 		}
+
 	} else {
 		// Take a shortcut and set the context if the root selector is an ID
 		// (but not if it'll be faster if the inner selector is an ID)
 		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
 				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
+
 			ret = Sizzle.find( parts.shift(), context, contextXML );
-			context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
+			context = ret.expr ?
+				Sizzle.filter( ret.expr, ret.set )[0] :
+				ret.set[0];
 		}
 
 		if ( context ) {
 			ret = seed ?
 				{ expr: parts.pop(), set: makeArray(seed) } :
 				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
-			set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
+
+			set = ret.expr ?
+				Sizzle.filter( ret.expr, ret.set ) :
+				ret.set;
 
 			if ( parts.length > 0 ) {
-				checkSet = makeArray(set);
+				checkSet = makeArray( set );
+
 			} else {
 				prune = false;
 			}
@@ -5476,6 +7765,7 @@
 
 				Expr.relative[ cur ]( checkSet, pop, contextXML );
 			}
+
 		} else {
 			checkSet = parts = [];
 		}
@@ -5492,12 +7782,14 @@
 	if ( toString.call(checkSet) === "[object Array]" ) {
 		if ( !prune ) {
 			results.push.apply( results, checkSet );
+
 		} else if ( context && context.nodeType === 1 ) {
 			for ( i = 0; checkSet[i] != null; i++ ) {
 				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
 					results.push( set[i] );
 				}
 			}
+
 		} else {
 			for ( i = 0; checkSet[i] != null; i++ ) {
 				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
@@ -5505,6 +7797,7 @@
 				}
 			}
 		}
+
 	} else {
 		makeArray( checkSet, results );
 	}
@@ -5517,15 +7810,15 @@
 	return results;
 };
 
-Sizzle.uniqueSort = function(results){
+Sizzle.uniqueSort = function( results ) {
 	if ( sortOrder ) {
 		hasDuplicate = baseHasDuplicate;
-		results.sort(sortOrder);
+		results.sort( sortOrder );
 
 		if ( hasDuplicate ) {
 			for ( var i = 1; i < results.length; i++ ) {
-				if ( results[i] === results[i-1] ) {
-					results.splice(i--, 1);
+				if ( results[i] === results[ i - 1 ] ) {
+					results.splice( i--, 1 );
 				}
 			}
 		}
@@ -5534,27 +7827,32 @@
 	return results;
 };
 
-Sizzle.matches = function(expr, set){
-	return Sizzle(expr, null, null, set);
+Sizzle.matches = function( expr, set ) {
+	return Sizzle( expr, null, null, set );
 };
 
-Sizzle.find = function(expr, context, isXML){
-	var set;
+Sizzle.matchesSelector = function( node, expr ) {
+	return Sizzle( expr, null, null, [node] ).length > 0;
+};
+
+Sizzle.find = function( expr, context, isXML ) {
+	var set, i, len, match, type, left;
 
 	if ( !expr ) {
 		return [];
 	}
 
-	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
-		var type = Expr.order[i], match;
-		
+	for ( i = 0, len = Expr.order.length; i < len; i++ ) {
+		type = Expr.order[i];
+
 		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
-			var left = match[1];
-			match.splice(1,1);
+			left = match[1];
+			match.splice( 1, 1 );
 
 			if ( left.substr( left.length - 1 ) !== "\\" ) {
-				match[1] = (match[1] || "").replace(/\\/g, "");
+				match[1] = (match[1] || "").replace( rBackslash, "" );
 				set = Expr.find[ type ]( match, context, isXML );
+
 				if ( set != null ) {
 					expr = expr.replace( Expr.match[ type ], "" );
 					break;
@@ -5564,20 +7862,29 @@
 	}
 
 	if ( !set ) {
-		set = context.getElementsByTagName("*");
+		set = typeof context.getElementsByTagName !== "undefined" ?
+			context.getElementsByTagName( "*" ) :
+			[];
 	}
 
-	return {set: set, expr: expr};
+	return { set: set, expr: expr };
 };
 
-Sizzle.filter = function(expr, set, inplace, not){
-	var old = expr, result = [], curLoop = set, match, anyFound,
-		isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
+Sizzle.filter = function( expr, set, inplace, not ) {
+	var match, anyFound,
+		type, found, item, filter, left,
+		i, pass,
+		old = expr,
+		result = [],
+		curLoop = set,
+		isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
 
 	while ( expr && set.length ) {
-		for ( var type in Expr.filter ) {
+		for ( type in Expr.filter ) {
 			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
-				var filter = Expr.filter[ type ], found, item, left = match[1];
+				filter = Expr.filter[ type ];
+				left = match[1];
+
 				anyFound = false;
 
 				match.splice(1,1);
@@ -5595,23 +7902,26 @@
 
 					if ( !match ) {
 						anyFound = found = true;
+
 					} else if ( match === true ) {
 						continue;
 					}
 				}
 
 				if ( match ) {
-					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+					for ( i = 0; (item = curLoop[i]) != null; i++ ) {
 						if ( item ) {
 							found = filter( item, match, i, curLoop );
-							var pass = not ^ !!found;
+							pass = not ^ found;
 
 							if ( inplace && found != null ) {
 								if ( pass ) {
 									anyFound = true;
+
 								} else {
 									curLoop[i] = false;
 								}
+
 							} else if ( pass ) {
 								result.push( item );
 								anyFound = true;
@@ -5640,6 +7950,7 @@
 		if ( expr === old ) {
 			if ( anyFound == null ) {
 				Sizzle.error( expr );
+
 			} else {
 				break;
 			}
@@ -5652,35 +7963,78 @@
 };
 
 Sizzle.error = function( msg ) {
-	throw "Syntax error, unrecognized expression: " + msg;
+	throw new Error( "Syntax error, unrecognized expression: " + msg );
+};
+
+var getText = Sizzle.getText = function( elem ) {
+    var i, node,
+		nodeType = elem.nodeType,
+		ret = "";
+
+	if ( nodeType ) {
+		if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+			// Use textContent || innerText for elements
+			if ( typeof elem.textContent === 'string' ) {
+				return elem.textContent;
+			} else if ( typeof elem.innerText === 'string' ) {
+				// Replace IE's carriage returns
+				return elem.innerText.replace( rReturn, '' );
+			} else {
+				// Traverse it's children
+				for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
+					ret += getText( elem );
+				}
+			}
+		} else if ( nodeType === 3 || nodeType === 4 ) {
+			return elem.nodeValue;
+		}
+	} else {
+
+		// If no nodeType, this is expected to be an array
+		for ( i = 0; (node = elem[i]); i++ ) {
+			// Do not traverse comment nodes
+			if ( node.nodeType !== 8 ) {
+				ret += getText( node );
+			}
+		}
+	}
+	return ret;
 };
 
 var Expr = Sizzle.selectors = {
 	order: [ "ID", "NAME", "TAG" ],
+
 	match: {
 		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
 		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
 		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
-		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
+		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
 		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
-		CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
+		CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
 		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
 		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
 	},
+
 	leftMatch: {},
+
 	attrMap: {
 		"class": "className",
 		"for": "htmlFor"
 	},
+
 	attrHandle: {
-		href: function(elem){
-			return elem.getAttribute("href");
+		href: function( elem ) {
+			return elem.getAttribute( "href" );
+		},
+		type: function( elem ) {
+			return elem.getAttribute( "type" );
 		}
 	},
+
 	relative: {
 		"+": function(checkSet, part){
 			var isPartStr = typeof part === "string",
-				isTag = isPartStr && !/\W/.test(part),
+				isTag = isPartStr && !rNonWord.test( part ),
 				isPartStrNotTag = isPartStr && !isTag;
 
 			if ( isTag ) {
@@ -5701,23 +8055,29 @@
 				Sizzle.filter( part, checkSet, true );
 			}
 		},
-		">": function(checkSet, part){
-			var isPartStr = typeof part === "string",
-				elem, i = 0, l = checkSet.length;
 
-			if ( isPartStr && !/\W/.test(part) ) {
+		">": function( checkSet, part ) {
+			var elem,
+				isPartStr = typeof part === "string",
+				i = 0,
+				l = checkSet.length;
+
+			if ( isPartStr && !rNonWord.test( part ) ) {
 				part = part.toLowerCase();
 
 				for ( ; i < l; i++ ) {
 					elem = checkSet[i];
+
 					if ( elem ) {
 						var parent = elem.parentNode;
 						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
 					}
 				}
+
 			} else {
 				for ( ; i < l; i++ ) {
 					elem = checkSet[i];
+
 					if ( elem ) {
 						checkSet[i] = isPartStr ?
 							elem.parentNode :
@@ -5730,39 +8090,50 @@
 				}
 			}
 		},
+
 		"": function(checkSet, part, isXML){
-			var doneName = done++, checkFn = dirCheck, nodeCheck;
+			var nodeCheck,
+				doneName = done++,
+				checkFn = dirCheck;
 
-			if ( typeof part === "string" && !/\W/.test(part) ) {
+			if ( typeof part === "string" && !rNonWord.test( part ) ) {
 				part = part.toLowerCase();
 				nodeCheck = part;
 				checkFn = dirNodeCheck;
 			}
 
-			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
+			checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
 		},
-		"~": function(checkSet, part, isXML){
-			var doneName = done++, checkFn = dirCheck, nodeCheck;
 
-			if ( typeof part === "string" && !/\W/.test(part) ) {
+		"~": function( checkSet, part, isXML ) {
+			var nodeCheck,
+				doneName = done++,
+				checkFn = dirCheck;
+
+			if ( typeof part === "string" && !rNonWord.test( part ) ) {
 				part = part.toLowerCase();
 				nodeCheck = part;
 				checkFn = dirNodeCheck;
 			}
 
-			checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
+			checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
 		}
 	},
+
 	find: {
-		ID: function(match, context, isXML){
+		ID: function( match, context, isXML ) {
 			if ( typeof context.getElementById !== "undefined" && !isXML ) {
 				var m = context.getElementById(match[1]);
-				return m ? [m] : [];
+				// Check parentNode to catch when Blackberry 4.6 returns
+				// nodes that are no longer in the document #6963
+				return m && m.parentNode ? [m] : [];
 			}
 		},
-		NAME: function(match, context){
+
+		NAME: function( match, context ) {
 			if ( typeof context.getElementsByName !== "undefined" ) {
-				var ret = [], results = context.getElementsByName(match[1]);
+				var ret = [],
+					results = context.getElementsByName( match[1] );
 
 				for ( var i = 0, l = results.length; i < l; i++ ) {
 					if ( results[i].getAttribute("name") === match[1] ) {
@@ -5773,13 +8144,16 @@
 				return ret.length === 0 ? null : ret;
 			}
 		},
-		TAG: function(match, context){
-			return context.getElementsByTagName(match[1]);
+
+		TAG: function( match, context ) {
+			if ( typeof context.getElementsByTagName !== "undefined" ) {
+				return context.getElementsByTagName( match[1] );
+			}
 		}
 	},
 	preFilter: {
-		CLASS: function(match, curLoop, inplace, result, not, isXML){
-			match = " " + match[1].replace(/\\/g, "") + " ";
+		CLASS: function( match, curLoop, inplace, result, not, isXML ) {
+			match = " " + match[1].replace( rBackslash, "" ) + " ";
 
 			if ( isXML ) {
 				return match;
@@ -5787,10 +8161,11 @@
 
 			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
 				if ( elem ) {
-					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
+					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
 						if ( !inplace ) {
 							result.push( elem );
 						}
+
 					} else if ( inplace ) {
 						curLoop[i] = false;
 					}
@@ -5799,16 +8174,25 @@
 
 			return false;
 		},
-		ID: function(match){
-			return match[1].replace(/\\/g, "");
+
+		ID: function( match ) {
+			return match[1].replace( rBackslash, "" );
 		},
-		TAG: function(match, curLoop){
-			return match[1].toLowerCase();
+
+		TAG: function( match, curLoop ) {
+			return match[1].replace( rBackslash, "" ).toLowerCase();
 		},
-		CHILD: function(match){
+
+		CHILD: function( match ) {
 			if ( match[1] === "nth" ) {
+				if ( !match[2] ) {
+					Sizzle.error( match[0] );
+				}
+
+				match[2] = match[2].replace(/^\+|\s*/g, '');
+
 				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
-				var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+				var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
 					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
 					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
 
@@ -5816,18 +8200,25 @@
 				match[2] = (test[1] + (test[2] || 1)) - 0;
 				match[3] = test[3] - 0;
 			}
+			else if ( match[2] ) {
+				Sizzle.error( match[0] );
+			}
 
 			// TODO: Move to normal caching system
 			match[0] = done++;
 
 			return match;
 		},
-		ATTR: function(match, curLoop, inplace, result, not, isXML){
-			var name = match[1].replace(/\\/g, "");
-			
+
+		ATTR: function( match, curLoop, inplace, result, not, isXML ) {
+			var name = match[1] = match[1].replace( rBackslash, "" );
+
 			if ( !isXML && Expr.attrMap[name] ) {
 				match[1] = Expr.attrMap[name];
 			}
+
+			// Handle if an un-quoted value was used
+			match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
 
 			if ( match[2] === "~=" ) {
 				match[4] = " " + match[4] + " ";
@@ -5835,122 +8226,170 @@
 
 			return match;
 		},
-		PSEUDO: function(match, curLoop, inplace, result, not){
+
+		PSEUDO: function( match, curLoop, inplace, result, not ) {
 			if ( match[1] === "not" ) {
 				// If we're dealing with a complex expression, or a simple one
 				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
 					match[3] = Sizzle(match[3], null, null, curLoop);
+
 				} else {
 					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+
 					if ( !inplace ) {
 						result.push.apply( result, ret );
 					}
+
 					return false;
 				}
+
 			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
 				return true;
 			}
-			
+
 			return match;
 		},
-		POS: function(match){
+
+		POS: function( match ) {
 			match.unshift( true );
+
 			return match;
 		}
 	},
+
 	filters: {
-		enabled: function(elem){
+		enabled: function( elem ) {
 			return elem.disabled === false && elem.type !== "hidden";
 		},
-		disabled: function(elem){
+
+		disabled: function( elem ) {
 			return elem.disabled === true;
 		},
-		checked: function(elem){
+
+		checked: function( elem ) {
 			return elem.checked === true;
 		},
-		selected: function(elem){
+
+		selected: function( elem ) {
 			// Accessing this property makes selected-by-default
 			// options in Safari work properly
-			elem.parentNode.selectedIndex;
+			if ( elem.parentNode ) {
+				elem.parentNode.selectedIndex;
+			}
+
 			return elem.selected === true;
 		},
-		parent: function(elem){
+
+		parent: function( elem ) {
 			return !!elem.firstChild;
 		},
-		empty: function(elem){
+
+		empty: function( elem ) {
 			return !elem.firstChild;
 		},
-		has: function(elem, i, match){
+
+		has: function( elem, i, match ) {
 			return !!Sizzle( match[3], elem ).length;
 		},
-		header: function(elem){
+
+		header: function( elem ) {
 			return (/h\d/i).test( elem.nodeName );
 		},
-		text: function(elem){
-			return "text" === elem.type;
+
+		text: function( elem ) {
+			var attr = elem.getAttribute( "type" ), type = elem.type;
+			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
+			// use getAttribute instead to test this case
+			return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
 		},
-		radio: function(elem){
-			return "radio" === elem.type;
+
+		radio: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
 		},
-		checkbox: function(elem){
-			return "checkbox" === elem.type;
+
+		checkbox: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
 		},
-		file: function(elem){
-			return "file" === elem.type;
+
+		file: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
 		},
-		password: function(elem){
-			return "password" === elem.type;
+
+		password: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
 		},
-		submit: function(elem){
-			return "submit" === elem.type;
+
+		submit: function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return (name === "input" || name === "button") && "submit" === elem.type;
 		},
-		image: function(elem){
-			return "image" === elem.type;
+
+		image: function( elem ) {
+			return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
 		},
-		reset: function(elem){
-			return "reset" === elem.type;
+
+		reset: function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return (name === "input" || name === "button") && "reset" === elem.type;
 		},
-		button: function(elem){
-			return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
+
+		button: function( elem ) {
+			var name = elem.nodeName.toLowerCase();
+			return name === "input" && "button" === elem.type || name === "button";
 		},
-		input: function(elem){
-			return (/input|select|textarea|button/i).test(elem.nodeName);
+
+		input: function( elem ) {
+			return (/input|select|textarea|button/i).test( elem.nodeName );
+		},
+
+		focus: function( elem ) {
+			return elem === elem.ownerDocument.activeElement;
 		}
 	},
 	setFilters: {
-		first: function(elem, i){
+		first: function( elem, i ) {
 			return i === 0;
 		},
-		last: function(elem, i, match, array){
+
+		last: function( elem, i, match, array ) {
 			return i === array.length - 1;
 		},
-		even: function(elem, i){
+
+		even: function( elem, i ) {
 			return i % 2 === 0;
 		},
-		odd: function(elem, i){
+
+		odd: function( elem, i ) {
 			return i % 2 === 1;
 		},
-		lt: function(elem, i, match){
+
+		lt: function( elem, i, match ) {
 			return i < match[3] - 0;
 		},
-		gt: function(elem, i, match){
+
+		gt: function( elem, i, match ) {
 			return i > match[3] - 0;
 		},
-		nth: function(elem, i, match){
+
+		nth: function( elem, i, match ) {
 			return match[3] - 0 === i;
 		},
-		eq: function(elem, i, match){
+
+		eq: function( elem, i, match ) {
 			return match[3] - 0 === i;
 		}
 	},
 	filter: {
-		PSEUDO: function(elem, match, i, array){
-			var name = match[1], filter = Expr.filters[ name ];
+		PSEUDO: function( elem, match, i, array ) {
+			var name = match[1],
+				filter = Expr.filters[ name ];
 
 			if ( filter ) {
 				return filter( elem, i, match, array );
+
 			} else if ( name === "contains" ) {
-				return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
+				return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
 			} else if ( name === "not" ) {
 				var not = match[3];
 
@@ -5961,72 +8400,96 @@
 				}
 
 				return true;
+
 			} else {
-				Sizzle.error( "Syntax error, unrecognized expression: " + name );
+				Sizzle.error( name );
 			}
 		},
-		CHILD: function(elem, match){
-			var type = match[1], node = elem;
-			switch (type) {
-				case 'only':
-				case 'first':
-					while ( (node = node.previousSibling) )	 {
-						if ( node.nodeType === 1 ) { 
-							return false; 
+
+		CHILD: function( elem, match ) {
+			var first, last,
+				doneName, parent, cache,
+				count, diff,
+				type = match[1],
+				node = elem;
+
+			switch ( type ) {
+				case "only":
+				case "first":
+					while ( (node = node.previousSibling) ) {
+						if ( node.nodeType === 1 ) {
+							return false;
 						}
 					}
-					if ( type === "first" ) { 
-						return true; 
+
+					if ( type === "first" ) {
+						return true;
 					}
+
 					node = elem;
-				case 'last':
-					while ( (node = node.nextSibling) )	 {
-						if ( node.nodeType === 1 ) { 
-							return false; 
+
+					/* falls through */
+				case "last":
+					while ( (node = node.nextSibling) ) {
+						if ( node.nodeType === 1 ) {
+							return false;
 						}
 					}
+
 					return true;
-				case 'nth':
-					var first = match[2], last = match[3];
+
+				case "nth":
+					first = match[2];
+					last = match[3];
 
 					if ( first === 1 && last === 0 ) {
 						return true;
 					}
-					
-					var doneName = match[0],
-						parent = elem.parentNode;
-	
-					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
-						var count = 0;
+
+					doneName = match[0];
+					parent = elem.parentNode;
+
+					if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
+						count = 0;
+
 						for ( node = parent.firstChild; node; node = node.nextSibling ) {
 							if ( node.nodeType === 1 ) {
 								node.nodeIndex = ++count;
 							}
-						} 
-						parent.sizcache = doneName;
+						}
+
+						parent[ expando ] = doneName;
 					}
-					
-					var diff = elem.nodeIndex - last;
+
+					diff = elem.nodeIndex - last;
+
 					if ( first === 0 ) {
 						return diff === 0;
+
 					} else {
 						return ( diff % first === 0 && diff / first >= 0 );
 					}
 			}
 		},
-		ID: function(elem, match){
+
+		ID: function( elem, match ) {
 			return elem.nodeType === 1 && elem.getAttribute("id") === match;
 		},
-		TAG: function(elem, match){
-			return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
+
+		TAG: function( elem, match ) {
+			return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
 		},
-		CLASS: function(elem, match){
+
+		CLASS: function( elem, match ) {
 			return (" " + (elem.className || elem.getAttribute("class")) + " ")
 				.indexOf( match ) > -1;
 		},
-		ATTR: function(elem, match){
+
+		ATTR: function( elem, match ) {
 			var name = match[1],
-				result = Expr.attrHandle[ name ] ?
+				result = Sizzle.attr ?
+					Sizzle.attr( elem, name ) :
+					Expr.attrHandle[ name ] ?
 					Expr.attrHandle[ name ]( elem ) :
 					elem[ name ] != null ?
 						elem[ name ] :
@@ -6037,6 +8500,8 @@
 
 			return result == null ?
 				type === "!=" :
+				!type && Sizzle.attr ?
+				result != null :
 				type === "=" ?
 				value === check :
 				type === "*=" ?
@@ -6055,8 +8520,10 @@
 				value === check || value.substr(0, check.length + 1) === check + "-" :
 				false;
 		},
-		POS: function(elem, match, i, array){
-			var name = match[2], filter = Expr.setFilters[ name ];
+
+		POS: function( elem, match, i, array ) {
+			var name = match[2],
+				filter = Expr.setFilters[ name ];
 
 			if ( filter ) {
 				return filter( elem, i, match, array );
@@ -6074,15 +8541,18 @@
 	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
 	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
 }
+// Expose origPOS
+// "global" as in regardless of relation to brackets/parens
+Expr.match.globalPOS = origPOS;
 
-var makeArray = function(array, results) {
+var makeArray = function( array, results ) {
 	array = Array.prototype.slice.call( array, 0 );
 
 	if ( results ) {
 		results.push.apply( results, array );
 		return results;
 	}
-	
+
 	return array;
 };
 
@@ -6094,17 +8564,20 @@
 	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
 
 // Provide a fallback method if it does not work
-} catch(e){
-	makeArray = function(array, results) {
-		var ret = results || [], i = 0;
+} catch( e ) {
+	makeArray = function( array, results ) {
+		var i = 0,
+			ret = results || [];
 
 		if ( toString.call(array) === "[object Array]" ) {
 			Array.prototype.push.apply( ret, array );
+
 		} else {
 			if ( typeof array.length === "number" ) {
 				for ( var l = array.length; i < l; i++ ) {
 					ret.push( array[i] );
 				}
+
 			} else {
 				for ( ; array[i]; i++ ) {
 					ret.push( array[i] );
@@ -6116,110 +8589,141 @@
 	};
 }
 
-var sortOrder;
+var sortOrder, siblingCheck;
 
 if ( document.documentElement.compareDocumentPosition ) {
 	sortOrder = function( a, b ) {
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+		}
+
 		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
-			if ( a == b ) {
-				hasDuplicate = true;
-			}
 			return a.compareDocumentPosition ? -1 : 1;
 		}
 
-		var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
-		if ( ret === 0 ) {
-			hasDuplicate = true;
-		}
-		return ret;
+		return a.compareDocumentPosition(b) & 4 ? -1 : 1;
 	};
-} else if ( "sourceIndex" in document.documentElement ) {
+
+} else {
 	sortOrder = function( a, b ) {
-		if ( !a.sourceIndex || !b.sourceIndex ) {
-			if ( a == b ) {
-				hasDuplicate = true;
-			}
-			return a.sourceIndex ? -1 : 1;
+		// The nodes are identical, we can exit early
+		if ( a === b ) {
+			hasDuplicate = true;
+			return 0;
+
+		// Fallback to using sourceIndex (in IE) if it's available on both nodes
+		} else if ( a.sourceIndex && b.sourceIndex ) {
+			return a.sourceIndex - b.sourceIndex;
 		}
 
-		var ret = a.sourceIndex - b.sourceIndex;
-		if ( ret === 0 ) {
-			hasDuplicate = true;
-		}
-		return ret;
-	};
-} else if ( document.createRange ) {
-	sortOrder = function( a, b ) {
-		if ( !a.ownerDocument || !b.ownerDocument ) {
-			if ( a == b ) {
-				hasDuplicate = true;
-			}
-			return a.ownerDocument ? -1 : 1;
+		var al, bl,
+			ap = [],
+			bp = [],
+			aup = a.parentNode,
+			bup = b.parentNode,
+			cur = aup;
+
+		// If the nodes are siblings (or identical) we can do a quick check
+		if ( aup === bup ) {
+			return siblingCheck( a, b );
+
+		// If no parents were found then the nodes are disconnected
+		} else if ( !aup ) {
+			return -1;
+
+		} else if ( !bup ) {
+			return 1;
 		}
 
-		var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
-		aRange.setStart(a, 0);
-		aRange.setEnd(a, 0);
-		bRange.setStart(b, 0);
-		bRange.setEnd(b, 0);
-		var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
-		if ( ret === 0 ) {
-			hasDuplicate = true;
+		// Otherwise they're somewhere else in the tree so we need
+		// to build up a full list of the parentNodes for comparison
+		while ( cur ) {
+			ap.unshift( cur );
+			cur = cur.parentNode;
 		}
-		return ret;
+
+		cur = bup;
+
+		while ( cur ) {
+			bp.unshift( cur );
+			cur = cur.parentNode;
+		}
+
+		al = ap.length;
+		bl = bp.length;
+
+		// Start walking down the tree looking for a discrepancy
+		for ( var i = 0; i < al && i < bl; i++ ) {
+			if ( ap[i] !== bp[i] ) {
+				return siblingCheck( ap[i], bp[i] );
+			}
+		}
+
+		// We ended someplace up the tree so do a sibling check
+		return i === al ?
+			siblingCheck( a, bp[i], -1 ) :
+			siblingCheck( ap[i], b, 1 );
+	};
+
+	siblingCheck = function( a, b, ret ) {
+		if ( a === b ) {
+			return ret;
+		}
+
+		var cur = a.nextSibling;
+
+		while ( cur ) {
+			if ( cur === b ) {
+				return -1;
+			}
+
+			cur = cur.nextSibling;
+		}
+
+		return 1;
 	};
 }
-
-// Utility function for retreiving the text value of an array of DOM nodes
-Sizzle.getText = function( elems ) {
-	var ret = "", elem;
-
-	for ( var i = 0; elems[i]; i++ ) {
-		elem = elems[i];
-
-		// Get the text from text nodes and CDATA nodes
-		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
-			ret += elem.nodeValue;
-
-		// Traverse everything else, except comment nodes
-		} else if ( elem.nodeType !== 8 ) {
-			ret += Sizzle.getText( elem.childNodes );
-		}
-	}
-
-	return ret;
-};
 
 // Check to see if the browser returns elements by name when
 // querying by getElementById (and provide a workaround)
 (function(){
 	// We're going to inject a fake input element with a specified name
 	var form = document.createElement("div"),
-		id = "script" + (new Date()).getTime();
+		id = "script" + (new Date()).getTime(),
+		root = document.documentElement;
+
 	form.innerHTML = "<a name='" + id + "'/>";
 
 	// Inject it into the root element, check its status, and remove it quickly
-	var root = document.documentElement;
 	root.insertBefore( form, root.firstChild );
 
 	// The workaround has to do additional checks after a getElementById
 	// Which slows things down for other browsers (hence the branching)
 	if ( document.getElementById( id ) ) {
-		Expr.find.ID = function(match, context, isXML){
+		Expr.find.ID = function( match, context, isXML ) {
 			if ( typeof context.getElementById !== "undefined" && !isXML ) {
 				var m = context.getElementById(match[1]);
-				return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
+
+				return m ?
+					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+						[m] :
+						undefined :
+					[];
 			}
 		};
 
-		Expr.filter.ID = function(elem, match){
+		Expr.filter.ID = function( elem, match ) {
 			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+
 			return elem.nodeType === 1 && node && node.nodeValue === match;
 		};
 	}
 
 	root.removeChild( form );
-	root = form = null; // release memory in IE
+
+	// release memory in IE
+	root = form = null;
 })();
 
 (function(){
@@ -6232,8 +8736,8 @@
 
 	// Make sure no comments are found
 	if ( div.getElementsByTagName("*").length > 0 ) {
-		Expr.find.TAG = function(match, context){
-			var results = context.getElementsByTagName(match[1]);
+		Expr.find.TAG = function( match, context ) {
+			var results = context.getElementsByTagName( match[1] );
 
 			// Filter out possible comments
 			if ( match[1] === "*" ) {
@@ -6254,19 +8758,25 @@
 
 	// Check to see if an attribute returns normalized href attributes
 	div.innerHTML = "<a href='#'></a>";
+
 	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
 			div.firstChild.getAttribute("href") !== "#" ) {
-		Expr.attrHandle.href = function(elem){
-			return elem.getAttribute("href", 2);
+
+		Expr.attrHandle.href = function( elem ) {
+			return elem.getAttribute( "href", 2 );
 		};
 	}
 
-	div = null; // release memory in IE
+	// release memory in IE
+	div = null;
 })();
 
 if ( document.querySelectorAll ) {
 	(function(){
-		var oldSizzle = Sizzle, div = document.createElement("div");
+		var oldSizzle = Sizzle,
+			div = document.createElement("div"),
+			id = "__sizzle__";
+
 		div.innerHTML = "<p class='TEST'></p>";
 
 		// Safari can't handle uppercase or unicode characters when
@@ -6274,18 +8784,89 @@
 		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
 			return;
 		}
-	
-		Sizzle = function(query, context, extra, seed){
+
+		Sizzle = function( query, context, extra, seed ) {
 			context = context || document;
 
 			// Only use querySelectorAll on non-XML documents
 			// (ID selectors don't work in non-HTML documents)
-			if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
-				try {
-					return makeArray( context.querySelectorAll(query), extra );
-				} catch(e){}
+			if ( !seed && !Sizzle.isXML(context) ) {
+				// See if we find a selector to speed up
+				var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+
+				if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+					// Speed-up: Sizzle("TAG")
+					if ( match[1] ) {
+						return makeArray( context.getElementsByTagName( query ), extra );
+
+					// Speed-up: Sizzle(".CLASS")
+					} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+						return makeArray( context.getElementsByClassName( match[2] ), extra );
+					}
+				}
+
+				if ( context.nodeType === 9 ) {
+					// Speed-up: Sizzle("body")
+					// The body element only exists once, optimize finding it
+					if ( query === "body" && context.body ) {
+						return makeArray( [ context.body ], extra );
+
+					// Speed-up: Sizzle("#ID")
+					} else if ( match && match[3] ) {
+						var elem = context.getElementById( match[3] );
+
+						// Check parentNode to catch when Blackberry 4.6 returns
+						// nodes that are no longer in the document #6963
+						if ( elem && elem.parentNode ) {
+							// Handle the case where IE and Opera return items
+							// by name instead of ID
+							if ( elem.id === match[3] ) {
+								return makeArray( [ elem ], extra );
+							}
+
+						} else {
+							return makeArray( [], extra );
+						}
+					}
+
+					try {
+						return makeArray( context.querySelectorAll(query), extra );
+					} catch(qsaError) {}
+
+				// qSA works strangely on Element-rooted queries
+				// We can work around this by specifying an extra ID on the root
+				// and working up from there (Thanks to Andrew Dupont for the technique)
+				// IE 8 doesn't work on object elements
+				} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+					var oldContext = context,
+						old = context.getAttribute( "id" ),
+						nid = old || id,
+						hasParent = context.parentNode,
+						relativeHierarchySelector = /^\s*[+~]/.test( query );
+
+					if ( !old ) {
+						context.setAttribute( "id", nid );
+					} else {
+						nid = nid.replace( /'/g, "\\$&" );
+					}
+					if ( relativeHierarchySelector && hasParent ) {
+						context = context.parentNode;
+					}
+
+					try {
+						if ( !relativeHierarchySelector || hasParent ) {
+							return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+						}
+
+					} catch(pseudoError) {
+					} finally {
+						if ( !old ) {
+							oldContext.removeAttribute( "id" );
+						}
+					}
+				}
 			}
-		
+
 			return oldSizzle(query, context, extra, seed);
 		};
 
@@ -6293,9 +8874,54 @@
 			Sizzle[ prop ] = oldSizzle[ prop ];
 		}
 
-		div = null; // release memory in IE
+		// release memory in IE
+		div = null;
 	})();
 }
+
+(function(){
+	var html = document.documentElement,
+		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
+
+	if ( matches ) {
+		// Check to see if it's possible to do matchesSelector
+		// on a disconnected node (IE 9 fails this)
+		var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
+			pseudoWorks = false;
+
+		try {
+			// This should fail with an exception
+			// Gecko does not error, returns false instead
+			matches.call( document.documentElement, "[test!='']:sizzle" );
+
+		} catch( pseudoError ) {
+			pseudoWorks = true;
+		}
+
+		Sizzle.matchesSelector = function( node, expr ) {
+			// Make sure that attribute selectors are quoted
+			expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+			if ( !Sizzle.isXML( node ) ) {
+				try {
+					if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
+						var ret = matches.call( node, expr );
+
+						// IE 9's matchesSelector returns false on disconnected nodes
+						if ( ret || !disconnectedMatch ||
+								// As well, disconnected nodes are said to be in a document
+								// fragment in IE 9, so check for that
+								node.document && node.document.nodeType !== 11 ) {
+							return ret;
+						}
+					}
+				} catch(e) {}
+			}
+
+			return Sizzle(expr, null, null, [node]).length > 0;
+		};
+	}
+})();
 
 (function(){
 	var div = document.createElement("div");
@@ -6314,32 +8940,35 @@
 	if ( div.getElementsByClassName("e").length === 1 ) {
 		return;
 	}
-	
+
 	Expr.order.splice(1, 0, "CLASS");
-	Expr.find.CLASS = function(match, context, isXML) {
+	Expr.find.CLASS = function( match, context, isXML ) {
 		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
 			return context.getElementsByClassName(match[1]);
 		}
 	};
 
-	div = null; // release memory in IE
+	// release memory in IE
+	div = null;
 })();
 
 function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
 	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
 		var elem = checkSet[i];
+
 		if ( elem ) {
-			elem = elem[dir];
 			var match = false;
 
+			elem = elem[dir];
+
 			while ( elem ) {
-				if ( elem.sizcache === doneName ) {
+				if ( elem[ expando ] === doneName ) {
 					match = checkSet[elem.sizset];
 					break;
 				}
 
 				if ( elem.nodeType === 1 && !isXML ){
-					elem.sizcache = doneName;
+					elem[ expando ] = doneName;
 					elem.sizset = i;
 				}
 
@@ -6359,21 +8988,24 @@
 function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
 	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
 		var elem = checkSet[i];
+
 		if ( elem ) {
-			elem = elem[dir];
 			var match = false;
 
+			elem = elem[dir];
+
 			while ( elem ) {
-				if ( elem.sizcache === doneName ) {
+				if ( elem[ expando ] === doneName ) {
 					match = checkSet[elem.sizset];
 					break;
 				}
 
 				if ( elem.nodeType === 1 ) {
 					if ( !isXML ) {
-						elem.sizcache = doneName;
+						elem[ expando ] = doneName;
 						elem.sizset = i;
 					}
+
 					if ( typeof cur !== "string" ) {
 						if ( elem === cur ) {
 							match = true;
@@ -6394,21 +9026,34 @@
 	}
 }
 
-Sizzle.contains = document.compareDocumentPosition ? function(a, b){
-	return !!(a.compareDocumentPosition(b) & 16);
-} : function(a, b){
-	return a !== b && (a.contains ? a.contains(b) : true);
-};
+if ( document.documentElement.contains ) {
+	Sizzle.contains = function( a, b ) {
+		return a !== b && (a.contains ? a.contains(b) : true);
+	};
 
-Sizzle.isXML = function(elem){
+} else if ( document.documentElement.compareDocumentPosition ) {
+	Sizzle.contains = function( a, b ) {
+		return !!(a.compareDocumentPosition(b) & 16);
+	};
+
+} else {
+	Sizzle.contains = function() {
+		return false;
+	};
+}
+
+Sizzle.isXML = function( elem ) {
 	// documentElement is verified for cases where it doesn't yet exist
-	// (such as loading iframes in IE - #4833) 
+	// (such as loading iframes in IE - #4833)
 	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+
 	return documentElement ? documentElement.nodeName !== "HTML" : false;
 };
 
-var posProcess = function(selector, context){
-	var tmpSet = [], later = "", match,
+var posProcess = function( selector, context, seed ) {
+	var match,
+		tmpSet = [],
+		later = "",
 		root = context.nodeType ? [context] : context;
 
 	// Position selectors must be done after the filter
@@ -6421,7 +9066,7 @@
 	selector = Expr.relative[selector] ? selector + "*" : selector;
 
 	for ( var i = 0, l = root.length; i < l; i++ ) {
-		Sizzle( selector, root[i], tmpSet );
+		Sizzle( selector, root[i], tmpSet, seed );
 	}
 
 	return Sizzle.filter( later, tmpSet );
@@ -6433,290 +9078,6 @@
 
 })();
 
-
-(function(tinymce) {
-	// Shorten names
-	var each = tinymce.each, DOM = tinymce.DOM, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, Event;
-
-	tinymce.create('tinymce.dom.EventUtils', {
-		EventUtils : function() {
-			this.inits = [];
-			this.events = [];
-		},
-
-		add : function(o, n, f, s) {
-			var cb, t = this, el = t.events, r;
-
-			if (n instanceof Array) {
-				r = [];
-
-				each(n, function(n) {
-					r.push(t.add(o, n, f, s));
-				});
-
-				return r;
-			}
-
-			// Handle array
-			if (o && o.hasOwnProperty && o instanceof Array) {
-				r = [];
-
-				each(o, function(o) {
-					o = DOM.get(o);
-					r.push(t.add(o, n, f, s));
-				});
-
-				return r;
-			}
-
-			o = DOM.get(o);
-
-			if (!o)
-				return;
-
-			// Setup event callback
-			cb = function(e) {
-				// Is all events disabled
-				if (t.disabled)
-					return;
-
-				e = e || window.event;
-
-				// Patch in target, preventDefault and stopPropagation in IE it's W3C valid
-				if (e && isIE) {
-					if (!e.target)
-						e.target = e.srcElement;
-
-					// Patch in preventDefault, stopPropagation methods for W3C compatibility
-					tinymce.extend(e, t._stoppers);
-				}
-
-				if (!s)
-					return f(e);
-
-				return f.call(s, e);
-			};
-
-			if (n == 'unload') {
-				tinymce.unloads.unshift({func : cb});
-				return cb;
-			}
-
-			if (n == 'init') {
-				if (t.domLoaded)
-					cb();
-				else
-					t.inits.push(cb);
-
-				return cb;
-			}
-
-			// Store away listener reference
-			el.push({
-				obj : o,
-				name : n,
-				func : f,
-				cfunc : cb,
-				scope : s
-			});
-
-			t._add(o, n, cb);
-
-			return f;
-		},
-
-		remove : function(o, n, f) {
-			var t = this, a = t.events, s = false, r;
-
-			// Handle array
-			if (o && o.hasOwnProperty && o instanceof Array) {
-				r = [];
-
-				each(o, function(o) {
-					o = DOM.get(o);
-					r.push(t.remove(o, n, f));
-				});
-
-				return r;
-			}
-
-			o = DOM.get(o);
-
-			each(a, function(e, i) {
-				if (e.obj == o && e.name == n && (!f || (e.func == f || e.cfunc == f))) {
-					a.splice(i, 1);
-					t._remove(o, n, e.cfunc);
-					s = true;
-					return false;
-				}
-			});
-
-			return s;
-		},
-
-		clear : function(o) {
-			var t = this, a = t.events, i, e;
-
-			if (o) {
-				o = DOM.get(o);
-
-				for (i = a.length - 1; i >= 0; i--) {
-					e = a[i];
-
-					if (e.obj === o) {
-						t._remove(e.obj, e.name, e.cfunc);
-						e.obj = e.cfunc = null;
-						a.splice(i, 1);
-					}
-				}
-			}
-		},
-
-		cancel : function(e) {
-			if (!e)
-				return false;
-
-			this.stop(e);
-
-			return this.prevent(e);
-		},
-
-		stop : function(e) {
-			if (e.stopPropagation)
-				e.stopPropagation();
-			else
-				e.cancelBubble = true;
-
-			return false;
-		},
-
-		prevent : function(e) {
-			if (e.preventDefault)
-				e.preventDefault();
-			else
-				e.returnValue = false;
-
-			return false;
-		},
-
-		destroy : function() {
-			var t = this;
-
-			each(t.events, function(e, i) {
-				t._remove(e.obj, e.name, e.cfunc);
-				e.obj = e.cfunc = null;
-			});
-
-			t.events = [];
-			t = null;
-		},
-
-		_add : function(o, n, f) {
-			if (o.attachEvent)
-				o.attachEvent('on' + n, f);
-			else if (o.addEventListener)
-				o.addEventListener(n, f, false);
-			else
-				o['on' + n] = f;
-		},
-
-		_remove : function(o, n, f) {
-			if (o) {
-				try {
-					if (o.detachEvent)
-						o.detachEvent('on' + n, f);
-					else if (o.removeEventListener)
-						o.removeEventListener(n, f, false);
-					else
-						o['on' + n] = null;
-				} catch (ex) {
-					// Might fail with permission denined on IE so we just ignore that
-				}
-			}
-		},
-
-		_pageInit : function(win) {
-			var t = this;
-
-			// Keep it from running more than once
-			if (t.domLoaded)
-				return;
-
-			t.domLoaded = true;
-
-			each(t.inits, function(c) {
-				c();
-			});
-
-			t.inits = [];
-		},
-
-		_wait : function(win) {
-			var t = this, doc = win.document;
-
-			// No need since the document is already loaded
-			if (win.tinyMCE_GZ && tinyMCE_GZ.loaded) {
-				t.domLoaded = 1;
-				return;
-			}
-
-			// Use IE method
-			if (doc.attachEvent) {
-				doc.attachEvent("onreadystatechange", function() {
-					if (doc.readyState === "complete") {
-						doc.detachEvent("onreadystatechange", arguments.callee);
-						t._pageInit(win);
-					}
-				});
-
-				if (doc.documentElement.doScroll && win == win.top) {
-					(function() {
-						if (t.domLoaded)
-							return;
-
-						try {
-							// If IE is used, use the trick by Diego Perini
-							// http://javascript.nwbox.com/IEContentLoaded/
-							doc.documentElement.doScroll("left");
-						} catch (ex) {
-							setTimeout(arguments.callee, 0);
-							return;
-						}
-
-						t._pageInit(win);
-					})();
-				}
-			} else if (doc.addEventListener) {
-				t._add(win, 'DOMContentLoaded', function() {
-					t._pageInit(win);
-				});
-			}
-
-			t._add(win, 'load', function() {
-				t._pageInit(win);
-			});
-		},
-
-		_stoppers : {
-			preventDefault : function() {
-				this.returnValue = false;
-			},
-
-			stopPropagation : function() {
-				this.cancelBubble = true;
-			}
-		}
-	});
-
-	Event = tinymce.dom.Event = new tinymce.dom.EventUtils();
-
-	// Dispatch DOM content loaded event for IE and Safari
-	Event._wait(window);
-
-	tinymce.addUnload(function() {
-		Event.destroy();
-	});
-})(tinymce);
 
 (function(tinymce) {
 	tinymce.dom.Element = function(id, settings) {
@@ -6734,20 +9095,20 @@
 				('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' + 
 				'setAttrib,setAttribs,getAttrib,addClass,removeClass,' + 
 				'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' + 
-				'isHidden,setHTML,get').split(/,/)
-			, function(k) {
-				t[k] = function() {
-					var a = [id], i;
+				'isHidden,setHTML,get').split(/,/), function(k) {
+					t[k] = function() {
+						var a = [id], i;
 
-					for (i = 0; i < arguments.length; i++)
-						a.push(arguments[i]);
+						for (i = 0; i < arguments.length; i++)
+							a.push(arguments[i]);
 
-					a = dom[k].apply(dom, a);
-					t.update(k);
+						a = dom[k].apply(dom, a);
+						t.update(k);
 
-					return a;
-				};
-		});
+						return a;
+					};
+			}
+		);
 
 		tinymce.extend(t, {
 			on : function(n, f, s) {
@@ -6833,15 +9194,16 @@
 	};
 
 	// Shorten names
-	var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each;
+	var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each, TreeWalker = tinymce.dom.TreeWalker;
 
 	tinymce.create('tinymce.dom.Selection', {
-		Selection : function(dom, win, serializer) {
+		Selection : function(dom, win, serializer, editor) {
 			var t = this;
 
 			t.dom = dom;
 			t.win = win;
 			t.serializer = serializer;
+			t.editor = editor;
 
 			// Add events
 			each([
@@ -6867,6 +9229,13 @@
 			tinymce.addUnload(t.destroy, t);
 		},
 
+		setCursorLocation: function(node, offset) {
+			var t = this; var r = t.dom.createRng();
+			r.setStart(node, offset);
+			r.setEnd(node, offset);
+			t.setRng(r);
+			t.collapse(false);
+		},
 		getContent : function(s) {
 			var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n;
 
@@ -6874,6 +9243,7 @@
 			wb = wa = '';
 			s.get = true;
 			s.format = s.format || 'html';
+			s.forced_root_block = '';
 			t.onBeforeGetContent.dispatch(t, s);
 
 			if (s.format == 'text')
@@ -6884,9 +9254,13 @@
 
 				if (n)
 					e.appendChild(n);
-			} else if (is(r.item) || is(r.htmlText))
-				e.innerHTML = r.item ? r.item(0).outerHTML : r.htmlText;
-			else
+			} else if (is(r.item) || is(r.htmlText)) {
+				// IE will produce invalid markup if elements are present that
+				// it doesn't understand like custom elements or HTML5 elements.
+				// Adding a BR in front of the contents and then remoiving it seems to fix it though.
+				e.innerHTML = '<br>' + (r.item ? r.item(0).outerHTML : r.htmlText);
+				e.removeChild(e.firstChild);
+			} else
 				e.innerHTML = r.toString();
 
 			// Keep whitespace before and after
@@ -6928,7 +9302,7 @@
 				} else {
 					rng.deleteContents();
 
-					if (doc.body.childNodes.length == 0) {
+					if (doc.body.childNodes.length === 0) {
 						doc.body.innerHTML = content;
 					} else {
 						// createContextualFragment doesn't exists in IE 9 DOMRanges
@@ -6958,7 +9332,12 @@
 
 				// Remove the caret position
 				self.dom.remove('__caret');
-				self.setRng(rng);
+
+				try {
+					self.setRng(rng);
+				} catch (ex) {
+					// Might fail on Opera for some odd reason
+				}
 			} else {
 				if (rng.item) {
 					// Delete content and get caret text selection
@@ -6966,7 +9345,12 @@
 					rng = self.getRng();
 				}
 
-				rng.pasteHTML(content);
+				// Explorer removes spaces from the beginning of pasted contents
+				if (/^\s+/.test(content)) {
+					rng.pasteHTML('<span id="__mce_tmp">_</span>' + content);
+					self.dom.remove('__mce_tmp');
+				} else
+					rng.pasteHTML(content);
 			}
 
 			// Dispatch set content event
@@ -6975,7 +9359,7 @@
 		},
 
 		getStart : function() {
-			var rng = this.getRng(), startElement, parentElement, checkRng, node;
+			var self = this, rng = self.getRng(), startElement, parentElement, checkRng, node;
 
 			if (rng.duplicate || rng.item) {
 				// Control selection, return first item
@@ -6986,6 +9370,9 @@
 				checkRng = rng.duplicate();
 				checkRng.collapse(1);
 				startElement = checkRng.parentElement();
+				if (startElement.ownerDocument !== self.dom.doc) {
+					startElement = self.dom.getRoot();
+				}
 
 				// Check if range parent is inside the start element, then return the inner parent element
 				// This will fix issues when a single element is selected, IE would otherwise return the wrong start element
@@ -7012,31 +9399,34 @@
 		},
 
 		getEnd : function() {
-			var t = this, r = t.getRng(), e, eo;
+			var self = this, rng = self.getRng(), endElement, endOffset;
 
-			if (r.duplicate || r.item) {
-				if (r.item)
-					return r.item(0);
+			if (rng.duplicate || rng.item) {
+				if (rng.item)
+					return rng.item(0);
 
-				r = r.duplicate();
-				r.collapse(0);
-				e = r.parentElement();
+				rng = rng.duplicate();
+				rng.collapse(0);
+				endElement = rng.parentElement();
+				if (endElement.ownerDocument !== self.dom.doc) {
+					endElement = self.dom.getRoot();
+				}
 
-				if (e && e.nodeName == 'BODY')
-					return e.lastChild || e;
+				if (endElement && endElement.nodeName == 'BODY')
+					return endElement.lastChild || endElement;
 
-				return e;
+				return endElement;
 			} else {
-				e = r.endContainer;
-				eo = r.endOffset;
+				endElement = rng.endContainer;
+				endOffset = rng.endOffset;
 
-				if (e.nodeType == 1 && e.hasChildNodes())
-					e = e.childNodes[eo > 0 ? eo - 1 : eo];
+				if (endElement.nodeType == 1 && endElement.hasChildNodes())
+					endElement = endElement.childNodes[endOffset > 0 ? endOffset - 1 : endOffset];
 
-				if (e && e.nodeType == 3)
-					return e.parentNode;
+				if (endElement && endElement.nodeType == 3)
+					return endElement.parentNode;
 
-				return e;
+				return endElement;
 			}
 		},
 
@@ -7054,45 +9444,71 @@
 				return index;
 			};
 
-			if (type == 2) {
-				function getLocation() {
-					var rng = t.getRng(true), root = dom.getRoot(), bookmark = {};
+			function normalizeTableCellSelection(rng) {
+				function moveEndPoint(start) {
+					var container, offset, childNodes, prefix = start ? 'start' : 'end';
 
-					function getPoint(rng, start) {
-						var container = rng[start ? 'startContainer' : 'endContainer'],
-							offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
+					container = rng[prefix + 'Container'];
+					offset = rng[prefix + 'Offset'];
 
-						if (container.nodeType == 3) {
-							if (normalized) {
-								for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling)
-									offset += node.nodeValue.length;
-							}
+					if (container.nodeType == 1 && container.nodeName == "TR") {
+						childNodes = container.childNodes;
+						container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
+						if (container) {
+							offset = start ? 0 : container.childNodes.length;
+							rng['set' + (start ? 'Start' : 'End')](container, offset);
+						}
+					}
+				};
 
-							point.push(offset);
-						} else {
-							childNodes = container.childNodes;
+				moveEndPoint(true);
+				moveEndPoint();
 
-							if (offset >= childNodes.length && childNodes.length) {
-								after = 1;
-								offset = Math.max(0, childNodes.length - 1);
-							}
+				return rng;
+			};
 
-							point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after);
+			function getLocation() {
+				var rng = t.getRng(true), root = dom.getRoot(), bookmark = {};
+
+				function getPoint(rng, start) {
+					var container = rng[start ? 'startContainer' : 'endContainer'],
+						offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
+
+					if (container.nodeType == 3) {
+						if (normalized) {
+							for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling)
+								offset += node.nodeValue.length;
 						}
 
-						for (; container && container != root; container = container.parentNode)
-							point.push(t.dom.nodeIndex(container, normalized));
+						point.push(offset);
+					} else {
+						childNodes = container.childNodes;
 
-						return point;
-					};
+						if (offset >= childNodes.length && childNodes.length) {
+							after = 1;
+							offset = Math.max(0, childNodes.length - 1);
+						}
 
-					bookmark.start = getPoint(rng, true);
+						point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after);
+					}
 
-					if (!t.isCollapsed())
-						bookmark.end = getPoint(rng);
+					for (; container && container != root; container = container.parentNode)
+						point.push(t.dom.nodeIndex(container, normalized));
 
-					return bookmark;
+					return point;
 				};
+
+				bookmark.start = getPoint(rng, true);
+
+				if (!t.isCollapsed())
+					bookmark.end = getPoint(rng);
+
+				return bookmark;
+			};
+
+			if (type == 2) {
+				if (t.tridentSel)
+					return t.tridentSel.getBookmark(type);
 
 				return getLocation();
 			}
@@ -7123,7 +9539,7 @@
 
 							// Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p>
 							rng.moveToElementText(rng2.parentElement());
-							if (rng.compareEndPoints('StartToEnd', rng2) == 0)
+							if (rng.compareEndPoints('StartToEnd', rng2) === 0)
 								rng2.move('character', -1);
 
 							rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');
@@ -7146,7 +9562,7 @@
 					return {name : name, index : findIndex(name, element)};
 
 				// W3C method
-				rng2 = rng.cloneRange();
+				rng2 = normalizeTableCellSelection(rng.cloneRange());
 
 				// Insert end marker
 				if (!collapsed) {
@@ -7154,6 +9570,7 @@
 					rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr));
 				}
 
+				rng = normalizeTableCellSelection(rng);
 				rng.collapse(true);
 				rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr));
 			}
@@ -7166,123 +9583,122 @@
 		moveToBookmark : function(bookmark) {
 			var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset;
 
-			// Clear selection cache
-			if (t.tridentSel)
-				t.tridentSel.destroy();
+			function setEndPoint(start) {
+				var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;
+
+				if (point) {
+					offset = point[0];
+
+					// Find container node
+					for (node = root, i = point.length - 1; i >= 1; i--) {
+						children = node.childNodes;
+
+						if (point[i] > children.length - 1)
+							return;
+
+						node = children[point[i]];
+					}
+
+					// Move text offset to best suitable location
+					if (node.nodeType === 3)
+						offset = Math.min(point[0], node.nodeValue.length);
+
+					// Move element offset to best suitable location
+					if (node.nodeType === 1)
+						offset = Math.min(point[0], node.childNodes.length);
+
+					// Set offset within container node
+					if (start)
+						rng.setStart(node, offset);
+					else
+						rng.setEnd(node, offset);
+				}
+
+				return true;
+			};
+
+			function restoreEndPoint(suffix) {
+				var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;
+
+				if (marker) {
+					node = marker.parentNode;
+
+					if (suffix == 'start') {
+						if (!keep) {
+							idx = dom.nodeIndex(marker);
+						} else {
+							node = marker.firstChild;
+							idx = 1;
+						}
+
+						startContainer = endContainer = node;
+						startOffset = endOffset = idx;
+					} else {
+						if (!keep) {
+							idx = dom.nodeIndex(marker);
+						} else {
+							node = marker.firstChild;
+							idx = 1;
+						}
+
+						endContainer = node;
+						endOffset = idx;
+					}
+
+					if (!keep) {
+						prev = marker.previousSibling;
+						next = marker.nextSibling;
+
+						// Remove all marker text nodes
+						each(tinymce.grep(marker.childNodes), function(node) {
+							if (node.nodeType == 3)
+								node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
+						});
+
+						// Remove marker but keep children if for example contents where inserted into the marker
+						// Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature
+						while (marker = dom.get(bookmark.id + '_' + suffix))
+							dom.remove(marker, 1);
+
+						// If siblings are text nodes then merge them unless it's Opera since it some how removes the node
+						// 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
+						if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) {
+							idx = prev.nodeValue.length;
+							prev.appendData(next.nodeValue);
+							dom.remove(next);
+
+							if (suffix == 'start') {
+								startContainer = endContainer = prev;
+								startOffset = endOffset = idx;
+							} else {
+								endContainer = prev;
+								endOffset = idx;
+							}
+						}
+					}
+				}
+			};
+
+			function addBogus(node) {
+				// Adds a bogus BR element for empty block elements
+				if (dom.isBlock(node) && !node.innerHTML && !isIE)
+					node.innerHTML = '<br data-mce-bogus="1" />';
+
+				return node;
+			};
 
 			if (bookmark) {
 				if (bookmark.start) {
 					rng = dom.createRng();
 					root = dom.getRoot();
 
-					function setEndPoint(start) {
-						var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;
-
-						if (point) {
-							offset = point[0];
-
-							// Find container node
-							for (node = root, i = point.length - 1; i >= 1; i--) {
-								children = node.childNodes;
-
-								if (point[i] > children.length - 1)
-									return;
-
-								node = children[point[i]];
-							}
-
-							// Move text offset to best suitable location
-							if (node.nodeType === 3)
-								offset = Math.min(point[0], node.nodeValue.length);
-
-							// Move element offset to best suitable location
-							if (node.nodeType === 1)
-								offset = Math.min(point[0], node.childNodes.length);
-
-							// Set offset within container node
-							if (start)
-								rng.setStart(node, offset);
-							else
-								rng.setEnd(node, offset);
-						}
-
-						return true;
-					};
+					if (t.tridentSel)
+						return t.tridentSel.moveToBookmark(bookmark);
 
 					if (setEndPoint(true) && setEndPoint()) {
 						t.setRng(rng);
 					}
 				} else if (bookmark.id) {
-					function restoreEndPoint(suffix) {
-						var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;
-
-						if (marker) {
-							node = marker.parentNode;
-
-							if (suffix == 'start') {
-								if (!keep) {
-									idx = dom.nodeIndex(marker);
-								} else {
-									node = marker.firstChild;
-									idx = 1;
-								}
-
-								startContainer = endContainer = node;
-								startOffset = endOffset = idx;
-							} else {
-								if (!keep) {
-									idx = dom.nodeIndex(marker);
-								} else {
-									node = marker.firstChild;
-									idx = 1;
-								}
-
-								endContainer = node;
-								endOffset = idx;
-							}
-
-							if (!keep) {
-								prev = marker.previousSibling;
-								next = marker.nextSibling;
-
-								// Remove all marker text nodes
-								each(tinymce.grep(marker.childNodes), function(node) {
-									if (node.nodeType == 3)
-										node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
-								});
-
-								// Remove marker but keep children if for example contents where inserted into the marker
-								// Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature
-								while (marker = dom.get(bookmark.id + '_' + suffix))
-									dom.remove(marker, 1);
-
-								// If siblings are text nodes then merge them unless it's Opera since it some how removes the node
-								// 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
-								if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) {
-									idx = prev.nodeValue.length;
-									prev.appendData(next.nodeValue);
-									dom.remove(next);
-
-									if (suffix == 'start') {
-										startContainer = endContainer = prev;
-										startOffset = endOffset = idx;
-									} else {
-										endContainer = prev;
-										endOffset = idx;
-									}
-								}
-							}
-						}
-					};
-
-					function addBogus(node) {
-						// Adds a bogus BR element for empty block elements or just a space on IE since it renders BR elements incorrectly
-						if (dom.isBlock(node) && !node.innerHTML)
-							node.innerHTML = !isIE ? '<br data-mce-bogus="1" />' : ' ';
-
-						return node;
-					};
-
 					// Restore start/end points
 					restoreEndPoint('start');
 					restoreEndPoint('end');
@@ -7303,6 +9719,32 @@
 		select : function(node, content) {
 			var t = this, dom = t.dom, rng = dom.createRng(), idx;
 
+			function setPoint(node, start) {
+				var walker = new TreeWalker(node, node);
+
+				do {
+					// Text node
+					if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length !== 0) {
+						if (start)
+							rng.setStart(node, 0);
+						else
+							rng.setEnd(node, node.nodeValue.length);
+
+						return;
+					}
+
+					// BR element
+					if (node.nodeName == 'BR') {
+						if (start)
+							rng.setStartBefore(node);
+						else
+							rng.setEndBefore(node);
+
+						return;
+					}
+				} while (node = (start ? walker.next() : walker.prev()));
+			};
+
 			if (node) {
 				idx = dom.nodeIndex(node);
 				rng.setStart(node.parentNode, idx);
@@ -7310,32 +9752,6 @@
 
 				// Find first/last text node or BR element
 				if (content) {
-					function setPoint(node, start) {
-						var walker = new tinymce.dom.TreeWalker(node, node);
-
-						do {
-							// Text node
-							if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) {
-								if (start)
-									rng.setStart(node, 0);
-								else
-									rng.setEnd(node, node.nodeValue.length);
-
-								return;
-							}
-
-							// BR element
-							if (node.nodeName == 'BR') {
-								if (start)
-									rng.setStartBefore(node);
-								else
-									rng.setEndBefore(node);
-
-								return;
-							}
-						} while (node = (start ? walker.next() : walker.prev()));
-					};
-
 					setPoint(node, 1);
 					setPoint(node);
 				}
@@ -7379,64 +9795,92 @@
 		},
 
 		getRng : function(w3c) {
-			var t = this, s, r, elm, doc = t.win.document;
+			var self = this, selection, rng, elm, doc = self.win.document;
 
 			// Found tridentSel object then we need to use that one
-			if (w3c && t.tridentSel)
-				return t.tridentSel.getRangeAt(0);
+			if (w3c && self.tridentSel) {
+				return self.tridentSel.getRangeAt(0);
+			}
 
 			try {
-				if (s = t.getSel())
-					r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange());
+				if (selection = self.getSel()) {
+					rng = selection.rangeCount > 0 ? selection.getRangeAt(0) : (selection.createRange ? selection.createRange() : doc.createRange());
+				}
 			} catch (ex) {
 				// IE throws unspecified error here if TinyMCE is placed in a frame/iframe
 			}
 
 			// We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet
-			if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) {
+			if (tinymce.isIE && rng && rng.setStart && doc.selection.createRange().item) {
 				elm = doc.selection.createRange().item(0);
-				r = doc.createRange();
-				r.setStartBefore(elm);
-				r.setEndAfter(elm);
+				rng = doc.createRange();
+				rng.setStartBefore(elm);
+				rng.setEndAfter(elm);
 			}
 
 			// No range found then create an empty one
 			// This can occur when the editor is placed in a hidden container element on Gecko
 			// Or on IE when there was an exception
-			if (!r)
-				r = doc.createRange ? doc.createRange() : doc.body.createTextRange();
+			if (!rng) {
+				rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
+			}
 
-			if (t.selectedRange && t.explicitRange) {
-				if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) {
+			// If range is at start of document then move it to start of body
+			if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
+				elm = self.dom.getRoot();
+				rng.setStart(elm, 0);
+				rng.setEnd(elm, 0);
+			}
+
+			if (self.selectedRange && self.explicitRange) {
+				if (rng.compareBoundaryPoints(rng.START_TO_START, self.selectedRange) === 0 && rng.compareBoundaryPoints(rng.END_TO_END, self.selectedRange) === 0) {
 					// Safari, Opera and Chrome only ever select text which causes the range to change.
 					// This lets us use the originally set range if the selection hasn't been changed by the user.
-					r = t.explicitRange;
+					rng = self.explicitRange;
 				} else {
-					t.selectedRange = null;
-					t.explicitRange = null;
+					self.selectedRange = null;
+					self.explicitRange = null;
 				}
 			}
 
-			return r;
+			return rng;
 		},
 
-		setRng : function(r) {
+		setRng : function(r, forward) {
 			var s, t = this;
-			
+
 			if (!t.tridentSel) {
 				s = t.getSel();
 
 				if (s) {
 					t.explicitRange = r;
-					s.removeAllRanges();
+
+					try {
+						s.removeAllRanges();
+					} catch (ex) {
+						// IE9 might throw errors here don't know why
+					}
+
 					s.addRange(r);
-					t.selectedRange = s.getRangeAt(0);
+
+					// Forward is set to false and we have an extend function
+					if (forward === false && s.extend) {
+						s.collapse(r.endContainer, r.endOffset);
+						s.extend(r.startContainer, r.startOffset);
+					}
+
+					// adding range isn't always successful so we need to check range count otherwise an exception can occur
+					t.selectedRange = s.rangeCount > 0 ? s.getRangeAt(0) : null;
 				}
 			} else {
 				// Is W3C Range
 				if (r.cloneRange) {
-					t.tridentSel.addRange(r);
-					return;
+					try {
+						t.tridentSel.addRange(r);
+						return;
+					} catch (ex) {
+						//IE9 throws an error here if called before selection is placed in the editor
+					}
 				}
 
 				// Is IE specific range
@@ -7459,6 +9903,14 @@
 		getNode : function() {
 			var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer;
 
+			function skipEmptyTextNodes(n, forwards) {
+				var orig = n;
+				while (n && n.nodeType === 3 && n.length === 0) {
+					n = forwards ? n.nextSibling : n.previousSibling;
+				}
+				return n || orig;
+			};
+
 			// Range maybe lost after the editor is made visible again
 			if (!rng)
 				return t.dom.getRoot();
@@ -7476,19 +9928,12 @@
 					}
 
 					// If the anchor node is a element instead of a text node then return this element
-					//if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1) 
+					//if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1)
 					//	return sel.anchorNode.childNodes[sel.anchorOffset];
 
 					// Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.
 					// This happens when you double click an underlined word in FireFox.
 					if (start.nodeType === 3 && end.nodeType === 3) {
-						function skipEmptyTextNodes(n, forwards) {
-							var orig = n;
-							while (n && n.nodeType === 3 && n.length === 0) {
-								n = forwards ? n.nextSibling : n.previousSibling;
-							}
-							return n || orig;
-						}
 						if (start.length === rng.startOffset) {
 							start = skipEmptyTextNodes(start.nextSibling, true);
 						} else {
@@ -7526,7 +9971,8 @@
 			if (sb && eb && sb != eb) {
 				n = sb;
 
-				while ((n = n.nextSibling) && n != eb) {
+				var walker = new TreeWalker(sb, dom.getRoot());
+				while ((n = walker.next()) && n != eb) {
 					if (dom.isBlock(n))
 						bl.push(n);
 				}
@@ -7538,25 +9984,259 @@
 			return bl;
 		},
 
-		destroy : function(s) {
-			var t = this;
+		isForward: function(){
+			var dom = this.dom, sel = this.getSel(), anchorRange, focusRange;
 
-			t.win = null;
+			// No support for selection direction then always return true
+			if (!sel || sel.anchorNode == null || sel.focusNode == null) {
+				return true;
+			}
 
-			if (t.tridentSel)
-				t.tridentSel.destroy();
+			anchorRange = dom.createRng();
+			anchorRange.setStart(sel.anchorNode, sel.anchorOffset);
+			anchorRange.collapse(true);
+
+			focusRange = dom.createRng();
+			focusRange.setStart(sel.focusNode, sel.focusOffset);
+			focusRange.collapse(true);
+
+			return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
+		},
+
+		normalize : function() {
+			var self = this, rng, normalized, collapsed, node, sibling;
+
+			function normalizeEndPoint(start) {
+				var container, offset, walker, dom = self.dom, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName;
+
+				function hasBrBeforeAfter(node, left) {
+					var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body);
+
+					while (node = walker[left ? 'prev' : 'next']()) {
+						if (node.nodeName === "BR") {
+							return true;
+						}
+					}
+				};
+
+				// Walks the dom left/right to find a suitable text node to move the endpoint into
+				// It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG
+				function findTextNodeRelative(left, startNode) {
+					var walker, lastInlineElement;
+
+					startNode = startNode || container;
+					walker = new TreeWalker(startNode, dom.getParent(startNode.parentNode, dom.isBlock) || body);
+
+					// Walk left until we hit a text node we can move to or a block/br/img
+					while (node = walker[left ? 'prev' : 'next']()) {
+						// Found text node that has a length
+						if (node.nodeType === 3 && node.nodeValue.length > 0) {
+							container = node;
+							offset = left ? node.nodeValue.length : 0;
+							normalized = true;
+							return;
+						}
+
+						// Break if we find a block or a BR/IMG/INPUT etc
+						if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
+							return;
+						}
+
+						lastInlineElement = node;
+					}
+
+					// Only fetch the last inline element when in caret mode for now
+					if (collapsed && lastInlineElement) {
+						container = lastInlineElement;
+						normalized = true;
+						offset = 0;
+					}
+				};
+
+				container = rng[(start ? 'start' : 'end') + 'Container'];
+				offset = rng[(start ? 'start' : 'end') + 'Offset'];
+				nonEmptyElementsMap = dom.schema.getNonEmptyElements();
+
+				// If the container is a document move it to the body element
+				if (container.nodeType === 9) {
+					container = dom.getRoot();
+					offset = 0;
+				}
+
+				// If the container is body try move it into the closest text node or position
+				if (container === body) {
+					// If start is before/after a image, table etc
+					if (start) {
+						node = container.childNodes[offset > 0 ? offset - 1 : 0];
+						if (node) {
+							nodeName = node.nodeName.toLowerCase();
+							if (nonEmptyElementsMap[node.nodeName] || node.nodeName == "TABLE") {
+								return;
+							}
+						}
+					}
+
+					// Resolve the index
+					if (container.hasChildNodes()) {
+						container = container.childNodes[Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1)];
+						offset = 0;
+
+						// Don't walk into elements that doesn't have any child nodes like a IMG
+						if (container.hasChildNodes() && !/TABLE/.test(container.nodeName)) {
+							// Walk the DOM to find a text node to place the caret at or a BR
+							node = container;
+							walker = new TreeWalker(container, body);
+
+							do {
+								// Found a text node use that position
+								if (node.nodeType === 3 && node.nodeValue.length > 0) {
+									offset = start ? 0 : node.nodeValue.length;
+									container = node;
+									normalized = true;
+									break;
+								}
+
+								// Found a BR/IMG element that we can place the caret before
+								if (nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
+									offset = dom.nodeIndex(node);
+									container = node.parentNode;
+
+									// Put caret after image when moving the end point
+									if (node.nodeName ==  "IMG" && !start) {
+										offset++;
+									}
+
+									normalized = true;
+									break;
+								}
+							} while (node = (start ? walker.next() : walker.prev()));
+						}
+					}
+				}
+
+				// Lean the caret to the left if possible
+				if (collapsed) {
+					// So this: <b>x</b><i>|x</i>
+					// Becomes: <b>x|</b><i>x</i>
+					// Seems that only gecko has issues with this
+					if (container.nodeType === 3 && offset === 0) {
+						findTextNodeRelative(true);
+					}
+
+					// Lean left into empty inline elements when the caret is before a BR
+					// So this: <i><b></b><i>|<br></i>
+					// Becomes: <i><b>|</b><i><br></i>
+					// Seems that only gecko has issues with this
+					if (container.nodeType === 1) {
+						node = container.childNodes[offset];
+						if(node && node.nodeName === 'BR' && !hasBrBeforeAfter(node) && !hasBrBeforeAfter(node, true)) {
+							findTextNodeRelative(true, container.childNodes[offset]);
+						}
+					}
+				}
+
+				// Lean the start of the selection right if possible
+				// So this: x[<b>x]</b>
+				// Becomes: x<b>[x]</b>
+				if (start && !collapsed && container.nodeType === 3 && offset === container.nodeValue.length) {
+					findTextNodeRelative(false);
+				}
+
+				// Set endpoint if it was normalized
+				if (normalized)
+					rng['set' + (start ? 'Start' : 'End')](container, offset);
+			};
+
+			// Normalize only on non IE browsers for now
+			if (tinymce.isIE)
+				return;
+			
+			rng = self.getRng();
+			collapsed = rng.collapsed;
+
+			// Normalize the end points
+			normalizeEndPoint(true);
+
+			if (!collapsed)
+				normalizeEndPoint();
+
+			// Set the selection if it was normalized
+			if (normalized) {
+				// If it was collapsed then make sure it still is
+				if (collapsed) {
+					rng.collapse(true);
+				}
+
+				//console.log(self.dom.dumpRng(rng));
+				self.setRng(rng, self.isForward());
+			}
+		},
+
+		selectorChanged: function(selector, callback) {
+			var self = this, currentSelectors;
+
+			if (!self.selectorChangedData) {
+				self.selectorChangedData = {};
+				currentSelectors = {};
+
+				self.editor.onNodeChange.addToTop(function(ed, cm, node) {
+					var dom = self.dom, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
+
+					// Check for new matching selectors
+					each(self.selectorChangedData, function(callbacks, selector) {
+						each(parents, function(node) {
+							if (dom.is(node, selector)) {
+								if (!currentSelectors[selector]) {
+									// Execute callbacks
+									each(callbacks, function(callback) {
+										callback(true, {node: node, selector: selector, parents: parents});
+									});
+
+									currentSelectors[selector] = callbacks;
+								}
+
+								matchedSelectors[selector] = callbacks;
+								return false;
+							}
+						});
+					});
+
+					// Check if current selectors still match
+					each(currentSelectors, function(callbacks, selector) {
+						if (!matchedSelectors[selector]) {
+							delete currentSelectors[selector];
+
+							each(callbacks, function(callback) {
+								callback(false, {node: node, selector: selector, parents: parents});
+							});
+						}
+					});
+				});
+			}
+
+			// Add selector listeners
+			if (!self.selectorChangedData[selector]) {
+				self.selectorChangedData[selector] = [];
+			}
+
+			self.selectorChangedData[selector].push(callback);
+
+			return self;
+		},
+
+		destroy : function(manual) {
+			var self = this;
+
+			self.win = null;
 
 			// Manual destroy then remove unload handler
-			if (!s)
-				tinymce.removeUnload(t.destroy);
+			if (!manual)
+				tinymce.removeUnload(self.destroy);
 		},
 
 		// IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode
 		_fixIESelection : function() {
 			var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm;
-
-			// Make HTML element unselectable since we are going to handle selection by hand
-			doc.documentElement.unselectable = true;
 
 			// Return range from point or null if it failed
 			function rngFromPoint(x, y) {
@@ -7607,6 +10287,9 @@
 				startRng = started = 0;
 			};
 
+			// Make HTML element unselectable since we are going to handle selection by hand
+			doc.documentElement.unselectable = true;
+			
 			// Detect when user selects outside BODY
 			dom.bind(doc, ['mousedown', 'contextmenu'], function(e) {
 				if (e.target.nodeName === 'HTML') {
@@ -7643,12 +10326,11 @@
 		if (!settings.apply_source_formatting)
 			settings.indent = false;
 
-		settings.remove_trailing_brs = true;
-
 		// Default DOM and Schema if they are undefined
 		dom = dom || tinymce.DOM;
 		schema = schema || new tinymce.html.Schema(settings);
 		settings.entity_encoding = settings.entity_encoding || 'named';
+		settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true;
 
 		onPreProcess = new tinymce.util.Dispatcher(self);
 
@@ -7682,13 +10364,13 @@
 			}
 		});
 
-		// Remove internal classes mceItem<..>
+		// Remove internal classes mceItem<..> or mceSelected
 		htmlParser.addAttributeFilter('class', function(nodes, name) {
 			var i = nodes.length, node, value;
 
 			while (i--) {
 				node = nodes[i];
-				value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, '');
+				value = node.attr('class').replace(/(?:^|\s)mce(Item\w+|Selected)(?!\S)/g, '');
 				node.attr('class', value.length > 0 ? value : null);
 			}
 		});
@@ -7705,6 +10387,15 @@
 			}
 		});
 
+		// Remove expando attributes
+		htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name, args) {
+			var i = nodes.length;
+
+			while (i--) {
+				nodes[i].attr(name, null);
+			}
+		});
+
 		// Force script into CDATA sections and remove the mce- prefix also add comments around styles
 		htmlParser.addNodeFilter('script,style', function(nodes, name) {
 			var i = nodes.length, node, value;
@@ -7712,8 +10403,8 @@
 			function trim(value) {
 				return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')
 						.replace(/^[\r\n]*|[\r\n]*$/g, '')
-						.replace(/^\s*(\/\/\s*<!--|\/\/\s*<!\[CDATA\[|<!--|<!\[CDATA\[)[\r\n]*/g, '')
-						.replace(/\s*(\/\/\s*\]\]>|\/\/\s*-->|\]\]>|-->|\]\]-->)\s*$/g, '');
+						.replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '')
+						.replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
 			};
 
 			while (i--) {
@@ -7811,7 +10502,7 @@
 
 				// Explorer won't clone contents of script and style and the
 				// selected index of select elements are cleared on a clone operation.
-				if (isIE && dom.select('script,style,select').length > 0) {
+				if (isIE && dom.select('script,style,select,map').length > 0) {
 					content = node.innerHTML;
 					node = node.cloneNode(false);
 					dom.setHTML(node, content);
@@ -7857,8 +10548,12 @@
 
 				// Parse and serialize HTML
 				args.content = htmlSerializer.serialize(
-					htmlParser.parse(args.getInner ? node.innerHTML : tinymce.trim(dom.getOuterHTML(node), args), args)
+					htmlParser.parse(tinymce.trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args)
 				);
+
+				// Replace all BOM characters for now until we can find a better solution
+				if (!args.cleanup)
+					args.content = args.content.replace(/\uFEFF/g, '');
 
 				// Post process
 				if (!args.no_events)
@@ -7893,7 +10588,7 @@
 			scriptLoadedCallbacks = {},
 			queueLoadedCallbacks = [],
 			loading = 0,
-			undefined;
+			undef;
 
 		function loadScript(url, callback) {
 			var t = this, dom = tinymce.DOM, elm, uri, loc, id;
@@ -7952,11 +10647,10 @@
 			}
 
 			// Create new script element
-			elm = dom.create('script', {
-				id : id,
-				type : 'text/javascript',
-				src : tinymce._addVer(url)
-			});
+			elm = document.createElement('script');
+			elm.id = id;
+			elm.type = 'text/javascript';
+			elm.src = tinymce._addVer(url);
 
 			// Add onload listener for non IE browsers since IE9
 			// fires onload event before the script is parsed and executed
@@ -8002,7 +10696,7 @@
 			var item, state = states[url];
 
 			// Add url to load queue
-			if (state == undefined) {
+			if (state == undef) {
 				queue.push(url);
 				states[url] = QUEUED;
 			}
@@ -8032,7 +10726,7 @@
 					callback.func.call(callback.scope);
 				});
 
-				scriptLoadedCallbacks[url] = undefined;
+				scriptLoadedCallbacks[url] = undef;
 			};
 
 			queueLoadedCallbacks.push({
@@ -8089,46 +10783,6 @@
 	tinymce.ScriptLoader = new tinymce.dom.ScriptLoader();
 })(tinymce);
 
-tinymce.dom.TreeWalker = function(start_node, root_node) {
-	var node = start_node;
-
-	function findSibling(node, start_name, sibling_name, shallow) {
-		var sibling, parent;
-
-		if (node) {
-			// Walk into nodes if it has a start
-			if (!shallow && node[start_name])
-				return node[start_name];
-
-			// Return the sibling if it has one
-			if (node != root_node) {
-				sibling = node[sibling_name];
-				if (sibling)
-					return sibling;
-
-				// Walk up the parents to look for siblings
-				for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
-					sibling = parent[sibling_name];
-					if (sibling)
-						return sibling;
-				}
-			}
-		}
-	};
-
-	this.current = function() {
-		return node;
-	};
-
-	this.next = function(shallow) {
-		return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));
-	};
-
-	this.prev = function(shallow) {
-		return (node = findSibling(node, 'lastChild', 'previousSibling', shallow));
-	};
-};
-
 (function(tinymce) {
 	tinymce.dom.RangeUtils = function(dom) {
 		var INVISIBLE_CHAR = '\uFEFF';
@@ -8151,6 +10805,24 @@
 
 				return;
 			}
+
+			function exclude(nodes) {
+				var node;
+
+				// First node is excluded
+				node = nodes[0];
+				if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) {
+					nodes.splice(0, 1);
+				}
+
+				// Last node is excluded
+				node = nodes[nodes.length - 1];
+				if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) {
+					nodes.splice(nodes.length - 1, 1);
+				}
+
+				return nodes;
+			};
 
 			function collectSiblings(node, name, end_node) {
 				var siblings = [];
@@ -8181,7 +10853,7 @@
 						if (!next)
 							siblings.reverse();
 
-						callback(siblings);
+						callback(exclude(siblings));
 					}
 				}
 			};
@@ -8194,28 +10866,28 @@
 			if (endContainer.nodeType == 1 && endContainer.hasChildNodes())
 				endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)];
 
-			// Find common ancestor and end points
-			ancestor = dom.findCommonAncestor(startContainer, endContainer);
-
 			// Same container
 			if (startContainer == endContainer)
-				return callback([startContainer]);
+				return callback(exclude([startContainer]));
 
+			// Find common ancestor and end points
+			ancestor = dom.findCommonAncestor(startContainer, endContainer);
+				
 			// Process left side
 			for (node = startContainer; node; node = node.parentNode) {
-				if (node == endContainer)
+				if (node === endContainer)
 					return walkBoundary(startContainer, ancestor, true);
 
-				if (node == ancestor)
+				if (node === ancestor)
 					break;
 			}
 
 			// Process right side
 			for (node = endContainer; node; node = node.parentNode) {
-				if (node == startContainer)
+				if (node === startContainer)
 					return walkBoundary(endContainer, ancestor);
 
-				if (node == ancestor)
+				if (node === ancestor)
 					break;
 			}
 
@@ -8234,48 +10906,46 @@
 			);
 
 			if (siblings.length)
-				callback(siblings);
+				callback(exclude(siblings));
 
 			// Walk right leaf
 			walkBoundary(endContainer, endPoint);
 		};
 
-		/*		this.split = function(rng) {
+		this.split = function(rng) {
 			var startContainer = rng.startContainer,
 				startOffset = rng.startOffset,
 				endContainer = rng.endContainer,
 				endOffset = rng.endOffset;
 
 			function splitText(node, offset) {
-				if (offset == node.nodeValue.length)
-					node.appendData(INVISIBLE_CHAR);
-
-				node = node.splitText(offset);
-
-				if (node.nodeValue === INVISIBLE_CHAR)
-					node.nodeValue = '';
-
-				return node;
+				return node.splitText(offset);
 			};
 
 			// Handle single text node
-			if (startContainer == endContainer) {
-				if (startContainer.nodeType == 3) {
-					if (startOffset != 0)
-						startContainer = endContainer = splitText(startContainer, startOffset);
+			if (startContainer == endContainer && startContainer.nodeType == 3) {
+				if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
+					endContainer = splitText(startContainer, startOffset);
+					startContainer = endContainer.previousSibling;
 
-					if (endOffset - startOffset != startContainer.nodeValue.length)
-						splitText(startContainer, endOffset - startOffset);
+					if (endOffset > startOffset) {
+						endOffset = endOffset - startOffset;
+						startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
+						endOffset = endContainer.nodeValue.length;
+						startOffset = 0;
+					} else {
+						endOffset = 0;
+					}
 				}
 			} else {
 				// Split startContainer text node if needed
-				if (startContainer.nodeType == 3 && startOffset != 0) {
+				if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
 					startContainer = splitText(startContainer, startOffset);
 					startOffset = 0;
 				}
 
 				// Split endContainer text node if needed
-				if (endContainer.nodeType == 3 && endOffset != endContainer.nodeValue.length) {
+				if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
 					endContainer = splitText(endContainer, endOffset).previousSibling;
 					endOffset = endContainer.nodeValue.length;
 				}
@@ -8288,7 +10958,7 @@
 				endOffset : endOffset
 			};
 		};
-*/
+
 	};
 
 	tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) {
@@ -8344,12 +11014,15 @@
 
 			t.destroy = function() {
 				each(items, function(item) {
-					dom.unbind(dom.get(item.id), 'focus', itemFocussed);
-					dom.unbind(dom.get(item.id), 'blur', itemBlurred);
+					var elm = dom.get(item.id);
+
+					dom.unbind(elm, 'focus', itemFocussed);
+					dom.unbind(elm, 'blur', itemBlurred);
 				});
 
-				dom.unbind(dom.get(root), 'focus', rootFocussed);
-				dom.unbind(dom.get(root), 'keydown', rootKeydown);
+				var rootElm = dom.get(root);
+				dom.unbind(rootElm, 'focus', rootFocussed);
+				dom.unbind(rootElm, 'keydown', rootKeydown);
 
 				items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null;
 				t.destroy = function() {};
@@ -8428,21 +11101,23 @@
 
 			// Set up state and listeners for each item.
 			each(items, function(item, idx) {
-				var tabindex;
+				var tabindex, elm;
 
 				if (!item.id) {
 					item.id = dom.uniqueId('_mce_item_');
 				}
 
+				elm = dom.get(item.id);
+
 				if (excludeFromTabOrder) {
-					dom.bind(item.id, 'blur', itemBlurred);
+					dom.bind(elm, 'blur', itemBlurred);
 					tabindex = '-1';
 				} else {
 					tabindex = (idx === 0 ? '0' : '-1');
 				}
 
-				dom.setAttrib(item.id, 'tabindex', tabindex);
-				dom.bind(dom.get(item.id), 'focus', itemFocussed);
+				elm.setAttribute('tabindex', tabindex);
+				dom.bind(elm, 'focus', itemFocussed);
 			});
 			
 			// Setup initial state for root element.
@@ -8451,13 +11126,15 @@
 			}
 
 			dom.setAttrib(root, 'tabindex', '-1');
-			
+
 			// Setup listeners for root element.
-			dom.bind(dom.get(root), 'focus', rootFocussed);
-			dom.bind(dom.get(root), 'keydown', rootKeydown);
+			var rootElm = dom.get(root);
+			dom.bind(rootElm, 'focus', rootFocussed);
+			dom.bind(rootElm, 'keydown', rootKeydown);
 		}
 	});
 })(tinymce);
+
 (function(tinymce) {
 	// Shorten class names
 	var DOM = tinymce.DOM, is = tinymce.is;
@@ -8772,8 +11449,8 @@
 		update : function() {
 			var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th;
 
-			tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth;
-			th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight;
+			tw = s.max_width ? Math.min(tb.offsetWidth, s.max_width) : tb.offsetWidth;
+			th = s.max_height ? Math.min(tb.offsetHeight, s.max_height) : tb.offsetHeight;
 
 			if (!DOM.boxModel)
 				t.element.setStyles({width : tw + 2, height : th + 2});
@@ -8863,7 +11540,7 @@
 					if (m.settings.onclick)
 						m.settings.onclick(e);
 
-					return Event.cancel(e); // Cancel to fix onbeforeunload problem
+					return false; // Cancel to fix onbeforeunload problem
 				}
 			});
 
@@ -8993,7 +11670,7 @@
 		// Internal functions
 		_setupKeyboardNav : function(){
 			var contextMenu, menuItems, t=this; 
-			contextMenu = DOM.select('#menu_' + t.id)[0];
+			contextMenu = DOM.get('menu_' + t.id);
 			menuItems = DOM.select('a[role=option]', 'menu_' + t.id);
 			menuItems.splice(0,0,contextMenu);
 			t.keyboardNav = new tinymce.ui.KeyboardNavigation({
@@ -9056,8 +11733,12 @@
 
 			n = DOM.add(n, s.element || 'span', {'class' : 'mceText', title : o.settings.title}, o.settings.title);
 
-			if (o.settings.style)
+			if (o.settings.style) {
+				if (typeof o.settings.style == "function")
+					o.settings.style = o.settings.style();
+
 				DOM.setAttrib(n, 'style', o.settings.style);
+			}
 
 			if (tb.childNodes.length == 1)
 				DOM.addClass(ro, 'mceFirst');
@@ -9089,9 +11770,8 @@
 
 			l = DOM.encode(s.label || '');
 			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) + '">';
-
-			if (s.image)
-				h += '<img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" />' + l;
+			if (s.image && !(this.editor  &&this.editor.forcedHighContrastMode) )
+				h += '<span class="mceIcon ' + s['class'] + '"><img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" /></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : '');
 			else
 				h += '<span class="mceIcon ' + s['class'] + '"></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : '');
 
@@ -9101,10 +11781,27 @@
 		},
 
 		postRender : function() {
-			var t = this, s = t.settings;
+			var t = this, s = t.settings, imgBookmark;
 
+			// In IE a large image that occupies the entire editor area will be deselected when a button is clicked, so
+			// need to keep the selection in case the selection is lost
+			if (tinymce.isIE && t.editor) {
+				tinymce.dom.Event.add(t.id, 'mousedown', function(e) {
+					var nodeName = t.editor.selection.getNode().nodeName;
+					imgBookmark = nodeName === 'IMG' ? t.editor.selection.getBookmark() : null;
+				});
+			}
 			tinymce.dom.Event.add(t.id, 'click', function(e) {
-				if (!t.isDisabled())
+				if (!t.isDisabled()) {
+					// restore the selection in case the selection is lost in IE
+					if (tinymce.isIE && t.editor && imgBookmark !== null) {
+						t.editor.selection.moveToBookmark(imgBookmark);
+					}
+					return s.onclick.call(s.scope, e);
+				}
+			});
+			tinymce.dom.Event.add(t.id, 'keyup', function(e) {
+				if (!t.isDisabled() && e.keyCode==tinymce.VK.SPACEBAR)
 					return s.onclick.call(s.scope, e);
 			});
 		}
@@ -9112,7 +11809,7 @@
 })(tinymce);
 
 (function(tinymce) {
-	var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;
+	var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef;
 
 	tinymce.create('tinymce.ui.ListBox:tinymce.ui.Control', {
 		ListBox : function(id, s, ed) {
@@ -9131,16 +11828,19 @@
 			t.onRenderMenu = new tinymce.util.Dispatcher(this);
 
 			t.classPrefix = 'mceListBox';
+			t.marked = {};
 		},
 
 		select : function(va) {
 			var t = this, fv, f;
 
-			if (va == undefined)
+			t.marked = {};
+
+			if (va == undef)
 				return t.selectByIndex(-1);
 
 			// Is string or number make function selector
-			if (va && va.call)
+			if (va && typeof(va)=="function")
 				f = va;
 			else {
 				f = function(v) {
@@ -9165,26 +11865,35 @@
 		},
 
 		selectByIndex : function(idx) {
-			var t = this, e, o;
+			var t = this, e, o, label;
+
+			t.marked = {};
 
 			if (idx != t.selectedIndex) {
 				e = DOM.get(t.id + '_text');
+				label = DOM.get(t.id + '_voiceDesc');
 				o = t.items[idx];
 
 				if (o) {
 					t.selectedValue = o.value;
 					t.selectedIndex = idx;
 					DOM.setHTML(e, DOM.encode(o.title));
+					DOM.setHTML(label, t.settings.title + " - " + o.title);
 					DOM.removeClass(e, 'mceTitle');
 					DOM.setAttrib(t.id, 'aria-valuenow', o.title);
 				} else {
 					DOM.setHTML(e, DOM.encode(t.settings.title));
+					DOM.setHTML(label, DOM.encode(t.settings.title));
 					DOM.addClass(e, 'mceTitle');
 					t.selectedValue = t.selectedIndex = null;
 					DOM.setAttrib(t.id, 'aria-valuenow', t.settings.title);
 				}
 				e = 0;
 			}
+		},
+
+		mark : function(value) {
+			this.marked[value] = true;
 		},
 
 		add : function(n, v, o) {
@@ -9207,7 +11916,7 @@
 		renderHTML : function() {
 			var h = '', t = this, s = t.settings, cp = t.classPrefix;
 
-			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>';
+			h = '<span role="listbox" aria-haspopup="true" aria-labelledby="' + t.id +'_voiceDesc" 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>';
 			h += '<td>' + DOM.createHTML('span', {id: t.id + '_voiceDesc', 'class': 'voiceLabel', style:'display:none;'}, t.settings.title); 
 			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>';
 			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>';
@@ -9217,9 +11926,9 @@
 		},
 
 		showMenu : function() {
-			var t = this, p1, p2, e = DOM.get(this.id), m;
+			var t = this, p2, e = DOM.get(this.id), m;
 
-			if (t.isDisabled() || t.items.length == 0)
+			if (t.isDisabled() || t.items.length === 0)
 				return;
 
 			if (t.menu && t.menu.isMenuVisible)
@@ -9230,7 +11939,6 @@
 				t.isMenuRendered = true;
 			}
 
-			p1 = DOM.getPos(this.settings.menu_container);
 			p2 = DOM.getPos(e);
 
 			m = t.menu;
@@ -9239,13 +11947,19 @@
 			m.settings.keyboard_focus = !tinymce.isOpera; // Opera is buggy when it comes to auto focus
 
 			// Select in menu
-			if (t.oldID)
-				m.items[t.oldID].setSelected(0);
+			each(t.items, function(o) {
+				if (m.items[o.id]) {
+					m.items[o.id].setSelected(0);
+				}
+			});
 
 			each(t.items, function(o) {
+				if (m.items[o.id] && t.marked[o.value]) {
+					m.items[o.id].setSelected(1);
+				}
+
 				if (o.value === t.selectedValue) {
 					m.items[o.id].setSelected(1);
-					t.oldID = o.id;
 				}
 			});
 
@@ -9281,7 +11995,7 @@
 			m = t.settings.control_manager.createDropMenu(t.id + '_menu', {
 				menu_line : 1,
 				'class' : t.classPrefix + 'Menu mceNoIcons',
-				max_width : 150,
+				max_width : 250,
 				max_height : 150
 			});
 
@@ -9301,9 +12015,10 @@
 
 			each(t.items, function(o) {
 				// No value then treat it as a title
-				if (o.value === undefined) {
+				if (o.value === undef) {
 					m.add({
 						title : o.title,
+						role : "option",
 						'class' : 'mceMenuItemTitle',
 						onclick : function() {
 							if (t.settings.onselect('') !== false)
@@ -9312,6 +12027,7 @@
 					});
 				} else {
 					o.id = DOM.uniqueId();
+					o.role= "option";
 					o.onclick = function() {
 						if (t.settings.onselect(o.value) !== false)
 							t.select(o.value); // Must be runned after
@@ -9387,8 +12103,9 @@
 		}
 	});
 })(tinymce);
+
 (function(tinymce) {
-	var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher;
+	var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef;
 
 	tinymce.create('tinymce.ui.NativeListBox:tinymce.ui.ListBox', {
 		NativeListBox : function(id, s) {
@@ -9408,11 +12125,11 @@
 		select : function(va) {
 			var t = this, fv, f;
 
-			if (va == undefined)
+			if (va == undef)
 				return t.selectByIndex(-1);
 
 			// Is string or number make function selector
-			if (va && va.call)
+			if (va && typeof(va)=="function")
 				f = va;
 			else {
 				f = function(v) {
@@ -9510,6 +12227,11 @@
 					Event.remove(t.id, 'blur', bf);
 				});
 
+				//prevent default left and right keys on chrome - so that the keyboard navigation is used.
+				if (tinymce.isWebKit && (e.keyCode==37 ||e.keyCode==39)) {
+					return Event.prevent(e);
+				}
+				
 				if (e.keyCode == 13 || e.keyCode == 32) {
 					onChange(e);
 					return Event.cancel(e);
@@ -9520,6 +12242,7 @@
 		}
 	});
 })(tinymce);
+
 (function(tinymce) {
 	var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each;
 
@@ -9555,7 +12278,7 @@
 			m.settings.vp_offset_x = p2.x;
 			m.settings.vp_offset_y = p2.y;
 			m.settings.keyboard_focus = t._focused;
-			m.showMenu(0, e.clientHeight);
+			m.showMenu(0, e.firstChild.clientHeight);
 
 			Event.add(DOM.doc, 'mousedown', t.hideMenu, t);
 			t.setState('Selected', 1);
@@ -9639,8 +12362,8 @@
 			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>';
 
 			h += '</tr></tbody>';
-			h = DOM.createHTML('table', {id : t.id, role: 'presentation', tabindex: '0',  'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h);
-			return DOM.createHTML('span', {role: 'button', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h);
+			h = DOM.createHTML('table', { role: 'presentation',   'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h);
+			return DOM.createHTML('div', {id : t.id, role: 'button', tabindex: '0', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h);
 		},
 
 		postRender : function() {
@@ -9739,7 +12462,7 @@
 			p2 = DOM.getPos(e);
 			DOM.setStyles(t.id + '_menu', {
 				left : p2.x,
-				top : p2.y + e.clientHeight,
+				top : p2.y + e.firstChild.clientHeight,
 				zIndex : 200000
 			});
 			e = 0;
@@ -9756,33 +12479,44 @@
 				DOM.select('a', t.id + '_menu')[0].focus(); // Select first link
 			}
 
+			t.keyboardNav = new tinymce.ui.KeyboardNavigation({
+				root: t.id + '_menu',
+				items: DOM.select('a', t.id + '_menu'),
+				onCancel: function() {
+					t.hideMenu();
+					t.focus();
+				}
+			});
+
+			t.keyboardNav.focus();
 			t.isMenuVisible = 1;
 		},
 
 		hideMenu : function(e) {
 			var t = this;
 
-			// Prevent double toogles by canceling the mouse click event to the button
-			if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';}))
-				return;
+			if (t.isMenuVisible) {
+				// Prevent double toogles by canceling the mouse click event to the button
+				if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';}))
+					return;
 
-			if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) {
-				DOM.removeClass(t.id, 'mceSplitButtonSelected');
-				Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
-				Event.remove(t.id + '_menu', 'keydown', t._keyHandler);
-				DOM.hide(t.id + '_menu');
+				if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) {
+					DOM.removeClass(t.id, 'mceSplitButtonSelected');
+					Event.remove(DOM.doc, 'mousedown', t.hideMenu, t);
+					Event.remove(t.id + '_menu', 'keydown', t._keyHandler);
+					DOM.hide(t.id + '_menu');
+				}
+
+				t.isMenuVisible = 0;
+				t.onHideMenu.dispatch();
+				t.keyboardNav.destroy();
 			}
-
-			t.onHideMenu.dispatch(t);
-
-			t.isMenuVisible = 0;
-			t.editor.focus();
 		},
 
 		renderMenu : function() {
 			var t = this, m, i = 0, s = t.settings, n, tb, tr, w, context;
 
-			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;'});
+			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;'});
 			m = DOM.add(w, 'div', {'class' : s['class'] + ' mceSplitButtonMenu'});
 			DOM.add(m, 'span', {'class' : 'mceMenuLine'});
 
@@ -9800,15 +12534,21 @@
 				}
 
 				n = DOM.add(tr, 'td');
-				n = DOM.add(n, 'a', {
-					role : 'option',
+				var settings = {
 					href : 'javascript:;',
 					style : {
 						backgroundColor : '#' + c
 					},
 					'title': t.editor.getLang('colors.' + c, c),
 					'data-mce-color' : '#' + c
-				});
+				};
+
+				// adding a proper ARIA role = button causes JAWS to read things incorrectly on IE.
+				if (!tinymce.isIE ) {
+					settings.role = 'option';
+				}
+
+				n = DOM.add(n, 'a', settings);
 
 				if (t.editor.forcedHighContrastMode) {
 					n = DOM.add(n, 'canvas', { width: 16, height: 16, 'aria-hidden': 'true' });
@@ -9834,15 +12574,6 @@
 			}
 
 			DOM.addClass(m, 'mceColorSplitMenu');
-			
-			new tinymce.ui.KeyboardNavigation({
-				root: t.id + '_menu',
-				items: DOM.select('a', t.id + '_menu'),
-				onCancel: function() {
-					t.hideMenu();
-					t.focus();
-				}
-			});
 
 			// Prevent IE from scrolling and hindering click to occur #4019
 			Event.add(t.id + '_menu', 'mousedown', function(e) {return Event.cancel(e);});
@@ -9855,7 +12586,7 @@
 				if (e && e.nodeName.toLowerCase() == 'a' && (c = e.getAttribute('data-mce-color')))
 					t.setColor(c);
 
-				return Event.cancel(e); // Prevent IE auto save warning
+				return false; // Prevent IE auto save warning
 			});
 
 			return w;
@@ -9884,11 +12615,17 @@
 		},
 
 		destroy : function() {
-			this.parent();
+			var self = this;
 
-			Event.clear(this.id + '_menu');
-			Event.clear(this.id + '_more');
-			DOM.remove(this.id + '_menu');
+			self.parent();
+
+			Event.clear(self.id + '_menu');
+			Event.clear(self.id + '_more');
+			DOM.remove(self.id + '_menu');
+
+			if (self.keyboardNav) {
+				self.keyboardNav.destroy();
+			}
 		}
 	});
 })(tinymce);
@@ -9914,7 +12651,8 @@
 	},
 	
 	focus : function() {
-		this.keyNav.focus();
+		var t = this;
+		dom.get(t.id).focus();
 	},
 	
 	postRender : function() {
@@ -9932,6 +12670,10 @@
 			root: t.id,
 			items: items,
 			onCancel: function() {
+				//Move focus if webkit so that navigation back will read the item.
+				if (tinymce.isWebKit) {
+					dom.get(t.editor.id+"_ifr").focus();
+				}
 				t.editor.focus();
 			},
 			excludeFromTabOrder: !t.settings.tab_focus_toolbar
@@ -9950,7 +12692,7 @@
 
 (function(tinymce) {
 // Shorten class names
-var dom = tinymce.DOM, each = tinymce.each
+var dom = tinymce.DOM, each = tinymce.each;
 tinymce.create('tinymce.ui.Toolbar:tinymce.ui.Container', {
 	renderHTML : function() {
 		var t = this, h = '', c, co, s = t.settings, i, pr, nx, cl;
@@ -10029,7 +12771,19 @@
 		},
 
 		get : function(n) {
-			return this.lookup[n];
+			if (this.lookup[n]) {
+				return this.lookup[n].instance;
+			} else {
+				return undefined;
+			}
+		},
+
+		dependencies : function(n) {
+			var result;
+			if (this.lookup[n]) {
+				result = this.lookup[n].dependencies;
+			}
+			return result || [];
 		},
 
 		requireLangPack : function(n) {
@@ -10039,27 +12793,61 @@
 				tinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js');
 		},
 
-		add : function(id, o) {
+		add : function(id, o, dependencies) {
 			this.items.push(o);
-			this.lookup[id] = o;
+			this.lookup[id] = {instance:o, dependencies:dependencies};
 			this.onAdd.dispatch(this, id, o);
 
 			return o;
 		},
+		createUrl: function(baseUrl, dep) {
+			if (typeof dep === "object") {
+				return dep
+			} else {
+				return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix};
+			}
+		},
+
+		addComponents: function(pluginName, scripts) {
+			var pluginUrl = this.urls[pluginName];
+			tinymce.each(scripts, function(script){
+				tinymce.ScriptLoader.add(pluginUrl+"/"+script);	
+			});
+		},
 
 		load : function(n, u, cb, s) {
-			var t = this;
+			var t = this, url = u;
+
+			function loadDependencies() {
+				var dependencies = t.dependencies(n);
+				tinymce.each(dependencies, function(dep) {
+					var newUrl = t.createUrl(u, dep);
+					t.load(newUrl.resource, newUrl, undefined, undefined);
+				});
+				if (cb) {
+					if (s) {
+						cb.call(s);
+					} else {
+						cb.call(tinymce.ScriptLoader);
+					}
+				}
+			}
 
 			if (t.urls[n])
 				return;
+			if (typeof u === "object")
+				url = u.prefix + u.resource + u.suffix;
 
-			if (u.indexOf('/') != 0 && u.indexOf('://') == -1)
-				u = tinymce.baseURL + '/' + u;
+			if (url.indexOf('/') !== 0 && url.indexOf('://') == -1)
+				url = tinymce.baseURL + '/' + url;
 
-			t.urls[n] = u.substring(0, u.lastIndexOf('/'));
+			t.urls[n] = url.substring(0, url.lastIndexOf('/'));
 
-			if (!t.lookup[n])
-				tinymce.ScriptLoader.add(u, cb, s);
+			if (t.lookup[n]) {
+				loadDependencies();
+			} else {
+				tinymce.ScriptLoader.add(url, loadDependencies, s);
+			}
 		}
 	});
 
@@ -10074,7 +12862,7 @@
 		DOM = tinymce.DOM, Event = tinymce.dom.Event,
 		ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
 		explode = tinymce.explode,
-		Dispatcher = tinymce.util.Dispatcher, undefined, instanceCounter = 0;
+		Dispatcher = tinymce.util.Dispatcher, undef, instanceCounter = 0;
 
 	// Setup some URLs where the editor API is located and where the document is
 	tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
@@ -10109,6 +12897,26 @@
 		init : function(s) {
 			var t = this, pl, sl = tinymce.ScriptLoader, e, el = [], ed;
 
+			function createId(elm) {
+				var id = elm.id;
+	
+				// Use element id, or unique name or generate a unique id
+				if (!id) {
+					id = elm.name;
+	
+					if (id && !DOM.get(id)) {
+						id = elm.name;
+					} else {
+						// Generate unique name
+						id = DOM.uniqueId();
+					}
+
+					elm.setAttribute('id', id);
+				}
+
+				return id;
+			};
+
 			function execCallback(se, n, s) {
 				var f = se[n];
 
@@ -10124,15 +12932,14 @@
 				return f.apply(s || this, Array.prototype.slice.call(arguments, 2));
 			};
 
-			s = extend({
-				theme : "simple",
-				language : "en"
-			}, s);
+			function hasClass(n, c) {
+				return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
+			};
 
 			t.settings = s;
 
 			// Legacy call
-			Event.add(document, 'init', function() {
+			Event.bind(window, 'ready', function() {
 				var l, co;
 
 				execCallback(s, 'onpageload');
@@ -10167,30 +12974,36 @@
 
 					case "textareas":
 					case "specific_textareas":
-						function hasClass(n, c) {
-							return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
-						};
-
-						each(DOM.select('textarea'), function(v) {
-							if (s.editor_deselector && hasClass(v, s.editor_deselector))
+						each(DOM.select('textarea'), function(elm) {
+							if (s.editor_deselector && hasClass(elm, s.editor_deselector))
 								return;
 
-							if (!s.editor_selector || hasClass(v, s.editor_selector)) {
-								// Can we use the name
-								e = DOM.get(v.name);
-								if (!v.id && !e)
-									v.id = v.name;
-
-								// Generate unique name if missing or already exists
-								if (!v.id || t.get(v.id))
-									v.id = DOM.uniqueId();
-
-								ed = new tinymce.Editor(v.id, s);
+							if (!s.editor_selector || hasClass(elm, s.editor_selector)) {
+								ed = new tinymce.Editor(createId(elm), s);
 								el.push(ed);
 								ed.render(1);
 							}
 						});
 						break;
+					
+					default:
+						if (s.types) {
+							// Process type specific selector
+							each(s.types, function(type) {
+								each(DOM.select(type.selector), function(elm) {
+									var editor = new tinymce.Editor(createId(elm), tinymce.extend({}, s, type));
+									el.push(editor);
+									editor.render(1);
+								});
+							});
+						} else if (s.selector) {
+							// Process global selector
+							each(DOM.select(s.selector), function(elm) {
+								var editor = new tinymce.Editor(createId(elm), s);
+								el.push(editor);
+								editor.render(1);
+							});
+						}
 				}
 
 				// Call onInit when all editors are initialized
@@ -10221,7 +13034,7 @@
 		},
 
 		get : function(id) {
-			if (id === undefined)
+			if (id === undef)
 				return this.editors;
 
 			return this.editors[id];
@@ -10274,6 +13087,12 @@
 		execCommand : function(c, u, v) {
 			var t = this, ed = t.get(v), w;
 
+			function clr() {
+				ed.destroy();
+				w.detachEvent('onunload', clr);
+				w = w.tinyMCE = w.tinymce = null; // IE leak
+			};
+
 			// Manager commands
 			switch (c) {
 				case "mceFocus":
@@ -10302,12 +13121,6 @@
 
 					// Fix IE memory leaks
 					if (tinymce.isIE) {
-						function clr() {
-							ed.destroy();
-							w.detachEvent('onunload', clr);
-							w = w.tinyMCE = w.tinymce = null; // IE leak
-						};
-
 						w.attachEvent('onunload', clr);
 					}
 
@@ -10390,162 +13203,84 @@
 (function(tinymce) {
 	// Shorten these names
 	var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend,
-		Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isGecko = tinymce.isGecko,
+		each = tinymce.each, isGecko = tinymce.isGecko,
 		isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, is = tinymce.is,
 		ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager,
-		inArray = tinymce.inArray, grep = tinymce.grep, explode = tinymce.explode;
+		explode = tinymce.explode;
 
 	tinymce.create('tinymce.Editor', {
-		Editor : function(id, s) {
-			var t = this;
+		Editor : function(id, settings) {
+			var self = this, TRUE = true;
 
-			t.id = t.editorId = id;
-
-			t.execCommands = {};
-			t.queryStateCommands = {};
-			t.queryValueCommands = {};
-
-			t.isNotDirty = false;
-
-			t.plugins = {};
-
-			// Add events to the editor
-			each([
-				'onPreInit',
-
-				'onBeforeRenderUI',
-
-				'onPostRender',
-
-				'onInit',
-
-				'onRemove',
-
-				'onActivate',
-
-				'onDeactivate',
-
-				'onClick',
-
-				'onEvent',
-
-				'onMouseUp',
-
-				'onMouseDown',
-
-				'onDblClick',
-
-				'onKeyDown',
-
-				'onKeyUp',
-
-				'onKeyPress',
-
-				'onContextMenu',
-
-				'onSubmit',
-
-				'onReset',
-
-				'onPaste',
-
-				'onPreProcess',
-
-				'onPostProcess',
-
-				'onBeforeSetContent',
-
-				'onBeforeGetContent',
-
-				'onSetContent',
-
-				'onGetContent',
-
-				'onLoadContent',
-
-				'onSaveContent',
-
-				'onNodeChange',
-
-				'onChange',
-
-				'onBeforeExecCommand',
-
-				'onExecCommand',
-
-				'onUndo',
-
-				'onRedo',
-
-				'onVisualAid',
-
-				'onSetProgressState'
-			], function(e) {
-				t[e] = new Dispatcher(t);
-			});
-
-			t.settings = s = extend({
+			self.settings = settings = extend({
 				id : id,
 				language : 'en',
-				docs_language : 'en',
-				theme : 'simple',
+				theme : 'advanced',
 				skin : 'default',
 				delta_width : 0,
 				delta_height : 0,
 				popup_css : '',
 				plugins : '',
 				document_base_url : tinymce.documentBaseURL,
-				add_form_submit_trigger : 1,
-				submit_patch : 1,
-				add_unload_trigger : 1,
-				convert_urls : 1,
-				relative_urls : 1,
-				remove_script_host : 1,
-				table_inline_editing : 0,
-				object_resizing : 1,
-				cleanup : 1,
-				accessibility_focus : 1,
-				custom_shortcuts : 1,
-				custom_undo_redo_keyboard_shortcuts : 1,
-				custom_undo_redo_restore_selection : 1,
-				custom_undo_redo : 1,
+				add_form_submit_trigger : TRUE,
+				submit_patch : TRUE,
+				add_unload_trigger : TRUE,
+				convert_urls : TRUE,
+				relative_urls : TRUE,
+				remove_script_host : TRUE,
+				table_inline_editing : false,
+				object_resizing : TRUE,
+				accessibility_focus : TRUE,
 				doctype : tinymce.isIE6 ? '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' : '<!DOCTYPE>', // Use old doctype on IE 6 to avoid horizontal scroll
-				visual_table_class : 'mceItemTable',
-				visual : 1,
+				visual : TRUE,
 				font_size_style_values : 'xx-small,x-small,small,medium,large,x-large,xx-large',
-				apply_source_formatting : 1,
+				font_size_legacy_values : 'xx-small,small,medium,large,x-large,xx-large,300%', // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size
+				apply_source_formatting : TRUE,
 				directionality : 'ltr',
 				forced_root_block : 'p',
-				hidden_input : 1,
-				padd_empty_editor : 1,
-				render_ui : 1,
-				init_theme : 1,
-				force_p_newlines : 1,
+				hidden_input : TRUE,
+				padd_empty_editor : TRUE,
+				render_ui : TRUE,
 				indentation : '30px',
-				keep_styles : 1,
-				fix_table_elements : 1,
-				inline_styles : 1,
-				convert_fonts_to_spans : true,
+				fix_table_elements : TRUE,
+				inline_styles : TRUE,
+				convert_fonts_to_spans : TRUE,
 				indent : 'simple',
-				indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',
-				indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr',
-				validate : true,
+				indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist',
+				indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist',
+				validate : TRUE,
 				entity_encoding : 'named',
-				url_converter : t.convertURL,
-				url_converter_scope : t,
-				ie7_compat : true
-			}, s);
+				url_converter : self.convertURL,
+				url_converter_scope : self,
+				ie7_compat : TRUE
+			}, settings);
 
-			t.documentBaseURI = new tinymce.util.URI(s.document_base_url || tinymce.documentBaseURL, {
+			self.id = self.editorId = id;
+
+			self.isNotDirty = false;
+
+			self.plugins = {};
+
+			self.documentBaseURI = new tinymce.util.URI(settings.document_base_url || tinymce.documentBaseURL, {
 				base_uri : tinyMCE.baseURI
 			});
 
-			t.baseURI = tinymce.baseURI;
+			self.baseURI = tinymce.baseURI;
 
-			t.contentCSS = [];
+			self.contentCSS = [];
+
+			self.contentStyles = [];
+
+			// Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic
+			self.setupEvents();
+
+			// Internal command handler objects
+			self.execCommands = {};
+			self.queryStateCommands = {};
+			self.queryValueCommands = {};
 
 			// Call setup
-			t.execCallback('setup', t);
+			self.execCallback('setup', self);
 		},
 
 		render : function(nst) {
@@ -10553,7 +13288,7 @@
 
 			// Page is not loaded yet, wait for it
 			if (!Event.domLoaded) {
-				Event.add(document, 'init', function() {
+				Event.add(window, 'ready', function() {
 					t.render();
 				});
 				return;
@@ -10565,15 +13300,20 @@
 			if (!t.getElement())
 				return;
 
-			// Is a iPad/iPhone, then skip initialization. We need to sniff here since the
-			// browser says it has contentEditable support but there is no visible caret
-			// We will remove this check ones Apple implements full contentEditable support
-			if (tinymce.isIDevice)
+			// Is a iPad/iPhone and not on iOS5, then skip initialization. We need to sniff 
+			// here since the browser says it has contentEditable support but there is no visible caret.
+			if (tinymce.isIDevice && !tinymce.isIOS5)
 				return;
 
 			// Add hidden input for non input elements inside form elements
 			if (!/TEXTAREA|INPUT/i.test(t.getElement().nodeName) && s.hidden_input && DOM.getParent(id, 'form'))
 				DOM.insertAfter(DOM.create('input', {type : 'hidden', name : id}), id);
+
+			// Hide target element early to prevent content flashing
+			if (!s.content_editable) {
+				t.orgVisibility = t.getElement().style.visibility;
+				t.getElement().style.visibility = 'hidden';
+			}
 
 			if (tinymce.WindowManager)
 				t.windowManager = new tinymce.WindowManager(t);
@@ -10636,16 +13376,26 @@
 				if (s.language && s.language_load !== false)
 					sl.add(tinymce.baseURL + '/langs/' + s.language + '.js');
 
-				if (s.theme && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme])
+				if (s.theme && typeof s.theme != "function" && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme])
 					ThemeManager.load(s.theme, 'themes/' + s.theme + '/editor_template' + tinymce.suffix + '.js');
 
 				each(explode(s.plugins), function(p) {
-					if (p && p.charAt(0) != '-' && !PluginManager.urls[p]) {
-						// Skip safari plugin, since it is removed as of 3.3b1
-						if (p == 'safari')
-							return;
-
-						PluginManager.load(p, 'plugins/' + p + '/editor_plugin' + tinymce.suffix + '.js');
+					if (p &&!PluginManager.urls[p]) {
+						if (p.charAt(0) == '-') {
+							p = p.substr(1, p.length);
+							var dependencies = PluginManager.dependencies(p);
+							each(dependencies, function(dep) {
+								var defaultSettings = {prefix:'plugins/', resource: dep, suffix:'/editor_plugin' + tinymce.suffix + '.js'};
+								dep = PluginManager.createUrl(defaultSettings, dep);
+								PluginManager.load(dep.resource, dep);
+							});
+						} else {
+							// Skip safari plugin, since it is removed as of 3.3b1
+							if (p == 'safari') {
+								return;
+							}
+							PluginManager.load(p, {prefix:'plugins/', resource: p, suffix:'/editor_plugin' + tinymce.suffix + '.js'});
+						}
 					}
 				});
 
@@ -10660,34 +13410,44 @@
 		},
 
 		init : function() {
-			var n, t = this, s = t.settings, w, h, e = t.getElement(), o, ti, u, bi, bc, re, i;
+			var n, t = this, s = t.settings, w, h, mh, e = t.getElement(), o, ti, u, bi, bc, re, i, initializedPlugins = [];
 
 			tinymce.add(t);
 
 			s.aria_label = s.aria_label || DOM.getAttrib(e, 'aria-label', t.getLang('aria.rich_text_area'));
 
 			if (s.theme) {
-				s.theme = s.theme.replace(/-/, '');
-				o = ThemeManager.get(s.theme);
-				t.theme = new o();
+				if (typeof s.theme != "function") {
+					s.theme = s.theme.replace(/-/, '');
+					o = ThemeManager.get(s.theme);
+					t.theme = new o();
 
-				if (t.theme.init && s.init_theme)
-					t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, ''));
+					if (t.theme.init)
+						t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, ''));
+				} else {
+					t.theme = s.theme;
+				}
 			}
 
-			// Create all plugins
-			each(explode(s.plugins.replace(/\-/g, '')), function(p) {
+			function initPlugin(p) {
 				var c = PluginManager.get(p), u = PluginManager.urls[p] || tinymce.documentBaseURL.replace(/\/$/, ''), po;
-
-				if (c) {
+				if (c && tinymce.inArray(initializedPlugins,p) === -1) {
+					each(PluginManager.dependencies(p), function(dep){
+						initPlugin(dep);
+					});
 					po = new c(t, u);
 
 					t.plugins[p] = po;
 
-					if (po.init)
+					if (po.init) {
 						po.init(t, u);
+						initializedPlugins.push(p);
+					}
 				}
-			});
+			}
+			
+			// Create all plugins
+			each(explode(s.plugins.replace(/\-/g, '')), initPlugin);
 
 			// Setup popup CSS path(s)
 			if (s.popup_css !== false) {
@@ -10702,85 +13462,93 @@
 
 			t.controlManager = new tinymce.ControlManager(t);
 
-			if (s.custom_undo_redo) {
-				t.onBeforeExecCommand.add(function(ed, cmd, ui, val, a) {
-					if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))
-						t.undoManager.beforeChange();
-				});
-
-				t.onExecCommand.add(function(ed, cmd, ui, val, a) {
-					if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!a || !a.skip_undo))
-						t.undoManager.add();
-				});
-			}
-
-			t.onExecCommand.add(function(ed, c) {
-				// Don't refresh the select lists until caret move
-				if (!/^(FontName|FontSize)$/.test(c))
-					t.nodeChanged();
-			});
-
-			// Remove ghost selections on images and tables in Gecko
-			if (isGecko) {
-				function repaint(a, o) {
-					if (!o || !o.initial)
-						t.execCommand('mceRepaint');
-				};
-
-				t.onUndo.add(repaint);
-				t.onRedo.add(repaint);
-				t.onSetContent.add(repaint);
-			}
-
 			// Enables users to override the control factory
 			t.onBeforeRenderUI.dispatch(t, t.controlManager);
 
 			// Measure box
-			if (s.render_ui) {
-				w = s.width || e.style.width || e.offsetWidth;
-				h = s.height || e.style.height || e.offsetHeight;
+			if (s.render_ui && t.theme) {
 				t.orgDisplay = e.style.display;
-				re = /^[0-9\.]+(|px)$/i;
 
-				if (re.test('' + w))
-					w = Math.max(parseInt(w) + (o.deltaWidth || 0), 100);
+				if (typeof s.theme != "function") {
+					w = s.width || e.style.width || e.offsetWidth;
+					h = s.height || e.style.height || e.offsetHeight;
+					mh = s.min_height || 100;
+					re = /^[0-9\.]+(|px)$/i;
 
-				if (re.test('' + h))
-					h = Math.max(parseInt(h) + (o.deltaHeight || 0), 100);
+					if (re.test('' + w))
+						w = Math.max(parseInt(w, 10) + (o.deltaWidth || 0), 100);
 
-				// Render UI
-				o = t.theme.renderUI({
-					targetNode : e,
-					width : w,
-					height : h,
-					deltaWidth : s.delta_width,
-					deltaHeight : s.delta_height
-				});
+					if (re.test('' + h))
+						h = Math.max(parseInt(h, 10) + (o.deltaHeight || 0), mh);
+
+					// Render UI
+					o = t.theme.renderUI({
+						targetNode : e,
+						width : w,
+						height : h,
+						deltaWidth : s.delta_width,
+						deltaHeight : s.delta_height
+					});
+
+					// Resize editor
+					DOM.setStyles(o.sizeContainer || o.editorContainer, {
+						width : w,
+						height : h
+					});
+
+					h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : '');
+					if (h < mh)
+						h = mh;
+				} else {
+					o = s.theme(t, e);
+
+					// Convert element type to id:s
+					if (o.editorContainer.nodeType) {
+						o.editorContainer = o.editorContainer.id = o.editorContainer.id || t.id + "_parent";
+					}
+
+					// Convert element type to id:s
+					if (o.iframeContainer.nodeType) {
+						o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || t.id + "_iframecontainer";
+					}
+
+					// Use specified iframe height or the targets offsetHeight
+					h = o.iframeHeight || e.offsetHeight;
+
+					// Store away the selection when it's changed to it can be restored later with a editor.focus() call
+					if (isIE) {
+						t.onInit.add(function(ed) {
+							ed.dom.bind(ed.getBody(), 'beforedeactivate keydown', function() {
+								ed.lastIERng = ed.selection.getRng();
+							});
+						});
+					}
+				}
 
 				t.editorContainer = o.editorContainer;
 			}
 
-
-			// User specified a document.domain value
-			if (document.domain && location.hostname != document.domain)
-				tinymce.relaxedDomain = document.domain;
-
-			// Resize editor
-			DOM.setStyles(o.sizeContainer || o.editorContainer, {
-				width : w,
-				height : h
-			});
-
 			// Load specified content CSS last
 			if (s.content_css) {
-				tinymce.each(explode(s.content_css), function(u) {
+				each(explode(s.content_css), function(u) {
 					t.contentCSS.push(t.documentBaseURI.toAbsolute(u));
 				});
 			}
 
-			h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : '');
-			if (h < 100)
-				h = 100;
+			// Load specified content CSS last
+			if (s.content_style) {
+				t.contentStyles.push(s.content_style);
+			}
+
+			// Content editable mode ends here
+			if (s.content_editable) {
+				e = n = o = null; // Fix IE leak
+				return t.initContentBody();
+			}
+
+			// User specified a document.domain value
+			if (document.domain && location.hostname != document.domain)
+				tinymce.relaxedDomain = document.domain;
 
 			t.iframeHTML = s.doctype + '<html><head xmlns="http://www.w3.org/1999/xhtml">';
 
@@ -10797,13 +13565,12 @@
 
 			t.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
 
-			// Firefox 2 doesn't load stylesheets correctly this way
-			if (!isGecko || !/Firefox\/2/.test(navigator.userAgent)) {
-				for (i = 0; i < t.contentCSS.length; i++)
-					t.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + t.contentCSS[i] + '" />';
-
-				t.contentCSS = [];
+			// Load the CSS by injecting them into the HTML this will reduce "flicker"
+			for (i = 0; i < t.contentCSS.length; i++) {
+				t.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + t.contentCSS[i] + '" />';
 			}
+
+			t.contentCSS = [];
 
 			bi = s.body_id || 'tinymce';
 			if (bi.indexOf('=') != -1) {
@@ -10817,12 +13584,12 @@
 				bc = bc[t.id] || '';
 			}
 
-			t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '"></body></html>';
+			t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '" onload="window.parent.tinyMCE.get(\'' + t.id + '\').onLoad.dispatch();"><br></body></html>';
 
 			// Domain relaxing enabled, then set document domain
 			if (tinymce.relaxedDomain && (isIE || (tinymce.isOpera && parseFloat(opera.version()) < 11))) {
 				// We need to write the contents here in IE since multiple writes messes up refresh button and back button
-				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();})()';				
+				u = 'javascript:(function(){document.open();document.domain="' + document.domain + '";var ed = window.parent.tinyMCE.get("' + t.id + '");document.write(ed.iframeHTML);document.close();ed.initContentBody();})()';
 			}
 
 			// Create iframe
@@ -10830,120 +13597,111 @@
 			n = DOM.add(o.iframeContainer, 'iframe', { 
 				id : t.id + "_ifr",
 				src : u || 'javascript:""', // Workaround for HTTPS warning in IE6/7
-				frameBorder : '0', 
+				frameBorder : '0',
+				allowTransparency : "true",
 				title : s.aria_label,
 				style : {
 					width : '100%',
-					height : h
+					height : h,
+					display : 'block' // Important for Gecko to render the iframe correctly
 				}
 			});
 
 			t.contentAreaContainer = o.iframeContainer;
-			DOM.get(o.editorContainer).style.display = t.orgDisplay;
+
+			if (o.editorContainer) {
+				DOM.get(o.editorContainer).style.display = t.orgDisplay;
+			}
+
+			// Restore visibility on target element
+			e.style.visibility = t.orgVisibility;
+
 			DOM.get(t.id).style.display = 'none';
 			DOM.setAttrib(t.id, 'aria-hidden', true);
 
 			if (!tinymce.relaxedDomain || !u)
-				t.setupIframe();
+				t.initContentBody();
 
 			e = n = o = null; // Cleanup
 		},
 
-		setupIframe : function() {
-			var t = this, s = t.settings, e = DOM.get(t.id), d = t.getDoc(), h, b;
+		initContentBody : function() {
+			var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), html, body, contentCssText;
 
 			// Setup iframe body
-			if (!isIE || !tinymce.relaxedDomain) {
-				d.open();
-				d.write(t.iframeHTML);
-				d.close();
+			if ((!isIE || !tinymce.relaxedDomain) && !settings.content_editable) {
+				doc.open();
+				doc.write(self.iframeHTML);
+				doc.close();
 
 				if (tinymce.relaxedDomain)
-					d.domain = tinymce.relaxedDomain;
+					doc.domain = tinymce.relaxedDomain;
 			}
 
-			// Design mode needs to be added here Ctrl+A will fail otherwise
-			if (!isIE) {
-				try {
-					if (!s.readonly)
-						d.designMode = 'On';
-				} catch (ex) {
-					// Will fail on Gecko if the editor is placed in an hidden container element
-					// The design mode will be set ones the editor is focused
-				}
+			if (settings.content_editable) {
+				DOM.addClass(targetElm, 'mceContentBody');
+				self.contentDocument = doc = settings.content_document || document;
+				self.contentWindow = settings.content_window || window;
+				self.bodyElement = targetElm;
+
+				// Prevent leak in IE
+				settings.content_document = settings.content_window = null;
 			}
 
-			// IE needs to use contentEditable or it will display non secure items for HTTPS
-			if (isIE) {
-				// It will not steal focus if we hide it while setting contentEditable
-				b = t.getBody();
-				DOM.hide(b);
+			// It will not steal focus while setting contentEditable
+			body = self.getBody();
+			body.disabled = true;
 
-				if (!s.readonly)
-					b.contentEditable = true;
+			if (!settings.readonly)
+				body.contentEditable = self.getParam('content_editable_state', true);
 
-				DOM.show(b);
-			}
+			body.disabled = false;
 
-			t.schema = new tinymce.html.Schema(s);
+			self.schema = new tinymce.html.Schema(settings);
 
-			t.dom = new tinymce.dom.DOMUtils(t.getDoc(), {
+			self.dom = new tinymce.dom.DOMUtils(doc, {
 				keep_values : true,
-				url_converter : t.convertURL,
-				url_converter_scope : t,
-				hex_colors : s.force_hex_style_colors,
-				class_filter : s.class_filter,
-				update_styles : 1,
-				fix_ie_paragraphs : 1,
-				schema : t.schema
+				url_converter : self.convertURL,
+				url_converter_scope : self,
+				hex_colors : settings.force_hex_style_colors,
+				class_filter : settings.class_filter,
+				update_styles : true,
+				root_element : settings.content_editable ? self.id : null,
+				schema : self.schema
 			});
 
-			t.parser = new tinymce.html.DomParser(s, t.schema);
-
-			// Force anchor names closed
-			t.parser.addAttributeFilter('name', function(nodes, name) {
-				var i = nodes.length, sibling, prevSibling, parent, node;
-
-				while (i--) {
-					node = nodes[i];
-					if (node.name === 'a' && node.firstChild) {
-						parent = node.parent;
-
-						// Move children after current node
-						sibling = node.lastChild;
-						do {
-							prevSibling = sibling.prev;
-							parent.insert(sibling, node);
-							sibling = prevSibling;
-						} while (sibling);
-					}
-				}
-			});
+			self.parser = new tinymce.html.DomParser(settings, self.schema);
 
 			// Convert src and href into data-mce-src, data-mce-href and data-mce-style
-			t.parser.addAttributeFilter('src,href,style', function(nodes, name) {
-				var i = nodes.length, node, dom = t.dom, value;
+			self.parser.addAttributeFilter('src,href,style', function(nodes, name) {
+				var i = nodes.length, node, dom = self.dom, value, internalName;
 
 				while (i--) {
 					node = nodes[i];
 					value = node.attr(name);
+					internalName = 'data-mce-' + name;
 
-					if (name === "style")
-						node.attr('data-mce-style', dom.serializeStyle(dom.parseStyle(value), node.name));
-					else
-						node.attr('data-mce-' + name, t.convertURL(value, name, node.name));
+					// Add internal attribute if we need to we don't on a refresh of the document
+					if (!node.attributes.map[internalName]) {	
+						if (name === "style")
+							node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name));
+						else
+							node.attr(internalName, self.convertURL(value, name, node.name));
+					}
 				}
 			});
 
 			// Keep scripts from executing
-			t.parser.addNodeFilter('script', function(nodes, name) {
-				var i = nodes.length;
+			self.parser.addNodeFilter('script', function(nodes, name) {
+				var i = nodes.length, node;
 
-				while (i--)
-					nodes[i].attr('type', 'mce-text/javascript');
+				while (i--) {
+					node = nodes[i];
+					node.attr('type', 'mce-' + (node.attr('type') || 'text/javascript'));
+				}
 			});
 
-			t.parser.addNodeFilter('#cdata', function(nodes, name) {
+			self.parser.addNodeFilter('#cdata', function(nodes, name) {
 				var i = nodes.length, node;
 
 				while (i--) {
@@ -10954,8 +13712,8 @@
 				}
 			});
 
-			t.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) {
-				var i = nodes.length, node, nonEmptyElements = t.schema.getNonEmptyElements();
+			self.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) {
+				var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements();
 
 				while (i--) {
 					node = nodes[i];
@@ -10965,335 +13723,154 @@
 				}
 			});
 
-			t.serializer = new tinymce.dom.Serializer(s, t.dom, t.schema);
+			self.serializer = new tinymce.dom.Serializer(settings, self.dom, self.schema);
 
-			t.selection = new tinymce.dom.Selection(t.dom, t.getWin(), t.serializer);
+			self.selection = new tinymce.dom.Selection(self.dom, self.getWin(), self.serializer, self);
 
-			t.formatter = new tinymce.Formatter(this);
+			self.formatter = new tinymce.Formatter(self);
 
-			// Register default formats
-			t.formatter.register({
-				alignleft : [
-					{selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}},
-					{selector : 'img,table', collapsed : false, styles : {'float' : 'left'}}
-				],
+			self.undoManager = new tinymce.UndoManager(self);
 
-				aligncenter : [
-					{selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}},
-					{selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}},
-					{selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}}
-				],
+			self.forceBlocks = new tinymce.ForceBlocks(self);
+			self.enterKey = new tinymce.EnterKey(self);
+			self.editorCommands = new tinymce.EditorCommands(self);
 
-				alignright : [
-					{selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}},
-					{selector : 'img,table', collapsed : false, styles : {'float' : 'right'}}
-				],
-
-				alignfull : [
-					{selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}}
-				],
-
-				bold : [
-					{inline : 'strong', remove : 'all'},
-					{inline : 'span', styles : {fontWeight : 'bold'}},
-					{inline : 'b', remove : 'all'}
-				],
-
-				italic : [
-					{inline : 'em', remove : 'all'},
-					{inline : 'span', styles : {fontStyle : 'italic'}},
-					{inline : 'i', remove : 'all'}
-				],
-
-				underline : [
-					{inline : 'span', styles : {textDecoration : 'underline'}, exact : true},
-					{inline : 'u', remove : 'all'}
-				],
-
-				strikethrough : [
-					{inline : 'span', styles : {textDecoration : 'line-through'}, exact : true},
-					{inline : 'strike', remove : 'all'}
-				],
-
-				forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false},
-				hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false},
-				fontname : {inline : 'span', styles : {fontFamily : '%value'}},
-				fontsize : {inline : 'span', styles : {fontSize : '%value'}},
-				fontsize_class : {inline : 'span', attributes : {'class' : '%value'}},
-				blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'},
-				subscript : {inline : 'sub'},
-				superscript : {inline : 'sup'},
-
-				removeformat : [
-					{selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true},
-					{selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},
-					{selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}
-				]
+			self.onExecCommand.add(function(editor, command) {
+				// Don't refresh the select lists until caret move
+				if (!/^(FontName|FontSize)$/.test(command))
+					self.nodeChanged();
 			});
-
-			// Register default block formats
-			each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) {
-				t.formatter.register(name, {block : name, remove : 'all'});
-			});
-
-			// Register user defined formats
-			t.formatter.register(t.settings.formats);
-
-			t.undoManager = new tinymce.UndoManager(t);
 
 			// Pass through
-			t.undoManager.onAdd.add(function(um, l) {
-				if (um.hasUndo())
-					return t.onChange.dispatch(t, l, um);
+			self.serializer.onPreProcess.add(function(se, o) {
+				return self.onPreProcess.dispatch(self, o, se);
 			});
 
-			t.undoManager.onUndo.add(function(um, l) {
-				return t.onUndo.dispatch(t, l, um);
+			self.serializer.onPostProcess.add(function(se, o) {
+				return self.onPostProcess.dispatch(self, o, se);
 			});
 
-			t.undoManager.onRedo.add(function(um, l) {
-				return t.onRedo.dispatch(t, l, um);
-			});
+			self.onPreInit.dispatch(self);
 
-			t.forceBlocks = new tinymce.ForceBlocks(t, {
-				forced_root_block : s.forced_root_block
-			});
+			if (!settings.browser_spellcheck && !settings.gecko_spellcheck)
+				doc.body.spellcheck = false;
 
-			t.editorCommands = new tinymce.EditorCommands(t);
-
-			// Pass through
-			t.serializer.onPreProcess.add(function(se, o) {
-				return t.onPreProcess.dispatch(t, o, se);
-			});
-
-			t.serializer.onPostProcess.add(function(se, o) {
-				return t.onPostProcess.dispatch(t, o, se);
-			});
-
-			t.onPreInit.dispatch(t);
-
-			if (!s.gecko_spellcheck)
-				t.getBody().spellcheck = 0;
-
-			if (!s.readonly)
-				t._addEvents();
-
-			t.controlManager.onPostRender.dispatch(t, t.controlManager);
-			t.onPostRender.dispatch(t);
-
-			if (s.directionality)
-				t.getBody().dir = s.directionality;
-
-			if (s.nowrap)
-				t.getBody().style.whiteSpace = "nowrap";
-
-			if (s.handle_node_change_callback) {
-				t.onNodeChange.add(function(ed, cm, n) {
-					t.execCallback('handle_node_change_callback', t.id, n, -1, -1, true, t.selection.isCollapsed());
-				});
+			if (!settings.readonly) {
+				self.bindNativeEvents();
 			}
 
-			if (s.save_callback) {
-				t.onSaveContent.add(function(ed, o) {
-					var h = t.execCallback('save_callback', t.id, o.content, t.getBody());
+			self.controlManager.onPostRender.dispatch(self, self.controlManager);
+			self.onPostRender.dispatch(self);
 
-					if (h)
-						o.content = h;
-				});
-			}
+			self.quirks = tinymce.util.Quirks(self);
 
-			if (s.onchange_callback) {
-				t.onChange.add(function(ed, l) {
-					t.execCallback('onchange_callback', t, l);
-				});
-			}
+			if (settings.directionality)
+				body.dir = settings.directionality;
 
-			if (s.protect) {
-				t.onBeforeSetContent.add(function(ed, o) {
-					if (s.protect) {
-						each(s.protect, function(pattern) {
-							o.content = o.content.replace(pattern, function(str) {
-								return '<!--mce:protected ' + escape(str) + '-->';
-							});
+			if (settings.nowrap)
+				body.style.whiteSpace = "nowrap";
+
+			if (settings.protect) {
+				self.onBeforeSetContent.add(function(ed, o) {
+					each(settings.protect, function(pattern) {
+						o.content = o.content.replace(pattern, function(str) {
+							return '<!--mce:protected ' + escape(str) + '-->';
 						});
-					}
-				});
-			}
-
-			if (s.convert_newlines_to_brs) {
-				t.onBeforeSetContent.add(function(ed, o) {
-					if (o.initial)
-						o.content = o.content.replace(/\r?\n/g, '<br />');
-				});
-			}
-
-			if (s.preformatted) {
-				t.onPostProcess.add(function(ed, o) {
-					o.content = o.content.replace(/^\s*<pre.*?>/, '');
-					o.content = o.content.replace(/<\/pre>\s*$/, '');
-
-					if (o.set)
-						o.content = '<pre class="mceItemHidden">' + o.content + '</pre>';
-				});
-			}
-
-			if (s.verify_css_classes) {
-				t.serializer.attribValueFilter = function(n, v) {
-					var s, cl;
-
-					if (n == 'class') {
-						// Build regexp for classes
-						if (!t.classesRE) {
-							cl = t.dom.getClasses();
-
-							if (cl.length > 0) {
-								s = '';
-
-								each (cl, function(o) {
-									s += (s ? '|' : '') + o['class'];
-								});
-
-								t.classesRE = new RegExp('(' + s + ')', 'gi');
-							}
-						}
-
-						return !t.classesRE || /(\bmceItem\w+\b|\bmceTemp\w+\b)/g.test(v) || t.classesRE.test(v) ? v : '';
-					}
-
-					return v;
-				};
-			}
-
-			if (s.cleanup_callback) {
-				t.onBeforeSetContent.add(function(ed, o) {
-					o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
-				});
-
-				t.onPreProcess.add(function(ed, o) {
-					if (o.set)
-						t.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o);
-
-					if (o.get)
-						t.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o);
-				});
-
-				t.onPostProcess.add(function(ed, o) {
-					if (o.set)
-						o.content = t.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
-
-					if (o.get)						
-						o.content = t.execCallback('cleanup_callback', 'get_from_editor', o.content, o);
-				});
-			}
-
-			if (s.save_callback) {
-				t.onGetContent.add(function(ed, o) {
-					if (o.save)
-						o.content = t.execCallback('save_callback', t.id, o.content, t.getBody());
-				});
-			}
-
-			if (s.handle_event_callback) {
-				t.onEvent.add(function(ed, e, o) {
-					if (t.execCallback('handle_event_callback', e, ed, o) === false)
-						Event.cancel(e);
+					});
 				});
 			}
 
 			// Add visual aids when new contents is added
-			t.onSetContent.add(function() {
-				t.addVisual(t.getBody());
+			self.onSetContent.add(function() {
+				self.addVisual(self.getBody());
 			});
 
 			// Remove empty contents
-			if (s.padd_empty_editor) {
-				t.onPostProcess.add(function(ed, o) {
+			if (settings.padd_empty_editor) {
+				self.onPostProcess.add(function(ed, o) {
 					o.content = o.content.replace(/^(<p[^>]*>(&nbsp;|&#160;|\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, '');
 				});
 			}
 
-			if (isGecko) {
-				// Fix gecko link bug, when a link is placed at the end of block elements there is
-				// no way to move the caret behind the link. This fix adds a bogus br element after the link
-				function fixLinks(ed, o) {
-					each(ed.dom.select('a'), function(n) {
-						var pn = n.parentNode;
+			self.load({initial : true, format : 'html'});
+			self.startContent = self.getContent({format : 'raw'});
 
-						if (ed.dom.isBlock(pn) && pn.lastChild === n)
-							ed.dom.add(pn, 'br', {'data-mce-bogus' : 1});
-					});
-				};
+			self.initialized = true;
 
-				t.onExecCommand.add(function(ed, cmd) {
-					if (cmd === 'CreateLink')
-						fixLinks(ed);
+			self.onInit.dispatch(self);
+			self.execCallback('setupcontent_callback', self.id, body, doc);
+			self.execCallback('init_instance_callback', self);
+			self.focus(true);
+			self.nodeChanged({initial : true});
+
+			// Add editor specific CSS styles
+			if (self.contentStyles.length > 0) {
+				contentCssText = '';
+
+				each(self.contentStyles, function(style) {
+					contentCssText += style + "\r\n";
 				});
 
-				t.onSetContent.add(t.selection.onSetContent.add(fixLinks));
-
-				if (!s.readonly) {
-					try {
-						// Design mode must be set here once again to fix a bug where
-						// Ctrl+A/Delete/Backspace didn't work if the editor was added using mceAddControl then removed then added again
-						d.designMode = 'Off';
-						d.designMode = 'On';
-					} catch (ex) {
-						// Will fail on Gecko if the editor is placed in an hidden container element
-						// The design mode will be set ones the editor is focused
-					}
-				}
+				self.dom.addStyle(contentCssText);
 			}
 
-			// A small timeout was needed since firefox will remove. Bug: #1838304
-			setTimeout(function () {
-				if (t.removed)
-					return;
+			// Load specified content CSS last
+			each(self.contentCSS, function(url) {
+				self.dom.loadCSS(url);
+			});
 
-				t.load({initial : true, format : 'html'});
-				t.startContent = t.getContent({format : 'raw'});
-				t.undoManager.add();
-				t.initialized = true;
+			// Handle auto focus
+			if (settings.auto_focus) {
+				setTimeout(function () {
+					var ed = tinymce.get(settings.auto_focus);
 
-				t.onInit.dispatch(t);
-				t.execCallback('setupcontent_callback', t.id, t.getBody(), t.getDoc());
-				t.execCallback('init_instance_callback', t);
-				t.focus(true);
-				t.nodeChanged({initial : 1});
+					ed.selection.select(ed.getBody(), 1);
+					ed.selection.collapse(1);
+					ed.getBody().focus();
+					ed.getWin().focus();
+				}, 100);
+			}
 
-				// Load specified content CSS last
-				each(t.contentCSS, function(u) {
-					t.dom.loadCSS(u);
-				});
-
-				// Handle auto focus
-				if (s.auto_focus) {
-					setTimeout(function () {
-						var ed = tinymce.get(s.auto_focus);
-
-						ed.selection.select(ed.getBody(), 1);
-						ed.selection.collapse(1);
-						ed.getWin().focus();
-					}, 100);
-				}
-			}, 1);
-	
-			e = null;
+			// Clean up references for IE
+			targetElm = doc = body = null;
 		},
 
+		focus : function(skip_focus) {
+			var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, ieRng, controlElm, doc = self.getDoc(), body;
 
-		focus : function(sf) {
-			var oed, t = this, ce = t.settings.content_editable, ieRng, controlElm, doc = t.getDoc();
+			if (!skip_focus) {
+				if (self.lastIERng) {
+					selection.setRng(self.lastIERng);
+				}
 
-			if (!sf) {
 				// Get selected control element
-				ieRng = t.selection.getRng();
+				ieRng = selection.getRng();
 				if (ieRng.item) {
 					controlElm = ieRng.item(0);
 				}
 
-				// Is not content editable
-				if (!ce)
-					t.getWin().focus();
+				self._refreshContentEditable();
+
+				// Focus the window iframe
+				if (!contentEditable) {
+					self.getWin().focus();
+				}
+
+				// Focus the body as well since it's contentEditable
+				if (tinymce.isGecko || contentEditable) {
+					body = self.getBody();
+
+					// Check for setActive since it doesn't scroll to the element
+					if (body.setActive) {
+						body.setActive();
+					} else {
+						body.focus();
+					}
+
+					if (contentEditable) {
+						selection.normalize();
+					}
+				}
 
 				// Restore selected control element
 				// This is needed when for example an image is selected within a
@@ -11303,17 +13880,16 @@
 					ieRng.addElement(controlElm);
 					ieRng.select();
 				}
-
 			}
 
-			if (tinymce.activeEditor != t) {
+			if (tinymce.activeEditor != self) {
 				if ((oed = tinymce.activeEditor) != null)
-					oed.onDeactivate.dispatch(oed, t);
+					oed.onDeactivate.dispatch(oed, self);
 
-				t.onActivate.dispatch(t, oed);
+				self.onActivate.dispatch(self, oed);
 			}
 
-			tinymce._setActive(t);
+			tinymce._setActive(self);
 		},
 
 		execCallback : function(n) {
@@ -11345,7 +13921,7 @@
 			if (!s)
 				return '';
 
-			return i18n[c + '.' + s] || s.replace(/{\#([^}]+)\}/g, function(a, b) {
+			return i18n[c + '.' + s] || s.replace(/\{\#([^\}]+)\}/g, function(a, b) {
 				return i18n[c + '.' + b] || '{#' + b + '}';
 			});
 		},
@@ -11379,37 +13955,40 @@
 		},
 
 		nodeChanged : function(o) {
-			var t = this, s = t.selection, n = s.getStart() || t.getBody();
+			var self = this, selection = self.selection, node;
 
 			// Fix for bug #1896577 it seems that this can not be fired while the editor is loading
-			if (t.initialized) {
+			if (self.initialized) {
 				o = o || {};
-				n = isIE && n.ownerDocument != t.getDoc() ? t.getBody() : n; // Fix for IE initial state
+
+				// Get start node
+				node = selection.getStart() || self.getBody();
+				node = isIE && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
 
 				// Get parents and add them to object
 				o.parents = [];
-				t.dom.getParent(n, function(node) {
+				self.dom.getParent(node, function(node) {
 					if (node.nodeName == 'BODY')
 						return true;
 
 					o.parents.push(node);
 				});
 
-				t.onNodeChange.dispatch(
-					t,
-					o ? o.controlManager || t.controlManager : t.controlManager,
-					n,
-					s.isCollapsed(),
+				self.onNodeChange.dispatch(
+					self,
+					o ? o.controlManager || self.controlManager : self.controlManager,
+					node,
+					selection.isCollapsed(),
 					o
 				);
 			}
 		},
 
-		addButton : function(n, s) {
-			var t = this;
+		addButton : function(name, settings) {
+			var self = this;
 
-			t.buttons = t.buttons || {};
-			t.buttons[n] = s;
+			self.buttons = self.buttons || {};
+			self.buttons[name] = settings;
 		},
 
 		addCommand : function(name, callback, scope) {
@@ -11427,7 +14006,7 @@
 		addShortcut : function(pa, desc, cmd_func, sc) {
 			var t = this, c;
 
-			if (!t.settings.custom_shortcuts)
+			if (t.settings.custom_shortcuts === false)
 				return false;
 
 			t.shortcuts = t.shortcuts || {};
@@ -11452,7 +14031,7 @@
 				var o = {
 					func : cmd_func,
 					scope : sc || this,
-					desc : desc,
+					desc : t.translate(desc),
 					alt : false,
 					ctrl : false,
 					shift : false
@@ -11484,9 +14063,9 @@
 			if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(cmd) && (!a || !a.skip_focus))
 				t.focus();
 
-			o = {};
-			t.onBeforeExecCommand.dispatch(t, cmd, ui, val, o);
-			if (o.terminate)
+			a = extend({}, a);
+			t.onBeforeExecCommand.dispatch(t, cmd, ui, val, a);
+			if (a.terminate)
 				return false;
 
 			// Command callback
@@ -11594,24 +14173,24 @@
 		},
 
 		show : function() {
-			var t = this;
+			var self = this;
 
-			DOM.show(t.getContainer());
-			DOM.hide(t.id);
-			t.load();
+			DOM.show(self.getContainer());
+			DOM.hide(self.id);
+			self.load();
 		},
 
 		hide : function() {
-			var t = this, d = t.getDoc();
+			var self = this, doc = self.getDoc();
 
 			// Fixed bug where IE has a blinking cursor left from the editor
-			if (isIE && d)
-				d.execCommand('SelectAll');
+			if (isIE && doc)
+				doc.execCommand('SelectAll');
 
 			// We must save before we hide so Safari doesn't crash
-			t.save();
-			DOM.hide(t.getContainer());
-			DOM.setStyle(t.id, 'display', t.orgDisplay);
+			self.save();
+			DOM.hide(self.getContainer());
+			DOM.setStyle(self.id, 'display', self.orgDisplay);
 		},
 
 		isHidden : function() {
@@ -11653,12 +14232,6 @@
 			o = o || {};
 			o.save = true;
 
-			// Add undo level will trigger onchange event
-			if (!o.no_events) {
-				t.undoManager.typing = false;
-				t.undoManager.add();
-			}
-
 			o.element = e;
 			h = o.content = t.getContent(o);
 
@@ -11688,7 +14261,7 @@
 		},
 
 		setContent : function(content, args) {
-			var self = this, rootNode, body = self.getBody();
+			var self = this, rootNode, body = self.getBody(), forcedRootBlockName;
 
 			// Setup args object
 			args = args || {};
@@ -11705,7 +14278,15 @@
 			// Padd empty content in Gecko and Safari. Commands will otherwise fail on the content
 			// It will also be impossible to place the caret in the editor unless there is a BR element present
 			if (!tinymce.isIE && (content.length === 0 || /^\s+$/.test(content))) {
-				body.innerHTML = '<br data-mce-bogus="1" />';
+				forcedRootBlockName = self.settings.forced_root_block;
+				if (forcedRootBlockName)
+					content = '<' + forcedRootBlockName + '><br data-mce-bogus="1"></' + forcedRootBlockName + '>';
+				else
+					content = '<br data-mce-bogus="1">';
+
+				body.innerHTML = content;
+				self.selection.select(body, true);
+				self.selection.collapse(true);
 				return;
 			}
 
@@ -11724,16 +14305,22 @@
 			if (!args.no_events)
 				self.onSetContent.dispatch(self, args);
 
+			// Don't normalize selection if the focused element isn't the body in content editable mode since it will steal focus otherwise
+			if (!self.settings.content_editable || document.activeElement === self.getBody()) {
+				self.selection.normalize();
+			}
+
 			return args.content;
 		},
 
 		getContent : function(args) {
-			var self = this, content;
+			var self = this, content, body = self.getBody();
 
 			// Setup args object
 			args = args || {};
 			args.format = args.format || 'html';
 			args.get = true;
+			args.getInner = true;
 
 			// Do preprocessing
 			if (!args.no_events)
@@ -11741,11 +14328,18 @@
 
 			// Get raw contents or by default the cleaned contents
 			if (args.format == 'raw')
-				content = self.getBody().innerHTML;
+				content = body.innerHTML;
+			else if (args.format == 'text')
+				content = body.innerText || body.textContent;
 			else
-				content = self.serializer.serialize(self.getBody(), args);
+				content = self.serializer.serialize(body, args);
 
-			args.content = tinymce.trim(content);
+			// Trim whitespace in beginning/end of HTML
+			if (args.format != 'text') {
+				args.content = tinymce.trim(content);
+			} else {
+				args.content = content;
+			}
 
 			// Do post processing
 			if (!args.no_events)
@@ -11761,12 +14355,12 @@
 		},
 
 		getContainer : function() {
-			var t = this;
+			var self = this;
 
-			if (!t.container)
-				t.container = DOM.get(t.editorContainer || t.id + '_parent');
+			if (!self.container)
+				self.container = DOM.get(self.editorContainer || self.id + '_parent');
 
-			return t.container;
+			return self.container;
 		},
 
 		getContentAreaContainer : function() {
@@ -11778,111 +14372,127 @@
 		},
 
 		getWin : function() {
-			var t = this, e;
+			var self = this, elm;
 
-			if (!t.contentWindow) {
-				e = DOM.get(t.id + "_ifr");
+			if (!self.contentWindow) {
+				elm = DOM.get(self.id + "_ifr");
 
-				if (e)
-					t.contentWindow = e.contentWindow;
+				if (elm)
+					self.contentWindow = elm.contentWindow;
 			}
 
-			return t.contentWindow;
+			return self.contentWindow;
 		},
 
 		getDoc : function() {
-			var t = this, w;
+			var self = this, win;
 
-			if (!t.contentDocument) {
-				w = t.getWin();
+			if (!self.contentDocument) {
+				win = self.getWin();
 
-				if (w)
-					t.contentDocument = w.document;
+				if (win)
+					self.contentDocument = win.document;
 			}
 
-			return t.contentDocument;
+			return self.contentDocument;
 		},
 
 		getBody : function() {
 			return this.bodyElement || this.getDoc().body;
 		},
 
-		convertURL : function(u, n, e) {
-			var t = this, s = t.settings;
+		convertURL : function(url, name, elm) {
+			var self = this, settings = self.settings;
 
 			// Use callback instead
-			if (s.urlconverter_callback)
-				return t.execCallback('urlconverter_callback', u, e, true, n);
+			if (settings.urlconverter_callback)
+				return self.execCallback('urlconverter_callback', url, elm, true, name);
 
 			// Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
-			if (!s.convert_urls || (e && e.nodeName == 'LINK') || u.indexOf('file:') === 0)
-				return u;
+			if (!settings.convert_urls || (elm && elm.nodeName == 'LINK') || url.indexOf('file:') === 0)
+				return url;
 
 			// Convert to relative
-			if (s.relative_urls)
-				return t.documentBaseURI.toRelative(u);
+			if (settings.relative_urls)
+				return self.documentBaseURI.toRelative(url);
 
 			// Convert to absolute
-			u = t.documentBaseURI.toAbsolute(u, s.remove_script_host);
+			url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
 
-			return u;
+			return url;
 		},
 
-		addVisual : function(e) {
-			var t = this, s = t.settings;
+		addVisual : function(elm) {
+			var self = this, settings = self.settings, dom = self.dom, cls;
 
-			e = e || t.getBody();
+			elm = elm || self.getBody();
 
-			if (!is(t.hasVisual))
-				t.hasVisual = s.visual;
+			if (!is(self.hasVisual))
+				self.hasVisual = settings.visual;
 
-			each(t.dom.select('table,a', e), function(e) {
-				var v;
+			each(dom.select('table,a', elm), function(elm) {
+				var value;
 
-				switch (e.nodeName) {
+				switch (elm.nodeName) {
 					case 'TABLE':
-						v = t.dom.getAttrib(e, 'border');
+						cls = settings.visual_table_class || 'mceItemTable';
+						value = dom.getAttrib(elm, 'border');
 
-						if (!v || v == '0') {
-							if (t.hasVisual)
-								t.dom.addClass(e, s.visual_table_class);
+						if (!value || value == '0') {
+							if (self.hasVisual)
+								dom.addClass(elm, cls);
 							else
-								t.dom.removeClass(e, s.visual_table_class);
+								dom.removeClass(elm, cls);
 						}
 
 						return;
 
 					case 'A':
-						v = t.dom.getAttrib(e, 'name');
+						if (!dom.getAttrib(elm, 'href', false)) {
+							value = dom.getAttrib(elm, 'name') || elm.id;
+							cls = 'mceItemAnchor';
 
-						if (v) {
-							if (t.hasVisual)
-								t.dom.addClass(e, 'mceItemAnchor');
-							else
-								t.dom.removeClass(e, 'mceItemAnchor');
+							if (value) {
+								if (self.hasVisual)
+									dom.addClass(elm, cls);
+								else
+									dom.removeClass(elm, cls);
+							}
 						}
 
 						return;
 				}
 			});
 
-			t.onVisualAid.dispatch(t, e, t.hasVisual);
+			self.onVisualAid.dispatch(self, elm, self.hasVisual);
 		},
 
 		remove : function() {
-			var t = this, e = t.getContainer();
+			var self = this, elm = self.getContainer();
 
-			t.removed = 1; // Cancels post remove event execution
-			t.hide();
+			if (!self.removed) {
+				self.removed = 1; // Cancels post remove event execution
+				self.hide();
 
-			t.execCallback('remove_instance_callback', t);
-			t.onRemove.dispatch(t);
+				// Don't clear the window or document if content editable
+				// is enabled since other instances might still be present
+				if (!self.settings.content_editable) {
+					Event.unbind(self.getWin());
+					Event.unbind(self.getDoc());
+				}
 
-			// Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command
-			t.onExecCommand.listeners = [];
+				Event.unbind(self.getBody());
+				Event.clear(elm);
 
-			tinymce.remove(t);
-			DOM.remove(e);
+				self.execCallback('remove_instance_callback', self);
+				self.onRemove.dispatch(self);
+
+				// Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command
+				self.onExecCommand.listeners = [];
+
+				tinymce.remove(self);
+				DOM.remove(elm);
+			}
 		},
 
 		destroy : function(s) {
@@ -11891,6 +14501,13 @@
 			// One time is enough
 			if (t.destroyed)
 				return;
+
+			// We must unbind on Gecko since it would otherwise produce the pesky "attempt to run compile-and-go script on a cleared scope" message
+			if (isGecko) {
+				Event.unbind(t.getDoc());
+				Event.unbind(t.getWin());
+				Event.unbind(t.getBody());
+			}
 
 			if (!s) {
 				tinymce.removeUnload(t.destroy);
@@ -11904,18 +14521,6 @@
 				t.controlManager.destroy();
 				t.selection.destroy();
 				t.dom.destroy();
-
-				// Remove all events
-
-				// Don't clear the window or document if content editable
-				// is enabled since other instances might still be present
-				if (!t.settings.content_editable) {
-					Event.clear(t.getWin());
-					Event.clear(t.getDoc());
-				}
-
-				Event.clear(t.getBody());
-				Event.clear(t.formElement);
 			}
 
 			if (t.formElement) {
@@ -11933,436 +14538,18 @@
 
 		// Internal functions
 
-		_addEvents : function() {
-			// 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset
-			var t = this, i, s = t.settings, dom = t.dom, lo = {
-				mouseup : 'onMouseUp',
-				mousedown : 'onMouseDown',
-				click : 'onClick',
-				keyup : 'onKeyUp',
-				keydown : 'onKeyDown',
-				keypress : 'onKeyPress',
-				submit : 'onSubmit',
-				reset : 'onReset',
-				contextmenu : 'onContextMenu',
-				dblclick : 'onDblClick',
-				paste : 'onPaste' // Doesn't work in all browsers yet
-			};
+		_refreshContentEditable : function() {
+			var self = this, body, parent;
 
-			function eventHandler(e, o) {
-				var ty = e.type;
+			// Check if the editor was hidden and the re-initalize contentEditable mode by removing and adding the body again
+			if (self._isHidden()) {
+				body = self.getBody();
+				parent = body.parentNode;
 
-				// Don't fire events when it's removed
-				if (t.removed)
-					return;
+				parent.removeChild(body);
+				parent.appendChild(body);
 
-				// Generic event handler
-				if (t.onEvent.dispatch(t, e, o) !== false) {
-					// Specific event handler
-					t[lo[e.fakeType || e.type]].dispatch(t, e, o);
-				}
-			};
-
-			// Add DOM events
-			each(lo, function(v, k) {
-				switch (k) {
-					case 'contextmenu':
-						dom.bind(t.getDoc(), k, eventHandler);
-						break;
-
-					case 'paste':
-						dom.bind(t.getBody(), k, function(e) {
-							eventHandler(e);
-						});
-						break;
-
-					case 'submit':
-					case 'reset':
-						dom.bind(t.getElement().form || DOM.getParent(t.id, 'form'), k, eventHandler);
-						break;
-
-					default:
-						dom.bind(s.content_editable ? t.getBody() : t.getDoc(), k, eventHandler);
-				}
-			});
-
-			dom.bind(s.content_editable ? t.getBody() : (isGecko ? t.getDoc() : t.getWin()), 'focus', function(e) {
-				t.focus(true);
-			});
-
-
-			// Fixes bug where a specified document_base_uri could result in broken images
-			// This will also fix drag drop of images in Gecko
-			if (tinymce.isGecko) {
-				dom.bind(t.getDoc(), 'DOMNodeInserted', function(e) {
-					var v;
-
-					e = e.target;
-
-					if (e.nodeType === 1 && e.nodeName === 'IMG' && (v = e.getAttribute('data-mce-src')))
-						e.src = t.documentBaseURI.toAbsolute(v);
-				});
-			}
-
-			// Set various midas options in Gecko
-			if (isGecko) {
-				function setOpts() {
-					var t = this, d = t.getDoc(), s = t.settings;
-
-					if (isGecko && !s.readonly) {
-						if (t._isHidden()) {
-							try {
-								if (!s.content_editable)
-									d.designMode = 'On';
-							} catch (ex) {
-								// Fails if it's hidden
-							}
-						}
-
-						try {
-							// Try new Gecko method
-							d.execCommand("styleWithCSS", 0, false);
-						} catch (ex) {
-							// Use old method
-							if (!t._isHidden())
-								try {d.execCommand("useCSS", 0, true);} catch (ex) {}
-						}
-
-						if (!s.table_inline_editing)
-							try {d.execCommand('enableInlineTableEditing', false, false);} catch (ex) {}
-
-						if (!s.object_resizing)
-							try {d.execCommand('enableObjectResizing', false, false);} catch (ex) {}
-					}
-				};
-
-				t.onBeforeExecCommand.add(setOpts);
-				t.onMouseDown.add(setOpts);
-			}
-
-			// Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
-			// WebKit can't even do simple things like selecting an image
-			// This also fixes so it's possible to select mceItemAnchors
-			if (tinymce.isWebKit) {
-				t.onClick.add(function(ed, e) {
-					e = e.target;
-
-					// Needs tobe the setBaseAndExtend or it will fail to select floated images
-					if (e.nodeName == 'IMG' || (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor'))) {
-						t.selection.getSel().setBaseAndExtent(e, 0, e, 1);
-						t.nodeChanged();
-					}
-				});
-			}
-
-			// Add node change handlers
-			t.onMouseUp.add(t.nodeChanged);
-			//t.onClick.add(t.nodeChanged);
-			t.onKeyUp.add(function(ed, e) {
-				var c = e.keyCode;
-
-				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)
-					t.nodeChanged();
-			});
-
-			// Add reset handler
-			t.onReset.add(function() {
-				t.setContent(t.startContent, {format : 'raw'});
-			});
-
-			// Add shortcuts
-			if (s.custom_shortcuts) {
-				if (s.custom_undo_redo_keyboard_shortcuts) {
-					t.addShortcut('ctrl+z', t.getLang('undo_desc'), 'Undo');
-					t.addShortcut('ctrl+y', t.getLang('redo_desc'), 'Redo');
-				}
-
-				// Add default shortcuts for gecko
-				t.addShortcut('ctrl+b', t.getLang('bold_desc'), 'Bold');
-				t.addShortcut('ctrl+i', t.getLang('italic_desc'), 'Italic');
-				t.addShortcut('ctrl+u', t.getLang('underline_desc'), 'Underline');
-
-				// BlockFormat shortcuts keys
-				for (i=1; i<=6; i++)
-					t.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
-
-				t.addShortcut('ctrl+7', '', ['FormatBlock', false, '<p>']);
-				t.addShortcut('ctrl+8', '', ['FormatBlock', false, '<div>']);
-				t.addShortcut('ctrl+9', '', ['FormatBlock', false, '<address>']);
-
-				function find(e) {
-					var v = null;
-
-					if (!e.altKey && !e.ctrlKey && !e.metaKey)
-						return v;
-
-					each(t.shortcuts, function(o) {
-						if (tinymce.isMac && o.ctrl != e.metaKey)
-							return;
-						else if (!tinymce.isMac && o.ctrl != e.ctrlKey)
-							return;
-
-						if (o.alt != e.altKey)
-							return;
-
-						if (o.shift != e.shiftKey)
-							return;
-
-						if (e.keyCode == o.keyCode || (e.charCode && e.charCode == o.charCode)) {
-							v = o;
-							return false;
-						}
-					});
-
-					return v;
-				};
-
-				t.onKeyUp.add(function(ed, e) {
-					var o = find(e);
-
-					if (o)
-						return Event.cancel(e);
-				});
-
-				t.onKeyPress.add(function(ed, e) {
-					var o = find(e);
-
-					if (o)
-						return Event.cancel(e);
-				});
-
-				t.onKeyDown.add(function(ed, e) {
-					var o = find(e);
-
-					if (o) {
-						o.func.call(o.scope);
-						return Event.cancel(e);
-					}
-				});
-			}
-
-			if (tinymce.isIE) {
-				// Fix so resize will only update the width and height attributes not the styles of an image
-				// It will also block mceItemNoResize items
-				dom.bind(t.getDoc(), 'controlselect', function(e) {
-					var re = t.resizeInfo, cb;
-
-					e = e.target;
-
-					// Don't do this action for non image elements
-					if (e.nodeName !== 'IMG')
-						return;
-
-					if (re)
-						dom.unbind(re.node, re.ev, re.cb);
-
-					if (!dom.hasClass(e, 'mceItemNoResize')) {
-						ev = 'resizeend';
-						cb = dom.bind(e, ev, function(e) {
-							var v;
-
-							e = e.target;
-
-							if (v = dom.getStyle(e, 'width')) {
-								dom.setAttrib(e, 'width', v.replace(/[^0-9%]+/g, ''));
-								dom.setStyle(e, 'width', '');
-							}
-
-							if (v = dom.getStyle(e, 'height')) {
-								dom.setAttrib(e, 'height', v.replace(/[^0-9%]+/g, ''));
-								dom.setStyle(e, 'height', '');
-							}
-						});
-					} else {
-						ev = 'resizestart';
-						cb = dom.bind(e, 'resizestart', Event.cancel, Event);
-					}
-
-					re = t.resizeInfo = {
-						node : e,
-						ev : ev,
-						cb : cb
-					};
-				});
-
-				t.onKeyDown.add(function(ed, e) {
-					var sel;
-
-					switch (e.keyCode) {
-						case 8:
-							sel = t.getDoc().selection;
-
-							// Fix IE control + backspace browser bug
-							if (sel.createRange && sel.createRange().item) {
-								ed.dom.remove(sel.createRange().item(0));
-								return Event.cancel(e);
-							}
-					}
-				});
-			}
-
-			if (tinymce.isOpera) {
-				t.onClick.add(function(ed, e) {
-					Event.prevent(e);
-				});
-			}
-
-			// Add custom undo/redo handlers
-			if (s.custom_undo_redo) {
-				function addUndo() {
-					t.undoManager.typing = false;
-					t.undoManager.add();
-				};
-
-				dom.bind(t.getDoc(), 'focusout', function(e) {
-					if (!t.removed && t.undoManager.typing)
-						addUndo();
-				});
-
-				// Add undo level when contents is drag/dropped within the editor
-				t.dom.bind(t.dom.getRoot(), 'dragend', function(e) {
-					addUndo();
-				});
-
-				t.onKeyUp.add(function(ed, e) {
-					var rng, parent, bookmark;
-
-					// Fix for bug #3168, to remove odd ".." nodes from the DOM we need to get/set the HTML of the parent node.
-					if (isIE && e.keyCode == 8) {
-						rng = t.selection.getRng();
-						if (rng.parentElement) {
-							parent = rng.parentElement();
-							bookmark = t.selection.getBookmark();
-							parent.innerHTML = parent.innerHTML;
-							t.selection.moveToBookmark(bookmark);
-						}
-					}
-
-					if ((e.keyCode >= 33 && e.keyCode <= 36) || (e.keyCode >= 37 && e.keyCode <= 40) || e.keyCode == 13 || e.keyCode == 45 || e.ctrlKey)
-						addUndo();
-				});
-
-				t.onKeyDown.add(function(ed, e) {
-					var rng, parent, bookmark, keyCode = e.keyCode;
-
-					// IE has a really odd bug where the DOM might include an node that doesn't have
-					// a proper structure. If you try to access nodeValue it would throw an illegal value exception.
-					// This seems to only happen when you delete contents and it seems to be avoidable if you refresh the element
-					// after you delete contents from it. See: #3008923
-					if (isIE && keyCode == 46) {
-						rng = t.selection.getRng();
-
-						if (rng.parentElement) {
-							parent = rng.parentElement();
-
-							if (!t.undoManager.typing) {
-								t.undoManager.beforeChange();
-								t.undoManager.typing = true;
-								t.undoManager.add();
-							}
-
-							// Select next word when ctrl key is used in combo with delete
-							if (e.ctrlKey) {
-								rng.moveEnd('word', 1);
-								rng.select();
-							}
-
-							// Delete contents
-							t.selection.getSel().clear();
-
-							// Check if we are within the same parent
-							if (rng.parentElement() == parent) {
-								bookmark = t.selection.getBookmark();
-
-								try {
-									// Update the HTML and hopefully it will remove the artifacts
-									parent.innerHTML = parent.innerHTML;
-								} catch (ex) {
-									// And since it's IE it can sometimes produce an unknown runtime error
-								}
-
-								// Restore the caret position
-								t.selection.moveToBookmark(bookmark);
-							}
-
-							// Block the default delete behavior since it might be broken
-							e.preventDefault();
-							return;
-						}
-					}
-
-					// Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter
-					if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45) {
-						// Add position before enter key is pressed, used by IE since it still uses the default browser behavior
-						// Todo: Remove this once we normalize enter behavior on IE
-						if (tinymce.isIE && keyCode == 13)
-							t.undoManager.beforeChange();
-
-						if (t.undoManager.typing)
-							addUndo();
-
-						return;
-					}
-
-					// If key isn't shift,ctrl,alt,capslock,metakey
-					if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !t.undoManager.typing) {
-						t.undoManager.beforeChange();
-						t.undoManager.add();
-						t.undoManager.typing = true;
-					}
-				});
-
-				t.onMouseDown.add(function() {
-					if (t.undoManager.typing)
-						addUndo();
-				});
-			}
-			
-			// Bug fix for FireFox keeping styles from end of selection instead of start.
-			if (tinymce.isGecko) {
-				function getAttributeApplyFunction() {
-					var template = t.dom.getAttribs(t.selection.getStart().cloneNode(false));
-
-					return function() {
-						var target = t.selection.getStart();
-						t.dom.removeAllAttribs(target);
-						each(template, function(attr) {
-							target.setAttributeNode(attr.cloneNode(true));
-						});
-					};
-				}
-
-				function isSelectionAcrossElements() {
-					var s = t.selection;
-
-					return !s.isCollapsed() && s.getStart() != s.getEnd();
-				}
-
-				t.onKeyPress.add(function(ed, e) {
-					var applyAttributes;
-
-					if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {
-						applyAttributes = getAttributeApplyFunction();
-						t.getDoc().execCommand('delete', false, null);
-						applyAttributes();
-
-						return Event.cancel(e);
-					}
-				});
-
-				t.dom.bind(t.getDoc(), 'cut', function(e) {
-					var applyAttributes;
-
-					if (isSelectionAcrossElements()) {
-						applyAttributes = getAttributeApplyFunction();
-						t.onKeyUp.addToTop(Event.cancel, Event);
-
-						setTimeout(function() {
-							applyAttributes();
-							t.onKeyUp.remove(Event.cancel, Event);
-						}, 0);
-					}
-				});
+				body.focus();
 			}
 		},
 
@@ -12374,20 +14561,306 @@
 
 			// Weird, wheres that cursor selection?
 			s = this.selection.getSel();
-			return (!s || !s.rangeCount || s.rangeCount == 0);
+			return (!s || !s.rangeCount || s.rangeCount === 0);
 		}
 	});
 })(tinymce);
+(function(tinymce) {
+	var each = tinymce.each;
 
+	tinymce.Editor.prototype.setupEvents = function() {
+		var self = this, settings = self.settings;
+
+		// Add events to the editor
+		each([
+			'onPreInit',
+
+			'onBeforeRenderUI',
+
+			'onPostRender',
+
+			'onLoad',
+
+			'onInit',
+
+			'onRemove',
+
+			'onActivate',
+
+			'onDeactivate',
+
+			'onClick',
+
+			'onEvent',
+
+			'onMouseUp',
+
+			'onMouseDown',
+
+			'onDblClick',
+
+			'onKeyDown',
+
+			'onKeyUp',
+
+			'onKeyPress',
+
+			'onContextMenu',
+
+			'onSubmit',
+
+			'onReset',
+
+			'onPaste',
+
+			'onPreProcess',
+
+			'onPostProcess',
+
+			'onBeforeSetContent',
+
+			'onBeforeGetContent',
+
+			'onSetContent',
+
+			'onGetContent',
+
+			'onLoadContent',
+
+			'onSaveContent',
+
+			'onNodeChange',
+
+			'onChange',
+
+			'onBeforeExecCommand',
+
+			'onExecCommand',
+
+			'onUndo',
+
+			'onRedo',
+
+			'onVisualAid',
+
+			'onSetProgressState',
+
+			'onSetAttrib'
+		], function(name) {
+			self[name] = new tinymce.util.Dispatcher(self);
+		});
+
+		// Handle legacy cleanup_callback option
+		if (settings.cleanup_callback) {
+			self.onBeforeSetContent.add(function(ed, o) {
+				o.content = ed.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
+			});
+
+			self.onPreProcess.add(function(ed, o) {
+				if (o.set)
+					ed.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o);
+
+				if (o.get)
+					ed.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o);
+			});
+
+			self.onPostProcess.add(function(ed, o) {
+				if (o.set)
+					o.content = ed.execCallback('cleanup_callback', 'insert_to_editor', o.content, o);
+
+				if (o.get)						
+					o.content = ed.execCallback('cleanup_callback', 'get_from_editor', o.content, o);
+			});
+		}
+
+		// Handle legacy save_callback option
+		if (settings.save_callback) {
+			self.onGetContent.add(function(ed, o) {
+				if (o.save)
+					o.content = ed.execCallback('save_callback', ed.id, o.content, ed.getBody());
+			});
+		}
+
+		// Handle legacy handle_event_callback option
+		if (settings.handle_event_callback) {
+			self.onEvent.add(function(ed, e, o) {
+				if (self.execCallback('handle_event_callback', e, ed, o) === false) {
+					e.preventDefault();
+					e.stopPropagation();
+				}
+			});
+		}
+
+		// Handle legacy handle_node_change_callback option
+		if (settings.handle_node_change_callback) {
+			self.onNodeChange.add(function(ed, cm, n) {
+				ed.execCallback('handle_node_change_callback', ed.id, n, -1, -1, true, ed.selection.isCollapsed());
+			});
+		}
+
+		// Handle legacy save_callback option
+		if (settings.save_callback) {
+			self.onSaveContent.add(function(ed, o) {
+				var h = ed.execCallback('save_callback', ed.id, o.content, ed.getBody());
+
+				if (h)
+					o.content = h;
+			});
+		}
+
+		// Handle legacy onchange_callback option
+		if (settings.onchange_callback) {
+			self.onChange.add(function(ed, l) {
+				ed.execCallback('onchange_callback', ed, l);
+			});
+		}
+	};
+
+	tinymce.Editor.prototype.bindNativeEvents = function() {
+		// 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset
+		var self = this, i, settings = self.settings, dom = self.dom, nativeToDispatcherMap;
+
+		nativeToDispatcherMap = {
+			mouseup : 'onMouseUp',
+			mousedown : 'onMouseDown',
+			click : 'onClick',
+			keyup : 'onKeyUp',
+			keydown : 'onKeyDown',
+			keypress : 'onKeyPress',
+			submit : 'onSubmit',
+			reset : 'onReset',
+			contextmenu : 'onContextMenu',
+			dblclick : 'onDblClick',
+			paste : 'onPaste' // Doesn't work in all browsers yet
+		};
+
+		// Handler that takes a native event and sends it out to a dispatcher like onKeyDown
+		function eventHandler(evt, args) {
+			var type = evt.type;
+
+			// Don't fire events when it's removed
+			if (self.removed)
+				return;
+
+			// Sends the native event out to a global dispatcher then to the specific event dispatcher
+			if (self.onEvent.dispatch(self, evt, args) !== false) {
+				self[nativeToDispatcherMap[evt.fakeType || evt.type]].dispatch(self, evt, args);
+			}
+		};
+
+		// Opera doesn't support focus event for contentEditable elements so we need to fake it
+		function doOperaFocus(e) {
+			self.focus(true);
+		};
+
+		function nodeChanged(ed, e) {
+			// Normalize selection for example <b>a</b><i>|a</i> becomes <b>a|</b><i>a</i> except for Ctrl+A since it selects everything
+			if (e.keyCode != 65 || !tinymce.VK.metaKeyPressed(e)) {
+				self.selection.normalize();
+			}
+
+			self.nodeChanged();
+		}
+
+		// Add DOM events
+		each(nativeToDispatcherMap, function(dispatcherName, nativeName) {
+			var root = settings.content_editable ? self.getBody() : self.getDoc();
+
+			switch (nativeName) {
+				case 'contextmenu':
+					dom.bind(root, nativeName, eventHandler);
+					break;
+
+				case 'paste':
+					dom.bind(self.getBody(), nativeName, eventHandler);
+					break;
+
+				case 'submit':
+				case 'reset':
+					dom.bind(self.getElement().form || tinymce.DOM.getParent(self.id, 'form'), nativeName, eventHandler);
+					break;
+
+				default:
+					dom.bind(root, nativeName, eventHandler);
+			}
+		});
+
+		// Set the editor as active when focused
+		dom.bind(settings.content_editable ? self.getBody() : (tinymce.isGecko ? self.getDoc() : self.getWin()), 'focus', function(e) {
+			self.focus(true);
+		});
+
+		if (settings.content_editable && tinymce.isOpera) {
+			dom.bind(self.getBody(), 'click', doOperaFocus);
+			dom.bind(self.getBody(), 'keydown', doOperaFocus);
+		}
+
+		// Add node change handler
+		self.onMouseUp.add(nodeChanged);
+
+		self.onKeyUp.add(function(ed, e) {
+			var keyCode = e.keyCode;
+
+			if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45 || keyCode == 46 || keyCode == 8 || (tinymce.isMac && (keyCode == 91 || keyCode == 93)) || e.ctrlKey)
+				nodeChanged(ed, e);
+		});
+
+		// Add reset handler
+		self.onReset.add(function() {
+			self.setContent(self.startContent, {format : 'raw'});
+		});
+
+		// Add shortcuts
+		function handleShortcut(e, execute) {
+			if (e.altKey || e.ctrlKey || e.metaKey) {
+				each(self.shortcuts, function(shortcut) {
+					var ctrlState = tinymce.isMac ? e.metaKey : e.ctrlKey;
+
+					if (shortcut.ctrl != ctrlState || shortcut.alt != e.altKey || shortcut.shift != e.shiftKey)
+						return;
+
+					if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) {
+						e.preventDefault();
+
+						if (execute) {
+							shortcut.func.call(shortcut.scope);
+						}
+
+						return true;
+					}
+				});
+			}
+		};
+
+		self.onKeyUp.add(function(ed, e) {
+			handleShortcut(e);
+		});
+
+		self.onKeyPress.add(function(ed, e) {
+			handleShortcut(e);
+		});
+
+		self.onKeyDown.add(function(ed, e) {
+			handleShortcut(e, true);
+		});
+
+		if (tinymce.isOpera) {
+			self.onClick.add(function(ed, e) {
+				e.preventDefault();
+			});
+		}
+	};
+})(tinymce);
 (function(tinymce) {
 	// Added for compression purposes
-	var each = tinymce.each, undefined, TRUE = true, FALSE = false;
+	var each = tinymce.each, undef, TRUE = true, FALSE = false;
 
 	tinymce.EditorCommands = function(editor) {
 		var dom = editor.dom,
 			selection = editor.selection,
 			commands = {state: {}, exec : {}, value : {}},
 			settings = editor.settings,
+			formatter = editor.formatter,
 			bookmark;
 
 		function execCommand(command, ui, value) {
@@ -12443,21 +14916,21 @@
 		// Private methods
 
 		function execNativeCommand(command, ui, value) {
-			if (ui === undefined)
+			if (ui === undef)
 				ui = FALSE;
 
-			if (value === undefined)
+			if (value === undef)
 				value = null;
 
 			return editor.getDoc().execCommand(command, ui, value);
 		};
 
 		function isFormatMatch(name) {
-			return editor.formatter.match(name);
+			return formatter.match(name);
 		};
 
 		function toggleFormat(name, value) {
-			editor.formatter.toggle(name, value ? {value : value} : undefined);
+			formatter.toggle(name, value ? {value : value} : undef);
 		};
 
 		function storeSelection(type) {
@@ -12517,7 +14990,7 @@
 				// Remove all other alignments first
 				each('left,center,right,full'.split(','), function(name) {
 					if (align != name)
-						editor.formatter.remove('align' + name);
+						formatter.remove('align' + name);
 				});
 
 				toggleFormat('align' + align);
@@ -12574,7 +15047,7 @@
 			},
 
 			RemoveFormat : function(command) {
-				editor.formatter.remove(command);
+				formatter.remove(command);
 			},
 
 			mceBlockQuote : function(command) {
@@ -12620,19 +15093,17 @@
 			},
 
 			mceInsertContent : function(command, ui, value) {
-				var caretNode, rng, rootNode, parent, node, rng, nodeRect, viewPortRect, args;
+				var parser, serializer, parentNode, rootNode, fragment, args,
+					marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement;
 
-				function findSuitableCaretNode(start_node, root_node) {
-					var node, walker = new tinymce.dom.TreeWalker(start_node, root_node);
+				//selection.normalize();
 
-					while ((node = walker.current())) {
-						if ((node.nodeType == 3 && tinymce.trim(node.nodeValue).length) || node.nodeName == 'BR' || node.nodeName == 'IMG')
-							return node;
+				// Setup parser and serializer
+				parser = editor.parser;
+				serializer = new tinymce.html.Serializer({}, editor.schema);
+				bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>';
 
-						walker.prev();
-					}
-				};
-
+				// Run beforeSetContent handlers on the HTML to be inserted
 				args = {content: value, format: 'html'};
 				selection.onBeforeSetContent.dispatch(selection, args);
 				value = args.content;
@@ -12641,91 +15112,114 @@
 				if (value.indexOf('{$caret}') == -1)
 					value += '{$caret}';
 
-				// Set the content at selection to a span and replace it's contents with the value
-				selection.setContent('<span id="__mce">\uFEFF</span>', {no_events : false});
-				dom.setOuterHTML('__mce', value.replace(/\{\$caret\}/, '<span data-mce-type="bookmark" id="__mce">\uFEFF</span>'));
+				// Replace the caret marker with a span bookmark element
+				value = value.replace(/\{\$caret\}/, bookmarkHtml);
 
-				caretNode = dom.select('#__mce')[0];
-				rootNode = dom.getRoot();
+				// Insert node maker where we will insert the new HTML and get it's parent
+				if (!selection.isCollapsed())
+					editor.getDoc().execCommand('Delete', false, null);
 
-				// Move the caret into the last suitable location within the previous sibling if it's a block since the block might be split
-				if (caretNode.previousSibling && dom.isBlock(caretNode.previousSibling) || caretNode.parentNode == rootNode) {
-					node = findSuitableCaretNode(caretNode.previousSibling, rootNode);
-					if (node) {
-						if (node.nodeName == 'BR')
-							node.parentNode.insertBefore(caretNode, node);
-						else
-							dom.insertAfter(caretNode, node);
-					}
-				}
+				parentNode = selection.getNode();
 
-				// Find caret root parent and clean it up using the serializer to avoid nesting
-				while (caretNode) {
-					if (caretNode === rootNode) {
-						// Clean up the parent element by parsing and serializing it
-						// This will remove invalid elements/attributes and fix nesting issues
-						dom.setOuterHTML(parent, 
-							new tinymce.html.Serializer({}, editor.schema).serialize(
-								new tinymce.html.DomParser({
-									remove_trailing_brs : true
-								}, editor.schema).parse(dom.getOuterHTML(parent))
-							)
-						);
+				// Parse the fragment within the context of the parent node
+				args = {context : parentNode.nodeName.toLowerCase()};
+				fragment = parser.parse(value, args);
 
-						break;
-					}
+				// Move the caret to a more suitable location
+				node = fragment.lastChild;
+				if (node.attr('id') == 'mce_marker') {
+					marker = node;
 
-					parent = caretNode;
-					caretNode = caretNode.parentNode;
-				}
-
-				// Find caret after cleanup and move selection to that location
-				caretNode = dom.select('#__mce')[0];
-				if (caretNode) {
-					node = findSuitableCaretNode(caretNode.previousSibling, rootNode);
-					dom.remove(caretNode);
-
-					if (node) {
-						rng = dom.createRng();
-
-						if (node.nodeType == 3) {
-							rng.setStart(node, node.length);
-							rng.setEnd(node, node.length);
-						} else {
-							if (node.nodeName == 'BR') {
-								rng.setStartBefore(node);
-								rng.setEndBefore(node);
-							} else {
-								rng.setStartAfter(node);
-								rng.setEndAfter(node);
-							}
+					for (node = node.prev; node; node = node.walk(true)) {
+						if (node.type == 3 || !dom.isBlock(node.name)) {
+							node.parent.insert(marker, node, node.name === 'br');
+							break;
 						}
-
-						selection.setRng(rng);
-
-						// Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well
-						if (!tinymce.isIE) {
-							node = dom.create('span', null, '\u00a0');
-							rng.insertNode(node);
-							nodeRect = dom.getRect(node);
-							viewPortRect = dom.getViewPort(editor.getWin());
-
-							// Check if node is out side the viewport if it is then scroll to it
-							if ((nodeRect.y > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) ||
-								(nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) {
-								editor.getBody().scrollLeft = nodeRect.x;
-								editor.getBody().scrollTop = nodeRect.y;
-							}
-
-							dom.remove(node);
-						}
-
-						// Make sure that the selection is collapsed after we removed the node fixes a WebKit bug
-						// where WebKit would place the endContainer/endOffset at a different location than the startContainer/startOffset
-						selection.collapse(true);
 					}
 				}
 
+				// If parser says valid we can insert the contents into that parent
+				if (!args.invalid) {
+					value = serializer.serialize(fragment);
+
+					// Check if parent is empty or only has one BR element then set the innerHTML of that parent
+					node = parentNode.firstChild;
+					node2 = parentNode.lastChild;
+					if (!node || (node === node2 && node.nodeName === 'BR'))
+						dom.setHTML(parentNode, value);
+					else
+						selection.setContent(value);
+				} else {
+					// If the fragment was invalid within that context then we need
+					// to parse and process the parent it's inserted into
+
+					// Insert bookmark node and get the parent
+					selection.setContent(bookmarkHtml);
+					parentNode = selection.getNode();
+					rootNode = editor.getBody();
+
+					// Opera will return the document node when selection is in root
+					if (parentNode.nodeType == 9)
+						parentNode = node = rootNode;
+					else
+						node = parentNode;
+
+					// Find the ancestor just before the root element
+					while (node !== rootNode) {
+						parentNode = node;
+						node = node.parentNode;
+					}
+
+					// Get the outer/inner HTML depending on if we are in the root and parser and serialize that
+					value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
+					value = serializer.serialize(
+						parser.parse(
+							// Need to replace by using a function since $ in the contents would otherwise be a problem
+							value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
+								return serializer.serialize(fragment);
+							})
+						)
+					);
+
+					// Set the inner/outer HTML depending on if we are in the root or not
+					if (parentNode == rootNode)
+						dom.setHTML(rootNode, value);
+					else
+						dom.setOuterHTML(parentNode, value);
+				}
+
+				marker = dom.get('mce_marker');
+
+				// Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well
+				nodeRect = dom.getRect(marker);
+				viewPortRect = dom.getViewPort(editor.getWin());
+
+				// Check if node is out side the viewport if it is then scroll to it
+				if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) ||
+					(nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) {
+					viewportBodyElement = tinymce.isIE ? editor.getDoc().documentElement : editor.getBody();
+					viewportBodyElement.scrollLeft = nodeRect.x;
+					viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25;
+				}
+
+				// Move selection before marker and remove it
+				rng = dom.createRng();
+
+				// If previous sibling is a text node set the selection to the end of that node
+				node = marker.previousSibling;
+				if (node && node.nodeType == 3) {
+					rng.setStart(node, node.nodeValue.length);
+				} else {
+					// If the previous sibling isn't a text node or doesn't exist set the selection before the marker node
+					rng.setStartBefore(marker);
+					rng.setEndBefore(marker);
+				}
+
+				// Remove the marker node and set the new range
+				dom.remove(marker);
+				selection.setRng(rng);
+
+				// Dispatch after event and add any visual elements needed
 				selection.onSetContent.dispatch(selection, args);
 				editor.addVisual();
 			},
@@ -12733,6 +15227,10 @@
 			mceInsertRawHTML : function(command, ui, value) {
 				selection.setContent('tiny_mce_marker');
 				editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value }));
+			},
+
+			mceToggleFormat : function(command, ui, value) {
+				toggleFormat(value);
 			},
 
 			mceSetContent : function(command, ui, value) {
@@ -12748,6 +15246,11 @@
 				intentValue = parseInt(intentValue);
 
 				if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {
+					// If forced_root_blocks is set to false we don't have a block to indent so lets create a div
+					if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) {
+						formatter.apply('div');
+					}
+
 					each(selection.getSelectedBlocks(), function(element) {
 						if (command == 'outdent') {
 							value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue);
@@ -12778,7 +15281,7 @@
 			},
 
 			mceToggleFormat : function(command, ui, value) {
-				editor.formatter.toggle(value);
+				formatter.toggle(value);
 			},
 
 			InsertHorizontalRule : function() {
@@ -12791,53 +15294,43 @@
 			},
 
 			mceReplaceContent : function(command, ui, value) {
-				editor.execCommand('mceInsertContent', false, selection.setContent(value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'}))));
+				editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'})));
 			},
 
 			mceInsertLink : function(command, ui, value) {
-				var link = dom.getParent(selection.getNode(), 'a'), img, floatVal;
+				var anchor;
 
-				if (tinymce.is(value, 'string'))
+				if (typeof(value) == 'string')
 					value = {href : value};
+
+				anchor = dom.getParent(selection.getNode(), 'a');
 
 				// Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
 				value.href = value.href.replace(' ', '%20');
 
-				if (!link) {
-					// WebKit can't create links on float images for some odd reason so just remove it and restore it later
-					if (tinymce.isWebKit) {
-						img = dom.getParent(selection.getNode(), 'img');
+				// Remove existing links if there could be child links or that the href isn't specified
+				if (!anchor || !value.href) {
+					formatter.remove('link');
+				}		
 
-						if (img) {
-							floatVal = img.style.cssFloat;
-							img.style.cssFloat = null;
-						}
-					}
-
-					execNativeCommand('CreateLink', FALSE, 'javascript:mctmp(0);');
-
-					// Restore float value
-					if (floatVal)
-						img.style.cssFloat = floatVal;
-
-					each(dom.select("a[href='javascript:mctmp(0);']"), function(link) {
-						dom.setAttribs(link, value);
-					});
-				} else {
-					if (value.href)
-						dom.setAttribs(link, value);
-					else
-						editor.dom.remove(link, TRUE);
+				// Apply new link to selection
+				if (value.href) {
+					formatter.apply('link', value, anchor);
 				}
 			},
-			
+
 			selectAll : function() {
 				var root = dom.getRoot(), rng = dom.createRng();
 
-				rng.setStart(root, 0);
-				rng.setEnd(root, root.childNodes.length);
+				// Old IE does a better job with selectall than new versions
+				if (selection.getRng().setStart) {
+					rng.setStart(root, 0);
+					rng.setEnd(root, root.childNodes.length);
 
-				editor.selection.setRng(rng);
+					selection.setRng(rng);
+				} else {
+					execNativeCommand('SelectAll');
+				}
 			}
 		});
 
@@ -12845,7 +15338,12 @@
 		addCommands({
 			// Override justify commands
 			'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) {
-				return isFormatMatch('align' + command.substring(7));
+				var name = 'align' + command.substring(7);
+				var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks();
+				var matches = tinymce.map(nodes, function(node) {
+					return !!formatter.matchNode(node, name);
+				});
+				return tinymce.inArray(matches, TRUE) !== -1;
 			},
 
 			'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) {
@@ -12871,7 +15369,10 @@
 			},
 
 			'InsertUnorderedList,InsertOrderedList' : function(command) {
-				return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL');
+				var list = dom.getParent(selection.getNode(), 'ul,ol');
+				return list && 
+				     (command === 'insertunorderedlist' && list.tagName === 'UL'
+				   || command === 'insertorderedlist' && list.tagName === 'OL');
 			}
 		}, 'state');
 
@@ -12892,17 +15393,15 @@
 		}, 'value');
 
 		// Add undo manager logic
-		if (settings.custom_undo_redo) {
-			addCommands({
-				Undo : function() {
-					editor.undoManager.undo();
-				},
+		addCommands({
+			Undo : function() {
+				editor.undoManager.undo();
+			},
 
-				Redo : function() {
-					editor.undoManager.redo();
-				}
-			});
-		}
+			Redo : function() {
+				editor.undoManager.redo();
+			}
+		});
 	};
 })(tinymce);
 
@@ -12910,25 +15409,122 @@
 	var Dispatcher = tinymce.util.Dispatcher;
 
 	tinymce.UndoManager = function(editor) {
-		var self, index = 0, data = [];
+		var self, index = 0, data = [], beforeBookmark, onAdd, onUndo, onRedo;
 
 		function getContent() {
-			return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}));
+			// Remove whitespace before/after and remove pure bogus nodes
+			return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}).replace(/<span[^>]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\/span>/g, ''));
 		};
 
-		return self = {
+		function addNonTypingUndoLevel() {
+			self.typing = false;
+			self.add();
+		};
+
+		// Create event instances
+		onBeforeAdd = new Dispatcher(self);
+		onAdd       = new Dispatcher(self);
+		onUndo      = new Dispatcher(self);
+		onRedo      = new Dispatcher(self);
+
+		// Pass though onAdd event from UndoManager to Editor as onChange
+		onAdd.add(function(undoman, level) {
+			if (undoman.hasUndo())
+				return editor.onChange.dispatch(editor, level, undoman);
+		});
+
+		// Pass though onUndo event from UndoManager to Editor
+		onUndo.add(function(undoman, level) {
+			return editor.onUndo.dispatch(editor, level, undoman);
+		});
+
+		// Pass though onRedo event from UndoManager to Editor
+		onRedo.add(function(undoman, level) {
+			return editor.onRedo.dispatch(editor, level, undoman);
+		});
+
+		// Add initial undo level when the editor is initialized
+		editor.onInit.add(function() {
+			self.add();
+		});
+
+		// Get position before an execCommand is processed
+		editor.onBeforeExecCommand.add(function(ed, cmd, ui, val, args) {
+			if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!args || !args.skip_undo)) {
+				self.beforeChange();
+			}
+		});
+
+		// Add undo level after an execCommand call was made
+		editor.onExecCommand.add(function(ed, cmd, ui, val, args) {
+			if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!args || !args.skip_undo)) {
+				self.add();
+			}
+		});
+
+		// Add undo level on save contents, drag end and blur/focusout
+		editor.onSaveContent.add(addNonTypingUndoLevel);
+		editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel);
+		editor.dom.bind(editor.getDoc(), tinymce.isGecko ? 'blur' : 'focusout', function(e) {
+			if (!editor.removed && self.typing) {
+				addNonTypingUndoLevel();
+			}
+		});
+
+		editor.onKeyUp.add(function(editor, e) {
+			var keyCode = e.keyCode;
+
+			if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) {
+				addNonTypingUndoLevel();
+			}
+		});
+
+		editor.onKeyDown.add(function(editor, e) {
+			var keyCode = e.keyCode;
+
+			// Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter
+			if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45) {
+				if (self.typing) {
+					addNonTypingUndoLevel();
+				}
+
+				return;
+			}
+
+			// If key isn't shift,ctrl,alt,capslock,metakey
+			if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !self.typing) {
+				self.beforeChange();
+				self.typing = true;
+				self.add();
+			}
+		});
+
+		editor.onMouseDown.add(function(editor, e) {
+			if (self.typing) {
+				addNonTypingUndoLevel();
+			}
+		});
+
+		// Add keyboard shortcuts for undo/redo keys
+		editor.addShortcut('ctrl+z', 'undo_desc', 'Undo');
+		editor.addShortcut('ctrl+y', 'redo_desc', 'Redo');
+
+		self = {
+			// Explose for debugging reasons
+			data : data,
+
 			typing : false,
+			
+			onBeforeAdd: onBeforeAdd,
 
-			onAdd : new Dispatcher(self),
+			onAdd : onAdd,
 
-			onUndo : new Dispatcher(self),
+			onUndo : onUndo,
 
-			onRedo : new Dispatcher(self),
+			onRedo : onRedo,
 
 			beforeChange : function() {
-				// Set before bookmark on previous level
-				if (data[index])
-					data[index].beforeBookmark = editor.selection.getBookmark(2, true);
+				beforeBookmark = editor.selection.getBookmark(2, true);
 			},
 
 			add : function(level) {
@@ -12936,11 +15532,17 @@
 
 				level = level || {};
 				level.content = getContent();
+				
+				self.onBeforeAdd.dispatch(self, level);
 
 				// Add undo level if needed
 				lastLevel = data[index];
 				if (lastLevel && lastLevel.content == level.content)
 					return null;
+
+				// Set before bookmark on previous level
+				if (data[index])
+					data[index].beforeBookmark = beforeBookmark;
 
 				// Time to compress
 				if (settings.custom_undo_redo_levels) {
@@ -13018,725 +15620,116 @@
 				return index < data.length - 1 && !this.typing;
 			}
 		};
+
+		return self;
 	};
 })(tinymce);
 
-(function(tinymce) {
-	// Shorten names
-	var Event = tinymce.dom.Event,
-		isIE = tinymce.isIE,
-		isGecko = tinymce.isGecko,
-		isOpera = tinymce.isOpera,
-		each = tinymce.each,
-		extend = tinymce.extend,
-		TRUE = true,
-		FALSE = false;
+tinymce.ForceBlocks = function(editor) {
+	var settings = editor.settings, dom = editor.dom, selection = editor.selection, blockElements = editor.schema.getBlockElements();
 
-	function cloneFormats(node) {
-		var clone, temp, inner;
+	function addRootBlocks() {
+		var node = selection.getStart(), rootNode = editor.getBody(), rng, startContainer, startOffset, endContainer, endOffset, rootBlockNode, tempNode, offset = -0xFFFFFF, wrapped, isInEditorDocument;
 
-		do {
-			if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {
-				if (clone) {
-					temp = node.cloneNode(false);
-					temp.appendChild(clone);
-					clone = temp;
-				} else {
-					clone = inner = node.cloneNode(false);
-				}
+		if (!node || node.nodeType !== 1 || !settings.forced_root_block)
+			return;
 
-				clone.removeAttribute('id');
-			}
-		} while (node = node.parentNode);
+		// Check if node is wrapped in block
+		while (node && node != rootNode) {
+			if (blockElements[node.nodeName])
+				return;
 
-		if (clone)
-			return {wrapper : clone, inner : inner};
-	};
-
-	// Checks if the selection/caret is at the end of the specified block element
-	function isAtEnd(rng, par) {
-		var rng2 = par.ownerDocument.createRange();
-
-		rng2.setStart(rng.endContainer, rng.endOffset);
-		rng2.setEndAfter(par);
-
-		// 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
-		return rng2.cloneContents().textContent.length == 0;
-	};
-
-	function isEmpty(n) {
-		n = n.innerHTML;
-
-		n = n.replace(/<(img|hr|table|input|select|textarea)[ \>]/gi, '-'); // Keep these convert them to - chars
-		n = n.replace(/<[^>]+>/g, ''); // Remove all tags
-
-		return n.replace(/[ \u00a0\t\r\n]+/g, '') == '';
-	};
-
-	function splitList(selection, dom, li) {
-		var listBlock, block;
-
-		if (isEmpty(li)) {
-			listBlock = dom.getParent(li, 'ul,ol');
-
-			if (!dom.getParent(listBlock.parentNode, 'ul,ol')) {
-				dom.split(listBlock, li);
-				block = dom.create('p', 0, '<br data-mce-bogus="1" />');
-				dom.replace(block, li);
-				selection.select(block, 1);
-			}
-
-			return FALSE;
+			node = node.parentNode;
 		}
 
-		return TRUE;
-	};
-
-	tinymce.create('tinymce.ForceBlocks', {
-		ForceBlocks : function(ed) {
-			var t = this, s = ed.settings, elm;
-
-			t.editor = ed;
-			t.dom = ed.dom;
-			elm = (s.forced_root_block || 'p').toLowerCase();
-			s.element = elm.toUpperCase();
-
-			ed.onPreInit.add(t.setup, t);
-
-			if (s.forced_root_block) {
-				ed.onInit.add(t.forceRoots, t);
-				ed.onSetContent.add(t.forceRoots, t);
-				ed.onBeforeGetContent.add(t.forceRoots, t);
-				ed.onExecCommand.add(function(ed, cmd) {
-					if (cmd == 'mceInsertContent') {
-						t.forceRoots();
-						ed.nodeChanged();
-					}
-				});
-			}
-		},
-
-		setup : function() {
-			var t = this, ed = t.editor, s = ed.settings, dom = ed.dom, selection = ed.selection;
-
-			// Force root blocks when typing and when getting output
-			if (s.forced_root_block) {
-				ed.onBeforeExecCommand.add(t.forceRoots, t);
-				ed.onKeyUp.add(t.forceRoots, t);
-				ed.onPreProcess.add(t.forceRoots, t);
+		// Get current selection
+		rng = selection.getRng();
+		if (rng.setStart) {
+			startContainer = rng.startContainer;
+			startOffset = rng.startOffset;
+			endContainer = rng.endContainer;
+			endOffset = rng.endOffset;
+		} else {
+			// Force control range into text range
+			if (rng.item) {
+				node = rng.item(0);
+				rng = editor.getDoc().body.createTextRange();
+				rng.moveToElementText(node);
 			}
 
-			if (s.force_br_newlines) {
-				// Force IE to produce BRs on enter
-				if (isIE) {
-					ed.onKeyPress.add(function(ed, e) {
-						var n;
+			isInEditorDocument = rng.parentElement().ownerDocument === editor.getDoc();
+			tmpRng = rng.duplicate();
+			tmpRng.collapse(true);
+			startOffset = tmpRng.move('character', offset) * -1;
 
-						if (e.keyCode == 13 && selection.getNode().nodeName != 'LI') {
-							selection.setContent('<br id="__" /> ', {format : 'raw'});
-							n = dom.get('__');
-							n.removeAttribute('id');
-							selection.select(n);
-							selection.collapse();
-							return Event.cancel(e);
-						}
-					});
-				}
+			if (!tmpRng.collapsed) {
+				tmpRng = rng.duplicate();
+				tmpRng.collapse(false);
+				endOffset = (tmpRng.move('character', offset) * -1) - startOffset;
 			}
+		}
 
-			if (s.force_p_newlines) {
-				if (!isIE) {
-					ed.onKeyPress.add(function(ed, e) {
-						if (e.keyCode == 13 && !e.shiftKey && !t.insertPara(e))
-							Event.cancel(e);
-					});
-				} else {
-					// Ungly hack to for IE to preserve the formatting when you press
-					// enter at the end of a block element with formatted contents
-					// This logic overrides the browsers default logic with
-					// custom logic that enables us to control the output
-					tinymce.addUnload(function() {
-						t._previousFormats = 0; // Fix IE leak
-					});
-
-					ed.onKeyPress.add(function(ed, e) {
-						t._previousFormats = 0;
-
-						// Clone the current formats, this will later be applied to the new block contents
-						if (e.keyCode == 13 && !e.shiftKey && ed.selection.isCollapsed() && s.keep_styles)
-							t._previousFormats = cloneFormats(ed.selection.getStart());
-					});
-
-					ed.onKeyUp.add(function(ed, e) {
-						// Let IE break the element and the wrap the new caret location in the previous formats
-						if (e.keyCode == 13 && !e.shiftKey) {
-							var parent = ed.selection.getStart(), fmt = t._previousFormats;
-
-							// Parent is an empty block
-							if (!parent.hasChildNodes() && fmt) {
-								parent = dom.getParent(parent, dom.isBlock);
-
-								if (parent && parent.nodeName != 'LI') {
-									parent.innerHTML = '';
-
-									if (t._previousFormats) {
-										parent.appendChild(fmt.wrapper);
-										fmt.inner.innerHTML = '\uFEFF';
-									} else
-										parent.innerHTML = '\uFEFF';
-
-									selection.select(parent, 1);
-									selection.collapse(true);
-									ed.getDoc().execCommand('Delete', false, null);
-									t._previousFormats = 0;
-								}
-							}
-						}
-					});
-				}
-
-				if (isGecko) {
-					ed.onKeyDown.add(function(ed, e) {
-						if ((e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey)
-							t.backspaceDelete(e, e.keyCode == 8);
-					});
-				}
-			}
-
-			// Workaround for missing shift+enter support, http://bugs.webkit.org/show_bug.cgi?id=16973
-			if (tinymce.isWebKit) {
-				function insertBr(ed) {
-					var rng = selection.getRng(), br, div = dom.create('div', null, ' '), divYPos, vpHeight = dom.getViewPort(ed.getWin()).h;
-
-					// Insert BR element
-					rng.insertNode(br = dom.create('br'));
-
-					// Place caret after BR
-					rng.setStartAfter(br);
-					rng.setEndAfter(br);
-					selection.setRng(rng);
-
-					// Could not place caret after BR then insert an nbsp entity and move the caret
-					if (selection.getSel().focusNode == br.previousSibling) {
-						selection.select(dom.insertAfter(dom.doc.createTextNode('\u00a0'), br));
-						selection.collapse(TRUE);
-					}
-
-					// Create a temporary DIV after the BR and get the position as it
-					// seems like getPos() returns 0 for text nodes and BR elements.
-					dom.insertAfter(div, br);
-					divYPos = dom.getPos(div).y;
-					dom.remove(div);
-
-					// Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117
-					if (divYPos > vpHeight) // It is not necessary to scroll if the DIV is inside the view port.
-						ed.getWin().scrollTo(0, divYPos);
-				};
-
-				ed.onKeyPress.add(function(ed, e) {
-					if (e.keyCode == 13 && (e.shiftKey || (s.force_br_newlines && !dom.getParent(selection.getNode(), 'h1,h2,h3,h4,h5,h6,ol,ul')))) {
-						insertBr(ed);
-						Event.cancel(e);
-					}
-				});
-			}
-
-			// IE specific fixes
-			if (isIE) {
-				// Replaces IE:s auto generated paragraphs with the specified element name
-				if (s.element != 'P') {
-					ed.onKeyPress.add(function(ed, e) {
-						t.lastElm = selection.getNode().nodeName;
-					});
-
-					ed.onKeyUp.add(function(ed, e) {
-						var bl, n = selection.getNode(), b = ed.getBody();
-
-						if (b.childNodes.length === 1 && n.nodeName == 'P') {
-							n = dom.rename(n, s.element);
-							selection.select(n);
-							selection.collapse();
-							ed.nodeChanged();
-						} else if (e.keyCode == 13 && !e.shiftKey && t.lastElm != 'P') {
-							bl = dom.getParent(n, 'p');
-
-							if (bl) {
-								dom.rename(bl, s.element);
-								ed.nodeChanged();
-							}
-						}
-					});
-				}
-			}
-		},
-
-		find : function(n, t, s) {
-			var ed = this.editor, w = ed.getDoc().createTreeWalker(n, 4, null, FALSE), c = -1;
-
-			while (n = w.nextNode()) {
-				c++;
-
-				// Index by node
-				if (t == 0 && n == s)
-					return c;
-
-				// Node by index
-				if (t == 1 && c == s)
-					return n;
-			}
-
-			return -1;
-		},
-
-		forceRoots : function(ed, e) {
-			var t = this, ed = t.editor, b = ed.getBody(), d = ed.getDoc(), se = ed.selection, s = se.getSel(), r = se.getRng(), si = -2, ei, so, eo, tr, c = -0xFFFFFF;
-			var nx, bl, bp, sp, le, nl = b.childNodes, i, n, eid;
-
-			// Fix for bug #1863847
-			//if (e && e.keyCode == 13)
-			//	return TRUE;
-
-			// Wrap non blocks into blocks
-			for (i = nl.length - 1; i >= 0; i--) {
-				nx = nl[i];
-
-				// Ignore internal elements
-				if (nx.nodeType === 1 && nx.getAttribute('data-mce-type')) {
-					bl = null;
+		// Wrap non block elements and text nodes
+		node = rootNode.firstChild;
+		while (node) {
+			if (node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName])) {
+				// Remove empty text nodes
+				if (node.nodeType === 3 && node.nodeValue.length == 0) {
+					tempNode = node;
+					node = node.nextSibling;
+					dom.remove(tempNode);
 					continue;
 				}
 
-				// Is text or non block element
-				if (nx.nodeType === 3 || (!t.dom.isBlock(nx) && nx.nodeType !== 8 && !/^(script|mce:script|style|mce:style)$/i.test(nx.nodeName))) {
-					if (!bl) {
-						// Create new block but ignore whitespace
-						if (nx.nodeType != 3 || /[^\s]/g.test(nx.nodeValue)) {
-							// Store selection
-							if (si == -2 && r) {
-								if (!isIE || r.setStart) {
-									// If selection is element then mark it
-									if (r.startContainer.nodeType == 1 && (n = r.startContainer.childNodes[r.startOffset]) && n.nodeType == 1) {
-										// Save the id of the selected element
-										eid = n.getAttribute("id");
-										n.setAttribute("id", "__mce");
-									} else {
-										// If element is inside body, might not be the case in contentEdiable mode
-										if (ed.dom.getParent(r.startContainer, function(e) {return e === b;})) {
-											so = r.startOffset;
-											eo = r.endOffset;
-											si = t.find(b, 0, r.startContainer);
-											ei = t.find(b, 0, r.endContainer);
-										}
-									}
-								} else {
-									// Force control range into text range
-									if (r.item) {
-										tr = d.body.createTextRange();
-										tr.moveToElementText(r.item(0));
-										r = tr;
-									}
+				if (!rootBlockNode) {
+					rootBlockNode = dom.create(settings.forced_root_block);
+					node.parentNode.insertBefore(rootBlockNode, node);
+					wrapped = true;
+				}
 
-									tr = d.body.createTextRange();
-									tr.moveToElementText(b);
-									tr.collapse(1);
-									bp = tr.move('character', c) * -1;
-
-									tr = r.duplicate();
-									tr.collapse(1);
-									sp = tr.move('character', c) * -1;
-
-									tr = r.duplicate();
-									tr.collapse(0);
-									le = (tr.move('character', c) * -1) - sp;
-
-									si = sp - bp;
-									ei = le;
-								}
-							}
-
-							// Uses replaceChild instead of cloneNode since it removes selected attribute from option elements on IE
-							// See: http://support.microsoft.com/kb/829907
-							bl = ed.dom.create(ed.settings.forced_root_block);
-							nx.parentNode.replaceChild(bl, nx);
-							bl.appendChild(nx);
-						}
-					} else {
-						if (bl.hasChildNodes())
-							bl.insertBefore(nx, bl.firstChild);
-						else
-							bl.appendChild(nx);
-					}
-				} else
-					bl = null; // Time to create new block
+				tempNode = node;
+				node = node.nextSibling;
+				rootBlockNode.appendChild(tempNode);
+			} else {
+				rootBlockNode = null;
+				node = node.nextSibling;
 			}
+		}
 
-			// Restore selection
-			if (si != -2) {
-				if (!isIE || r.setStart) {
-					bl = b.getElementsByTagName(ed.settings.element)[0];
-					r = d.createRange();
-
-					// Select last location or generated block
-					if (si != -1)
-						r.setStart(t.find(b, 1, si), so);
-					else
-						r.setStart(bl, 0);
-
-					// Select last location or generated block
-					if (ei != -1)
-						r.setEnd(t.find(b, 1, ei), eo);
-					else
-						r.setEnd(bl, 0);
-
-					if (s) {
-						s.removeAllRanges();
-						s.addRange(r);
-					}
-				} else {
+		if (wrapped) {
+			if (rng.setStart) {
+				rng.setStart(startContainer, startOffset);
+				rng.setEnd(endContainer, endOffset);
+				selection.setRng(rng);
+			} else {
+				// Only select if the previous selection was inside the document to prevent auto focus in quirks mode
+				if (isInEditorDocument) {
 					try {
-						r = s.createRange();
-						r.moveToElementText(b);
-						r.collapse(1);
-						r.moveStart('character', si);
-						r.moveEnd('character', ei);
-						r.select();
+						rng = editor.getDoc().body.createTextRange();
+						rng.moveToElementText(rootNode);
+						rng.collapse(true);
+						rng.moveStart('character', startOffset);
+
+						if (endOffset > 0)
+							rng.moveEnd('character', endOffset);
+
+						rng.select();
 					} catch (ex) {
 						// Ignore
 					}
 				}
-			} else if ((!isIE || r.setStart) && (n = ed.dom.get('__mce'))) {
-				// Restore the id of the selected element
-				if (eid)
-					n.setAttribute('id', eid);
-				else
-					n.removeAttribute('id');
-
-				// Move caret before selected element
-				r = d.createRange();
-				r.setStartBefore(n);
-				r.setEndBefore(n);
-				se.setRng(r);
-			}
-		},
-
-		getParentBlock : function(n) {
-			var d = this.dom;
-
-			return d.getParent(n, d.isBlock);
-		},
-
-		insertPara : function(e) {
-			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;
-			var rb, ra, dir, sn, so, en, eo, sb, eb, bn, bef, aft, sc, ec, n, vp = dom.getViewPort(ed.getWin()), y, ch, car;
-
-			ed.undoManager.beforeChange();
-
-			// If root blocks are forced then use Operas default behavior since it's really good
-// Removed due to bug: #1853816
-//			if (se.forced_root_block && isOpera)
-//				return TRUE;
-
-			// Setup before range
-			rb = d.createRange();
-
-			// If is before the first block element and in body, then move it into first block element
-			rb.setStart(s.anchorNode, s.anchorOffset);
-			rb.collapse(TRUE);
-
-			// Setup after range
-			ra = d.createRange();
-
-			// If is before the first block element and in body, then move it into first block element
-			ra.setStart(s.focusNode, s.focusOffset);
-			ra.collapse(TRUE);
-
-			// Setup start/end points
-			dir = rb.compareBoundaryPoints(rb.START_TO_END, ra) < 0;
-			sn = dir ? s.anchorNode : s.focusNode;
-			so = dir ? s.anchorOffset : s.focusOffset;
-			en = dir ? s.focusNode : s.anchorNode;
-			eo = dir ? s.focusOffset : s.anchorOffset;
-
-			// If selection is in empty table cell
-			if (sn === en && /^(TD|TH)$/.test(sn.nodeName)) {
-				if (sn.firstChild.nodeName == 'BR')
-					dom.remove(sn.firstChild); // Remove BR
-
-				// Create two new block elements
-				if (sn.childNodes.length == 0) {
-					ed.dom.add(sn, se.element, null, '<br />');
-					aft = ed.dom.add(sn, se.element, null, '<br />');
-				} else {
-					n = sn.innerHTML;
-					sn.innerHTML = '';
-					ed.dom.add(sn, se.element, null, n);
-					aft = ed.dom.add(sn, se.element, null, '<br />');
-				}
-
-				// Move caret into the last one
-				r = d.createRange();
-				r.selectNodeContents(aft);
-				r.collapse(1);
-				ed.selection.setRng(r);
-
-				return FALSE;
 			}
 
-			// If the caret is in an invalid location in FF we need to move it into the first block
-			if (sn == b && en == b && b.firstChild && ed.dom.isBlock(b.firstChild)) {
-				sn = en = sn.firstChild;
-				so = eo = 0;
-				rb = d.createRange();
-				rb.setStart(sn, 0);
-				ra = d.createRange();
-				ra.setStart(en, 0);
-			}
-
-			// Never use body as start or end node
-			sn = sn.nodeName == "HTML" ? d.body : sn; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
-			sn = sn.nodeName == "BODY" ? sn.firstChild : sn;
-			en = en.nodeName == "HTML" ? d.body : en; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
-			en = en.nodeName == "BODY" ? en.firstChild : en;
-
-			// Get start and end blocks
-			sb = t.getParentBlock(sn);
-			eb = t.getParentBlock(en);
-			bn = sb ? sb.nodeName : se.element; // Get block name to create
-
-			// Return inside list use default browser behavior
-			if (n = t.dom.getParent(sb, 'li,pre')) {
-				if (n.nodeName == 'LI')
-					return splitList(ed.selection, t.dom, n);
-
-				return TRUE;
-			}
-
-			// If caption or absolute layers then always generate new blocks within
-			if (sb && (sb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
-				bn = se.element;
-				sb = null;
-			}
-
-			// If caption or absolute layers then always generate new blocks within
-			if (eb && (eb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
-				bn = se.element;
-				eb = null;
-			}
-
-			// Use P instead
-			if (/(TD|TABLE|TH|CAPTION)/.test(bn) || (sb && bn == "DIV" && /left|right/gi.test(dom.getStyle(sb, 'float', 1)))) {
-				bn = se.element;
-				sb = eb = null;
-			}
-
-			// Setup new before and after blocks
-			bef = (sb && sb.nodeName == bn) ? sb.cloneNode(0) : ed.dom.create(bn);
-			aft = (eb && eb.nodeName == bn) ? eb.cloneNode(0) : ed.dom.create(bn);
-
-			// Remove id from after clone
-			aft.removeAttribute('id');
-
-			// Is header and cursor is at the end, then force paragraph under
-			if (/^(H[1-6])$/.test(bn) && isAtEnd(r, sb))
-				aft = ed.dom.create(se.element);
-
-			// Find start chop node
-			n = sc = sn;
-			do {
-				if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
-					break;
-
-				sc = n;
-			} while ((n = n.previousSibling ? n.previousSibling : n.parentNode));
-
-			// Find end chop node
-			n = ec = en;
-			do {
-				if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
-					break;
-
-				ec = n;
-			} while ((n = n.nextSibling ? n.nextSibling : n.parentNode));
-
-			// Place first chop part into before block element
-			if (sc.nodeName == bn)
-				rb.setStart(sc, 0);
-			else
-				rb.setStartBefore(sc);
-
-			rb.setEnd(sn, so);
-			bef.appendChild(rb.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari
-
-			// Place secnd chop part within new block element
-			try {
-				ra.setEndAfter(ec);
-			} catch(ex) {
-				//console.debug(s.focusNode, s.focusOffset);
-			}
-
-			ra.setStart(en, eo);
-			aft.appendChild(ra.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari
-
-			// Create range around everything
-			r = d.createRange();
-			if (!sc.previousSibling && sc.parentNode.nodeName == bn) {
-				r.setStartBefore(sc.parentNode);
-			} else {
-				if (rb.startContainer.nodeName == bn && rb.startOffset == 0)
-					r.setStartBefore(rb.startContainer);
-				else
-					r.setStart(rb.startContainer, rb.startOffset);
-			}
-
-			if (!ec.nextSibling && ec.parentNode.nodeName == bn)
-				r.setEndAfter(ec.parentNode);
-			else
-				r.setEnd(ra.endContainer, ra.endOffset);
-
-			// Delete and replace it with new block elements
-			r.deleteContents();
-
-			if (isOpera)
-				ed.getWin().scrollTo(0, vp.y);
-
-			// Never wrap blocks in blocks
-			if (bef.firstChild && bef.firstChild.nodeName == bn)
-				bef.innerHTML = bef.firstChild.innerHTML;
-
-			if (aft.firstChild && aft.firstChild.nodeName == bn)
-				aft.innerHTML = aft.firstChild.innerHTML;
-
-			// Padd empty blocks
-			if (isEmpty(bef))
-				bef.innerHTML = '<br />';
-
-			function appendStyles(e, en) {
-				var nl = [], nn, n, i;
-
-				e.innerHTML = '';
-
-				// Make clones of style elements
-				if (se.keep_styles) {
-					n = en;
-					do {
-						// We only want style specific elements
-						if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(n.nodeName)) {
-							nn = n.cloneNode(FALSE);
-							dom.setAttrib(nn, 'id', ''); // Remove ID since it needs to be unique
-							nl.push(nn);
-						}
-					} while (n = n.parentNode);
-				}
-
-				// Append style elements to aft
-				if (nl.length > 0) {
-					for (i = nl.length - 1, nn = e; i >= 0; i--)
-						nn = nn.appendChild(nl[i]);
-
-					// Padd most inner style element
-					nl[0].innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there
-					return nl[0]; // Move caret to most inner element
-				} else
-					e.innerHTML = isOpera ? '\u00a0' : '<br />'; // Extra space for Opera so that the caret can move there
-			};
-
-			// Fill empty afterblook with current style
-			if (isEmpty(aft))
-				car = appendStyles(aft, en);
-
-			// Opera needs this one backwards for older versions
-			if (isOpera && parseFloat(opera.version()) < 9.5) {
-				r.insertNode(bef);
-				r.insertNode(aft);
-			} else {
-				r.insertNode(aft);
-				r.insertNode(bef);
-			}
-
-			// Normalize
-			aft.normalize();
-			bef.normalize();
-
-			function first(n) {
-				return d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE).nextNode() || n;
-			};
-
-			// Move cursor and scroll into view
-			r = d.createRange();
-			r.selectNodeContents(isGecko ? first(car || aft) : car || aft);
-			r.collapse(1);
-			s.removeAllRanges();
-			s.addRange(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
-			y = ed.dom.getPos(aft).y;
-			//ch = aft.clientHeight;
-
-			// Is element within viewport
-			if (y < vp.y || y + 25 > vp.y + vp.h) {
-				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
-
-				/*console.debug(
-					'Element: y=' + y + ', h=' + ch + ', ' +
-					'Viewport: y=' + vp.y + ", h=" + vp.h + ', bottom=' + (vp.y + vp.h)
-				);*/
-			}
-
-			ed.undoManager.add();
-
-			return FALSE;
-		},
-
-		backspaceDelete : function(e, bs) {
-			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;
-
-			// Delete when caret is behind a element doesn't work correctly on Gecko see #3011651
-			if (!bs && r.collapsed && sc.nodeType == 1 && r.startOffset == sc.childNodes.length) {
-				walker = new tinymce.dom.TreeWalker(sc.lastChild, sc);
-
-				// Walk the dom backwards until we find a text node
-				for (n = sc.lastChild; n; n = walker.prev()) {
-					if (n.nodeType == 3) {
-						r.setStart(n, n.nodeValue.length);
-						r.collapse(true);
-						se.setRng(r);
-						return;
-					}
-				}
-			}
-
-			// The caret sometimes gets stuck in Gecko if you delete empty paragraphs
-			// This workaround removes the element by hand and moves the caret to the previous element
-			if (sc && ed.dom.isBlock(sc) && !/^(TD|TH)$/.test(sc.nodeName) && bs) {
-				if (sc.childNodes.length == 0 || (sc.childNodes.length == 1 && sc.firstChild.nodeName == 'BR')) {
-					// Find previous block element
-					n = sc;
-					while ((n = n.previousSibling) && !ed.dom.isBlock(n)) ;
-
-					if (n) {
-						if (sc != b.firstChild) {
-							// Find last text node
-							w = ed.dom.doc.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE);
-							while (tn = w.nextNode())
-								n = tn;
-
-							// Place caret at the end of last text node
-							r = ed.getDoc().createRange();
-							r.setStart(n, n.nodeValue ? n.nodeValue.length : 0);
-							r.setEnd(n, n.nodeValue ? n.nodeValue.length : 0);
-							se.setRng(r);
-
-							// Remove the target container
-							ed.dom.remove(sc);
-						}
-
-						return Event.cancel(e);
-					}
-				}
-			}
+			editor.nodeChanged();
 		}
-	});
-})(tinymce);
+	};
+
+	// Force root blocks
+	if (settings.forced_root_block) {
+		editor.onKeyUp.add(addRootBlocks);
+		editor.onNodeChange.add(addRootBlocks);
+	}
+};
 
 (function(tinymce) {
 	// Shorten names
@@ -13794,28 +15787,40 @@
 			return c;
 		},
 
-		createControl : function(n) {
-			var c, t = this, ed = t.editor;
+		createControl : function(name) {
+			var ctrl, i, l, self = this, editor = self.editor, factories, ctrlName;
 
-			each(ed.plugins, function(p) {
-				if (p.createControl) {
-					c = p.createControl(n, t);
-
-					if (c)
-						return false;
-				}
-			});
-
-			switch (n) {
-				case "|":
-				case "separator":
-					return t.createSeparator();
+			// Build control factory cache
+			if (!self.controlFactories) {
+				self.controlFactories = [];
+				each(editor.plugins, function(plugin) {
+					if (plugin.createControl) {
+						self.controlFactories.push(plugin);
+					}
+				});
 			}
 
-			if (!c && ed.buttons && (c = ed.buttons[n]))
-				return t.createButton(n, c);
+			// Create controls by asking cached factories
+			factories = self.controlFactories;
+			for (i = 0, l = factories.length; i < l; i++) {
+				ctrl = factories[i].createControl(name, self);
 
-			return t.add(c);
+				if (ctrl) {
+					return self.add(ctrl);
+				}
+			}
+
+			// Create sepearator
+			if (name === "|" || name === "separator") {
+				return self.createSeparator();
+			}
+
+			// Create control from button collection
+			if (editor.buttons && (ctrl = editor.buttons[name])) {
+				return self.createButton(name, ctrl);
+			}
+
+			return self.add(ctrl);
 		},
 
 		createDropMenu : function(id, s, cc) {
@@ -13829,6 +15834,8 @@
 			s['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin';
 			if (v = ed.getParam('skin_variant'))
 				s['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1);
+
+			s['class'] += ed.settings.directionality == "rtl" ? ' mceRtl' : '';
 
 			id = t.prefix + id;
 			cls = cc || t._cls.dropmenu || tinymce.ui.DropMenu;
@@ -13894,7 +15901,12 @@
 
 			id = t.prefix + id;
 
-			if (ed.settings.use_native_selects)
+
+			function useNativeListForAccessibility(ed) {
+				return ed.settings.use_accessible_selects && !tinymce.isGecko
+			}
+
+			if (ed.settings.use_native_selects || useNativeListForAccessibility(ed))
 				c = new tinymce.ui.NativeListBox(id, s);
 			else {
 				cls = cc || t._cls.listbox || tinymce.ui.ListBox;
@@ -13957,7 +15969,7 @@
 				ed.onMouseDown.add(c.hideMenu, c);
 			} else {
 				cls = t._cls.button || tinymce.ui.Button;
-				c = new cls(id, s);
+				c = new cls(id, s, ed);
 			}
 
 			return t.add(c);
@@ -14243,8 +16255,9 @@
 			MCE_ATTR_RE = /^(src|href|style)$/,
 			FALSE = false,
 			TRUE = true,
-			undefined,
-			pendingFormats = {apply : [], remove : []};
+			formatChangeData,
+			undef,
+			getContentEditable = dom.getContentEditable;
 
 		function isArray(obj) {
 			return obj instanceof Array;
@@ -14255,7 +16268,104 @@
 		};
 
 		function isCaretNode(node) {
-			return node.nodeType === 1 && (node.face === 'mceinline' || node.style.fontFamily === 'mceinline');
+			return node.nodeType === 1 && node.id === '_mce_caret';
+		};
+
+		function defaultFormats() {
+			register({
+				alignleft : [
+					{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}, defaultBlock: 'div'},
+					{selector : 'img,table', collapsed : false, styles : {'float' : 'left'}}
+				],
+
+				aligncenter : [
+					{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}, defaultBlock: 'div'},
+					{selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}},
+					{selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}}
+				],
+
+				alignright : [
+					{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}, defaultBlock: 'div'},
+					{selector : 'img,table', collapsed : false, styles : {'float' : 'right'}}
+				],
+
+				alignfull : [
+					{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}, defaultBlock: 'div'}
+				],
+
+				bold : [
+					{inline : 'strong', remove : 'all'},
+					{inline : 'span', styles : {fontWeight : 'bold'}},
+					{inline : 'b', remove : 'all'}
+				],
+
+				italic : [
+					{inline : 'em', remove : 'all'},
+					{inline : 'span', styles : {fontStyle : 'italic'}},
+					{inline : 'i', remove : 'all'}
+				],
+
+				underline : [
+					{inline : 'span', styles : {textDecoration : 'underline'}, exact : true},
+					{inline : 'u', remove : 'all'}
+				],
+
+				strikethrough : [
+					{inline : 'span', styles : {textDecoration : 'line-through'}, exact : true},
+					{inline : 'strike', remove : 'all'}
+				],
+
+				forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false},
+				hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false},
+				fontname : {inline : 'span', styles : {fontFamily : '%value'}},
+				fontsize : {inline : 'span', styles : {fontSize : '%value'}},
+				fontsize_class : {inline : 'span', attributes : {'class' : '%value'}},
+				blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'},
+				subscript : {inline : 'sub'},
+				superscript : {inline : 'sup'},
+
+				link : {inline : 'a', selector : 'a', remove : 'all', split : true, deep : true,
+					onmatch : function(node) {
+						return true;
+					},
+
+					onformat : function(elm, fmt, vars) {
+						each(vars, function(value, key) {
+							dom.setAttrib(elm, key, value);
+						});
+					}
+				},
+
+				removeformat : [
+					{selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true},
+					{selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},
+					{selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}
+				]
+			});
+
+			// Register default block formats
+			each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) {
+				register(name, {block : name, remove : 'all'});
+			});
+
+			// Register user defined formats
+			register(ed.settings.formats);
+		};
+
+		function addKeyboardShortcuts() {
+			// Add some inline shortcuts
+			ed.addShortcut('ctrl+b', 'bold_desc', 'Bold');
+			ed.addShortcut('ctrl+i', 'italic_desc', 'Italic');
+			ed.addShortcut('ctrl+u', 'underline_desc', 'Underline');
+
+			// BlockFormat shortcuts keys
+			for (var i = 1; i <= 6; i++) {
+				ed.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
+			}
+
+			ed.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']);
+			ed.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']);
+			ed.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']);
 		};
 
 		// Public functions
@@ -14277,15 +16387,15 @@
 					each(format, function(format) {
 						// Set deep to false by default on selector formats this to avoid removing
 						// alignment on images inside paragraphs when alignment is changed on paragraphs
-						if (format.deep === undefined)
+						if (format.deep === undef)
 							format.deep = !format.selector;
 
 						// Default to true
-						if (format.split === undefined)
+						if (format.split === undef)
 							format.split = !format.selector || format.inline;
 
 						// Default to true
-						if (format.remove === undefined && format.selector && !format.inline)
+						if (format.remove === undef && format.selector && !format.inline)
 							format.remove = 'none';
 
 						// Mark format as a mixed format inline + block level
@@ -14330,34 +16440,14 @@
 		function apply(name, vars, node) {
 			var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed();
 
-			function moveStart(rng) {
-				var container = rng.startContainer,
-					offset = rng.startOffset,
-					walker, node;
-
-				// Move startContainer/startOffset in to a suitable node
-				if (container.nodeType == 1 || container.nodeValue === "") {
-					container = container.nodeType == 1 ? container.childNodes[offset] : container;
-
-					// Might fail if the offset is behind the last element in it's container
-					if (container) {
-						walker = new TreeWalker(container, container.parentNode);
-						for (node = walker.current(); node; node = walker.next()) {
-							if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
-								rng.setStart(node, 0);
-								break;
-							}
-						}
-					}
-				}
-
-				return rng;
-			};
-
 			function setElementFormat(elm, fmt) {
 				fmt = fmt || format;
 
 				if (elm) {
+					if (fmt.onformat) {
+						fmt.onformat(elm, fmt, vars, node);
+					}
+
 					each(fmt.styles, function(value, name) {
 						dom.setStyle(elm, name, replaceVars(value, vars));
 					});
@@ -14374,9 +16464,90 @@
 					});
 				}
 			};
+			function adjustSelectionToVisibleSelection() {
+				function findSelectionEnd(start, end) {
+					var walker = new TreeWalker(end);
+					for (node = walker.current(); node; node = walker.prev()) {
+						if (node.childNodes.length > 1 || node == start || node.tagName == 'BR') {
+							return node;
+						}
+					}
+				};
 
-			function applyRngStyle(rng) {
-				var newWrappers = [], wrapName, wrapElm;
+				// Adjust selection so that a end container with a end offset of zero is not included in the selection
+				// as this isn't visible to the user.
+				var rng = ed.selection.getRng();
+				var start = rng.startContainer;
+				var end = rng.endContainer;
+
+				if (start != end && rng.endOffset === 0) {
+					var newEnd = findSelectionEnd(start, end);
+					var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length;
+
+					rng.setEnd(newEnd, endOffset);
+				}
+
+				return rng;
+			}
+			
+			function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){
+				var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm;
+				
+				// find the index of the first child list.
+				each(node.childNodes, function(n, index) {
+					if (n.nodeName === "UL" || n.nodeName === "OL") {
+						listIndex = index;
+						list = n;
+						return false;
+					}
+				});
+				
+				// get the index of the bookmarks
+				each(node.childNodes, function(n, index) {
+					if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") {
+						if (n.id == bookmark.id + "_start") {
+							startIndex = index;
+						} else if (n.id == bookmark.id + "_end") {
+							endIndex = index;
+						}
+					}
+				});
+				
+				// if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally
+				if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) {
+					each(tinymce.grep(node.childNodes), process);
+					return 0;
+				} else {
+					currentWrapElm = dom.clone(wrapElm, FALSE);
+
+					// create a list of the nodes on the same side of the list as the selection
+					each(tinymce.grep(node.childNodes), function(n, index) {
+						if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) {
+							nodes.push(n); 
+							n.parentNode.removeChild(n);
+						}
+					});
+
+					// insert the wrapping element either before or after the list.
+					if (startIndex < listIndex) {
+						node.insertBefore(currentWrapElm, list);
+					} else if (startIndex > listIndex) {
+						node.insertBefore(currentWrapElm, list.nextSibling);
+					}
+					
+					// add the new nodes to the list.
+					newWrappers.push(currentWrapElm);
+
+					each(nodes, function(node) {
+						currentWrapElm.appendChild(node);
+					});
+
+					return currentWrapElm;
+				}
+			};
+
+			function applyRngStyle(rng, bookmark, node_specific) {
+				var newWrappers = [], wrapName, wrapElm, contentEditable = true;
 
 				// Setup wrapper element
 				wrapName = format.inline || format.block;
@@ -14387,7 +16558,18 @@
 					var currentWrapElm;
 
 					function process(node) {
-						var nodeName = node.nodeName.toLowerCase(), parentName = node.parentNode.nodeName.toLowerCase(), found;
+						var nodeName, parentName, found, hasContentEditableState, lastContentEditable;
+
+						lastContentEditable = contentEditable;
+						nodeName = node.nodeName.toLowerCase();
+						parentName = node.parentNode.nodeName.toLowerCase();
+
+						// Node has a contentEditable value
+						if (node.nodeType === 1 && getContentEditable(node)) {
+							lastContentEditable = contentEditable;
+							contentEditable = getContentEditable(node) === "true";
+							hasContentEditableState = true; // We don't want to wrap the container only it's children
+						}
 
 						// Stop wrapping on br elements
 						if (isEq(nodeName, 'br')) {
@@ -14407,7 +16589,7 @@
 						}
 
 						// Can we rename the block
-						if (format.block && !format.wrapper && isTextBlock(nodeName)) {
+						if (contentEditable && !hasContentEditableState && format.block && !format.wrapper && isTextBlock(nodeName)) {
 							node = dom.rename(node, wrapName);
 							setElementFormat(node);
 							newWrappers.push(node);
@@ -14438,22 +16620,29 @@
 						}
 
 						// Is it valid to wrap this item
-						if (isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
-								!(node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279)) {
+						if (contentEditable && !hasContentEditableState && isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
+								!(!node_specific && node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279) && !isCaretNode(node)) {
 							// Start wrapping
 							if (!currentWrapElm) {
 								// Wrap the node
-								currentWrapElm = wrapElm.cloneNode(FALSE);
+								currentWrapElm = dom.clone(wrapElm, FALSE);
 								node.parentNode.insertBefore(currentWrapElm, node);
 								newWrappers.push(currentWrapElm);
 							}
 
 							currentWrapElm.appendChild(node);
+						} else if (nodeName == 'li' && bookmark) {
+							// Start wrapping - if we are in a list node and have a bookmark, then we will always begin by wrapping in a new element.
+							currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process);
 						} else {
 							// Start a new wrapper for possible children
 							currentWrapElm = 0;
-
+							
 							each(tinymce.grep(node.childNodes), process);
+
+							if (hasContentEditableState) {
+								contentEditable = lastContentEditable; // Restore last contentEditable state from stack
+							}
 
 							// End the last wrapper
 							currentWrapElm = 0;
@@ -14471,7 +16660,7 @@
 							var i, currentWrapElm, children;
 
 							if (node.nodeName === 'A') {
-								currentWrapElm = wrapElm.cloneNode(FALSE);
+								currentWrapElm = dom.clone(wrapElm, FALSE);
 								newWrappers.push(currentWrapElm);
 
 								children = tinymce.grep(node.childNodes);
@@ -14489,6 +16678,7 @@
 				}
 
 				// Cleanup
+				
 				each(newWrappers, function(node) {
 					var childCount;
 
@@ -14515,7 +16705,7 @@
 
 						// If child was found and of the same type as the current node
 						if (child && matchName(child, format)) {
-							clone = child.cloneNode(FALSE);
+							clone = dom.clone(child, FALSE);
 							setElementFormat(clone);
 
 							dom.replace(clone, node, TRUE);
@@ -14581,7 +16771,7 @@
 						}
 
 						// Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b>
-						if (node) {
+						if (node && format.merge_siblings !== false) {
 							node = mergeSiblings(getNonWhiteSpaceSibling(node), node);
 							node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));
 						}
@@ -14591,20 +16781,29 @@
 
 			if (format) {
 				if (node) {
-					rng = dom.createRng();
-
-					rng.setStartBefore(node);
-					rng.setEndAfter(node);
-
-					applyRngStyle(expandRng(rng, formatList));
+					if (node.nodeType) {
+						rng = dom.createRng();
+						rng.setStartBefore(node);
+						rng.setEndAfter(node);
+						applyRngStyle(expandRng(rng, formatList), null, true);
+					} else {
+						applyRngStyle(node, null, true);
+					}
 				} else {
 					if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
 						// Obtain selection node before selection is unselected by applyRngStyle()
 						var curSelNode = ed.selection.getNode();
 
+						// If the formats have a default block and we can't find a parent block then start wrapping it with a DIV this is for forced_root_blocks: false
+						// It's kind of a hack but people should be using the default block type P since all desktop editors work that way
+						if (!forcedRootBlock && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
+							apply(formatList[0].defaultBlock);
+						}
+
 						// Apply formatting to selection
+						ed.selection.setRng(adjustSelectionToVisibleSelection());
 						bookmark = selection.getBookmark();
-						applyRngStyle(expandRng(selection.getRng(TRUE), formatList));
+						applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark);
 
 						// Colored nodes should be underlined so that the color of the underline matches the text color.
 						if (format.styles && (format.styles.color || format.styles.textDecoration)) {
@@ -14613,7 +16812,7 @@
 						}
 
 						selection.moveToBookmark(bookmark);
-						selection.setRng(moveStart(selection.getRng(TRUE)));
+						moveStart(selection.getRng(TRUE));
 						ed.nodeChanged();
 					} else
 						performCaretAction('apply', name, vars);
@@ -14622,64 +16821,40 @@
 		};
 
 		function remove(name, vars, node) {
-			var formatList = get(name), format = formatList[0], bookmark, i, rng;
-
-			function moveStart(rng) {
-				var container = rng.startContainer,
-					offset = rng.startOffset,
-					walker, node, nodes, tmpNode;
-
-				// Convert text node into index if possible
-				if (container.nodeType == 3 && offset >= container.nodeValue.length - 1) {
-					container = container.parentNode;
-					offset = nodeIndex(container) + 1;
-				}
-
-				// Move startContainer/startOffset in to a suitable node
-				if (container.nodeType == 1) {
-					nodes = container.childNodes;
-					container = nodes[Math.min(offset, nodes.length - 1)];
-					walker = new TreeWalker(container);
-
-					// If offset is at end of the parent node walk to the next one
-					if (offset > nodes.length - 1)
-						walker.next();
-
-					for (node = walker.current(); node; node = walker.next()) {
-						if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
-							// IE has a "neat" feature where it moves the start node into the closest element
-							// we can avoid this by inserting an element before it and then remove it after we set the selection
-							tmpNode = dom.create('a', null, INVISIBLE_CHAR);
-							node.parentNode.insertBefore(tmpNode, node);
-
-							// Set selection and remove tmpNode
-							rng.setStart(node, 0);
-							selection.setRng(rng);
-							dom.remove(tmpNode);
-
-							return;
-						}
-					}
-				}
-			};
+			var formatList = get(name), format = formatList[0], bookmark, i, rng, contentEditable = true;
 
 			// Merges the styles for each node
 			function process(node) {
-				var children, i, l;
+				var children, i, l, localContentEditable, lastContentEditable, hasContentEditableState;
+
+				// Node has a contentEditable value
+				if (node.nodeType === 1 && getContentEditable(node)) {
+					lastContentEditable = contentEditable;
+					contentEditable = getContentEditable(node) === "true";
+					hasContentEditableState = true; // We don't want to wrap the container only it's children
+				}
 
 				// Grab the children first since the nodelist might be changed
 				children = tinymce.grep(node.childNodes);
 
 				// Process current node
-				for (i = 0, l = formatList.length; i < l; i++) {
-					if (removeFormat(formatList[i], vars, node, node))
-						break;
+				if (contentEditable && !hasContentEditableState) {
+					for (i = 0, l = formatList.length; i < l; i++) {
+						if (removeFormat(formatList[i], vars, node, node))
+							break;
+					}
 				}
 
 				// Process the children
 				if (format.deep) {
-					for (i = 0, l = children.length; i < l; i++)
-						process(children[i]);
+					if (children.length) {					
+						for (i = 0, l = children.length; i < l; i++)
+							process(children[i]);
+
+						if (hasContentEditableState) {
+							contentEditable = lastContentEditable; // Restore last contentEditable state from stack
+						}
+					}
 				}
 			};
 
@@ -14710,7 +16885,7 @@
 					formatRootParent = format_root.parentNode;
 
 					for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {
-						clone = parent.cloneNode(FALSE);
+						clone = dom.clone(parent, FALSE);
 
 						for (i = 0; i < formatList.length; i++) {
 							if (removeFormat(formatList[i], vars, clone, clone)) {
@@ -14765,7 +16940,7 @@
 			};
 
 			function removeRngStyle(rng) {
-				var startContainer, endContainer;
+				var startContainer, endContainer, node;
 
 				rng = expandRng(rng, formatList, TRUE);
 
@@ -14774,6 +16949,12 @@
 					endContainer = getContainer(rng);
 
 					if (startContainer != endContainer) {
+						// WebKit will render the table incorrectly if we wrap a TD in a SPAN so lets see if the can use the first child instead
+						// This will happen if you tripple click a table cell and use remove formatting
+						if (/^(TR|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) {
+							startContainer = (startContainer.nodeName == "TD" ? startContainer.firstChild : startContainer.firstChild.firstChild) || startContainer;
+						}
+
 						// Wrap start/end nodes in span element since these might be cloned/moved
 						startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'});
 						endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'});
@@ -14810,10 +16991,15 @@
 
 			// Handle node
 			if (node) {
-				rng = dom.createRng();
-				rng.setStartBefore(node);
-				rng.setEndAfter(node);
-				removeRngStyle(rng);
+				if (node.nodeType) {
+					rng = dom.createRng();
+					rng.setStartBefore(node);
+					rng.setEndAfter(node);
+					removeRngStyle(rng);
+				} else {
+					removeRngStyle(node);
+				}
+
 				return;
 			}
 
@@ -14823,7 +17009,7 @@
 				selection.moveToBookmark(bookmark);
 
 				// 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
-				if (match(name, vars, selection.getStart())) {
+				if (format.inline && match(name, vars, selection.getStart())) {
 					moveStart(selection.getRng(true));
 				}
 
@@ -14835,7 +17021,7 @@
 		function toggle(name, vars, node) {
 			var fmt = get(name);
 
-			if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0]['toggle']))
+			if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle))
 				remove(name, vars, node);
 			else
 				apply(name, vars, node);
@@ -14847,10 +17033,15 @@
 			function matchItems(node, format, item_name) {
 				var key, value, items = format[item_name], i;
 
+				// Custom match
+				if (format.onmatch) {
+					return format.onmatch(node, format, item_name);
+				}
+
 				// Check all items
 				if (items) {
 					// Non indexed object
-					if (items.length === undefined) {
+					if (items.length === undef) {
 						for (key in items) {
 							if (items.hasOwnProperty(key)) {
 								if (item_name === 'attributes')
@@ -14899,7 +17090,7 @@
 		};
 
 		function match(name, vars, node) {
-			var startNode, i;
+			var startNode;
 
 			function matchParents(node) {
 				// Find first node with similar format settings
@@ -14914,21 +17105,6 @@
 			// Check specified node
 			if (node)
 				return matchParents(node);
-
-			// Check pending formats
-			if (selection.isCollapsed()) {
-				for (i = pendingFormats.apply.length - 1; i >= 0; i--) {
-					if (pendingFormats.apply[i].name == name)
-						return true;
-				}
-
-				for (i = pendingFormats.remove.length - 1; i >= 0; i--) {
-					if (pendingFormats.remove[i].name == name)
-						return false;
-				}
-
-				return matchParents(selection.getNode());
-			}
 
 			// Check selected node
 			node = selection.getNode();
@@ -14948,33 +17124,6 @@
 		function matchAll(names, vars) {
 			var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name;
 
-			// If the selection is collapsed then check pending formats
-			if (selection.isCollapsed()) {
-				for (ni = 0; ni < names.length; ni++) {
-					// If the name is to be removed, then stop it from being added
-					for (i = pendingFormats.remove.length - 1; i >= 0; i--) {
-						name = names[ni];
-
-						if (pendingFormats.remove[i].name == name) {
-							checkedMap[name] = true;
-							break;
-						}
-					}
-				}
-
-				// If the format is to be applied
-				for (i = pendingFormats.apply.length - 1; i >= 0; i--) {
-					for (ni = 0; ni < names.length; ni++) {
-						name = names[ni];
-
-						if (!checkedMap[name] && pendingFormats.apply[i].name == name) {
-							checkedMap[name] = true;
-							matchedFormatNames.push(name);
-						}
-					}
-				}
-			}
-
 			// Check start of selection for formats
 			startElement = selection.getStart();
 			dom.getParent(startElement, function(node) {
@@ -14988,7 +17137,7 @@
 						matchedFormatNames.push(name);
 					}
 				}
-			});
+			}, dom.getRoot());
 
 			return matchedFormatNames;
 		};
@@ -15017,6 +17166,62 @@
 			return FALSE;
 		};
 
+		function formatChanged(formats, callback, similar) {
+			var currentFormats;
+
+			// Setup format node change logic
+			if (!formatChangeData) {
+				formatChangeData = {};
+				currentFormats = {};
+
+				ed.onNodeChange.addToTop(function(ed, cm, node) {
+					var parents = getParents(node), matchedFormats = {};
+
+					// Check for new formats
+					each(formatChangeData, function(callbacks, format) {
+						each(parents, function(node) {
+							if (matchNode(node, format, {}, callbacks.similar)) {
+								if (!currentFormats[format]) {
+									// Execute callbacks
+									each(callbacks, function(callback) {
+										callback(true, {node: node, format: format, parents: parents});
+									});
+
+									currentFormats[format] = callbacks;
+								}
+
+								matchedFormats[format] = callbacks;
+								return false;
+							}
+						});
+					});
+
+					// Check if current formats still match
+					each(currentFormats, function(callbacks, format) {
+						if (!matchedFormats[format]) {
+							delete currentFormats[format];
+
+							each(callbacks, function(callback) {
+								callback(false, {node: node, format: format, parents: parents});
+							});
+						}
+					});
+				});
+			}
+
+			// Add format listeners
+			each(formats.split(','), function(format) {
+				if (!formatChangeData[format]) {
+					formatChangeData[format] = [];
+					formatChangeData[format].similar = similar;
+				}
+
+				formatChangeData[format].push(callback);
+			});
+
+			return this;
+		};
+
 		// Expose to public
 		tinymce.extend(this, {
 			get : get,
@@ -15027,8 +17232,13 @@
 			match : match,
 			matchAll : matchAll,
 			matchNode : matchNode,
-			canApply : canApply
+			canApply : canApply,
+			formatChanged: formatChanged
 		});
+
+		// Initialize
+		defaultFormats();
+		addKeyboardShortcuts();
 
 		// Private functions
 
@@ -15083,7 +17293,7 @@
 		};
 
 		function isWhiteSpaceNode(node) {
-			return node && node.nodeType === 3 && /^([\s\r\n]+|)$/.test(node.nodeValue);
+			return node && node.nodeType === 3 && /^([\t \r\n]+|)$/.test(node.nodeValue);
 		};
 
 		function wrap(node, name, attrs) {
@@ -15096,34 +17306,46 @@
 		};
 
 		function expandRng(rng, format, remove) {
-			var startContainer = rng.startContainer,
+			var sibling, lastIdx, leaf, endPoint,
+				startContainer = rng.startContainer,
 				startOffset = rng.startOffset,
 				endContainer = rng.endContainer,
-				endOffset = rng.endOffset, sibling, lastIdx, leaf;
+				endOffset = rng.endOffset;
 
 			// This function walks up the tree if there is no siblings before/after the node
-			function findParentContainer(container, child_name, sibling_name, root) {
-				var parent, child;
+			function findParentContainer(start) {
+				var container, parent, child, sibling, siblingName, root;
 
-				root = root || dom.getRoot();
+				container = parent = start ? startContainer : endContainer;
+				siblingName = start ? 'previousSibling' : 'nextSibling';
+				root = dom.getRoot();
+
+				// If it's a text node and the offset is inside the text
+				if (container.nodeType == 3 && !isWhiteSpaceNode(container)) {
+					if (start ? startOffset > 0 : endOffset < container.nodeValue.length) {
+						return container;
+					}
+				}
 
 				for (;;) {
-					// Check if we can move up are we at root level or body level
-					parent = container.parentNode;
+					// Stop expanding on block elements
+					if (!format[0].block_expand && isBlock(parent))
+						return parent;
 
-					// Stop expanding on block elements or root depending on format
-					if (parent == root || (!format[0].block_expand && isBlock(parent)))
-						return container;
-
-					for (sibling = parent[child_name]; sibling && sibling != container; sibling = sibling[sibling_name]) {
-						if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
-							return container;
-
-						if (sibling.nodeType == 3 && !isWhiteSpaceNode(sibling))
-							return container;
+					// Walk left/right
+					for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
+						if (!isBookmarkNode(sibling) && !isWhiteSpaceNode(sibling)) {
+							return parent;
+						}
 					}
 
-					container = container.parentNode;
+					// Check if we can move up are we at root level or body level
+					if (parent.parentNode == root) {
+						container = parent;
+						break;
+					}
+
+					parent = parent.parentNode;
 				}
 
 				return container;
@@ -15132,7 +17354,7 @@
 			// This function walks down the tree to find the leaf at the selection.
 			// The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node.
 			function findLeaf(node, offset) {
-				if (offset === undefined)
+				if (offset === undef)
 					offset = node.nodeType === 3 ? node.length : node.childNodes.length;
 				while (node && node.hasChildNodes()) {
 					node = node.childNodes[offset];
@@ -15160,24 +17382,178 @@
 					endOffset = endContainer.nodeValue.length;
 			}
 
-			// Exclude bookmark nodes if possible
-			if (isBookmarkNode(startContainer.parentNode))
-				startContainer = startContainer.parentNode;
+			// Expands the node to the closes contentEditable false element if it exists
+			function findParentContentEditable(node) {
+				var parent = node;
 
-			if (isBookmarkNode(startContainer))
+				while (parent) {
+					if (parent.nodeType === 1 && getContentEditable(parent)) {
+						return getContentEditable(parent) === "false" ? parent : node;
+					}
+
+					parent = parent.parentNode;
+				}
+
+				return node;
+			};
+
+			function findWordEndPoint(container, offset, start) {
+				var walker, node, pos, lastTextNode;
+
+				function findSpace(node, offset) {
+					var pos, pos2, str = node.nodeValue;
+
+					if (typeof(offset) == "undefined") {
+						offset = start ? str.length : 0;
+					}
+
+					if (start) {
+						pos = str.lastIndexOf(' ', offset);
+						pos2 = str.lastIndexOf('\u00a0', offset);
+						pos = pos > pos2 ? pos : pos2;
+
+						// Include the space on remove to avoid tag soup
+						if (pos !== -1 && !remove) {
+							pos++;
+						}
+					} else {
+						pos = str.indexOf(' ', offset);
+						pos2 = str.indexOf('\u00a0', offset);
+						pos = pos !== -1 && (pos2 === -1 || pos < pos2) ? pos : pos2;
+					}
+
+					return pos;
+				};
+
+				if (container.nodeType === 3) {
+					pos = findSpace(container, offset);
+
+					if (pos !== -1) {
+						return {container : container, offset : pos};
+					}
+
+					lastTextNode = container;
+				}
+
+				// Walk the nodes inside the block
+				walker = new TreeWalker(container, dom.getParent(container, isBlock) || ed.getBody());
+				while (node = walker[start ? 'prev' : 'next']()) {
+					if (node.nodeType === 3) {
+						lastTextNode = node;
+						pos = findSpace(node);
+
+						if (pos !== -1) {
+							return {container : node, offset : pos};
+						}
+					} else if (isBlock(node)) {
+						break;
+					}
+				}
+
+				if (lastTextNode) {
+					if (start) {
+						offset = 0;
+					} else {
+						offset = lastTextNode.length;
+					}
+
+					return {container: lastTextNode, offset: offset};
+				}
+			};
+
+			function findSelectorEndPoint(container, sibling_name) {
+				var parents, i, y, curFormat;
+
+				if (container.nodeType == 3 && container.nodeValue.length === 0 && container[sibling_name])
+					container = container[sibling_name];
+
+				parents = getParents(container);
+				for (i = 0; i < parents.length; i++) {
+					for (y = 0; y < format.length; y++) {
+						curFormat = format[y];
+
+						// If collapsed state is set then skip formats that doesn't match that
+						if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed)
+							continue;
+
+						if (dom.is(parents[i], curFormat.selector))
+							return parents[i];
+					}
+				}
+
+				return container;
+			};
+
+			function findBlockEndPoint(container, sibling_name, sibling_name2) {
+				var node;
+
+				// Expand to block of similar type
+				if (!format[0].wrapper)
+					node = dom.getParent(container, format[0].block);
+
+				// Expand to first wrappable block element or any block element
+				if (!node)
+					node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock);
+
+				// Exclude inner lists from wrapping
+				if (node && format[0].wrapper)
+					node = getParents(node, 'ul,ol').reverse()[0] || node;
+
+				// Didn't find a block element look for first/last wrappable element
+				if (!node) {
+					node = container;
+
+					while (node[sibling_name] && !isBlock(node[sibling_name])) {
+						node = node[sibling_name];
+
+						// Break on BR but include it will be removed later on
+						// we can't remove it now since we need to check if it can be wrapped
+						if (isEq(node, 'br'))
+							break;
+					}
+				}
+
+				return node || container;
+			};
+
+			// Expand to closest contentEditable element
+			startContainer = findParentContentEditable(startContainer);
+			endContainer = findParentContentEditable(endContainer);
+
+			// Exclude bookmark nodes if possible
+			if (isBookmarkNode(startContainer.parentNode) || isBookmarkNode(startContainer)) {
+				startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
 				startContainer = startContainer.nextSibling || startContainer;
 
-			if (isBookmarkNode(endContainer.parentNode)) {
-				endOffset = dom.nodeIndex(endContainer);
-				endContainer = endContainer.parentNode;
+				if (startContainer.nodeType == 3)
+					startOffset = 0;
 			}
 
-			if (isBookmarkNode(endContainer) && endContainer.previousSibling) {
-				endContainer = endContainer.previousSibling;
-				endOffset = endContainer.length;
+			if (isBookmarkNode(endContainer.parentNode) || isBookmarkNode(endContainer)) {
+				endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
+				endContainer = endContainer.previousSibling || endContainer;
+
+				if (endContainer.nodeType == 3)
+					endOffset = endContainer.length;
 			}
 
 			if (format[0].inline) {
+				if (rng.collapsed) {
+					// Expand left to closest word boundery
+					endPoint = findWordEndPoint(startContainer, startOffset, true);
+					if (endPoint) {
+						startContainer = endPoint.container;
+						startOffset = endPoint.offset;
+					}
+
+					// Expand right to closest word boundery
+					endPoint = findWordEndPoint(endContainer, endOffset);
+					if (endPoint) {
+						endContainer = endPoint.container;
+						endOffset = endPoint.offset;
+					}
+				}
+
 				// Avoid applying formatting to a trailing space.
 				leaf = findLeaf(endContainer, endOffset);
 				if (leaf.node) {
@@ -15190,47 +17566,27 @@
 						if (leaf.offset > 1) {
 							endContainer = leaf.node;
 							endContainer.splitText(leaf.offset - 1);
-						} else if (leaf.node.previousSibling) {
-							endContainer = leaf.node.previousSibling;
 						}
 					}
 				}
 			}
-			
+
 			// Move start/end point up the tree if the leaves are sharp and if we are in different containers
 			// Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!
 			// This will reduce the number of wrapper elements that needs to be created
 			// Move start point up the tree
 			if (format[0].inline || format[0].block_expand) {
-				startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');
-				endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');
+				if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) {
+					startContainer = findParentContainer(true);
+				}
+
+				if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) {
+					endContainer = findParentContainer();
+				}
 			}
 
 			// Expand start/end container to matching selector
 			if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) {
-				function findSelectorEndPoint(container, sibling_name) {
-					var parents, i, y, curFormat;
-
-					if (container.nodeType == 3 && container.nodeValue.length == 0 && container[sibling_name])
-						container = container[sibling_name];
-
-					parents = getParents(container);
-					for (i = 0; i < parents.length; i++) {
-						for (y = 0; y < format.length; y++) {
-							curFormat = format[y];
-
-							// If collapsed state is set then skip formats that doesn't match that
-							if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed)
-								continue;
-
-							if (dom.is(parents[i], curFormat.selector))
-								return parents[i];
-						}
-					}
-
-					return container;
-				};
-
 				// Find new startContainer/endContainer if there is better one
 				startContainer = findSelectorEndPoint(startContainer, 'previousSibling');
 				endContainer = findSelectorEndPoint(endContainer, 'nextSibling');
@@ -15238,38 +17594,6 @@
 
 			// Expand start/end container to matching block element or text node
 			if (format[0].block || format[0].selector) {
-				function findBlockEndPoint(container, sibling_name, sibling_name2) {
-					var node;
-
-					// Expand to block of similar type
-					if (!format[0].wrapper)
-						node = dom.getParent(container, format[0].block);
-
-					// Expand to first wrappable block element or any block element
-					if (!node)
-						node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock);
-
-					// Exclude inner lists from wrapping
-					if (node && format[0].wrapper)
-						node = getParents(node, 'ul,ol').reverse()[0] || node;
-
-					// Didn't find a block element look for first/last wrappable element
-					if (!node) {
-						node = container;
-
-						while (node[sibling_name] && !isBlock(node[sibling_name])) {
-							node = node[sibling_name];
-
-							// Break on BR but include it will be removed later on
-							// we can't remove it now since we need to check if it can be wrapped
-							if (isEq(node, 'br'))
-								break;
-						}
-					}
-
-					return node || container;
-				};
-
 				// Find new startContainer/endContainer if there is better one
 				startContainer = findBlockEndPoint(startContainer, 'previousSibling');
 				endContainer = findBlockEndPoint(endContainer, 'nextSibling');
@@ -15277,10 +17601,10 @@
 				// Non block element then try to expand up the leaf
 				if (format[0].block) {
 					if (!isBlock(startContainer))
-						startContainer = findParentContainer(startContainer, 'firstChild', 'nextSibling');
+						startContainer = findParentContainer(true);
 
 					if (!isBlock(endContainer))
-						endContainer = findParentContainer(endContainer, 'lastChild', 'previousSibling');
+						endContainer = findParentContainer();
 				}
 			}
 
@@ -15406,14 +17730,14 @@
 		function removeNode(node, format) {
 			var parentNode = node.parentNode, rootBlockElm;
 
+			function find(node, next, inc) {
+				node = getNonWhiteSpaceSibling(node, next, inc);
+
+				return !node || (node.nodeName == 'BR' || isBlock(node));
+			};
+
 			if (format.block) {
 				if (!forcedRootBlock) {
-					function find(node, next, inc) {
-						node = getNonWhiteSpaceSibling(node, next, inc);
-
-						return !node || (node.nodeName == 'BR' || isBlock(node));
-					};
-
 					// Append BR elements if needed before we remove the block
 					if (isBlock(node) && !isBlock(parentNode)) {
 						if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1))
@@ -15493,7 +17817,7 @@
 							value = obj2[name];
 
 							// Obj2 doesn't have obj1 item
-							if (value === undefined)
+							if (value === undef)
 								return FALSE;
 
 							// Obj2 item has a different value
@@ -15526,20 +17850,20 @@
 				return TRUE;
 			};
 
+			function findElementSibling(node, sibling_name) {
+				for (sibling = node; sibling; sibling = sibling[sibling_name]) {
+					if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0)
+						return node;
+
+					if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
+						return sibling;
+				}
+
+				return node;
+			};
+
 			// Check if next/prev exists and that they are elements
 			if (prev && next) {
-				function findElementSibling(node, sibling_name) {
-					for (sibling = node; sibling; sibling = sibling[sibling_name]) {
-						if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0)
-							return node;
-
-						if (sibling.nodeType == 1 && !isBookmarkNode(sibling))
-							return sibling;
-					}
-
-					return node;
-				};
-
 				// If previous sibling is empty then jump over it
 				prev = findElementSibling(prev, 'previousSibling');
 				next = findElementSibling(next, 'nextSibling');
@@ -15573,7 +17897,7 @@
 		};
 
 		function getContainer(rng, start) {
-			var container, offset, lastIdx;
+			var container, offset, lastIdx, walker;
 
 			container = rng[start ? 'startContainer' : 'endContainer'];
 			offset = rng[start ? 'startOffset' : 'endOffset'];
@@ -15587,106 +17911,334 @@
 				container = container.childNodes[offset > lastIdx ? lastIdx : offset];
 			}
 
+			// If start text node is excluded then walk to the next node
+			if (container.nodeType === 3 && start && offset >= container.nodeValue.length) {
+				container = new TreeWalker(container, ed.getBody()).next() || container;
+			}
+
+			// If end text node is excluded then walk to the previous node
+			if (container.nodeType === 3 && !start && offset === 0) {
+				container = new TreeWalker(container, ed.getBody()).prev() || container;
+			}
+
 			return container;
 		};
 
 		function performCaretAction(type, name, vars) {
-			var i, currentPendingFormats = pendingFormats[type],
-				otherPendingFormats = pendingFormats[type == 'apply' ? 'remove' : 'apply'];
+			var caretContainerId = '_mce_caret', debug = ed.settings.caret_debug;
 
-			function hasPending() {
-				return pendingFormats.apply.length || pendingFormats.remove.length;
+			// Creates a caret container bogus element
+			function createCaretContainer(fill) {
+				var caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style: debug ? 'color:red' : ''});
+
+				if (fill) {
+					caretContainer.appendChild(ed.getDoc().createTextNode(INVISIBLE_CHAR));
+				}
+
+				return caretContainer;
 			};
 
-			function resetPending() {
-				pendingFormats.apply = [];
-				pendingFormats.remove = [];
+			function isCaretContainerEmpty(node, nodes) {
+				while (node) {
+					if ((node.nodeType === 3 && node.nodeValue !== INVISIBLE_CHAR) || node.childNodes.length > 1) {
+						return false;
+					}
+
+					// Collect nodes
+					if (nodes && node.nodeType === 1) {
+						nodes.push(node);
+					}
+
+					node = node.firstChild;
+				}
+
+				return true;
+			};
+			
+			// Returns any parent caret container element
+			function getParentCaretContainer(node) {
+				while (node) {
+					if (node.id === caretContainerId) {
+						return node;
+					}
+
+					node = node.parentNode;
+				}
 			};
 
-			function perform(caret_node) {
-				// Apply pending formats
-				each(pendingFormats.apply.reverse(), function(item) {
-					apply(item.name, item.vars, caret_node);
+			// Finds the first text node in the specified node
+			function findFirstTextNode(node) {
+				var walker;
 
-					// Colored nodes should be underlined so that the color of the underline matches the text color.
-					if (item.name === 'forecolor' && item.vars.value)
-						processUnderlineAndColor(caret_node.parentNode);
-				});
+				if (node) {
+					walker = new TreeWalker(node, node);
 
-				// Remove pending formats
-				each(pendingFormats.remove.reverse(), function(item) {
-					remove(item.name, item.vars, caret_node);
-				});
-
-				dom.remove(caret_node, 1);
-				resetPending();
+					for (node = walker.current(); node; node = walker.next()) {
+						if (node.nodeType === 3) {
+							return node;
+						}
+					}
+				}
 			};
 
-			// Check if it already exists then ignore it
-			for (i = currentPendingFormats.length - 1; i >= 0; i--) {
-				if (currentPendingFormats[i].name == name)
+			// Removes the caret container for the specified node or all on the current document
+			function removeCaretContainer(node, move_caret) {
+				var child, rng;
+
+				if (!node) {
+					node = getParentCaretContainer(selection.getStart());
+
+					if (!node) {
+						while (node = dom.get(caretContainerId)) {
+							removeCaretContainer(node, false);
+						}
+					}
+				} else {
+					rng = selection.getRng(true);
+
+					if (isCaretContainerEmpty(node)) {
+						if (move_caret !== false) {
+							rng.setStartBefore(node);
+							rng.setEndBefore(node);
+						}
+
+						dom.remove(node);
+					} else {
+						child = findFirstTextNode(node);
+
+						if (child.nodeValue.charAt(0) === INVISIBLE_CHAR) {
+							child = child.deleteData(0, 1);
+						}
+
+						dom.remove(node, 1);
+					}
+
+					selection.setRng(rng);
+				}
+			};
+			
+			// Applies formatting to the caret postion
+			function applyCaretFormat() {
+				var rng, caretContainer, textNode, offset, bookmark, container, text;
+
+				rng = selection.getRng(true);
+				offset = rng.startOffset;
+				container = rng.startContainer;
+				text = container.nodeValue;
+
+				caretContainer = getParentCaretContainer(selection.getStart());
+				if (caretContainer) {
+					textNode = findFirstTextNode(caretContainer);
+				}
+
+				// Expand to word is caret is in the middle of a text node and the char before/after is a alpha numeric character
+				if (text && offset > 0 && offset < text.length && /\w/.test(text.charAt(offset)) && /\w/.test(text.charAt(offset - 1))) {
+					// Get bookmark of caret position
+					bookmark = selection.getBookmark();
+
+					// Collapse bookmark range (WebKit)
+					rng.collapse(true);
+
+					// Expand the range to the closest word and split it at those points
+					rng = expandRng(rng, get(name));
+					rng = rangeUtils.split(rng);
+
+					// Apply the format to the range
+					apply(name, vars, rng);
+
+					// Move selection back to caret position
+					selection.moveToBookmark(bookmark);
+				} else {
+					if (!caretContainer || textNode.nodeValue !== INVISIBLE_CHAR) {
+						caretContainer = createCaretContainer(true);
+						textNode = caretContainer.firstChild;
+
+						rng.insertNode(caretContainer);
+						offset = 1;
+
+						apply(name, vars, caretContainer);
+					} else {
+						apply(name, vars, caretContainer);
+					}
+
+					// Move selection to text node
+					selection.setCursorLocation(textNode, offset);
+				}
+			};
+
+			function removeCaretFormat() {
+				var rng = selection.getRng(true), container, offset, bookmark,
+					hasContentAfter, node, formatNode, parents = [], i, caretContainer;
+
+				container = rng.startContainer;
+				offset = rng.startOffset;
+				node = container;
+
+				if (container.nodeType == 3) {
+					if (offset != container.nodeValue.length || container.nodeValue === INVISIBLE_CHAR) {
+						hasContentAfter = true;
+					}
+
+					node = node.parentNode;
+				}
+
+				while (node) {
+					if (matchNode(node, name, vars)) {
+						formatNode = node;
+						break;
+					}
+
+					if (node.nextSibling) {
+						hasContentAfter = true;
+					}
+
+					parents.push(node);
+					node = node.parentNode;
+				}
+
+				// Node doesn't have the specified format
+				if (!formatNode) {
 					return;
-			}
+				}
 
-			currentPendingFormats.push({name : name, vars : vars});
+				// Is there contents after the caret then remove the format on the element
+				if (hasContentAfter) {
+					// Get bookmark of caret position
+					bookmark = selection.getBookmark();
 
-			// Check if it's in the other type, then remove it
-			for (i = otherPendingFormats.length - 1; i >= 0; i--) {
-				if (otherPendingFormats[i].name == name)
-					otherPendingFormats.splice(i, 1);
-			}
+					// Collapse bookmark range (WebKit)
+					rng.collapse(true);
 
-			// Pending apply or remove formats
-			if (hasPending()) {
-				ed.getDoc().execCommand('FontName', false, 'mceinline');
-				pendingFormats.lastRng = selection.getRng();
+					// Expand the range to the closest word and split it at those points
+					rng = expandRng(rng, get(name), true);
+					rng = rangeUtils.split(rng);
 
-				// IE will convert the current word
-				each(dom.select('font,span'), function(node) {
-					var bookmark;
+					// Remove the format from the range
+					remove(name, vars, rng);
 
-					if (isCaretNode(node)) {
-						bookmark = selection.getBookmark();
-						perform(node);
-						selection.moveToBookmark(bookmark);
-						ed.nodeChanged();
+					// Move selection back to caret position
+					selection.moveToBookmark(bookmark);
+				} else {
+					caretContainer = createCaretContainer();
+
+					node = caretContainer;
+					for (i = parents.length - 1; i >= 0; i--) {
+						node.appendChild(dom.clone(parents[i], false));
+						node = node.firstChild;
+					}
+
+					// Insert invisible character into inner most format element
+					node.appendChild(dom.doc.createTextNode(INVISIBLE_CHAR));
+					node = node.firstChild;
+
+					// Insert caret container after the formated node
+					dom.insertAfter(caretContainer, formatNode);
+
+					// Move selection to text node
+					selection.setCursorLocation(node, 1);
+				}
+			};
+
+			// Checks if the parent caret container node isn't empty if that is the case it
+			// will remove the bogus state on all children that isn't empty
+			function unmarkBogusCaretParents() {
+				var i, caretContainer, node;
+
+				caretContainer = getParentCaretContainer(selection.getStart());
+				if (caretContainer && !dom.isEmpty(caretContainer)) {
+					tinymce.walk(caretContainer, function(node) {
+						if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) {
+							dom.setAttrib(node, 'data-mce-bogus', null);
+						}
+					}, 'childNodes');
+				}
+			};
+
+			// Only bind the caret events once
+			if (!self._hasCaretEvents) {
+				// Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements
+				ed.onBeforeGetContent.addToTop(function() {
+					var nodes = [], i;
+
+					if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) {
+						// Mark children
+						i = nodes.length;
+						while (i--) {
+							dom.setAttrib(nodes[i], 'data-mce-bogus', '1');
+						}
 					}
 				});
 
-				// Only register listeners once if we need to
-				if (!pendingFormats.isListening && hasPending()) {
-					pendingFormats.isListening = true;
-
-					each('onKeyDown,onKeyUp,onKeyPress,onMouseUp'.split(','), function(event) {
-						ed[event].addToTop(function(ed, e) {
-							// Do we have pending formats and is the selection moved has moved
-							if (hasPending() && !tinymce.dom.RangeUtils.compareRanges(pendingFormats.lastRng, selection.getRng())) {
-								each(dom.select('font,span'), function(node) {
-									var textNode, rng;
-
-									// Look for marker
-									if (isCaretNode(node)) {
-										textNode = node.firstChild;
-
-										if (textNode) {
-											perform(node);
-
-											rng = dom.createRng();
-											rng.setStart(textNode, textNode.nodeValue.length);
-											rng.setEnd(textNode, textNode.nodeValue.length);
-											selection.setRng(rng);
-											ed.nodeChanged();
-										} else
-											dom.remove(node);
-									}
-								});
-
-								// Always unbind and clear pending styles on keyup
-								if (e.type == 'keyup' || e.type == 'mouseup')
-									resetPending();
-							}
-						});
+				// Remove caret container on mouse up and on key up
+				tinymce.each('onMouseUp onKeyUp'.split(' '), function(name) {
+					ed[name].addToTop(function() {
+						removeCaretContainer();
+						unmarkBogusCaretParents();
 					});
+				});
+
+				// Remove caret container on keydown and it's a backspace, enter or left/right arrow keys
+				ed.onKeyDown.addToTop(function(ed, e) {
+					var keyCode = e.keyCode;
+
+					if (keyCode == 8 || keyCode == 37 || keyCode == 39) {
+						removeCaretContainer(getParentCaretContainer(selection.getStart()));
+					}
+
+					unmarkBogusCaretParents();
+				});
+
+				// Remove bogus state if they got filled by contents using editor.selection.setContent
+				selection.onSetContent.add(unmarkBogusCaretParents);
+
+				self._hasCaretEvents = true;
+			}
+
+			// Do apply or remove caret format
+			if (type == "apply") {
+				applyCaretFormat();
+			} else {
+				removeCaretFormat();
+			}
+		};
+
+		function moveStart(rng) {
+			var container = rng.startContainer,
+					offset = rng.startOffset, isAtEndOfText,
+					walker, node, nodes, tmpNode;
+
+			// Convert text node into index if possible
+			if (container.nodeType == 3 && offset >= container.nodeValue.length) {
+				// Get the parent container location and walk from there
+				offset = nodeIndex(container);
+				container = container.parentNode;
+				isAtEndOfText = true;
+			}
+
+			// Move startContainer/startOffset in to a suitable node
+			if (container.nodeType == 1) {
+				nodes = container.childNodes;
+				container = nodes[Math.min(offset, nodes.length - 1)];
+				walker = new TreeWalker(container, dom.getParent(container, dom.isBlock));
+
+				// If offset is at end of the parent node walk to the next one
+				if (offset > nodes.length - 1 || isAtEndOfText)
+					walker.next();
+
+				for (node = walker.current(); node; node = walker.next()) {
+					if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
+						// IE has a "neat" feature where it moves the start node into the closest element
+						// we can avoid this by inserting an element before it and then remove it after we set the selection
+						tmpNode = dom.create('a', null, INVISIBLE_CHAR);
+						node.parentNode.insertBefore(tmpNode, node);
+
+						// Set selection and remove tmpNode
+						rng.setStart(node, 0);
+						selection.setRng(rng);
+						dom.remove(tmpNode);
+
+						return;
+					}
 				}
 			}
 		};
@@ -15696,17 +18248,27 @@
 tinymce.onAddEditor.add(function(tinymce, ed) {
 	var filters, fontSizes, dom, settings = ed.settings;
 
-	if (settings.inline_styles) {
-		fontSizes = tinymce.explode(settings.font_size_style_values);
+	function replaceWithSpan(node, styles) {
+		tinymce.each(styles, function(value, name) {
+			if (value)
+				dom.setStyle(node, name, value);
+		});
 
-		function replaceWithSpan(node, styles) {
-			tinymce.each(styles, function(value, name) {
-				if (value)
-					dom.setStyle(node, name, value);
+		dom.rename(node, 'span');
+	};
+
+	function convert(editor, params) {
+		dom = editor.dom;
+
+		if (settings.convert_fonts_to_spans) {
+			tinymce.each(dom.select('font,u,strike', params.node), function(node) {
+				filters[node.nodeName.toLowerCase()](ed.dom, node);
 			});
+		}
+	};
 
-			dom.rename(node, 'span');
-		};
+	if (settings.inline_styles) {
+		fontSizes = tinymce.explode(settings.font_size_legacy_values);
 
 		filters = {
 			font : function(dom, node) {
@@ -15714,7 +18276,7 @@
 					backgroundColor : node.style.backgroundColor,
 					color : node.color,
 					fontFamily : node.face,
-					fontSize : fontSizes[parseInt(node.size) - 1]
+					fontSize : fontSizes[parseInt(node.size, 10) - 1]
 				});
 			},
 
@@ -15731,16 +18293,6 @@
 			}
 		};
 
-		function convert(editor, params) {
-			dom = editor.dom;
-
-			if (settings.convert_fonts_to_spans) {
-				tinymce.each(dom.select('font,u,strike', params.node), function(node) {
-					filters[node.nodeName.toLowerCase()](ed.dom, node);
-				});
-			}
-		};
-
 		ed.onPreProcess.add(convert);
 		ed.onSetContent.add(convert);
 
@@ -15750,3 +18302,558 @@
 	}
 });
 
+(function(tinymce) {
+	var TreeWalker = tinymce.dom.TreeWalker;
+
+	tinymce.EnterKey = function(editor) {
+		var dom = editor.dom, selection = editor.selection, settings = editor.settings, undoManager = editor.undoManager, nonEmptyElementsMap = editor.schema.getNonEmptyElements();
+
+		function handleEnterKey(evt) {
+			var rng = selection.getRng(true), tmpRng, editableRoot, container, offset, parentBlock, documentMode, shiftKey,
+				newBlock, fragment, containerBlock, parentBlockName, containerBlockName, newBlockName, isAfterLastNodeInContainer;
+
+			// Returns true if the block can be split into two blocks or not
+			function canSplitBlock(node) {
+				return node &&
+					dom.isBlock(node) &&
+					!/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) &&
+					!/^(fixed|absolute)/i.test(node.style.position) && 
+					dom.getContentEditable(node) !== "true";
+			};
+
+			// Renders empty block on IE
+			function renderBlockOnIE(block) {
+				var oldRng;
+
+				if (tinymce.isIE && dom.isBlock(block)) {
+					oldRng = selection.getRng();
+					block.appendChild(dom.create('span', null, '\u00a0'));
+					selection.select(block);
+					block.lastChild.outerHTML = '';
+					selection.setRng(oldRng);
+				}
+			};
+
+			// Remove the first empty inline element of the block so this: <p><b><em></em></b>x</p> becomes this: <p>x</p>
+			function trimInlineElementsOnLeftSideOfBlock(block) {
+				var node = block, firstChilds = [], i;
+
+				// Find inner most first child ex: <p><i><b>*</b></i></p>
+				while (node = node.firstChild) {
+					if (dom.isBlock(node)) {
+						return;
+					}
+
+					if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
+						firstChilds.push(node);
+					}
+				}
+
+				i = firstChilds.length;
+				while (i--) {
+					node = firstChilds[i];
+					if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) {
+						dom.remove(node);
+					} else {
+						// Remove <a> </a> see #5381
+						if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') {
+							dom.remove(node);
+						}
+					}
+				}
+			};
+			
+			// Moves the caret to a suitable position within the root for example in the first non pure whitespace text node or before an image
+			function moveToCaretPosition(root) {
+				var walker, node, rng, y, viewPort, lastNode = root, tempElm;
+
+				rng = dom.createRng();
+
+				if (root.hasChildNodes()) {
+					walker = new TreeWalker(root, root);
+
+					while (node = walker.current()) {
+						if (node.nodeType == 3) {
+							rng.setStart(node, 0);
+							rng.setEnd(node, 0);
+							break;
+						}
+
+						if (nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
+							rng.setStartBefore(node);
+							rng.setEndBefore(node);
+							break;
+						}
+
+						lastNode = node;
+						node = walker.next();
+					}
+
+					if (!node) {
+						rng.setStart(lastNode, 0);
+						rng.setEnd(lastNode, 0);
+					}
+				} else {
+					if (root.nodeName == 'BR') {
+						if (root.nextSibling && dom.isBlock(root.nextSibling)) {
+							// Trick on older IE versions to render the caret before the BR between two lists
+							if (!documentMode || documentMode < 9) {
+								tempElm = dom.create('br');
+								root.parentNode.insertBefore(tempElm, root);
+							}
+
+							rng.setStartBefore(root);
+							rng.setEndBefore(root);
+						} else {
+							rng.setStartAfter(root);
+							rng.setEndAfter(root);
+						}
+					} else {
+						rng.setStart(root, 0);
+						rng.setEnd(root, 0);
+					}
+				}
+
+				selection.setRng(rng);
+
+				// Remove tempElm created for old IE:s
+				dom.remove(tempElm);
+
+				viewPort = dom.getViewPort(editor.getWin());
+
+				// 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
+				y = dom.getPos(root).y;
+				if (y < viewPort.y || y + 25 > viewPort.y + viewPort.h) {
+					editor.getWin().scrollTo(0, y < viewPort.y ? y : y - viewPort.h + 25); // Needs to be hardcoded to roughly one line of text if a huge text block is broken into two blocks
+				}
+			};
+
+			// Creates a new block element by cloning the current one or creating a new one if the name is specified
+			// This function will also copy any text formatting from the parent block and add it to the new one
+			function createNewBlock(name) {
+				var node = container, block, clonedNode, caretNode;
+
+				block = name || parentBlockName == "TABLE" ? dom.create(name || newBlockName) : parentBlock.cloneNode(false);
+				caretNode = block;
+
+				// Clone any parent styles
+				if (settings.keep_styles !== false) {
+					do {
+						if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {
+							clonedNode = node.cloneNode(false);
+							dom.setAttrib(clonedNode, 'id', ''); // Remove ID since it needs to be document unique
+
+							if (block.hasChildNodes()) {
+								clonedNode.appendChild(block.firstChild);
+								block.appendChild(clonedNode);
+							} else {
+								caretNode = clonedNode;
+								block.appendChild(clonedNode);
+							}
+						}
+					} while (node = node.parentNode);
+				}
+
+				// BR is needed in empty blocks on non IE browsers
+				if (!tinymce.isIE) {
+					caretNode.innerHTML = '<br>';
+				}
+
+				return block;
+			};
+
+			// Returns true/false if the caret is at the start/end of the parent block element
+			function isCaretAtStartOrEndOfBlock(start) {
+				var walker, node, name;
+
+				// Caret is in the middle of a text node like "a|b"
+				if (container.nodeType == 3 && (start ? offset > 0 : offset < container.nodeValue.length)) {
+					return false;
+				}
+
+				// If after the last element in block node edge case for #5091
+				if (container.parentNode == parentBlock && isAfterLastNodeInContainer && !start) {
+					return true;
+				}
+
+				// If the caret if before the first element in parentBlock
+				if (start && container.nodeType == 1 && container == parentBlock.firstChild) {
+					return true;
+				}
+
+				// Caret can be before/after a table
+				if (container.nodeName === "TABLE" || (container.previousSibling && container.previousSibling.nodeName == "TABLE")) {
+					return (isAfterLastNodeInContainer && !start) || (!isAfterLastNodeInContainer && start);
+				}
+
+				// Walk the DOM and look for text nodes or non empty elements
+				walker = new TreeWalker(container, parentBlock);
+	
+				// If caret is in beginning or end of a text block then jump to the next/previous node
+				if (container.nodeType == 3) {
+					if (start && offset == 0) {
+						walker.prev();
+					} else if (!start && offset == container.nodeValue.length) {
+						walker.next();
+					}
+				}
+
+				while (node = walker.current()) {
+					if (node.nodeType === 1) {
+						// Ignore bogus elements
+						if (!node.getAttribute('data-mce-bogus')) {
+							// Keep empty elements like <img /> <input /> but not trailing br:s like <p>text|<br></p>
+							name = node.nodeName.toLowerCase();
+							if (nonEmptyElementsMap[name] && name !== 'br') {
+								return false;
+							}
+						}
+					} else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) {
+						return false;
+					}
+
+					if (start) {
+						walker.prev();
+					} else {
+						walker.next();
+					}
+				}
+
+				return true;
+			};
+
+			// Wraps any text nodes or inline elements in the specified forced root block name
+			function wrapSelfAndSiblingsInDefaultBlock(container, offset) {
+				var newBlock, parentBlock, startNode, node, next, blockName = newBlockName || 'P';
+
+				// Not in a block element or in a table cell or caption
+				parentBlock = dom.getParent(container, dom.isBlock);
+				if (!parentBlock || !canSplitBlock(parentBlock)) {
+					parentBlock = parentBlock || editableRoot;
+
+					if (!parentBlock.hasChildNodes()) {
+						newBlock = dom.create(blockName);
+						parentBlock.appendChild(newBlock);
+						rng.setStart(newBlock, 0);
+						rng.setEnd(newBlock, 0);
+						return newBlock;
+					}
+
+					// Find parent that is the first child of parentBlock
+					node = container;
+					while (node.parentNode != parentBlock) {
+						node = node.parentNode;
+					}
+
+					// Loop left to find start node start wrapping at
+					while (node && !dom.isBlock(node)) {
+						startNode = node;
+						node = node.previousSibling;
+					}
+
+					if (startNode) {
+						newBlock = dom.create(blockName);
+						startNode.parentNode.insertBefore(newBlock, startNode);
+
+						// Start wrapping until we hit a block
+						node = startNode;
+						while (node && !dom.isBlock(node)) {
+							next = node.nextSibling;
+							newBlock.appendChild(node);
+							node = next;
+						}
+
+						// Restore range to it's past location
+						rng.setStart(container, offset);
+						rng.setEnd(container, offset);
+					}
+				}
+
+				return container;
+			};
+
+			// Inserts a block or br before/after or in the middle of a split list of the LI is empty
+			function handleEmptyListItem() {
+				function isFirstOrLastLi(first) {
+					var node = containerBlock[first ? 'firstChild' : 'lastChild'];
+
+					// Find first/last element since there might be whitespace there
+					while (node) {
+						if (node.nodeType == 1) {
+							break;
+						}
+
+						node = node[first ? 'nextSibling' : 'previousSibling'];
+					}
+
+					return node === parentBlock;
+				};
+
+				newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
+
+				if (isFirstOrLastLi(true) && isFirstOrLastLi()) {
+					// Is first and last list item then replace the OL/UL with a text block
+					dom.replace(newBlock, containerBlock);
+				} else if (isFirstOrLastLi(true)) {
+					// First LI in list then remove LI and add text block before list
+					containerBlock.parentNode.insertBefore(newBlock, containerBlock);
+				} else if (isFirstOrLastLi()) {
+					// Last LI in list then temove LI and add text block after list
+					dom.insertAfter(newBlock, containerBlock);
+					renderBlockOnIE(newBlock);
+				} else {
+					// Middle LI in list the split the list and insert a text block in the middle
+					// Extract after fragment and insert it after the current block
+					tmpRng = rng.cloneRange();
+					tmpRng.setStartAfter(parentBlock);
+					tmpRng.setEndAfter(containerBlock);
+					fragment = tmpRng.extractContents();
+					dom.insertAfter(fragment, containerBlock);
+					dom.insertAfter(newBlock, containerBlock);
+				}
+
+				dom.remove(parentBlock);
+				moveToCaretPosition(newBlock);
+				undoManager.add();
+			};
+
+			// Walks the parent block to the right and look for BR elements
+			function hasRightSideBr() {
+				var walker = new TreeWalker(container, parentBlock), node;
+
+				while (node = walker.current()) {
+					if (node.nodeName == 'BR') {
+						return true;
+					}
+
+					node = walker.next();
+				}
+			}
+			
+			// Inserts a BR element if the forced_root_block option is set to false or empty string
+			function insertBr() {
+				var brElm, extraBr;
+
+				if (container && container.nodeType == 3 && offset >= container.nodeValue.length) {
+					// Insert extra BR element at the end block elements
+					if (!tinymce.isIE && !hasRightSideBr()) {
+						brElm = dom.create('br');
+						rng.insertNode(brElm);
+						rng.setStartAfter(brElm);
+						rng.setEndAfter(brElm);
+						extraBr = true;
+					}
+				}
+
+				brElm = dom.create('br');
+				rng.insertNode(brElm);
+
+				// Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it
+				if (tinymce.isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) {
+					brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm);
+				}
+
+				if (!extraBr) {
+					rng.setStartAfter(brElm);
+					rng.setEndAfter(brElm);
+				} else {
+					rng.setStartBefore(brElm);
+					rng.setEndBefore(brElm);
+				}
+
+				selection.setRng(rng);
+				undoManager.add();
+			};
+
+			// Trims any linebreaks at the beginning of node user for example when pressing enter in a PRE element
+			function trimLeadingLineBreaks(node) {
+				do {
+					if (node.nodeType === 3) {
+						node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
+					}
+
+					node = node.firstChild;
+				} while (node);
+			};
+
+			function getEditableRoot(node) {
+				var root = dom.getRoot(), parent, editableRoot;
+
+				// Get all parents until we hit a non editable parent or the root
+				parent = node;
+				while (parent !== root && dom.getContentEditable(parent) !== "false") {
+					if (dom.getContentEditable(parent) === "true") {
+						editableRoot = parent;
+					}
+
+					parent = parent.parentNode;
+				}
+				
+				return parent !== root ? editableRoot : root;
+			};
+
+			// Adds a BR at the end of blocks that only contains an IMG or INPUT since these might be floated and then they won't expand the block
+			function addBrToBlockIfNeeded(block) {
+				var lastChild;
+
+				// IE will render the blocks correctly other browsers needs a BR
+				if (!tinymce.isIE) {
+					block.normalize(); // Remove empty text nodes that got left behind by the extract
+
+					// Check if the block is empty or contains a floated last child
+					lastChild = block.lastChild;
+					if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) {
+						dom.add(block, 'br');
+					}
+				}
+			};
+
+			// Delete any selected contents
+			if (!rng.collapsed) {
+				editor.execCommand('Delete');
+				return;
+			}
+
+			// Event is blocked by some other handler for example the lists plugin
+			if (evt.isDefaultPrevented()) {
+				return;
+			}
+
+			// Setup range items and newBlockName
+			container = rng.startContainer;
+			offset = rng.startOffset;
+			newBlockName = (settings.force_p_newlines ? 'p' : '') || settings.forced_root_block;
+			newBlockName = newBlockName ? newBlockName.toUpperCase() : '';
+			documentMode = dom.doc.documentMode;
+			shiftKey = evt.shiftKey;
+
+			// Resolve node index
+			if (container.nodeType == 1 && container.hasChildNodes()) {
+				isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
+				container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
+				if (isAfterLastNodeInContainer && container.nodeType == 3) {
+					offset = container.nodeValue.length;
+				} else {
+					offset = 0;
+				}
+			}
+
+			// Get editable root node normaly the body element but sometimes a div or span
+			editableRoot = getEditableRoot(container);
+
+			// If there is no editable root then enter is done inside a contentEditable false element
+			if (!editableRoot) {
+				return;
+			}
+
+			undoManager.beforeChange();
+
+			// If editable root isn't block nor the root of the editor
+			if (!dom.isBlock(editableRoot) && editableRoot != dom.getRoot()) {
+				if (!newBlockName || shiftKey) {
+					insertBr();
+				}
+
+				return;
+			}
+
+			// Wrap the current node and it's sibling in a default block if it's needed.
+			// for example this <td>text|<b>text2</b></td> will become this <td><p>text|<b>text2</p></b></td>
+			// This won't happen if root blocks are disabled or the shiftKey is pressed
+			if ((newBlockName && !shiftKey) || (!newBlockName && shiftKey)) {
+				container = wrapSelfAndSiblingsInDefaultBlock(container, offset);
+			}
+
+			// Find parent block and setup empty block paddings
+			parentBlock = dom.getParent(container, dom.isBlock);
+			containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
+
+			// Setup block names
+			parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
+			containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
+
+			// Handle enter in LI
+			if (parentBlockName == 'LI') {
+				if (!newBlockName && shiftKey) {
+					insertBr();
+					return;
+				}
+
+				// Handle enter inside an empty list item
+				if (dom.isEmpty(parentBlock)) {
+					// Let the list plugin or browser handle nested lists for now
+					if (/^(UL|OL|LI)$/.test(containerBlock.parentNode.nodeName)) {
+						return false;
+					}
+
+					handleEmptyListItem();
+					return;
+				}
+			}
+
+			// Don't split PRE tags but insert a BR instead easier when writing code samples etc
+			if (parentBlockName == 'PRE' && settings.br_in_pre !== false) {
+				if (!shiftKey) {
+					insertBr();
+					return;
+				}
+			} else {
+				// If no root block is configured then insert a BR by default or if the shiftKey is pressed
+				if ((!newBlockName && !shiftKey && parentBlockName != 'LI') || (newBlockName && shiftKey)) {
+					insertBr();
+					return;
+				}
+			}
+
+			// Default block name if it's not configured
+			newBlockName = newBlockName || 'P';
+
+			// Insert new block before/after the parent block depending on caret location
+			if (isCaretAtStartOrEndOfBlock()) {
+				// If the caret is at the end of a header we produce a P tag after it similar to Word unless we are in a hgroup
+				if (/^(H[1-6]|PRE)$/.test(parentBlockName) && containerBlockName != 'HGROUP') {
+					newBlock = createNewBlock(newBlockName);
+				} else {
+					newBlock = createNewBlock();
+				}
+
+				// Split the current container block element if enter is pressed inside an empty inner block element
+				if (settings.end_container_on_empty_block && canSplitBlock(containerBlock) && dom.isEmpty(parentBlock)) {
+					// Split container block for example a BLOCKQUOTE at the current blockParent location for example a P
+					newBlock = dom.split(containerBlock, parentBlock);
+				} else {
+					dom.insertAfter(newBlock, parentBlock);
+				}
+
+				moveToCaretPosition(newBlock);
+			} else if (isCaretAtStartOrEndOfBlock(true)) {
+				// Insert new block before
+				newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
+				renderBlockOnIE(newBlock);
+			} else {
+				// Extract after fragment and insert it after the current block
+				tmpRng = rng.cloneRange();
+				tmpRng.setEndAfter(parentBlock);
+				fragment = tmpRng.extractContents();
+				trimLeadingLineBreaks(fragment);
+				newBlock = fragment.firstChild;
+				dom.insertAfter(fragment, parentBlock);
+				trimInlineElementsOnLeftSideOfBlock(newBlock);
+				addBrToBlockIfNeeded(parentBlock);
+				moveToCaretPosition(newBlock);
+			}
+
+			dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique
+			undoManager.add();
+		}
+
+		editor.onKeyDown.add(function(ed, evt) {
+			if (evt.keyCode == 13) {
+				if (handleEnterKey(evt) !== false) {
+					evt.preventDefault();
+				}
+			}
+		});
+	};
+})(tinymce);
+

--
Gitblit v1.9.1