<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">/*!
 * jQuery JavaScript Library v3.6.1
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2022-08-26T17:52Z
 */
( function( global, factory ) {

	"use strict";

	if ( typeof module === "object" &amp;&amp; typeof module.exports === "object" ) {

		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket trac-14549 for more info.
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}

// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

// Edge &lt;= 12 - 13+, Firefox &lt;=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";

var arr = [];

var getProto = Object.getPrototypeOf;

var slice = arr.slice;

var flat = arr.flat ? function( array ) {
	return arr.flat.call( array );
} : function( array ) {
	return arr.concat.apply( [], array );
};


var push = arr.push;

var indexOf = arr.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var fnToString = hasOwn.toString;

var ObjectFunctionString = fnToString.call( Object );

var support = {};

var isFunction = function isFunction( obj ) {

		// Support: Chrome &lt;=57, Firefox &lt;=52
		// In some browsers, typeof returns "function" for HTML &lt;object&gt; elements
		// (i.e., `typeof document.createElement( "object" ) === "function"`).
		// We don't want to classify *any* DOM node as a function.
		// Support: QtWeb &lt;=3.8.5, WebKit &lt;=534.34, wkhtmltopdf tool &lt;=0.12.5
		// Plus for old WebKit, typeof returns "function" for HTML collections
		// (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
		return typeof obj === "function" &amp;&amp; typeof obj.nodeType !== "number" &amp;&amp;
			typeof obj.item !== "function";
	};


var isWindow = function isWindow( obj ) {
		return obj != null &amp;&amp; obj === obj.window;
	};


var document = window.document;



	var preservedScriptAttributes = {
		type: true,
		src: true,
		nonce: true,
		noModule: true
	};

	function DOMEval( code, node, doc ) {
		doc = doc || document;

		var i, val,
			script = doc.createElement( "script" );

		script.text = code;
		if ( node ) {
			for ( i in preservedScriptAttributes ) {

				// Support: Firefox 64+, Edge 18+
				// Some browsers don't support the "nonce" property on scripts.
				// On the other hand, just using `getAttribute` is not enough as
				// the `nonce` attribute is reset to an empty string whenever it
				// becomes browsing-context connected.
				// See https://github.com/whatwg/html/issues/2369
				// See https://html.spec.whatwg.org/#nonce-attributes
				// The `node.getAttribute` check was added for the sake of
				// `jQuery.globalEval` so that it can fake a nonce-containing node
				// via an object.
				val = node[ i ] || node.getAttribute &amp;&amp; node.getAttribute( i );
				if ( val ) {
					script.setAttribute( i, val );
				}
			}
		}
		doc.head.appendChild( script ).parentNode.removeChild( script );
	}


function toType( obj ) {
	if ( obj == null ) {
		return obj + "";
	}

	// Support: Android &lt;=2.3 only (functionish RegExp)
	return typeof obj === "object" || typeof obj === "function" ?
		class2type[ toString.call( obj ) ] || "object" :
		typeof obj;
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module



var
	version = "3.6.1",

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	};

jQuery.fn = jQuery.prototype = {

	// The current version of jQuery being used
	jquery: version,

	constructor: jQuery,

	// The default length of a jQuery object is 0
	length: 0,

	toArray: function() {
		return slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {

		// Return all the elements in a clean array
		if ( num == null ) {
			return slice.call( this );
		}

		// Return just the one element from the set
		return num &lt; 0 ? this[ num + this.length ] : this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	each: function( callback ) {
		return jQuery.each( this, callback );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map( this, function( elem, i ) {
			return callback.call( elem, i, elem );
		} ) );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	even: function() {
		return this.pushStack( jQuery.grep( this, function( _elem, i ) {
			return ( i + 1 ) % 2;
		} ) );
	},

	odd: function() {
		return this.pushStack( jQuery.grep( this, function( _elem, i ) {
			return i % 2;
		} ) );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i &lt; 0 ? len : 0 );
		return this.pushStack( j &gt;= 0 &amp;&amp; j &lt; len ? [ this[ j ] ] : [] );
	},

	end: function() {
		return this.prevObject || this.constructor();
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: arr.sort,
	splice: arr.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// Skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" &amp;&amp; !isFunction( target ) ) {
		target = {};
	}

	// Extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i &lt; length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				copy = options[ name ];

				// Prevent Object.prototype pollution
				// Prevent never-ending loop
				if ( name === "__proto__" || target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep &amp;&amp; copy &amp;&amp; ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = Array.isArray( copy ) ) ) ) {
					src = target[ name ];

					// Ensure proper type for the source value
					if ( copyIsArray &amp;&amp; !Array.isArray( src ) ) {
						clone = [];
					} else if ( !copyIsArray &amp;&amp; !jQuery.isPlainObject( src ) ) {
						clone = {};
					} else {
						clone = src;
					}
					copyIsArray = false;

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	isPlainObject: function( obj ) {
		var proto, Ctor;

		// Detect obvious negatives
		// Use toString instead of jQuery.type to catch host objects
		if ( !obj || toString.call( obj ) !== "[object Object]" ) {
			return false;
		}

		proto = getProto( obj );

		// Objects with no prototype (e.g., `Object.create( null )`) are plain
		if ( !proto ) {
			return true;
		}

		// Objects with prototype are plain iff they were constructed by a global Object function
		Ctor = hasOwn.call( proto, "constructor" ) &amp;&amp; proto.constructor;
		return typeof Ctor === "function" &amp;&amp; fnToString.call( Ctor ) === ObjectFunctionString;
	},

	isEmptyObject: function( obj ) {
		var name;

		for ( name in obj ) {
			return false;
		}
		return true;
	},

	// Evaluates a script in a provided context; falls back to the global one
	// if not specified.
	globalEval: function( code, options, doc ) {
		DOMEval( code, { nonce: options &amp;&amp; options.nonce }, doc );
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i &lt; length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
						[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		return arr == null ? -1 : indexOf.call( arr, elem, i );
	},

	// Support: Android &lt;=4.0 only, PhantomJS 1 only
	// push.apply(_, arraylike) throws on ancient WebKit
	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		for ( ; j &lt; len; j++ ) {
			first[ i++ ] = second[ j ];
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i &lt; length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i &lt; length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return flat( ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

if ( typeof Symbol === "function" ) {
	jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
	function( _i, name ) {
		class2type[ "[object " + name + "]" ] = name.toLowerCase();
	} );

function isArrayLike( obj ) {

	// Support: real iOS 8.2 only (not reproducible in simulator)
	// `in` check used to prevent JIT error (gh-2145)
	// hasOwn isn't used here due to false negatives
	// regarding Nodelist length in IE
	var length = !!obj &amp;&amp; "length" in obj &amp;&amp; obj.length,
		type = toType( obj );

	if ( isFunction( obj ) || isWindow( obj ) ) {
		return false;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" &amp;&amp; length &gt; 0 &amp;&amp; ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.3.6
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://js.foundation/
 *
 * Date: 2021-02-16
 */
( function( window ) {
var i,
	support,
	Expr,
	getText,
	isXML,
	tokenize,
	compile,
	select,
	outermostContext,
	sortInput,
	hasDuplicate,

	// Local document vars
	setDocument,
	document,
	docElem,
	documentIsHTML,
	rbuggyQSA,
	rbuggyMatches,
	matches,
	contains,

	// Instance-specific data
	expando = "sizzle" + 1 * new Date(),
	preferredDoc = window.document,
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),
	nonnativeSelectorCache = createCache(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	// Instance methods
	hasOwn = ( {} ).hasOwnProperty,
	arr = [],
	pop = arr.pop,
	pushNative = arr.push,
	push = arr.push,
	slice = arr.slice,

	// Use a stripped-down indexOf as it's faster than native
	// https://jsperf.com/thor-indexof-vs-for/5
	indexOf = function( list, elem ) {
		var i = 0,
			len = list.length;
		for ( ; i &lt; len; i++ ) {
			if ( list[ i ] === elem ) {
				return i;
			}
		}
		return -1;
	},

	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" +
		"ismap|loop|multiple|open|readonly|required|scoped",

	// Regular expressions

	// http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",

	// https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
	identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace +
		"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +

		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +

		// "Attribute values must be CSS identifiers [capture 5]
		// or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" +
		whitespace + "*\\]",

	pseudos = ":(" + identifier + ")(?:\\((" +

		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +

		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +

		// 3. anything else (capture 2)
		".*" +
		")\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rwhitespace = new RegExp( whitespace + "+", "g" ),
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" +
		whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([&gt;+~]|" + whitespace + ")" + whitespace +
		"*" ),
	rdescend = new RegExp( whitespace + "|&gt;" ),

	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		"ID": new RegExp( "^#(" + identifier + ")" ),
		"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
		"TAG": new RegExp( "^(" + identifier + "|[*])" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" +
			whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" +
			whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),

		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		"needsContext": new RegExp( "^" + whitespace +
			"*[&gt;+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
			"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rhtml = /HTML$/i,
	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	rnative = /^[^{]+\{\s*\[native \w/,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rsibling = /[+~]/,

	// CSS escapes
	// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ),
	funescape = function( escape, nonHex ) {
		var high = "0x" + escape.slice( 1 ) - 0x10000;

		return nonHex ?

			// Strip the backslash prefix from a non-hex escape sequence
			nonHex :

			// Replace a hexadecimal escape sequence with the encoded Unicode code point
			// Support: IE &lt;=11+
			// For values outside the Basic Multilingual Plane (BMP), manually construct a
			// surrogate pair
			high &lt; 0 ?
				String.fromCharCode( high + 0x10000 ) :
				String.fromCharCode( high &gt;&gt; 10 | 0xD800, high &amp; 0x3FF | 0xDC00 );
	},

	// CSS string/identifier serialization
	// https://drafts.csswg.org/cssom/#common-serializing-idioms
	rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
	fcssescape = function( ch, asCodePoint ) {
		if ( asCodePoint ) {

			// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
			if ( ch === "\0" ) {
				return "\uFFFD";
			}

			// Control characters and (dependent upon position) numbers get escaped as code points
			return ch.slice( 0, -1 ) + "\\" +
				ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
		}

		// Other potentially-special ASCII characters get backslash-escaped
		return "\\" + ch;
	},

	// Used for iframes
	// See setDocument()
	// Removing the function wrapper causes a "Permission Denied"
	// error in IE
	unloadHandler = function() {
		setDocument();
	},

	inDisabledFieldset = addCombinator(
		function( elem ) {
			return elem.disabled === true &amp;&amp; elem.nodeName.toLowerCase() === "fieldset";
		},
		{ dir: "parentNode", next: "legend" }
	);

// Optimize for push.apply( _, NodeList )
try {
	push.apply(
		( arr = slice.call( preferredDoc.childNodes ) ),
		preferredDoc.childNodes
	);

	// Support: Android&lt;4.0
	// Detect silently failing push.apply
	// eslint-disable-next-line no-unused-expressions
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = { apply: arr.length ?

		// Leverage slice if possible
		function( target, els ) {
			pushNative.apply( target, slice.call( els ) );
		} :

		// Support: IE&lt;9
		// Otherwise append directly
		function( target, els ) {
			var j = target.length,
				i = 0;

			// Can't trust NodeList.length
			while ( ( target[ j++ ] = els[ i++ ] ) ) {}
			target.length = j - 1;
		}
	};
}

function Sizzle( selector, context, results, seed ) {
	var m, i, elem, nid, match, groups, newSelector,
		newContext = context &amp;&amp; context.ownerDocument,

		// nodeType defaults to 9, since context defaults to document
		nodeType = context ? context.nodeType : 9;

	results = results || [];

	// Return early from calls with invalid selector or context
	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 &amp;&amp; nodeType !== 9 &amp;&amp; nodeType !== 11 ) {

		return results;
	}

	// Try to shortcut find operations (as opposed to filters) in HTML documents
	if ( !seed ) {
		setDocument( context );
		context = context || document;

		if ( documentIsHTML ) {

			// If the selector is sufficiently simple, try using a "get*By*" DOM method
			// (excepting DocumentFragment context, where the methods don't exist)
			if ( nodeType !== 11 &amp;&amp; ( match = rquickExpr.exec( selector ) ) ) {

				// ID selector
				if ( ( m = match[ 1 ] ) ) {

					// Document context
					if ( nodeType === 9 ) {
						if ( ( elem = context.getElementById( m ) ) ) {

							// Support: IE, Opera, Webkit
							// TODO: identify versions
							// getElementById can match elements by name instead of ID
							if ( elem.id === m ) {
								results.push( elem );
								return results;
							}
						} else {
							return results;
						}

					// Element context
					} else {

						// Support: IE, Opera, Webkit
						// TODO: identify versions
						// getElementById can match elements by name instead of ID
						if ( newContext &amp;&amp; ( elem = newContext.getElementById( m ) ) &amp;&amp;
							contains( context, elem ) &amp;&amp;
							elem.id === m ) {

							results.push( elem );
							return results;
						}
					}

				// Type selector
				} else if ( match[ 2 ] ) {
					push.apply( results, context.getElementsByTagName( selector ) );
					return results;

				// Class selector
				} else if ( ( m = match[ 3 ] ) &amp;&amp; support.getElementsByClassName &amp;&amp;
					context.getElementsByClassName ) {

					push.apply( results, context.getElementsByClassName( m ) );
					return results;
				}
			}

			// Take advantage of querySelectorAll
			if ( support.qsa &amp;&amp;
				!nonnativeSelectorCache[ selector + " " ] &amp;&amp;
				( !rbuggyQSA || !rbuggyQSA.test( selector ) ) &amp;&amp;

				// Support: IE 8 only
				// Exclude object elements
				( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) {

				newSelector = selector;
				newContext = context;

				// qSA considers elements outside a scoping root when evaluating child or
				// descendant combinators, which is not what we want.
				// In such cases, we work around the behavior by prefixing every selector in the
				// list with an ID selector referencing the scope context.
				// The technique has to be used as well when a leading combinator is used
				// as such selectors are not recognized by querySelectorAll.
				// Thanks to Andrew Dupont for this technique.
				if ( nodeType === 1 &amp;&amp;
					( rdescend.test( selector ) || rcombinators.test( selector ) ) ) {

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) &amp;&amp; testContext( context.parentNode ) ||
						context;

					// We can use :scope instead of the ID hack if the browser
					// supports it &amp; if we're not changing the context.
					if ( newContext !== context || !support.scope ) {

						// Capture the context ID, setting it first if necessary
						if ( ( nid = context.getAttribute( "id" ) ) ) {
							nid = nid.replace( rcssescape, fcssescape );
						} else {
							context.setAttribute( "id", ( nid = expando ) );
						}
					}

					// Prefix every selector in the list
					groups = tokenize( selector );
					i = groups.length;
					while ( i-- ) {
						groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
							toSelector( groups[ i ] );
					}
					newSelector = groups.join( "," );
				}

				try {
					push.apply( results,
						newContext.querySelectorAll( newSelector )
					);
					return results;
				} catch ( qsaError ) {
					nonnativeSelectorCache( selector, true );
				} finally {
					if ( nid === expando ) {
						context.removeAttribute( "id" );
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed );
}

/**
 * Create key-value caches of limited size
 * @returns {function(string, object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var keys = [];

	function cache( key, value ) {

		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
		if ( keys.push( key + " " ) &gt; Expr.cacheLength ) {

			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return ( cache[ key + " " ] = value );
	}
	return cache;
}

/**
 * Mark a function for special use by Sizzle
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created element and returns a boolean result
 */
function assert( fn ) {
	var el = document.createElement( "fieldset" );

	try {
		return !!fn( el );
	} catch ( e ) {
		return false;
	} finally {

		// Remove from its parent by default
		if ( el.parentNode ) {
			el.parentNode.removeChild( el );
		}

		// release memory in IE
		el = null;
	}
}

/**
 * Adds the same handler for all of the specified attrs
 * @param {String} attrs Pipe-separated list of attributes
 * @param {Function} handler The method that will be applied
 */
function addHandle( attrs, handler ) {
	var arr = attrs.split( "|" ),
		i = arr.length;

	while ( i-- ) {
		Expr.attrHandle[ arr[ i ] ] = handler;
	}
}

/**
 * Checks document order of two siblings
 * @param {Element} a
 * @param {Element} b
 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
 */
function siblingCheck( a, b ) {
	var cur = b &amp;&amp; a,
		diff = cur &amp;&amp; a.nodeType === 1 &amp;&amp; b.nodeType === 1 &amp;&amp;
			a.sourceIndex - b.sourceIndex;

	// Use IE sourceIndex if available on both nodes
	if ( diff ) {
		return diff;
	}

	// Check if b follows a
	if ( cur ) {
		while ( ( cur = cur.nextSibling ) ) {
			if ( cur === b ) {
				return -1;
			}
		}
	}

	return a ? 1 : -1;
}

/**
 * Returns a function to use in pseudos for input types
 * @param {String} type
 */
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" &amp;&amp; elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for buttons
 * @param {String} type
 */
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return ( name === "input" || name === "button" ) &amp;&amp; elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for :enabled/:disabled
 * @param {Boolean} disabled true for :disabled; false for :enabled
 */
function createDisabledPseudo( disabled ) {

	// Known :disabled false positives: fieldset[disabled] &gt; legend:nth-of-type(n+2) :can-disable
	return function( elem ) {

		// Only certain elements can match :enabled or :disabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
		if ( "form" in elem ) {

			// Check for inherited disabledness on relevant non-disabled elements:
			// * listed form-associated elements in a disabled fieldset
			//   https://html.spec.whatwg.org/multipage/forms.html#category-listed
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
			// * option elements in a disabled optgroup
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
			// All such elements have a "form" property.
			if ( elem.parentNode &amp;&amp; elem.disabled === false ) {

				// Option elements defer to a parent optgroup if present
				if ( "label" in elem ) {
					if ( "label" in elem.parentNode ) {
						return elem.parentNode.disabled === disabled;
					} else {
						return elem.disabled === disabled;
					}
				}

				// Support: IE 6 - 11
				// Use the isDisabled shortcut property to check for disabled fieldset ancestors
				return elem.isDisabled === disabled ||

					// Where there is no isDisabled, check manually
					/* jshint -W018 */
					elem.isDisabled !== !disabled &amp;&amp;
					inDisabledFieldset( elem ) === disabled;
			}

			return elem.disabled === disabled;

		// Try to winnow out elements that can't be disabled before trusting the disabled property.
		// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
		// even exist on them, let alone have a boolean value.
		} else if ( "label" in elem ) {
			return elem.disabled === disabled;
		}

		// Remaining elements are neither :enabled nor :disabled
		return false;
	};
}

/**
 * Returns a function to use in pseudos for positionals
 * @param {Function} fn
 */
function createPositionalPseudo( fn ) {
	return markFunction( function( argument ) {
		argument = +argument;
		return markFunction( function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
					seed[ j ] = !( matches[ j ] = seed[ j ] );
				}
			}
		} );
	} );
}

/**
 * Checks a node for validity as a Sizzle context
 * @param {Element|Object=} context
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */
function testContext( context ) {
	return context &amp;&amp; typeof context.getElementsByTagName !== "undefined" &amp;&amp; context;
}

// Expose support vars for convenience
support = Sizzle.support = {};

/**
 * Detects XML nodes
 * @param {Element|Object} elem An element or a document
 * @returns {Boolean} True iff elem is a non-HTML XML node
 */
isXML = Sizzle.isXML = function( elem ) {
	var namespace = elem &amp;&amp; elem.namespaceURI,
		docElem = elem &amp;&amp; ( elem.ownerDocument || elem ).documentElement;

	// Support: IE &lt;=8
	// Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
	// https://bugs.jquery.com/ticket/4833
	return !rhtml.test( namespace || docElem &amp;&amp; docElem.nodeName || "HTML" );
};

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [doc] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
setDocument = Sizzle.setDocument = function( node ) {
	var hasCompare, subWindow,
		doc = node ? node.ownerDocument || node : preferredDoc;

	// Return early if doc is invalid or already selected
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Update global variables
	document = doc;
	docElem = document.documentElement;
	documentIsHTML = !isXML( document );

	// Support: IE 9 - 11+, Edge 12 - 18+
	// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( preferredDoc != document &amp;&amp;
		( subWindow = document.defaultView ) &amp;&amp; subWindow.top !== subWindow ) {

		// Support: IE 11, Edge
		if ( subWindow.addEventListener ) {
			subWindow.addEventListener( "unload", unloadHandler, false );

		// Support: IE 9 - 10 only
		} else if ( subWindow.attachEvent ) {
			subWindow.attachEvent( "onunload", unloadHandler );
		}
	}

	// Support: IE 8 - 11+, Edge 12 - 18+, Chrome &lt;=16 - 25 only, Firefox &lt;=3.6 - 31 only,
	// Safari 4 - 5 only, Opera &lt;=11.6 - 12.x only
	// IE/Edge &amp; older browsers don't support the :scope pseudo-class.
	// Support: Safari 6.0 only
	// Safari 6.0 supports :scope but it's an alias of :root there.
	support.scope = assert( function( el ) {
		docElem.appendChild( el ).appendChild( document.createElement( "div" ) );
		return typeof el.querySelectorAll !== "undefined" &amp;&amp;
			!el.querySelectorAll( ":scope fieldset div" ).length;
	} );

	/* Attributes
	---------------------------------------------------------------------- */

	// Support: IE&lt;8
	// Verify that getAttribute really returns attributes and not properties
	// (excepting IE8 booleans)
	support.attributes = assert( function( el ) {
		el.className = "i";
		return !el.getAttribute( "className" );
	} );

	/* getElement(s)By*
	---------------------------------------------------------------------- */

	// Check if getElementsByTagName("*") returns only elements
	support.getElementsByTagName = assert( function( el ) {
		el.appendChild( document.createComment( "" ) );
		return !el.getElementsByTagName( "*" ).length;
	} );

	// Support: IE&lt;9
	support.getElementsByClassName = rnative.test( document.getElementsByClassName );

	// Support: IE&lt;10
	// Check if getElementById returns elements by name
	// The broken getElementById methods don't pick up programmatically-set names,
	// so use a roundabout getElementsByName test
	support.getById = assert( function( el ) {
		docElem.appendChild( el ).id = expando;
		return !document.getElementsByName || !document.getElementsByName( expando ).length;
	} );

	// ID filter and find
	if ( support.getById ) {
		Expr.filter[ "ID" ] = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute( "id" ) === attrId;
			};
		};
		Expr.find[ "ID" ] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" &amp;&amp; documentIsHTML ) {
				var elem = context.getElementById( id );
				return elem ? [ elem ] : [];
			}
		};
	} else {
		Expr.filter[ "ID" ] =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== "undefined" &amp;&amp;
					elem.getAttributeNode( "id" );
				return node &amp;&amp; node.value === attrId;
			};
		};

		// Support: IE 6 - 7 only
		// getElementById is not reliable as a find shortcut
		Expr.find[ "ID" ] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" &amp;&amp; documentIsHTML ) {
				var node, i, elems,
					elem = context.getElementById( id );

				if ( elem ) {

					// Verify the id attribute
					node = elem.getAttributeNode( "id" );
					if ( node &amp;&amp; node.value === id ) {
						return [ elem ];
					}

					// Fall back on getElementsByName
					elems = context.getElementsByName( id );
					i = 0;
					while ( ( elem = elems[ i++ ] ) ) {
						node = elem.getAttributeNode( "id" );
						if ( node &amp;&amp; node.value === id ) {
							return [ elem ];
						}
					}
				}

				return [];
			}
		};
	}

	// Tag
	Expr.find[ "TAG" ] = support.getElementsByTagName ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( tag );

			// DocumentFragment nodes don't have gEBTN
			} else if ( support.qsa ) {
				return context.querySelectorAll( tag );
			}
		} :

		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,

				// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( ( elem = results[ i++ ] ) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Class
	Expr.find[ "CLASS" ] = support.getElementsByClassName &amp;&amp; function( className, context ) {
		if ( typeof context.getElementsByClassName !== "undefined" &amp;&amp; documentIsHTML ) {
			return context.getElementsByClassName( className );
		}
	};

	/* QSA/matchesSelector
	---------------------------------------------------------------------- */

	// QSA and matchesSelector support

	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
	rbuggyMatches = [];

	// qSa(:focus) reports false when true (Chrome 21)
	// We allow this because of a bug in IE8/9 that throws an error
	// whenever `document.activeElement` is accessed on an iframe
	// So, we allow :focus to pass through QSA all the time to avoid the IE error
	// See https://bugs.jquery.com/ticket/13378
	rbuggyQSA = [];

	if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) {

		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert( function( el ) {

			var input;

			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explicitly
			// setting a boolean content attribute,
			// since its presence should be enough
			// https://bugs.jquery.com/ticket/12359
			docElem.appendChild( el ).innerHTML = "&lt;a id='" + expando + "'&gt;&lt;/a&gt;" +
				"&lt;select id='" + expando + "-\r\\' msallowcapture=''&gt;" +
				"&lt;option selected=''&gt;&lt;/option&gt;&lt;/select&gt;";

			// Support: IE8, Opera 11-12.16
			// Nothing should be selected when empty strings follow ^= or $= or *=
			// The test attribute must be unknown in Opera but "safe" for WinRT
			// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
			if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
			}

			// Support: IE8
			// Boolean attributes and "value" are not treated correctly
			if ( !el.querySelectorAll( "[selected]" ).length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
			}

			// Support: Chrome&lt;29, Android&lt;4.4, Safari&lt;7.0+, iOS&lt;7.0+, PhantomJS&lt;1.9.8+
			if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
				rbuggyQSA.push( "~=" );
			}

			// Support: IE 11+, Edge 15 - 18+
			// IE 11/Edge don't find elements on a `[name='']` query in some cases.
			// Adding a temporary attribute to the document before the selection works
			// around the issue.
			// Interestingly, IE 10 &amp; older don't seem to have the issue.
			input = document.createElement( "input" );
			input.setAttribute( "name", "" );
			el.appendChild( input );
			if ( !el.querySelectorAll( "[name='']" ).length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" +
					whitespace + "*(?:''|\"\")" );
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here and will not see later tests
			if ( !el.querySelectorAll( ":checked" ).length ) {
				rbuggyQSA.push( ":checked" );
			}

			// Support: Safari 8+, iOS 8+
			// https://bugs.webkit.org/show_bug.cgi?id=136851
			// In-page `selector#id sibling-combinator selector` fails
			if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
				rbuggyQSA.push( ".#.+[+~]" );
			}

			// Support: Firefox &lt;=3.6 - 5 only
			// Old Firefox doesn't throw on a badly-escaped identifier.
			el.querySelectorAll( "\\\f" );
			rbuggyQSA.push( "[\\r\\n\\f]" );
		} );

		assert( function( el ) {
			el.innerHTML = "&lt;a href='' disabled='disabled'&gt;&lt;/a&gt;" +
				"&lt;select disabled='disabled'&gt;&lt;option/&gt;&lt;/select&gt;";

			// Support: Windows 8 Native Apps
			// The type and name attributes are restricted during .innerHTML assignment
			var input = document.createElement( "input" );
			input.setAttribute( "type", "hidden" );
			el.appendChild( input ).setAttribute( "name", "D" );

			// Support: IE8
			// Enforce case-sensitivity of name attribute
			if ( el.querySelectorAll( "[name=d]" ).length ) {
				rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here and will not see later tests
			if ( el.querySelectorAll( ":enabled" ).length !== 2 ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Support: IE9-11+
			// IE's :disabled selector does not pick up the children of disabled fieldsets
			docElem.appendChild( el ).disabled = true;
			if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Support: Opera 10 - 11 only
			// Opera 10-11 does not throw on post-comma invalid pseudos
			el.querySelectorAll( "*,:x" );
			rbuggyQSA.push( ",.*:" );
		} );
	}

	if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches ||
		docElem.webkitMatchesSelector ||
		docElem.mozMatchesSelector ||
		docElem.oMatchesSelector ||
		docElem.msMatchesSelector ) ) ) ) {

		assert( function( el ) {

			// Check to see if it's possible to do matchesSelector
			// on a disconnected node (IE 9)
			support.disconnectedMatch = matches.call( el, "*" );

			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( el, "[s!='']:x" );
			rbuggyMatches.push( "!=", pseudos );
		} );
	}

	rbuggyQSA = rbuggyQSA.length &amp;&amp; new RegExp( rbuggyQSA.join( "|" ) );
	rbuggyMatches = rbuggyMatches.length &amp;&amp; new RegExp( rbuggyMatches.join( "|" ) );

	/* Contains
	---------------------------------------------------------------------- */
	hasCompare = rnative.test( docElem.compareDocumentPosition );

	// Element contains another
	// Purposefully self-exclusive
	// As in, an element does not contain itself
	contains = hasCompare || rnative.test( docElem.contains ) ?
		function( a, b ) {
			var adown = a.nodeType === 9 ? a.documentElement : a,
				bup = b &amp;&amp; b.parentNode;
			return a === bup || !!( bup &amp;&amp; bup.nodeType === 1 &amp;&amp; (
				adown.contains ?
					adown.contains( bup ) :
					a.compareDocumentPosition &amp;&amp; a.compareDocumentPosition( bup ) &amp; 16
			) );
		} :
		function( a, b ) {
			if ( b ) {
				while ( ( b = b.parentNode ) ) {
					if ( b === a ) {
						return true;
					}
				}
			}
			return false;
		};

	/* Sorting
	---------------------------------------------------------------------- */

	// Document order sorting
	sortOrder = hasCompare ?
	function( a, b ) {

		// Flag for duplicate removal
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		// Sort on method existence if only one input has compareDocumentPosition
		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
		if ( compare ) {
			return compare;
		}

		// Calculate position if both inputs belong to the same document
		// Support: IE 11+, Edge 17 - 18+
		// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
		// two documents; shallow comparisons work.
		// eslint-disable-next-line eqeqeq
		compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?
			a.compareDocumentPosition( b ) :

			// Otherwise we know they are disconnected
			1;

		// Disconnected nodes
		if ( compare &amp; 1 ||
			( !support.sortDetached &amp;&amp; b.compareDocumentPosition( a ) === compare ) ) {

			// Choose the first element that is related to our preferred document
			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			if ( a == document || a.ownerDocument == preferredDoc &amp;&amp;
				contains( preferredDoc, a ) ) {
				return -1;
			}

			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			if ( b == document || b.ownerDocument == preferredDoc &amp;&amp;
				contains( preferredDoc, b ) ) {
				return 1;
			}

			// Maintain original order
			return sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;
		}

		return compare &amp; 4 ? -1 : 1;
	} :
	function( a, b ) {

		// Exit early if the nodes are identical
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		var cur,
			i = 0,
			aup = a.parentNode,
			bup = b.parentNode,
			ap = [ a ],
			bp = [ b ];

		// Parentless nodes are either documents or disconnected
		if ( !aup || !bup ) {

			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			/* eslint-disable eqeqeq */
			return a == document ? -1 :
				b == document ? 1 :
				/* eslint-enable eqeqeq */
				aup ? -1 :
				bup ? 1 :
				sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;

		// If the nodes are siblings, we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		}

		// Otherwise we need full lists of their ancestors for comparison
		cur = a;
		while ( ( cur = cur.parentNode ) ) {
			ap.unshift( cur );
		}
		cur = b;
		while ( ( cur = cur.parentNode ) ) {
			bp.unshift( cur );
		}

		// Walk down the tree looking for a discrepancy
		while ( ap[ i ] === bp[ i ] ) {
			i++;
		}

		return i ?

			// Do a sibling check if the nodes have a common ancestor
			siblingCheck( ap[ i ], bp[ i ] ) :

			// Otherwise nodes in our document sort first
			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			/* eslint-disable eqeqeq */
			ap[ i ] == preferredDoc ? -1 :
			bp[ i ] == preferredDoc ? 1 :
			/* eslint-enable eqeqeq */
			0;
	};

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	setDocument( elem );

	if ( support.matchesSelector &amp;&amp; documentIsHTML &amp;&amp;
		!nonnativeSelectorCache[ expr + " " ] &amp;&amp;
		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &amp;&amp;
		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {

		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||

				// As well, disconnected nodes are said to be in a document
				// fragment in IE 9
				elem.document &amp;&amp; elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch ( e ) {
			nonnativeSelectorCache( expr, true );
		}
	}

	return Sizzle( expr, document, null, [ elem ] ).length &gt; 0;
};

Sizzle.contains = function( context, elem ) {

	// Set document vars if needed
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( ( context.ownerDocument || context ) != document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {

	// Set document vars if needed
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( ( elem.ownerDocument || elem ) != document ) {
		setDocument( elem );
	}

	var fn = Expr.attrHandle[ name.toLowerCase() ],

		// Don't get fooled by Object.prototype properties (jQuery #13807)
		val = fn &amp;&amp; hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
			fn( elem, name, !documentIsHTML ) :
			undefined;

	return val !== undefined ?
		val :
		support.attributes || !documentIsHTML ?
			elem.getAttribute( name ) :
			( val = elem.getAttributeNode( name ) ) &amp;&amp; val.specified ?
				val.value :
				null;
};

Sizzle.escape = function( sel ) {
	return ( sel + "" ).replace( rcssescape, fcssescape );
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Document sorting and removing duplicates
 * @param {ArrayLike} results
 */
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		j = 0,
		i = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	hasDuplicate = !support.detectDuplicates;
	sortInput = !support.sortStable &amp;&amp; results.slice( 0 );
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		while ( ( elem = results[ i++ ] ) ) {
			if ( elem === results[ i ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	// Clear input after sorting to release objects
	// See https://github.com/jquery/sizzle/pull/225
	sortInput = null;

	return results;
};

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( !nodeType ) {

		// If no nodeType, this is expected to be an array
		while ( ( node = elem[ i++ ] ) ) {

			// Do not traverse comment nodes
			ret += getText( node );
		}
	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {

		// Use textContent for elements
		// innerText usage removed for consistency of new lines (jQuery #11153)
		if ( typeof elem.textContent === "string" ) {
			return elem.textContent;
		} else {

			// Traverse its children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				ret += getText( elem );
			}
		}
	} else if ( nodeType === 3 || nodeType === 4 ) {
		return elem.nodeValue;
	}

	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		"&gt;": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[ 1 ] = match[ 1 ].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[ 3 ] = ( match[ 3 ] || match[ 4 ] ||
				match[ 5 ] || "" ).replace( runescape, funescape );

			if ( match[ 2 ] === "~=" ) {
				match[ 3 ] = " " + match[ 3 ] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {

			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[ 1 ] = match[ 1 ].toLowerCase();

			if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {

				// nth-* requires argument
				if ( !match[ 3 ] ) {
					Sizzle.error( match[ 0 ] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[ 4 ] = +( match[ 4 ] ?
					match[ 5 ] + ( match[ 6 ] || 1 ) :
					2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) );
				match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );

				// other types prohibit arguments
			} else if ( match[ 3 ] ) {
				Sizzle.error( match[ 0 ] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var excess,
				unquoted = !match[ 6 ] &amp;&amp; match[ 2 ];

			if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[ 3 ] ) {
				match[ 2 ] = match[ 4 ] || match[ 5 ] || "";

			// Strip excess characters from unquoted arguments
			} else if ( unquoted &amp;&amp; rpseudo.test( unquoted ) &amp;&amp;

				// Get excess from tokenize (recursively)
				( excess = tokenize( unquoted, true ) ) &amp;&amp;

				// advance to the next closing parenthesis
				( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {

				// excess is a negative index
				match[ 0 ] = match[ 0 ].slice( 0, excess );
				match[ 2 ] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		"TAG": function( nodeNameSelector ) {
			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
			return nodeNameSelector === "*" ?
				function() {
					return true;
				} :
				function( elem ) {
					return elem.nodeName &amp;&amp; elem.nodeName.toLowerCase() === nodeName;
				};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				( pattern = new RegExp( "(^|" + whitespace +
					")" + className + "(" + whitespace + "|$)" ) ) &amp;&amp; classCache(
						className, function( elem ) {
							return pattern.test(
								typeof elem.className === "string" &amp;&amp; elem.className ||
								typeof elem.getAttribute !== "undefined" &amp;&amp;
									elem.getAttribute( "class" ) ||
								""
							);
				} );
		},

		"ATTR": function( name, operator, check ) {
			return function( elem ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				/* eslint-disable max-len */

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check &amp;&amp; result.indexOf( check ) === 0 :
					operator === "*=" ? check &amp;&amp; result.indexOf( check ) &gt; -1 :
					operator === "$=" ? check &amp;&amp; result.slice( -check.length ) === check :
					operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) &gt; -1 :
					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
					false;
				/* eslint-enable max-len */

			};
		},

		"CHILD": function( type, what, _argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 &amp;&amp; last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, _context, xml ) {
					var cache, uniqueCache, outerCache, node, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType &amp;&amp; elem.nodeName.toLowerCase(),
						useCache = !xml &amp;&amp; !ofType,
						diff = false;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( ( node = node[ dir ] ) ) {
									if ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) {

										return false;
									}
								}

								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" &amp;&amp; !start &amp;&amp; "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward &amp;&amp; useCache ) {

							// Seek `elem` from a previously-cached index

							// ...in a gzip-friendly way
							node = parent;
							outerCache = node[ expando ] || ( node[ expando ] = {} );

							// Support: IE &lt;9 only
							// Defend against cloned attroperties (jQuery gh-1709)
							uniqueCache = outerCache[ node.uniqueID ] ||
								( outerCache[ node.uniqueID ] = {} );

							cache = uniqueCache[ type ] || [];
							nodeIndex = cache[ 0 ] === dirruns &amp;&amp; cache[ 1 ];
							diff = nodeIndex &amp;&amp; cache[ 2 ];
							node = nodeIndex &amp;&amp; parent.childNodes[ nodeIndex ];

							while ( ( node = ++nodeIndex &amp;&amp; node &amp;&amp; node[ dir ] ||

								// Fallback to seeking `elem` from the start
								( diff = nodeIndex = 0 ) || start.pop() ) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 &amp;&amp; ++diff &amp;&amp; node === elem ) {
									uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						} else {

							// Use previously-cached element index if available
							if ( useCache ) {

								// ...in a gzip-friendly way
								node = elem;
								outerCache = node[ expando ] || ( node[ expando ] = {} );

								// Support: IE &lt;9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[ node.uniqueID ] ||
									( outerCache[ node.uniqueID ] = {} );

								cache = uniqueCache[ type ] || [];
								nodeIndex = cache[ 0 ] === dirruns &amp;&amp; cache[ 1 ];
								diff = nodeIndex;
							}

							// xml :nth-child(...)
							// or :nth-last-child(...) or :nth(-last)?-of-type(...)
							if ( diff === false ) {

								// Use the same loop as above to seek `elem` from the start
								while ( ( node = ++nodeIndex &amp;&amp; node &amp;&amp; node[ dir ] ||
									( diff = nodeIndex = 0 ) || start.pop() ) ) {

									if ( ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) &amp;&amp;
										++diff ) {

										// Cache the index of each encountered element
										if ( useCache ) {
											outerCache = node[ expando ] ||
												( node[ expando ] = {} );

											// Support: IE &lt;9 only
											// Defend against cloned attroperties (jQuery gh-1709)
											uniqueCache = outerCache[ node.uniqueID ] ||
												( outerCache[ node.uniqueID ] = {} );

											uniqueCache[ type ] = [ dirruns, diff ];
										}

										if ( node === elem ) {
											break;
										}
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 &amp;&amp; diff / first &gt;= 0 );
					}
				};
		},

		"PSEUDO": function( pseudo, argument ) {

			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length &gt; 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction( function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf( seed, matched[ i ] );
							seed[ idx ] = !( matches[ idx ] = matched[ i ] );
						}
					} ) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {

		// Potentially complex pseudos
		"not": markFunction( function( selector ) {

			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction( function( seed, matches, _context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( ( elem = unmatched[ i ] ) ) {
							seed[ i ] = !( matches[ i ] = elem );
						}
					}
				} ) :
				function( elem, _context, xml ) {
					input[ 0 ] = elem;
					matcher( input, null, xml, results );

					// Don't keep the element (issue #299)
					input[ 0 ] = null;
					return !results.pop();
				};
		} ),

		"has": markFunction( function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length &gt; 0;
			};
		} ),

		"contains": markFunction( function( text ) {
			text = text.replace( runescape, funescape );
			return function( elem ) {
				return ( elem.textContent || getText( elem ) ).indexOf( text ) &gt; -1;
			};
		} ),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// http://www.w3.org/TR/selectors/#lang-pseudo
		"lang": markFunction( function( lang ) {

			// lang value must be a valid identifier
			if ( !ridentifier.test( lang || "" ) ) {
				Sizzle.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( ( elemLang = documentIsHTML ?
						elem.lang :
						elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( ( elem = elem.parentNode ) &amp;&amp; elem.nodeType === 1 );
				return false;
			};
		} ),

		// Miscellaneous
		"target": function( elem ) {
			var hash = window.location &amp;&amp; window.location.hash;
			return hash &amp;&amp; hash.slice( 1 ) === elem.id;
		},

		"root": function( elem ) {
			return elem === docElem;
		},

		"focus": function( elem ) {
			return elem === document.activeElement &amp;&amp;
				( !document.hasFocus || document.hasFocus() ) &amp;&amp;
				!!( elem.type || elem.href || ~elem.tabIndex );
		},

		// Boolean properties
		"enabled": createDisabledPseudo( false ),
		"disabled": createDisabledPseudo( true ),

		"checked": function( elem ) {

			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return ( nodeName === "input" &amp;&amp; !!elem.checked ) ||
				( nodeName === "option" &amp;&amp; !!elem.selected );
		},

		"selected": function( elem ) {

			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				// eslint-disable-next-line no-unused-expressions
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		"empty": function( elem ) {

			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
			//   but not by others (comment: 8; processing instruction: 7; etc.)
			// nodeType &lt; 6 works because attributes (2) do not appear as children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeType &lt; 6 ) {
					return false;
				}
			}
			return true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos[ "empty" ]( elem );
		},

		// Element/input types
		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" &amp;&amp; elem.type === "button" || name === "button";
		},

		"text": function( elem ) {
			var attr;
			return elem.nodeName.toLowerCase() === "input" &amp;&amp;
				elem.type === "text" &amp;&amp;

				// Support: IE&lt;8
				// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
				( ( attr = elem.getAttribute( "type" ) ) == null ||
					attr.toLowerCase() === "text" );
		},

		// Position-in-collection
		"first": createPositionalPseudo( function() {
			return [ 0 ];
		} ),

		"last": createPositionalPseudo( function( _matchIndexes, length ) {
			return [ length - 1 ];
		} ),

		"eq": createPositionalPseudo( function( _matchIndexes, length, argument ) {
			return [ argument &lt; 0 ? argument + length : argument ];
		} ),

		"even": createPositionalPseudo( function( matchIndexes, length ) {
			var i = 0;
			for ( ; i &lt; length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		"odd": createPositionalPseudo( function( matchIndexes, length ) {
			var i = 1;
			for ( ; i &lt; length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		"lt": createPositionalPseudo( function( matchIndexes, length, argument ) {
			var i = argument &lt; 0 ?
				argument + length :
				argument &gt; length ?
					length :
					argument;
			for ( ; --i &gt;= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		"gt": createPositionalPseudo( function( matchIndexes, length, argument ) {
			var i = argument &lt; 0 ? argument + length : argument;
			for ( ; ++i &lt; length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} )
	}
};

Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ];

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();

tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || ( match = rcomma.exec( soFar ) ) ) {
			if ( match ) {

				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[ 0 ].length ) || soFar;
			}
			groups.push( ( tokens = [] ) );
		}

		matched = false;

		// Combinators
		if ( ( match = rcombinators.exec( soFar ) ) ) {
			matched = match.shift();
			tokens.push( {
				value: matched,

				// Cast descendant combinators to space
				type: match[ 0 ].replace( rtrim, " " )
			} );
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( ( match = matchExpr[ type ].exec( soFar ) ) &amp;&amp; ( !preFilters[ type ] ||
				( match = preFilters[ type ]( match ) ) ) ) {
				matched = match.shift();
				tokens.push( {
					value: matched,
					type: type,
					matches: match
				} );
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :

			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
};

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i &lt; len; i++ ) {
		selector += tokens[ i ].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		skip = combinator.next,
		key = skip || dir,
		checkNonElements = base &amp;&amp; key === "parentNode",
		doneName = done++;

	return combinator.first ?

		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( ( elem = elem[ dir ] ) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
			return false;
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var oldCache, uniqueCache, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
			if ( xml ) {
				while ( ( elem = elem[ dir ] ) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( ( elem = elem[ dir ] ) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || ( elem[ expando ] = {} );

						// Support: IE &lt;9 only
						// Defend against cloned attroperties (jQuery gh-1709)
						uniqueCache = outerCache[ elem.uniqueID ] ||
							( outerCache[ elem.uniqueID ] = {} );

						if ( skip &amp;&amp; skip === elem.nodeName.toLowerCase() ) {
							elem = elem[ dir ] || elem;
						} else if ( ( oldCache = uniqueCache[ key ] ) &amp;&amp;
							oldCache[ 0 ] === dirruns &amp;&amp; oldCache[ 1 ] === doneName ) {

							// Assign to newCache so results back-propagate to previous elements
							return ( newCache[ 2 ] = oldCache[ 2 ] );
						} else {

							// Reuse newcache so results back-propagate to previous elements
							uniqueCache[ key ] = newCache;

							// A match means we're done; a fail means we have to keep checking
							if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
								return true;
							}
						}
					}
				}
			}
			return false;
		};
}

function elementMatcher( matchers ) {
	return matchers.length &gt; 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[ i ]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[ 0 ];
}

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i &lt; len; i++ ) {
		Sizzle( selector, contexts[ i ], results );
	}
	return results;
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i &lt; len; i++ ) {
		if ( ( elem = unmatched[ i ] ) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter &amp;&amp; !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder &amp;&amp; !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction( function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts(
				selector || "*",
				context.nodeType ? [ context ] : context,
				[]
			),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter &amp;&amp; ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?

				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( ( elem = temp[ i ] ) ) {
					matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {

					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( ( elem = matcherOut[ i ] ) ) {

							// Restore matcherIn since elem is not yet a final match
							temp.push( ( matcherIn[ i ] = elem ) );
						}
					}
					postFinder( null, ( matcherOut = [] ), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( ( elem = matcherOut[ i ] ) &amp;&amp;
						( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) &gt; -1 ) {

						seed[ temp ] = !( results[ temp ] = elem );
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	} );
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[ 0 ].type ],
		implicitRelative = leadingRelative || Expr.relative[ " " ],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf( checkContext, elem ) &gt; -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			var ret = ( !leadingRelative &amp;&amp; ( xml || context !== outermostContext ) ) || (
				( checkContext = context ).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );

			// Avoid hanging onto element (issue #299)
			checkContext = null;
			return ret;
		} ];

	for ( ; i &lt; len; i++ ) {
		if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {
			matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
		} else {
			matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {

				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j &lt; len; j++ ) {
					if ( Expr.relative[ tokens[ j ].type ] ) {
						break;
					}
				}
				return setMatcher(
					i &gt; 1 &amp;&amp; elementMatcher( matchers ),
					i &gt; 1 &amp;&amp; toSelector(

					// If the preceding token was a descendant combinator, insert an implicit any-element `*`
					tokens
						.slice( 0, i - 1 )
						.concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
					).replace( rtrim, "$1" ),
					matcher,
					i &lt; j &amp;&amp; matcherFromTokens( tokens.slice( i, j ) ),
					j &lt; len &amp;&amp; matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
					j &lt; len &amp;&amp; toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length &gt; 0,
		byElement = elementMatchers.length &gt; 0,
		superMatcher = function( seed, context, xml, results, outermost ) {
			var elem, j, matcher,
				matchedCount = 0,
				i = "0",
				unmatched = seed &amp;&amp; [],
				setMatched = [],
				contextBackup = outermostContext,

				// We must always have either seed elements or outermost context
				elems = seed || byElement &amp;&amp; Expr.find[ "TAG" ]( "*", outermost ),

				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),
				len = elems.length;

			if ( outermost ) {

				// Support: IE 11+, Edge 17 - 18+
				// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
				// two documents; shallow comparisons work.
				// eslint-disable-next-line eqeqeq
				outermostContext = context == document || context || outermost;
			}

			// Add elements passing elementMatchers directly to results
			// Support: IE&lt;9, Safari
			// Tolerate NodeList properties (IE: "length"; Safari: &lt;number&gt;) matching elements by id
			for ( ; i !== len &amp;&amp; ( elem = elems[ i ] ) != null; i++ ) {
				if ( byElement &amp;&amp; elem ) {
					j = 0;

					// Support: IE 11+, Edge 17 - 18+
					// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
					// two documents; shallow comparisons work.
					// eslint-disable-next-line eqeqeq
					if ( !context &amp;&amp; elem.ownerDocument != document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( ( matcher = elementMatchers[ j++ ] ) ) {
						if ( matcher( elem, context || document, xml ) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {

					// They will have gone through all possible matchers
					if ( ( elem = !matcher &amp;&amp; elem ) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet &amp;&amp; i !== matchedCount ) {
				j = 0;
				while ( ( matcher = setMatchers[ j++ ] ) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {

					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount &gt; 0 ) {
						while ( i-- ) {
							if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
								setMatched[ i ] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost &amp;&amp; !seed &amp;&amp; setMatched.length &gt; 0 &amp;&amp;
					( matchedCount + setMatchers.length ) &gt; 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {

		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[ i ] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache(
			selector,
			matcherFromGroupMatchers( elementMatchers, setMatchers )
		);

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
};

/**
 * A low-level selection function that works with Sizzle's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with Sizzle.compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
select = Sizzle.select = function( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" &amp;&amp; selector,
		match = !seed &amp;&amp; tokenize( ( selector = compiled.selector || selector ) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[ 0 ] = match[ 0 ].slice( 0 );
		if ( tokens.length &gt; 2 &amp;&amp; ( token = tokens[ 0 ] ).type === "ID" &amp;&amp;
			context.nodeType === 9 &amp;&amp; documentIsHTML &amp;&amp; Expr.relative[ tokens[ 1 ].type ] ) {

			context = ( Expr.find[ "ID" ]( token.matches[ 0 ]
				.replace( runescape, funescape ), context ) || [] )[ 0 ];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[ i ];

			// Abort if we hit a combinator
			if ( Expr.relative[ ( type = token.type ) ] ) {
				break;
			}
			if ( ( find = Expr.find[ type ] ) ) {

				// Search, expanding context for leading sibling combinators
				if ( ( seed = find(
					token.matches[ 0 ].replace( runescape, funescape ),
					rsibling.test( tokens[ 0 ].type ) &amp;&amp; testContext( context.parentNode ) ||
						context
				) ) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length &amp;&amp; toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) &amp;&amp; testContext( context.parentNode ) || context
	);
	return results;
};

// One-time assignments

// Sort stability
support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;

// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;

// Initialize against the default document
setDocument();

// Support: Webkit&lt;537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert( function( el ) {

	// Should return 1, but returns 4 (following)
	return el.compareDocumentPosition( document.createElement( "fieldset" ) ) &amp; 1;
} );

// Support: IE&lt;8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert( function( el ) {
	el.innerHTML = "&lt;a href='#'&gt;&lt;/a&gt;";
	return el.firstChild.getAttribute( "href" ) === "#";
} ) ) {
	addHandle( "type|href|height|width", function( elem, name, isXML ) {
		if ( !isXML ) {
			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
		}
	} );
}

// Support: IE&lt;9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert( function( el ) {
	el.innerHTML = "&lt;input/&gt;";
	el.firstChild.setAttribute( "value", "" );
	return el.firstChild.getAttribute( "value" ) === "";
} ) ) {
	addHandle( "value", function( elem, _name, isXML ) {
		if ( !isXML &amp;&amp; elem.nodeName.toLowerCase() === "input" ) {
			return elem.defaultValue;
		}
	} );
}

// Support: IE&lt;9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert( function( el ) {
	return el.getAttribute( "disabled" ) == null;
} ) ) {
	addHandle( booleans, function( elem, name, isXML ) {
		var val;
		if ( !isXML ) {
			return elem[ name ] === true ? name.toLowerCase() :
				( val = elem.getAttributeNode( name ) ) &amp;&amp; val.specified ?
					val.value :
					null;
		}
	} );
}

return Sizzle;

} )( window );



jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;

// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;




var dir = function( elem, dir, until ) {
	var matched = [],
		truncate = until !== undefined;

	while ( ( elem = elem[ dir ] ) &amp;&amp; elem.nodeType !== 9 ) {
		if ( elem.nodeType === 1 ) {
			if ( truncate &amp;&amp; jQuery( elem ).is( until ) ) {
				break;
			}
			matched.push( elem );
		}
	}
	return matched;
};


var siblings = function( n, elem ) {
	var matched = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType === 1 &amp;&amp; n !== elem ) {
			matched.push( n );
		}
	}

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;



function nodeName( elem, name ) {

	return elem.nodeName &amp;&amp; elem.nodeName.toLowerCase() === name.toLowerCase();

}
var rsingleTag = ( /^&lt;([a-z][^\/\0&gt;:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?&gt;(?:&lt;\/\1&gt;|)$/i );



// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			return !!qualifier.call( elem, i, elem ) !== not;
		} );
	}

	// Single element
	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		} );
	}

	// Arraylike of elements (jQuery, arguments, Array)
	if ( typeof qualifier !== "string" ) {
		return jQuery.grep( elements, function( elem ) {
			return ( indexOf.call( qualifier, elem ) &gt; -1 ) !== not;
		} );
	}

	// Filtered directly for both simple and complex selectors
	return jQuery.filter( qualifier, elements, not );
}

jQuery.filter = function( expr, elems, not ) {
	var elem = elems[ 0 ];

	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	if ( elems.length === 1 &amp;&amp; elem.nodeType === 1 ) {
		return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
	}

	return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
		return elem.nodeType === 1;
	} ) );
};

jQuery.fn.extend( {
	find: function( selector ) {
		var i, ret,
			len = this.length,
			self = this;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter( function() {
				for ( i = 0; i &lt; len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			} ) );
		}

		ret = this.pushStack( [] );

		for ( i = 0; i &lt; len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		return len &gt; 1 ? jQuery.uniqueSort( ret ) : ret;
	},
	filter: function( selector ) {
		return this.pushStack( winnow( this, selector || [], false ) );
	},
	not: function( selector ) {
		return this.pushStack( winnow( this, selector || [], true ) );
	},
	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" &amp;&amp; rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	}
} );


// Initialize a jQuery object


// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over &lt;tag&gt; to avoid XSS via location.hash (trac-9521)
	// Strict HTML recognition (trac-11290: must start with &lt;)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(&lt;[\w\W]+&gt;)[^&gt;]*|#([\w-]+))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector[ 0 ] === "&lt;" &amp;&amp;
				selector[ selector.length - 1 ] === "&gt;" &amp;&amp;
				selector.length &gt;= 3 ) {

				// Assume that strings that start and end with &lt;&gt; are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match &amp;&amp; ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -&gt; $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context &amp;&amp; context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) &amp;&amp; jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					if ( elem ) {

						// Inject the element directly into the jQuery object
						this[ 0 ] = elem;
						this.length = 1;
					}
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( isFunction( selector ) ) {
			return root.ready !== undefined ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );
		}

		return jQuery.makeArray( selector, this );
	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );


var rparentsprev = /^(?:parents|prev(?:Until|All))/,

	// Methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend( {
	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter( function() {
			var i = 0;
			for ( ; i &lt; l; i++ ) {
				if ( jQuery.contains( this, targets[ i ] ) ) {
					return true;
				}
			}
		} );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			targets = typeof selectors !== "string" &amp;&amp; jQuery( selectors );

		// Positional selectors never match, since there's no _selection_ context
		if ( !rneedsContext.test( selectors ) ) {
			for ( ; i &lt; l; i++ ) {
				for ( cur = this[ i ]; cur &amp;&amp; cur !== context; cur = cur.parentNode ) {

					// Always skip document fragments
					if ( cur.nodeType &lt; 11 &amp;&amp; ( targets ?
						targets.index( cur ) &gt; -1 :

						// Don't pass non-elements to Sizzle
						cur.nodeType === 1 &amp;&amp;
							jQuery.find.matchesSelector( cur, selectors ) ) ) {

						matched.push( cur );
						break;
					}
				}
			}
		}

		return this.pushStack( matched.length &gt; 1 ? jQuery.uniqueSort( matched ) : matched );
	},

	// Determine the position of an element within the set
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] &amp;&amp; this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// Index in selector
		if ( typeof elem === "string" ) {
			return indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		return this.pushStack(
			jQuery.uniqueSort(
				jQuery.merge( this.get(), jQuery( selector, context ) )
			)
		);
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	}
} );

function sibling( cur, dir ) {
	while ( ( cur = cur[ dir ] ) &amp;&amp; cur.nodeType !== 1 ) {}
	return cur;
}

jQuery.each( {
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent &amp;&amp; parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, _i, until ) {
		return dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, _i, until ) {
		return dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, _i, until ) {
		return dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return siblings( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return siblings( elem.firstChild );
	},
	contents: function( elem ) {
		if ( elem.contentDocument != null &amp;&amp;

			// Support: IE 11+
			// &lt;object&gt; elements with no `data` attribute has an object
			// `contentDocument` with a `null` prototype.
			getProto( elem.contentDocument ) ) {

			return elem.contentDocument;
		}

		// Support: IE 9 - 11 only, iOS 7 only, Android Browser &lt;=4.3 only
		// Treat the template element as a regular one in browsers that
		// don't support it.
		if ( nodeName( elem, "template" ) ) {
			elem = elem.content || elem;
		}

		return jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector &amp;&amp; typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length &gt; 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.uniqueSort( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );



// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
	var object = {};
	jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	} );
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		createOptions( options ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,

		// Last fire value for non-forgettable lists
		memory,

		// Flag to know if list was already fired
		fired,

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

		// Queue of execution data for repeatable lists
		queue = [],

		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,

		// Fire callbacks
		fire = function() {

			// Enforce single-firing
			locked = locked || options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			fired = firing = true;
			for ( ; queue.length; firingIndex = -1 ) {
				memory = queue.shift();
				while ( ++firingIndex &lt; list.length ) {

					// Run callback and check for early termination
					if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &amp;&amp;
						options.stopOnFalse ) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if ( !options.memory ) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if ( locked ) {

				// Keep an empty list if we have data for future add calls
				if ( memory ) {
					list = [];

				// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},

		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {

					// If we have memory from a past run, we should fire after adding
					if ( memory &amp;&amp; !firing ) {
						firingIndex = list.length - 1;
						queue.push( memory );
					}

					( function add( args ) {
						jQuery.each( args, function( _, arg ) {
							if ( isFunction( arg ) ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg &amp;&amp; arg.length &amp;&amp; toType( arg ) !== "string" ) {

								// Inspect recursively
								add( arg );
							}
						} );
					} )( arguments );

					if ( memory &amp;&amp; !firing ) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function() {
				jQuery.each( arguments, function( _, arg ) {
					var index;
					while ( ( index = jQuery.inArray( arg, list, index ) ) &gt; -1 ) {
						list.splice( index, 1 );

						// Handle firing indexes
						if ( index &lt;= firingIndex ) {
							firingIndex--;
						}
					}
				} );
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ?
					jQuery.inArray( fn, list ) &gt; -1 :
					list.length &gt; 0;
			},

			// Remove all callbacks from the list
			empty: function() {
				if ( list ) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function() {
				locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function() {
				locked = queue = [];
				if ( !memory &amp;&amp; !firing ) {
					list = memory = "";
				}
				return this;
			},
			locked: function() {
				return !!locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( !locked ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					queue.push( args );
					if ( !firing ) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};


function Identity( v ) {
	return v;
}
function Thrower( ex ) {
	throw ex;
}

function adoptValue( value, resolve, reject, noValue ) {
	var method;

	try {

		// Check for promise aspect first to privilege synchronous behavior
		if ( value &amp;&amp; isFunction( ( method = value.promise ) ) ) {
			method.call( value ).done( resolve ).fail( reject );

		// Other thenables
		} else if ( value &amp;&amp; isFunction( ( method = value.then ) ) ) {
			method.call( value, resolve, reject );

		// Other non-thenables
		} else {

			// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
			// * false: [ value ].slice( 0 ) =&gt; resolve( value )
			// * true: [ value ].slice( 1 ) =&gt; resolve()
			resolve.apply( undefined, [ value ].slice( noValue ) );
		}

	// For Promises/A+, convert exceptions into rejections
	// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
	// Deferred#then to conditionally suppress rejection.
	} catch ( value ) {

		// Support: Android 4.0 only
		// Strict mode functions invoked without .call/.apply get global-object context
		reject.apply( undefined, [ value ] );
	}
}

jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

				// action, add listener, callbacks,
				// ... .then handlers, argument index, [final state]
				[ "notify", "progress", jQuery.Callbacks( "memory" ),
					jQuery.Callbacks( "memory" ), 2 ],
				[ "resolve", "done", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 0, "resolved" ],
				[ "reject", "fail", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 1, "rejected" ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				"catch": function( fn ) {
					return promise.then( null, fn );
				},

				// Keep pipe for back-compat
				pipe: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;

					return jQuery.Deferred( function( newDefer ) {
						jQuery.each( tuples, function( _i, tuple ) {

							// Map tuples (progress, done, fail) to arguments (done, fail, progress)
							var fn = isFunction( fns[ tuple[ 4 ] ] ) &amp;&amp; fns[ tuple[ 4 ] ];

							// deferred.progress(function() { bind to newDefer or newDefer.notify })
							// deferred.done(function() { bind to newDefer or newDefer.resolve })
							// deferred.fail(function() { bind to newDefer or newDefer.reject })
							deferred[ tuple[ 1 ] ]( function() {
								var returned = fn &amp;&amp; fn.apply( this, arguments );
								if ( returned &amp;&amp; isFunction( returned.promise ) ) {
									returned.promise()
										.progress( newDefer.notify )
										.done( newDefer.resolve )
										.fail( newDefer.reject );
								} else {
									newDefer[ tuple[ 0 ] + "With" ](
										this,
										fn ? [ returned ] : arguments
									);
								}
							} );
						} );
						fns = null;
					} ).promise();
				},
				then: function( onFulfilled, onRejected, onProgress ) {
					var maxDepth = 0;
					function resolve( depth, deferred, handler, special ) {
						return function() {
							var that = this,
								args = arguments,
								mightThrow = function() {
									var returned, then;

									// Support: Promises/A+ section 2.3.3.3.3
									// https://promisesaplus.com/#point-59
									// Ignore double-resolution attempts
									if ( depth &lt; maxDepth ) {
										return;
									}

									returned = handler.apply( that, args );

									// Support: Promises/A+ section 2.3.1
									// https://promisesaplus.com/#point-48
									if ( returned === deferred.promise() ) {
										throw new TypeError( "Thenable self-resolution" );
									}

									// Support: Promises/A+ sections 2.3.3.1, 3.5
									// https://promisesaplus.com/#point-54
									// https://promisesaplus.com/#point-75
									// Retrieve `then` only once
									then = returned &amp;&amp;

										// Support: Promises/A+ section 2.3.4
										// https://promisesaplus.com/#point-64
										// Only check objects and functions for thenability
										( typeof returned === "object" ||
											typeof returned === "function" ) &amp;&amp;
										returned.then;

									// Handle a returned thenable
									if ( isFunction( then ) ) {

										// Special processors (notify) just wait for resolution
										if ( special ) {
											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special )
											);

										// Normal processors (resolve) also hook into progress
										} else {

											// ...and disregard older resolution values
											maxDepth++;

											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special ),
												resolve( maxDepth, deferred, Identity,
													deferred.notifyWith )
											);
										}

									// Handle all other returned values
									} else {

										// Only substitute handlers pass on context
										// and multiple values (non-spec behavior)
										if ( handler !== Identity ) {
											that = undefined;
											args = [ returned ];
										}

										// Process the value(s)
										// Default process is resolve
										( special || deferred.resolveWith )( that, args );
									}
								},

								// Only normal processors (resolve) catch and reject exceptions
								process = special ?
									mightThrow :
									function() {
										try {
											mightThrow();
										} catch ( e ) {

											if ( jQuery.Deferred.exceptionHook ) {
												jQuery.Deferred.exceptionHook( e,
													process.stackTrace );
											}

											// Support: Promises/A+ section 2.3.3.3.4.1
											// https://promisesaplus.com/#point-61
											// Ignore post-resolution exceptions
											if ( depth + 1 &gt;= maxDepth ) {

												// Only substitute handlers pass on context
												// and multiple values (non-spec behavior)
												if ( handler !== Thrower ) {
													that = undefined;
													args = [ e ];
												}

												deferred.rejectWith( that, args );
											}
										}
									};

							// Support: Promises/A+ section 2.3.3.3.1
							// https://promisesaplus.com/#point-57
							// Re-resolve promises immediately to dodge false rejection from
							// subsequent errors
							if ( depth ) {
								process();
							} else {

								// Call an optional hook to record the stack, in case of exception
								// since it's otherwise lost when execution goes async
								if ( jQuery.Deferred.getStackHook ) {
									process.stackTrace = jQuery.Deferred.getStackHook();
								}
								window.setTimeout( process );
							}
						};
					}

					return jQuery.Deferred( function( newDefer ) {

						// progress_handlers.add( ... )
						tuples[ 0 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onProgress ) ?
									onProgress :
									Identity,
								newDefer.notifyWith
							)
						);

						// fulfilled_handlers.add( ... )
						tuples[ 1 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onFulfilled ) ?
									onFulfilled :
									Identity
							)
						);

						// rejected_handlers.add( ... )
						tuples[ 2 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onRejected ) ?
									onRejected :
									Thrower
							)
						);
					} ).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 5 ];

			// promise.progress = list.add
			// promise.done = list.add
			// promise.fail = list.add
			promise[ tuple[ 1 ] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(
					function() {

						// state = "resolved" (i.e., fulfilled)
						// state = "rejected"
						state = stateString;
					},

					// rejected_callbacks.disable
					// fulfilled_callbacks.disable
					tuples[ 3 - i ][ 2 ].disable,

					// rejected_handlers.disable
					// fulfilled_handlers.disable
					tuples[ 3 - i ][ 3 ].disable,

					// progress_callbacks.lock
					tuples[ 0 ][ 2 ].lock,

					// progress_handlers.lock
					tuples[ 0 ][ 3 ].lock
				);
			}

			// progress_handlers.fire
			// fulfilled_handlers.fire
			// rejected_handlers.fire
			list.add( tuple[ 3 ].fire );

			// deferred.notify = function() { deferred.notifyWith(...) }
			// deferred.resolve = function() { deferred.resolveWith(...) }
			// deferred.reject = function() { deferred.rejectWith(...) }
			deferred[ tuple[ 0 ] ] = function() {
				deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
				return this;
			};

			// deferred.notifyWith = list.fireWith
			// deferred.resolveWith = list.fireWith
			// deferred.rejectWith = list.fireWith
			deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
		} );

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( singleValue ) {
		var

			// count of uncompleted subordinates
			remaining = arguments.length,

			// count of unprocessed arguments
			i = remaining,

			// subordinate fulfillment data
			resolveContexts = Array( i ),
			resolveValues = slice.call( arguments ),

			// the primary Deferred
			primary = jQuery.Deferred(),

			// subordinate callback factory
			updateFunc = function( i ) {
				return function( value ) {
					resolveContexts[ i ] = this;
					resolveValues[ i ] = arguments.length &gt; 1 ? slice.call( arguments ) : value;
					if ( !( --remaining ) ) {
						primary.resolveWith( resolveContexts, resolveValues );
					}
				};
			};

		// Single- and empty arguments are adopted like Promise.resolve
		if ( remaining &lt;= 1 ) {
			adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject,
				!remaining );

			// Use .then() to unwrap secondary thenables (cf. gh-3000)
			if ( primary.state() === "pending" ||
				isFunction( resolveValues[ i ] &amp;&amp; resolveValues[ i ].then ) ) {

				return primary.then();
			}
		}

		// Multiple arguments are aggregated like Promise.all array elements
		while ( i-- ) {
			adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject );
		}

		return primary.promise();
	}
} );


// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;

jQuery.Deferred.exceptionHook = function( error, stack ) {

	// Support: IE 8 - 9 only
	// Console exists when dev tools are open, which can happen at any time
	if ( window.console &amp;&amp; window.console.warn &amp;&amp; error &amp;&amp; rerrorNames.test( error.name ) ) {
		window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
	}
};




jQuery.readyException = function( error ) {
	window.setTimeout( function() {
		throw error;
	} );
};




// The deferred used on DOM ready
var readyList = jQuery.Deferred();

jQuery.fn.ready = function( fn ) {

	readyList
		.then( fn )

		// Wrap jQuery.readyException in a function so that the lookup
		// happens at the time of error handling instead of callback
		// registration.
		.catch( function( error ) {
			jQuery.readyException( error );
		} );

	return this;
};

jQuery.extend( {

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See trac-6781
	readyWait: 1,

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true &amp;&amp; --jQuery.readyWait &gt; 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );
	}
} );

jQuery.ready.then = readyList.then;

// The ready event handler and self cleanup method
function completed() {
	document.removeEventListener( "DOMContentLoaded", completed );
	window.removeEventListener( "load", completed );
	jQuery.ready();
}

// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE &lt;=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
	( document.readyState !== "loading" &amp;&amp; !document.documentElement.doScroll ) ) {

	// Handle it asynchronously to allow scripts the opportunity to delay ready
	window.setTimeout( jQuery.ready );

} else {

	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", completed );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", completed );
}




// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,
		len = elems.length,
		bulk = key == null;

	// Sets many values
	if ( toType( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			access( elems, fn, i, key[ i ], true, emptyGet, raw );
		}

	// Sets one value
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !isFunction( value ) ) {
			raw = true;
		}

		if ( bulk ) {

			// Bulk operations run against the entire set
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			} else {
				bulk = fn;
				fn = function( elem, _key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {
			for ( ; i &lt; len; i++ ) {
				fn(
					elems[ i ], key, raw ?
						value :
						value.call( elems[ i ], i, fn( elems[ i ], key ) )
				);
			}
		}
	}

	if ( chainable ) {
		return elems;
	}

	// Gets
	if ( bulk ) {
		return fn.call( elems );
	}

	return len ? fn( elems[ 0 ], key ) : emptyGet;
};


// Matches dashed string for camelizing
var rmsPrefix = /^-ms-/,
	rdashAlpha = /-([a-z])/g;

// Used by camelCase as callback to replace()
function fcamelCase( _all, letter ) {
	return letter.toUpperCase();
}

// Convert dashed to camelCase; used by the css and data modules
// Support: IE &lt;=9 - 11, Edge 12 - 15
// Microsoft forgot to hump their vendor prefix (trac-9572)
function camelCase( string ) {
	return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
}
var acceptData = function( owner ) {

	// Accepts only:
	//  - Node
	//    - Node.ELEMENT_NODE
	//    - Node.DOCUMENT_NODE
	//  - Object
	//    - Any
	return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};




function Data() {
	this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

Data.prototype = {

	cache: function( owner ) {

		// Check if the owner object already has a cache
		var value = owner[ this.expando ];

		// If not, create one
		if ( !value ) {
			value = {};

			// We can accept data for non-element nodes in modern browsers,
			// but we should not, see trac-8335.
			// Always return an empty object.
			if ( acceptData( owner ) ) {

				// If it is a node unlikely to be stringify-ed or looped over
				// use plain assignment
				if ( owner.nodeType ) {
					owner[ this.expando ] = value;

				// Otherwise secure it in a non-enumerable property
				// configurable must be true to allow the property to be
				// deleted when data is removed
				} else {
					Object.defineProperty( owner, this.expando, {
						value: value,
						configurable: true
					} );
				}
			}
		}

		return value;
	},
	set: function( owner, data, value ) {
		var prop,
			cache = this.cache( owner );

		// Handle: [ owner, key, value ] args
		// Always use camelCase key (gh-2257)
		if ( typeof data === "string" ) {
			cache[ camelCase( data ) ] = value;

		// Handle: [ owner, { properties } ] args
		} else {

			// Copy the properties one-by-one to the cache object
			for ( prop in data ) {
				cache[ camelCase( prop ) ] = data[ prop ];
			}
		}
		return cache;
	},
	get: function( owner, key ) {
		return key === undefined ?
			this.cache( owner ) :

			// Always use camelCase key (gh-2257)
			owner[ this.expando ] &amp;&amp; owner[ this.expando ][ camelCase( key ) ];
	},
	access: function( owner, key, value ) {

		// In cases where either:
		//
		//   1. No key was specified
		//   2. A string key was specified, but no value provided
		//
		// Take the "read" path and allow the get method to determine
		// which value to return, respectively either:
		//
		//   1. The entire cache object
		//   2. The data stored at the key
		//
		if ( key === undefined ||
				( ( key &amp;&amp; typeof key === "string" ) &amp;&amp; value === undefined ) ) {

			return this.get( owner, key );
		}

		// When the key is not a string, or both a key and value
		// are specified, set or extend (existing objects) with either:
		//
		//   1. An object of properties
		//   2. A key and value
		//
		this.set( owner, key, value );

		// Since the "set" path can have two possible entry points
		// return the expected data based on which path was taken[*]
		return value !== undefined ? value : key;
	},
	remove: function( owner, key ) {
		var i,
			cache = owner[ this.expando ];

		if ( cache === undefined ) {
			return;
		}

		if ( key !== undefined ) {

			// Support array or space separated string of keys
			if ( Array.isArray( key ) ) {

				// If key is an array of keys...
				// We always set camelCase keys, so remove that.
				key = key.map( camelCase );
			} else {
				key = camelCase( key );

				// If a key with the spaces exists, use it.
				// Otherwise, create an array by matching non-whitespace
				key = key in cache ?
					[ key ] :
					( key.match( rnothtmlwhite ) || [] );
			}

			i = key.length;

			while ( i-- ) {
				delete cache[ key[ i ] ];
			}
		}

		// Remove the expando if there's no more data
		if ( key === undefined || jQuery.isEmptyObject( cache ) ) {

			// Support: Chrome &lt;=35 - 45
			// Webkit &amp; Blink performance suffers when deleting properties
			// from DOM nodes, so set to undefined instead
			// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
			if ( owner.nodeType ) {
				owner[ this.expando ] = undefined;
			} else {
				delete owner[ this.expando ];
			}
		}
	},
	hasData: function( owner ) {
		var cache = owner[ this.expando ];
		return cache !== undefined &amp;&amp; !jQuery.isEmptyObject( cache );
	}
};
var dataPriv = new Data();

var dataUser = new Data();



//	Implementation Summary
//
//	1. Enforce API surface and semantic compatibility with 1.9.x branch
//	2. Improve the module's maintainability by reducing the storage
//		paths to a single mechanism.
//	3. Use the same single mechanism to support "private" and "user" data.
//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
//	5. Avoid exposing implementation details on user objects (eg. expando properties)
//	6. Provide a clear path for implementation upgrade to WeakMap in 2014

var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /[A-Z]/g;

function getData( data ) {
	if ( data === "true" ) {
		return true;
	}

	if ( data === "false" ) {
		return false;
	}

	if ( data === "null" ) {
		return null;
	}

	// Only convert to a number if it doesn't change the string
	if ( data === +data + "" ) {
		return +data;
	}

	if ( rbrace.test( data ) ) {
		return JSON.parse( data );
	}

	return data;
}

function dataAttr( elem, key, data ) {
	var name;

	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined &amp;&amp; elem.nodeType === 1 ) {
		name = "data-" + key.replace( rmultiDash, "-$&amp;" ).toLowerCase();
		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = getData( data );
			} catch ( e ) {}

			// Make sure we set the data so it isn't changed later
			dataUser.set( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}

jQuery.extend( {
	hasData: function( elem ) {
		return dataUser.hasData( elem ) || dataPriv.hasData( elem );
	},

	data: function( elem, name, data ) {
		return dataUser.access( elem, name, data );
	},

	removeData: function( elem, name ) {
		dataUser.remove( elem, name );
	},

	// TODO: Now that all calls to _data and _removeData have been replaced
	// with direct calls to dataPriv methods, these can be deprecated.
	_data: function( elem, name, data ) {
		return dataPriv.access( elem, name, data );
	},

	_removeData: function( elem, name ) {
		dataPriv.remove( elem, name );
	}
} );

jQuery.fn.extend( {
	data: function( key, value ) {
		var i, name, data,
			elem = this[ 0 ],
			attrs = elem &amp;&amp; elem.attributes;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = dataUser.get( elem );

				if ( elem.nodeType === 1 &amp;&amp; !dataPriv.get( elem, "hasDataAttrs" ) ) {
					i = attrs.length;
					while ( i-- ) {

						// Support: IE 11 only
						// The attrs elements can be null (trac-14894)
						if ( attrs[ i ] ) {
							name = attrs[ i ].name;
							if ( name.indexOf( "data-" ) === 0 ) {
								name = camelCase( name.slice( 5 ) );
								dataAttr( elem, name, data[ name ] );
							}
						}
					}
					dataPriv.set( elem, "hasDataAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each( function() {
				dataUser.set( this, key );
			} );
		}

		return access( this, function( value ) {
			var data;

			// The calling jQuery object (element matches) is not empty
			// (and therefore has an element appears at this[ 0 ]) and the
			// `value` parameter was not undefined. An empty jQuery object
			// will result in `undefined` for elem = this[ 0 ] which will
			// throw an exception if an attempt to read a data cache is made.
			if ( elem &amp;&amp; value === undefined ) {

				// Attempt to get data from the cache
				// The key will always be camelCased in Data
				data = dataUser.get( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// Attempt to "discover" the data in
				// HTML5 custom data-* attrs
				data = dataAttr( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// We tried really hard, but the data doesn't exist.
				return;
			}

			// Set the data...
			this.each( function() {

				// We always store the camelCased key
				dataUser.set( this, key, value );
			} );
		}, null, value, arguments.length &gt; 1, null, true );
	},

	removeData: function( key ) {
		return this.each( function() {
			dataUser.remove( this, key );
		} );
	}
} );


jQuery.extend( {
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = dataPriv.get( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || Array.isArray( data ) ) {
					queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// Clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength &amp;&amp; hooks ) {
			hooks.empty.fire();
		}
	},

	// Not public - generate a queueHooks object, or return the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
			empty: jQuery.Callbacks( "once memory" ).add( function() {
				dataPriv.remove( elem, [ type + "queue", key ] );
			} )
		} );
	}
} );

jQuery.fn.extend( {
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length &lt; setter ) {
			return jQuery.queue( this[ 0 ], type );
		}

		return data === undefined ?
			this :
			this.each( function() {
				var queue = jQuery.queue( this, type, data );

				// Ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" &amp;&amp; queue[ 0 ] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			} );
	},
	dequeue: function( type ) {
		return this.each( function() {
			jQuery.dequeue( this, type );
		} );
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},

	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while ( i-- ) {
			tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
			if ( tmp &amp;&amp; tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;

var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );


var cssExpand = [ "Top", "Right", "Bottom", "Left" ];

var documentElement = document.documentElement;



	var isAttached = function( elem ) {
			return jQuery.contains( elem.ownerDocument, elem );
		},
		composed = { composed: true };

	// Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only
	// Check attachment across shadow DOM boundaries when possible (gh-3504)
	// Support: iOS 10.0-10.2 only
	// Early iOS 10 versions support `attachShadow` but not `getRootNode`,
	// leading to errors. We need to check for `getRootNode`.
	if ( documentElement.getRootNode ) {
		isAttached = function( elem ) {
			return jQuery.contains( elem.ownerDocument, elem ) ||
				elem.getRootNode( composed ) === elem.ownerDocument;
		};
	}
var isHiddenWithinTree = function( elem, el ) {

		// isHiddenWithinTree might be called from jQuery#filter function;
		// in that case, element will be second argument
		elem = el || elem;

		// Inline style trumps all
		return elem.style.display === "none" ||
			elem.style.display === "" &amp;&amp;

			// Otherwise, check computed style
			// Support: Firefox &lt;=43 - 45
			// Disconnected elements can have computed display: none, so first confirm that elem is
			// in the document.
			isAttached( elem ) &amp;&amp;

			jQuery.css( elem, "display" ) === "none";
	};



function adjustCSS( elem, prop, valueParts, tween ) {
	var adjusted, scale,
		maxIterations = 20,
		currentValue = tween ?
			function() {
				return tween.cur();
			} :
			function() {
				return jQuery.css( elem, prop, "" );
			},
		initial = currentValue(),
		unit = valueParts &amp;&amp; valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

		// Starting value computation is required for potential unit mismatches
		initialInUnit = elem.nodeType &amp;&amp;
			( jQuery.cssNumber[ prop ] || unit !== "px" &amp;&amp; +initial ) &amp;&amp;
			rcssNum.exec( jQuery.css( elem, prop ) );

	if ( initialInUnit &amp;&amp; initialInUnit[ 3 ] !== unit ) {

		// Support: Firefox &lt;=54
		// Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
		initial = initial / 2;

		// Trust units reported by jQuery.css
		unit = unit || initialInUnit[ 3 ];

		// Iteratively approximate from a nonzero starting point
		initialInUnit = +initial || 1;

		while ( maxIterations-- ) {

			// Evaluate and update our best guess (doubling guesses that zero out).
			// Finish if the scale equals or crosses 1 (making the old*new product non-positive).
			jQuery.style( elem, prop, initialInUnit + unit );
			if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) &lt;= 0 ) {
				maxIterations = 0;
			}
			initialInUnit = initialInUnit / scale;

		}

		initialInUnit = initialInUnit * 2;
		jQuery.style( elem, prop, initialInUnit + unit );

		// Make sure we update the tween properties later on
		valueParts = valueParts || [];
	}

	if ( valueParts ) {
		initialInUnit = +initialInUnit || +initial || 0;

		// Apply relative offset (+=/-=) if specified
		adjusted = valueParts[ 1 ] ?
			initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
			+valueParts[ 2 ];
		if ( tween ) {
			tween.unit = unit;
			tween.start = initialInUnit;
			tween.end = adjusted;
		}
	}
	return adjusted;
}


var defaultDisplayMap = {};

function getDefaultDisplay( elem ) {
	var temp,
		doc = elem.ownerDocument,
		nodeName = elem.nodeName,
		display = defaultDisplayMap[ nodeName ];

	if ( display ) {
		return display;
	}

	temp = doc.body.appendChild( doc.createElement( nodeName ) );
	display = jQuery.css( temp, "display" );

	temp.parentNode.removeChild( temp );

	if ( display === "none" ) {
		display = "block";
	}
	defaultDisplayMap[ nodeName ] = display;

	return display;
}

function showHide( elements, show ) {
	var display, elem,
		values = [],
		index = 0,
		length = elements.length;

	// Determine new display value for elements that need to change
	for ( ; index &lt; length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		display = elem.style.display;
		if ( show ) {

			// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
			// check is required in this first loop unless we have a nonempty display value (either
			// inline or about-to-be-restored)
			if ( display === "none" ) {
				values[ index ] = dataPriv.get( elem, "display" ) || null;
				if ( !values[ index ] ) {
					elem.style.display = "";
				}
			}
			if ( elem.style.display === "" &amp;&amp; isHiddenWithinTree( elem ) ) {
				values[ index ] = getDefaultDisplay( elem );
			}
		} else {
			if ( display !== "none" ) {
				values[ index ] = "none";

				// Remember what we're overwriting
				dataPriv.set( elem, "display", display );
			}
		}
	}

	// Set the display of the elements in a second loop to avoid constant reflow
	for ( index = 0; index &lt; length; index++ ) {
		if ( values[ index ] != null ) {
			elements[ index ].style.display = values[ index ];
		}
	}

	return elements;
}

jQuery.fn.extend( {
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		if ( typeof state === "boolean" ) {
			return state ? this.show() : this.hide();
		}

		return this.each( function() {
			if ( isHiddenWithinTree( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		} );
	}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );

var rtagName = ( /&lt;([a-z][^\/\0&gt;\x20\t\r\n\f]*)/i );

var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );



( function() {
	var fragment = document.createDocumentFragment(),
		div = fragment.appendChild( document.createElement( "div" ) ),
		input = document.createElement( "input" );

	// Support: Android 4.0 - 4.3 only
	// Check state lost if the name is set (trac-11217)
	// Support: Windows Web Apps (WWA)
	// `name` and `type` must use .setAttribute for WWA (trac-14901)
	input.setAttribute( "type", "radio" );
	input.setAttribute( "checked", "checked" );
	input.setAttribute( "name", "t" );

	div.appendChild( input );

	// Support: Android &lt;=4.1 only
	// Older WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE &lt;=11 only
	// Make sure textarea (and checkbox) defaultValue is properly cloned
	div.innerHTML = "&lt;textarea&gt;x&lt;/textarea&gt;";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;

	// Support: IE &lt;=9 only
	// IE &lt;=9 replaces &lt;option&gt; tags with their contents when inserted outside of
	// the select element.
	div.innerHTML = "&lt;option&gt;&lt;/option&gt;";
	support.option = !!div.lastChild;
} )();


// We have to close these tags to support XHTML (trac-13200)
var wrapMap = {

	// XHTML parsers do not magically insert elements in the
	// same way that tag soup parsers do. So we cannot shorten
	// this by omitting &lt;tbody&gt; or other required elements.
	thead: [ 1, "&lt;table&gt;", "&lt;/table&gt;" ],
	col: [ 2, "&lt;table&gt;&lt;colgroup&gt;", "&lt;/colgroup&gt;&lt;/table&gt;" ],
	tr: [ 2, "&lt;table&gt;&lt;tbody&gt;", "&lt;/tbody&gt;&lt;/table&gt;" ],
	td: [ 3, "&lt;table&gt;&lt;tbody&gt;&lt;tr&gt;", "&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;" ],

	_default: [ 0, "", "" ]
};

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// Support: IE &lt;=9 only
if ( !support.option ) {
	wrapMap.optgroup = wrapMap.option = [ 1, "&lt;select multiple='multiple'&gt;", "&lt;/select&gt;" ];
}


function getAll( context, tag ) {

	// Support: IE &lt;=9 - 11 only
	// Use typeof to avoid zero-argument method invocation on host objects (trac-15151)
	var ret;

	if ( typeof context.getElementsByTagName !== "undefined" ) {
		ret = context.getElementsByTagName( tag || "*" );

	} else if ( typeof context.querySelectorAll !== "undefined" ) {
		ret = context.querySelectorAll( tag || "*" );

	} else {
		ret = [];
	}

	if ( tag === undefined || tag &amp;&amp; nodeName( context, tag ) ) {
		return jQuery.merge( [ context ], ret );
	}

	return ret;
}


// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var i = 0,
		l = elems.length;

	for ( ; i &lt; l; i++ ) {
		dataPriv.set(
			elems[ i ],
			"globalEval",
			!refElements || dataPriv.get( refElements[ i ], "globalEval" )
		);
	}
}


var rhtml = /&lt;|&amp;#?\w+;/;

function buildFragment( elems, context, scripts, selection, ignored ) {
	var elem, tmp, tag, wrap, attached, j,
		fragment = context.createDocumentFragment(),
		nodes = [],
		i = 0,
		l = elems.length;

	for ( ; i &lt; l; i++ ) {
		elem = elems[ i ];

		if ( elem || elem === 0 ) {

			// Add nodes directly
			if ( toType( elem ) === "object" ) {

				// Support: Android &lt;=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

			// Convert non-html into a text node
			} else if ( !rhtml.test( elem ) ) {
				nodes.push( context.createTextNode( elem ) );

			// Convert html into DOM nodes
			} else {
				tmp = tmp || fragment.appendChild( context.createElement( "div" ) );

				// Deserialize a standard representation
				tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
				wrap = wrapMap[ tag ] || wrapMap._default;
				tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];

				// Descend through wrappers to the right content
				j = wrap[ 0 ];
				while ( j-- ) {
					tmp = tmp.lastChild;
				}

				// Support: Android &lt;=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, tmp.childNodes );

				// Remember the top-level container
				tmp = fragment.firstChild;

				// Ensure the created nodes are orphaned (trac-12392)
				tmp.textContent = "";
			}
		}
	}

	// Remove wrapper from fragment
	fragment.textContent = "";

	i = 0;
	while ( ( elem = nodes[ i++ ] ) ) {

		// Skip elements already in the context collection (trac-4087)
		if ( selection &amp;&amp; jQuery.inArray( elem, selection ) &gt; -1 ) {
			if ( ignored ) {
				ignored.push( elem );
			}
			continue;
		}

		attached = isAttached( elem );

		// Append to fragment
		tmp = getAll( fragment.appendChild( elem ), "script" );

		// Preserve script evaluation history
		if ( attached ) {
			setGlobalEval( tmp );
		}

		// Capture executables
		if ( scripts ) {
			j = 0;
			while ( ( elem = tmp[ j++ ] ) ) {
				if ( rscriptType.test( elem.type || "" ) ) {
					scripts.push( elem );
				}
			}
		}
	}

	return fragment;
}


var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

// Support: IE &lt;=9 - 11+
// focus() and blur() are asynchronous, except when they are no-op.
// So expect focus to be synchronous when the element is already active,
// and blur to be synchronous when the element is not already active.
// (focus and blur are always synchronous in other supported browsers,
// this just defines when we can count on it).
function expectSync( elem, type ) {
	return ( elem === safeActiveElement() ) === ( type === "focus" );
}

// Support: IE &lt;=9 only
// Accessing document.activeElement can throw unexpectedly
// https://bugs.jquery.com/ticket/13393
function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

function on( elem, types, selector, data, fn, one ) {
	var origFn, type;

	// Types can be a map of types/handlers
	if ( typeof types === "object" ) {

		// ( types-Object, selector, data )
		if ( typeof selector !== "string" ) {

			// ( types-Object, data )
			data = data || selector;
			selector = undefined;
		}
		for ( type in types ) {
			on( elem, type, selector, data, types[ type ], one );
		}
		return elem;
	}

	if ( data == null &amp;&amp; fn == null ) {

		// ( types, fn )
		fn = selector;
		data = selector = undefined;
	} else if ( fn == null ) {
		if ( typeof selector === "string" ) {

			// ( types, selector, fn )
			fn = data;
			data = undefined;
		} else {

			// ( types, data, fn )
			fn = data;
			data = selector;
			selector = undefined;
		}
	}
	if ( fn === false ) {
		fn = returnFalse;
	} else if ( !fn ) {
		return elem;
	}

	if ( one === 1 ) {
		origFn = fn;
		fn = function( event ) {

			// Can use an empty set, since event contains the info
			jQuery().off( event );
			return origFn.apply( this, arguments );
		};

		// Use same guid so caller can remove using origFn
		fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
	}
	return elem.each( function() {
		jQuery.event.add( this, types, fn, data, selector );
	} );
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	global: {},

	add: function( elem, types, handler, data, selector ) {

		var handleObjIn, eventHandle, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.get( elem );

		// Only attach events to objects that accept data
		if ( !acceptData( elem ) ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Ensure that invalid selectors throw exceptions at attach time
		// Evaluate against documentElement in case elem is a non-element node (e.g., document)
		if ( selector ) {
			jQuery.find.matchesSelector( documentElement, selector );
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		if ( !( events = elemData.events ) ) {
			events = elemData.events = Object.create( null );
		}
		if ( !( eventHandle = elemData.handle ) ) {
			eventHandle = elemData.handle = function( e ) {

				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" &amp;&amp; jQuery.event.triggered !== e.type ?
					jQuery.event.dispatch.apply( elem, arguments ) : undefined;
			};
		}

		// Handle multiple events separated by a space
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// There *must* be a type, no attaching namespace-only handlers
			if ( !type ) {
				continue;
			}

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend( {
				type: type,
				origType: origType,
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector &amp;&amp; jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join( "." )
			}, handleObjIn );

			// Init the event handler queue if we're the first
			if ( !( handlers = events[ type ] ) ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener if the special events handler returns false
				if ( !special.setup ||
					special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var j, origCount, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.hasData( elem ) &amp;&amp; dataPriv.get( elem );

		if ( !elemData || !( events = elemData.events ) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector ? special.delegateType : special.bindType ) || type;
			handlers = events[ type ] || [];
			tmp = tmp[ 2 ] &amp;&amp;
				new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );

			// Remove matching events
			origCount = j = handlers.length;
			while ( j-- ) {
				handleObj = handlers[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &amp;&amp;
					( !handler || handler.guid === handleObj.guid ) &amp;&amp;
					( !tmp || tmp.test( handleObj.namespace ) ) &amp;&amp;
					( !selector || selector === handleObj.selector ||
						selector === "**" &amp;&amp; handleObj.selector ) ) {
					handlers.splice( j, 1 );

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount &amp;&amp; !handlers.length ) {
				if ( !special.teardown ||
					special.teardown.call( elem, namespaces, elemData.handle ) === false ) {

					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove data and the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			dataPriv.remove( elem, "handle events" );
		}
	},

	dispatch: function( nativeEvent ) {

		var i, j, ret, matched, handleObj, handlerQueue,
			args = new Array( arguments.length ),

			// Make a writable jQuery.Event from the native event object
			event = jQuery.event.fix( nativeEvent ),

			handlers = (
				dataPriv.get( this, "events" ) || Object.create( null )
			)[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[ 0 ] = event;

		for ( i = 1; i &lt; arguments.length; i++ ) {
			args[ i ] = arguments[ i ];
		}

		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch &amp;&amp; special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( ( matched = handlerQueue[ i++ ] ) &amp;&amp; !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

			j = 0;
			while ( ( handleObj = matched.handlers[ j++ ] ) &amp;&amp;
				!event.isImmediatePropagationStopped() ) {

				// If the event is namespaced, then each handler is only invoked if it is
				// specially universal or its namespaces are a superset of the event's.
				if ( !event.rnamespace || handleObj.namespace === false ||
					event.rnamespace.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
						handleObj.handler ).apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( ( event.result = ret ) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var i, handleObj, sel, matchedHandlers, matchedSelectors,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		if ( delegateCount &amp;&amp;

			// Support: IE &lt;=9
			// Black-hole SVG &lt;use&gt; instance trees (trac-13180)
			cur.nodeType &amp;&amp;

			// Support: Firefox &lt;=42
			// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
			// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
			// Support: IE 11 only
			// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
			!( event.type === "click" &amp;&amp; event.button &gt;= 1 ) ) {

			for ( ; cur !== this; cur = cur.parentNode || this ) {

				// Don't check non-elements (trac-13208)
				// Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764)
				if ( cur.nodeType === 1 &amp;&amp; !( event.type === "click" &amp;&amp; cur.disabled === true ) ) {
					matchedHandlers = [];
					matchedSelectors = {};
					for ( i = 0; i &lt; delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (trac-13203)
						sel = handleObj.selector + " ";

						if ( matchedSelectors[ sel ] === undefined ) {
							matchedSelectors[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) &gt; -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matchedSelectors[ sel ] ) {
							matchedHandlers.push( handleObj );
						}
					}
					if ( matchedHandlers.length ) {
						handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		cur = this;
		if ( delegateCount &lt; handlers.length ) {
			handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	addProp: function( name, hook ) {
		Object.defineProperty( jQuery.Event.prototype, name, {
			enumerable: true,
			configurable: true,

			get: isFunction( hook ) ?
				function() {
					if ( this.originalEvent ) {
						return hook( this.originalEvent );
					}
				} :
				function() {
					if ( this.originalEvent ) {
						return this.originalEvent[ name ];
					}
				},

			set: function( value ) {
				Object.defineProperty( this, name, {
					enumerable: true,
					configurable: true,
					writable: true,
					value: value
				} );
			}
		} );
	},

	fix: function( originalEvent ) {
		return originalEvent[ jQuery.expando ] ?
			originalEvent :
			new jQuery.Event( originalEvent );
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		click: {

			// Utilize native event to ensure correct state for checkable inputs
			setup: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Claim the first handler
				if ( rcheckableType.test( el.type ) &amp;&amp;
					el.click &amp;&amp; nodeName( el, "input" ) ) {

					// dataPriv.set( el, "click", ... )
					leverageNative( el, "click", returnTrue );
				}

				// Return false to allow normal processing in the caller
				return false;
			},
			trigger: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Force setup before triggering a click
				if ( rcheckableType.test( el.type ) &amp;&amp;
					el.click &amp;&amp; nodeName( el, "input" ) ) {

					leverageNative( el, "click" );
				}

				// Return non-false to allow normal event-path propagation
				return true;
			},

			// For cross-browser consistency, suppress native .click() on links
			// Also prevent it if we're currently inside a leveraged native-event stack
			_default: function( event ) {
				var target = event.target;
				return rcheckableType.test( target.type ) &amp;&amp;
					target.click &amp;&amp; nodeName( target, "input" ) &amp;&amp;
					dataPriv.get( target, "click" ) ||
					nodeName( target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined &amp;&amp; event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	}
};

// Ensure the presence of an event listener that handles manually-triggered
// synthetic events by interrupting progress until reinvoked in response to
// *native* events that it fires directly, ensuring that state changes have
// already occurred before other listeners are invoked.
function leverageNative( el, type, expectSync ) {

	// Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add
	if ( !expectSync ) {
		if ( dataPriv.get( el, type ) === undefined ) {
			jQuery.event.add( el, type, returnTrue );
		}
		return;
	}

	// Register the controller as a special universal handler for all event namespaces
	dataPriv.set( el, type, false );
	jQuery.event.add( el, type, {
		namespace: false,
		handler: function( event ) {
			var notAsync, result,
				saved = dataPriv.get( this, type );

			if ( ( event.isTrigger &amp; 1 ) &amp;&amp; this[ type ] ) {

				// Interrupt processing of the outer synthetic .trigger()ed event
				// Saved data should be false in such cases, but might be a leftover capture object
				// from an async native handler (gh-4350)
				if ( !saved.length ) {

					// Store arguments for use when handling the inner native event
					// There will always be at least one argument (an event object), so this array
					// will not be confused with a leftover capture object.
					saved = slice.call( arguments );
					dataPriv.set( this, type, saved );

					// Trigger the native event and capture its result
					// Support: IE &lt;=9 - 11+
					// focus() and blur() are asynchronous
					notAsync = expectSync( this, type );
					this[ type ]();
					result = dataPriv.get( this, type );
					if ( saved !== result || notAsync ) {
						dataPriv.set( this, type, false );
					} else {
						result = {};
					}
					if ( saved !== result ) {

						// Cancel the outer synthetic event
						event.stopImmediatePropagation();
						event.preventDefault();

						// Support: Chrome 86+
						// In Chrome, if an element having a focusout handler is blurred by
						// clicking outside of it, it invokes the handler synchronously. If
						// that handler calls `.remove()` on the element, the data is cleared,
						// leaving `result` undefined. We need to guard against this.
						return result &amp;&amp; result.value;
					}

				// If this is an inner synthetic event for an event with a bubbling surrogate
				// (focus or blur), assume that the surrogate already propagated from triggering the
				// native event and prevent that from happening again here.
				// This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
				// bubbling surrogate propagates *after* the non-bubbling base), but that seems
				// less bad than duplication.
				} else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {
					event.stopPropagation();
				}

			// If this is a native event triggered above, everything is now in order
			// Fire an inner synthetic event with the original arguments
			} else if ( saved.length ) {

				// ...and capture the result
				dataPriv.set( this, type, {
					value: jQuery.event.trigger(

						// Support: IE &lt;=9 - 11+
						// Extend with the prototype to reset the above stopImmediatePropagation()
						jQuery.extend( saved[ 0 ], jQuery.Event.prototype ),
						saved.slice( 1 ),
						this
					)
				} );

				// Abort handling of the native event
				event.stopImmediatePropagation();
			}
		}
	} );
}

jQuery.removeEvent = function( elem, type, handle ) {

	// This "if" is needed for plain objects
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle );
	}
};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src &amp;&amp; src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &amp;&amp;

				// Support: Android &lt;=2.3 only
				src.returnValue === false ?
			returnTrue :
			returnFalse;

		// Create target properties
		// Support: Safari &lt;=6 - 7 only
		// Target should not be a text node (trac-504, trac-13143)
		this.target = ( src.target &amp;&amp; src.target.nodeType === 3 ) ?
			src.target.parentNode :
			src.target;

		this.currentTarget = src.currentTarget;
		this.relatedTarget = src.relatedTarget;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src &amp;&amp; src.timeStamp || Date.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,
	isSimulated: false,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e &amp;&amp; !this.isSimulated ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e &amp;&amp; !this.isSimulated ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e &amp;&amp; !this.isSimulated ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
	altKey: true,
	bubbles: true,
	cancelable: true,
	changedTouches: true,
	ctrlKey: true,
	detail: true,
	eventPhase: true,
	metaKey: true,
	pageX: true,
	pageY: true,
	shiftKey: true,
	view: true,
	"char": true,
	code: true,
	charCode: true,
	key: true,
	keyCode: true,
	button: true,
	buttons: true,
	clientX: true,
	clientY: true,
	offsetX: true,
	offsetY: true,
	pointerId: true,
	pointerType: true,
	screenX: true,
	screenY: true,
	targetTouches: true,
	toElement: true,
	touches: true,
	which: true
}, jQuery.event.addProp );

jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {
	jQuery.event.special[ type ] = {

		// Utilize native event if possible so blur/focus sequence is correct
		setup: function() {

			// Claim the first handler
			// dataPriv.set( this, "focus", ... )
			// dataPriv.set( this, "blur", ... )
			leverageNative( this, type, expectSync );

			// Return false to allow normal processing in the caller
			return false;
		},
		trigger: function() {

			// Force setup before trigger
			leverageNative( this, type );

			// Return non-false to allow normal event-path propagation
			return true;
		},

		// Suppress native focus or blur if we're currently inside
		// a leveraged native-event stack
		_default: function( event ) {
			return dataPriv.get( event.target, type );
		},

		delegateType: delegateType
	};
} );

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target &amp;&amp; !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

jQuery.fn.extend( {

	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types &amp;&amp; types.preventDefault &amp;&amp; types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	}
} );


var

	// Support: IE &lt;=10 - 11, Edge 12 - 13 only
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /&lt;script|&lt;style|&lt;link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,

	rcleanScript = /^\s*&lt;!\[CDATA\[|\]\]&gt;\s*$/g;

// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
	if ( nodeName( elem, "table" ) &amp;&amp;
		nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {

		return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
	}

	return elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
		elem.type = elem.type.slice( 5 );
	} else {
		elem.removeAttribute( "type" );
	}

	return elem;
}

function cloneCopyEvent( src, dest ) {
	var i, l, type, pdataOld, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.get( src );
		events = pdataOld.events;

		if ( events ) {
			dataPriv.remove( dest, "handle events" );

			for ( type in events ) {
				for ( i = 0, l = events[ type ].length; i &lt; l; i++ ) {
					jQuery.event.add( dest, type, events[ type ][ i ] );
				}
			}
		}
	}

	// 2. Copy user data
	if ( dataUser.hasData( src ) ) {
		udataOld = dataUser.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		dataUser.set( dest, udataCur );
	}
}

// Fix IE bugs, see support tests
function fixInput( src, dest ) {
	var nodeName = dest.nodeName.toLowerCase();

	// Fails to persist the checked state of a cloned checkbox or radio button.
	if ( nodeName === "input" &amp;&amp; rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Fails to return the selected option to the default selected state when cloning options
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = flat( args );

	var fragment, first, scripts, hasScripts, node, doc,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		valueIsFunction = isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( valueIsFunction ||
			( l &gt; 1 &amp;&amp; typeof value === "string" &amp;&amp;
				!support.checkClone &amp;&amp; rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( valueIsFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (trac-8070).
			for ( ; i &lt; l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android &lt;=4.0 only, PhantomJS 1 only
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i &lt; hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &amp;&amp;
						!dataPriv.access( node, "globalEval" ) &amp;&amp;
						jQuery.contains( doc, node ) ) {

						if ( node.src &amp;&amp; ( node.type || "" ).toLowerCase()  !== "module" ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl &amp;&amp; !node.noModule ) {
								jQuery._evalUrl( node.src, {
									nonce: node.nonce || node.getAttribute( "nonce" )
								}, doc );
							}
						} else {

							// Unwrap a CDATA section containing script contents. This shouldn't be
							// needed as in XML documents they're already not visible when
							// inspecting element contents and in HTML documents they have no
							// meaning but we're preserving that logic for backwards compatibility.
							// This will be removed completely in 4.0. See gh-4904.
							DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );
						}
					}
				}
			}
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		nodes = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = nodes[ i ] ) != null; i++ ) {
		if ( !keepData &amp;&amp; node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData &amp;&amp; isAttached( node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html;
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = isAttached( elem );

		// Fix IE cloning issues
		if ( !support.noCloneChecked &amp;&amp; ( elem.nodeType === 1 || elem.nodeType === 11 ) &amp;&amp;
				!jQuery.isXMLDoc( elem ) ) {

			// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			for ( i = 0, l = srcElements.length; i &lt; l; i++ ) {
				fixInput( srcElements[ i ], destElements[ i ] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0, l = srcElements.length; i &lt; l; i++ ) {
					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length &gt; 0 ) {
			setGlobalEval( destElements, !inPage &amp;&amp; getAll( elem, "script" ) );
		}

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems ) {
		var data, elem, type,
			special = jQuery.event.special,
			i = 0;

		for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
			if ( acceptData( elem ) ) {
				if ( ( data = elem[ dataPriv.expando ] ) ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Support: Chrome &lt;=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataPriv.expando ] = undefined;
				}
				if ( elem[ dataUser.expando ] ) {

					// Support: Chrome &lt;=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataUser.expando ] = undefined;
				}
			}
		}
	}
} );

jQuery.fn.extend( {
	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().each( function() {
					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
						this.textContent = value;
					}
				} );
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {
			if ( elem.nodeType === 1 ) {

				// Prevent memory leaks
				jQuery.cleanData( getAll( elem, false ) );

				// Remove any remaining nodes
				elem.textContent = "";
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined &amp;&amp; elem.nodeType === 1 ) {
				return elem.innerHTML;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" &amp;&amp; !rnoInnerhtml.test( value ) &amp;&amp;
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i &lt; l; i++ ) {
						elem = this[ i ] || {};

						// Remove element nodes and prevent memory leaks
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) &lt; 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1,
			i = 0;

		for ( ; i &lt;= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Support: Android &lt;=4.0 only, PhantomJS 1 only
			// .get() because push.apply(_, arraylike) throws on ancient WebKit
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var rcustomProp = /^--/;


var getStyles = function( elem ) {

		// Support: IE &lt;=11 only, Firefox &lt;=30 (trac-15098, trac-14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};

var swap = function( elem, options, callback ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.call( elem );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};


var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );

var whitespace = "[\\x20\\t\\r\\n\\f]";


var rtrimCSS = new RegExp(
	"^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$",
	"g"
);




( function() {

	// Executing both pixelPosition &amp; boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {

		// This is a singleton, we need to execute it only once
		if ( !div ) {
			return;
		}

		container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
			"margin-top:1px;padding:0;border:0";
		div.style.cssText =
			"position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
			"margin:auto;border:1px;padding:1px;" +
			"width:60%;top:1%";
		documentElement.appendChild( container ).appendChild( div );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";

		// Support: Android 4.0 - 4.3 only, Firefox &lt;=3 - 44
		reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;

		// Support: Android 4.0 - 4.3 only, Safari &lt;=9.1 - 10.1, iOS &lt;=7.0 - 9.3
		// Some styles come back with percentage values, even though they shouldn't
		div.style.right = "60%";
		pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;

		// Support: IE 9 - 11 only
		// Detect misreporting of content dimensions for box-sizing:border-box elements
		boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;

		// Support: IE 9 only
		// Detect overflow:scroll screwiness (gh-3699)
		// Support: Chrome &lt;=64
		// Don't get tricked when zoom affects offsetWidth (gh-4029)
		div.style.position = "absolute";
		scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;

		documentElement.removeChild( container );

		// Nullify the div so it wouldn't be stored in the memory and
		// it will also be a sign that checks already performed
		div = null;
	}

	function roundPixelMeasures( measure ) {
		return Math.round( parseFloat( measure ) );
	}

	var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
		reliableTrDimensionsVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE &lt;=9 - 11 only
	// Style of cloned element affects source element cloned (trac-8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	jQuery.extend( support, {
		boxSizingReliable: function() {
			computeStyleTests();
			return boxSizingReliableVal;
		},
		pixelBoxStyles: function() {
			computeStyleTests();
			return pixelBoxStylesVal;
		},
		pixelPosition: function() {
			computeStyleTests();
			return pixelPositionVal;
		},
		reliableMarginLeft: function() {
			computeStyleTests();
			return reliableMarginLeftVal;
		},
		scrollboxSize: function() {
			computeStyleTests();
			return scrollboxSizeVal;
		},

		// Support: IE 9 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Behavior in IE 9 is more subtle than in newer versions &amp; it passes
		// some versions of this test; make sure not to make it pass there!
		//
		// Support: Firefox 70+
		// Only Firefox includes border widths
		// in computed dimensions. (gh-4529)
		reliableTrDimensions: function() {
			var table, tr, trChild, trStyle;
			if ( reliableTrDimensionsVal == null ) {
				table = document.createElement( "table" );
				tr = document.createElement( "tr" );
				trChild = document.createElement( "div" );

				table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
				tr.style.cssText = "border:1px solid";

				// Support: Chrome 86+
				// Height set through cssText does not get applied.
				// Computed height then comes back as 0.
				tr.style.height = "1px";
				trChild.style.height = "9px";

				// Support: Android 8 Chrome 86+
				// In our bodyBackground.html iframe,
				// display for all div elements is set to "inline",
				// which causes a problem only in Android 8 Chrome 86.
				// Ensuring the div is display: block
				// gets around this issue.
				trChild.style.display = "block";

				documentElement
					.appendChild( table )
					.appendChild( tr )
					.appendChild( trChild );

				trStyle = window.getComputedStyle( tr );
				reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) +
					parseInt( trStyle.borderTopWidth, 10 ) +
					parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight;

				documentElement.removeChild( table );
			}
			return reliableTrDimensionsVal;
		}
	} );
} )();


function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,
		isCustomProp = rcustomProp.test( name ),

		// Support: Firefox 51+
		// Retrieving style before computed somehow
		// fixes an issue with getting wrong values
		// on detached elements
		style = elem.style;

	computed = computed || getStyles( elem );

	// getPropertyValue is needed for:
	//   .css('filter') (IE 9 only, trac-12537)
	//   .css('--customProperty) (gh-3144)
	if ( computed ) {
		ret = computed.getPropertyValue( name ) || computed[ name ];

		// trim whitespace for custom property (issue gh-4926)
		if ( isCustomProp ) {

			// rtrim treats U+000D CARRIAGE RETURN and U+000C FORM FEED
			// as whitespace while CSS does not, but this is not a problem
			// because CSS preprocessing replaces them with U+000A LINE FEED
			// (which *is* CSS whitespace)
			// https://www.w3.org/TR/css-syntax-3/#input-preprocessing
			ret = ret.replace( rtrimCSS, "$1" );
		}

		if ( ret === "" &amp;&amp; !isAttached( elem ) ) {
			ret = jQuery.style( elem, name );
		}

		// A tribute to the "awesome hack by Dean Edwards"
		// Android Browser returns percentage for some values,
		// but width seems to be reliably pixels.
		// This is against the CSSOM draft spec:
		// https://drafts.csswg.org/cssom/#resolved-values
		if ( !support.pixelBoxStyles() &amp;&amp; rnumnonpx.test( ret ) &amp;&amp; rboxStyle.test( name ) ) {

			// Remember the original values
			width = style.width;
			minWidth = style.minWidth;
			maxWidth = style.maxWidth;

			// Put in the new values to get a computed value out
			style.minWidth = style.maxWidth = style.width = ret;
			ret = computed.width;

			// Revert the changed values
			style.width = width;
			style.minWidth = minWidth;
			style.maxWidth = maxWidth;
		}
	}

	return ret !== undefined ?

		// Support: IE &lt;=9 - 11 only
		// IE returns zIndex value as an integer.
		ret + "" :
		ret;
}


function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var cssPrefixes = [ "Webkit", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style,
	vendorProps = {};

// Return a vendor-prefixed property or undefined
function vendorPropName( name ) {

	// Check for vendor prefixed names
	var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
function finalPropName( name ) {
	var final = jQuery.cssProps[ name ] || vendorProps[ name ];

	if ( final ) {
		return final;
	}
	if ( name in emptyStyle ) {
		return name;
	}
	return vendorProps[ name ] = vendorPropName( name ) || name;
}


var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	};

function setPositiveNumber( _elem, value, subtract ) {

	// Any relative (+/-) values have already been
	// normalized at this point
	var matches = rcssNum.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
		value;
}

function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
	var i = dimension === "width" ? 1 : 0,
		extra = 0,
		delta = 0;

	// Adjustment may not be necessary
	if ( box === ( isBorderBox ? "border" : "content" ) ) {
		return 0;
	}

	for ( ; i &lt; 4; i += 2 ) {

		// Both box models exclude margin
		if ( box === "margin" ) {
			delta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
		}

		// If we get here with a content-box, we're seeking "padding" or "border" or "margin"
		if ( !isBorderBox ) {

			// Add padding
			delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// For "border" or "margin", add border
			if ( box !== "padding" ) {
				delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );

			// But still keep track of it otherwise
			} else {
				extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}

		// If we get here with a border-box (content + padding + border), we're seeking "content" or
		// "padding" or "margin"
		} else {

			// For "content", subtract padding
			if ( box === "content" ) {
				delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// For "content" or "padding", subtract border
			if ( box !== "margin" ) {
				delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	// Account for positive content-box scroll gutter when requested by providing computedVal
	if ( !isBorderBox &amp;&amp; computedVal &gt;= 0 ) {

		// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
		// Assuming integer scroll gutter, subtract the rest and round down
		delta += Math.max( 0, Math.ceil(
			elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
			computedVal -
			delta -
			extra -
			0.5

		// If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
		// Use an explicit zero to avoid NaN (gh-3964)
		) ) || 0;
	}

	return delta;
}

function getWidthOrHeight( elem, dimension, extra ) {

	// Start with computed style
	var styles = getStyles( elem ),

		// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
		// Fake content-box until we know it's needed to know the true value.
		boxSizingNeeded = !support.boxSizingReliable() || extra,
		isBorderBox = boxSizingNeeded &amp;&amp;
			jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
		valueIsBorderBox = isBorderBox,

		val = curCSS( elem, dimension, styles ),
		offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );

	// Support: Firefox &lt;=54
	// Return a confounding non-pixel value or feign ignorance, as appropriate.
	if ( rnumnonpx.test( val ) ) {
		if ( !extra ) {
			return val;
		}
		val = "auto";
	}


	// Support: IE 9 - 11 only
	// Use offsetWidth/offsetHeight for when box sizing is unreliable.
	// In those cases, the computed value can be trusted to be border-box.
	if ( ( !support.boxSizingReliable() &amp;&amp; isBorderBox ||

		// Support: IE 10 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Interestingly, in some cases IE 9 doesn't suffer from this issue.
		!support.reliableTrDimensions() &amp;&amp; nodeName( elem, "tr" ) ||

		// Fall back to offsetWidth/offsetHeight when value is "auto"
		// This happens for inline elements with no explicit setting (gh-3571)
		val === "auto" ||

		// Support: Android &lt;=4.1 - 4.3 only
		// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
		!parseFloat( val ) &amp;&amp; jQuery.css( elem, "display", false, styles ) === "inline" ) &amp;&amp;

		// Make sure the element is visible &amp; connected
		elem.getClientRects().length ) {

		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

		// Where available, offsetWidth/offsetHeight approximate border box dimensions.
		// Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
		// retrieved value as a content box dimension.
		valueIsBorderBox = offsetProp in elem;
		if ( valueIsBorderBox ) {
			val = elem[ offsetProp ];
		}
	}

	// Normalize "" and auto
	val = parseFloat( val ) || 0;

	// Adjust for the element's box model
	return ( val +
		boxModelAdjustment(
			elem,
			dimension,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles,

			// Provide the current computed size to request scroll gutter calculation (gh-3589)
			val
		)
	) + "px";
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		"animationIterationCount": true,
		"columnCount": true,
		"fillOpacity": true,
		"flexGrow": true,
		"flexShrink": true,
		"fontWeight": true,
		"gridArea": true,
		"gridColumn": true,
		"gridColumnEnd": true,
		"gridColumnStart": true,
		"gridRow": true,
		"gridRowEnd": true,
		"gridRowStart": true,
		"lineHeight": true,
		"opacity": true,
		"order": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name ),
			style = elem.style;

		// Make sure that we're working with the right name. We don't
		// want to query the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Gets hook for the prefixed version, then unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (trac-7345)
			if ( type === "string" &amp;&amp; ( ret = rcssNum.exec( value ) ) &amp;&amp; ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug trac-9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set (trac-7116)
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			// The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
			// "px" to a few hardcoded values.
			if ( type === "number" &amp;&amp; !isCustomProp ) {
				value += ret &amp;&amp; ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// background-* props affect original clone's values
			if ( !support.clearCloneStyle &amp;&amp; value === "" &amp;&amp; name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				if ( isCustomProp ) {
					style.setProperty( name, value );
				} else {
					style[ name ] = value;
				}
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks &amp;&amp; "get" in hooks &amp;&amp;
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var val, num, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name );

		// Make sure that we're working with the right name. We don't
		// want to modify the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Try prefixed name followed by the unprefixed name
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks &amp;&amp; "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		// Convert "normal" to computed value
		if ( val === "normal" &amp;&amp; name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Make numeric if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}

		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( _i, dimension ) {
	jQuery.cssHooks[ dimension ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &amp;&amp;

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth &amp; zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE &lt;=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
					swap( elem, cssShow, function() {
						return getWidthOrHeight( elem, dimension, extra );
					} ) :
					getWidthOrHeight( elem, dimension, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = getStyles( elem ),

				// Only read styles.position if the test has a chance to fail
				// to avoid forcing a reflow.
				scrollboxSizeBuggy = !support.scrollboxSize() &amp;&amp;
					styles.position === "absolute",

				// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
				boxSizingNeeded = scrollboxSizeBuggy || extra,
				isBorderBox = boxSizingNeeded &amp;&amp;
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
				subtract = extra ?
					boxModelAdjustment(
						elem,
						dimension,
						extra,
						isBorderBox,
						styles
					) :
					0;

			// Account for unreliable border-box dimensions by comparing offset* to computed and
			// faking a content-box to get border and padding (gh-3699)
			if ( isBorderBox &amp;&amp; scrollboxSizeBuggy ) {
				subtract -= Math.ceil(
					elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
					parseFloat( styles[ dimension ] ) -
					boxModelAdjustment( elem, dimension, "border", false, styles ) -
					0.5
				);
			}

			// Convert to pixels if value adjustment is needed
			if ( subtract &amp;&amp; ( matches = rcssNum.exec( value ) ) &amp;&amp;
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ dimension ] = value;
				value = jQuery.css( elem, dimension );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
				elem.getBoundingClientRect().left -
					swap( elem, { marginLeft: 0 }, function() {
						return elem.getBoundingClientRect().left;
					} )
			) + "px";
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i &lt; 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( prefix !== "margin" ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( Array.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i &lt; len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length &gt; 1 );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks &amp;&amp; hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks &amp;&amp; hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null &amp;&amp; tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// Passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails.
			// Simple values such as "10px" are parsed to Float;
			// complex values such as "rotate(1rad)" are returned as-is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// Use step hook for back compat.
			// Use cssHook if its there.
			// Use .style if available and use plain properties where available.
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 &amp;&amp; (
				jQuery.cssHooks[ tween.prop ] ||
					tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE &lt;=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType &amp;&amp; tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back compat &lt;1.8 extension point
jQuery.fx.step = {};




var
	fxNow, inProgress,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

function schedule() {
	if ( inProgress ) {
		if ( document.hidden === false &amp;&amp; window.requestAnimationFrame ) {
			window.requestAnimationFrame( schedule );
		} else {
			window.setTimeout( schedule, jQuery.fx.interval );
		}

		jQuery.fx.tick();
	}
}

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = Date.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		i = 0,
		attrs = { height: type };

	// If we include width, step value is 1 to do all cssExpand values,
	// otherwise step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i &lt; 4; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index &lt; length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// We're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
		isBox = "width" in props || "height" in props,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType &amp;&amp; isHiddenWithinTree( elem ),
		dataShow = dataPriv.get( elem, "fxshow" );

	// Queue-skipping animations hijack the fx hooks
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// Ensure the complete handler is called before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// Detect show/hide animations
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.test( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// Pretend to be hidden if this is a "show" and
				// there is still data from a stopped show/hide
				if ( value === "show" &amp;&amp; dataShow &amp;&amp; dataShow[ prop ] !== undefined ) {
					hidden = true;

				// Ignore all other no-op show/hide data
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow &amp;&amp; dataShow[ prop ] || jQuery.style( elem, prop );
		}
	}

	// Bail out if this is a no-op like .hide().hide()
	propTween = !jQuery.isEmptyObject( props );
	if ( !propTween &amp;&amp; jQuery.isEmptyObject( orig ) ) {
		return;
	}

	// Restrict "overflow" and "display" styles during box animations
	if ( isBox &amp;&amp; elem.nodeType === 1 ) {

		// Support: IE &lt;=9 - 11, Edge 12 - 15
		// Record all 3 overflow attributes because IE does not infer the shorthand
		// from identically-valued overflowX and overflowY and Edge just mirrors
		// the overflowX value there.
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Identify a display type, preferring old show/hide data over the CSS cascade
		restoreDisplay = dataShow &amp;&amp; dataShow.display;
		if ( restoreDisplay == null ) {
			restoreDisplay = dataPriv.get( elem, "display" );
		}
		display = jQuery.css( elem, "display" );
		if ( display === "none" ) {
			if ( restoreDisplay ) {
				display = restoreDisplay;
			} else {

				// Get nonempty value(s) by temporarily forcing visibility
				showHide( [ elem ], true );
				restoreDisplay = elem.style.display || restoreDisplay;
				display = jQuery.css( elem, "display" );
				showHide( [ elem ] );
			}
		}

		// Animate inline elements as inline-block
		if ( display === "inline" || display === "inline-block" &amp;&amp; restoreDisplay != null ) {
			if ( jQuery.css( elem, "float" ) === "none" ) {

				// Restore the original display value at the end of pure show/hide animations
				if ( !propTween ) {
					anim.done( function() {
						style.display = restoreDisplay;
					} );
					if ( restoreDisplay == null ) {
						display = style.display;
						restoreDisplay = display === "none" ? "" : display;
					}
				}
				style.display = "inline-block";
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		anim.always( function() {
			style.overflow = opts.overflow[ 0 ];
			style.overflowX = opts.overflow[ 1 ];
			style.overflowY = opts.overflow[ 2 ];
		} );
	}

	// Implement show/hide animations
	propTween = false;
	for ( prop in orig ) {

		// General show/hide setup for this element animation
		if ( !propTween ) {
			if ( dataShow ) {
				if ( "hidden" in dataShow ) {
					hidden = dataShow.hidden;
				}
			} else {
				dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
			}

			// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
			if ( toggle ) {
				dataShow.hidden = !hidden;
			}

			// Show elements before animating them
			if ( hidden ) {
				showHide( [ elem ], true );
			}

			/* eslint-disable no-loop-func */

			anim.done( function() {

				/* eslint-enable no-loop-func */

				// The final step of a "hide" animation is actually hiding the element
				if ( !hidden ) {
					showHide( [ elem ] );
				}
				dataPriv.remove( elem, "fxshow" );
				for ( prop in orig ) {
					jQuery.style( elem, prop, orig[ prop ] );
				}
			} );
		}

		// Per-property setup
		propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
		if ( !( prop in dataShow ) ) {
			dataShow[ prop ] = propTween.start;
			if ( hidden ) {
				propTween.end = propTween.start;
				propTween.start = 0;
			}
		}
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( Array.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks &amp;&amp; "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// Not quite $.extend, this won't overwrite existing keys.
			// Reusing 'index' because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// Don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3 only
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index &lt; length; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			// If there's more to do, yield
			if ( percent &lt; 1 &amp;&amp; length ) {
				return remaining;
			}

			// If this was an empty animation, synthesize a final progress notification
			if ( !length ) {
				deferred.notifyWith( elem, [ animation, 1, 0 ] );
			}

			// Resolve the animation and report its conclusion
			deferred.resolveWith( elem, [ animation ] );
			return false;
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
					animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// If we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index &lt; length; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// Resolve when we played the last frame; otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index &lt; length; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					result.stop.bind( result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	// Attach callbacks from options
	animation
		.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	return animation;
}

jQuery.Animation = jQuery.extend( Animation, {

	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnothtmlwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index &lt; length; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed &amp;&amp; typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn &amp;&amp; easing ||
			isFunction( speed ) &amp;&amp; speed,
		duration: speed,
		easing: fn &amp;&amp; easing || easing &amp;&amp; !isFunction( easing ) &amp;&amp; easing
	};

	// Go to the end state if fx are off
	if ( jQuery.fx.off ) {
		opt.duration = 0;

	} else {
		if ( typeof opt.duration !== "number" ) {
			if ( opt.duration in jQuery.fx.speeds ) {
				opt.duration = jQuery.fx.speeds[ opt.duration ];

			} else {
				opt.duration = jQuery.fx.speeds._default;
			}
		}
	}

	// Normalize opt.queue - true/undefined/null -&gt; "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// Show any hidden elements after setting opacity to 0
		return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()

			// Animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || dataPriv.get( this, "finish" ) ) {
					anim.stop( true );
				}
			};

		doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null &amp;&amp; type + "queueHooks",
				timers = jQuery.timers,
				data = dataPriv.get( this );

			if ( index ) {
				if ( data[ index ] &amp;&amp; data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] &amp;&amp; data[ index ].stop &amp;&amp; rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &amp;&amp;
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// Start the next in the queue if the last step wasn't forced.
			// Timers currently will call their complete callbacks, which
			// will dequeue but only if they were gotoEnd.
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = dataPriv.get( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// Enable finishing flag on private data
			data.finish = true;

			// Empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks &amp;&amp; hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// Look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &amp;&amp; timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// Look for any animations in the old queue and finish them
			for ( index = 0; index &lt; length; index++ ) {
				if ( queue[ index ] &amp;&amp; queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// Turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		i = 0,
		timers = jQuery.timers;

	fxNow = Date.now();

	for ( ; i &lt; timers.length; i++ ) {
		timer = timers[ i ];

		// Run the timer and safely remove it when done (allowing for external removal)
		if ( !timer() &amp;&amp; timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	jQuery.fx.start();
};

jQuery.fx.interval = 13;
jQuery.fx.start = function() {
	if ( inProgress ) {
		return;
	}

	inProgress = true;
	schedule();
};

jQuery.fx.stop = function() {
	inProgress = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var input = document.createElement( "input" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	input.type = "checkbox";

	// Support: Android &lt;=4.3 only
	// Default value for a checkbox should be "on"
	support.checkOn = input.value !== "";

	// Support: IE &lt;=11 only
	// Must access selectedIndex to make default options select
	support.optSelected = opt.selected;

	// Support: IE &lt;=11 only
	// An input loses its value after becoming a radio
	input = document.createElement( "input" );
	input.value = "t";
	input.type = "radio";
	support.radioValue = input.value === "t";
} )();


var boolHook,
	attrHandle = jQuery.expr.attrHandle;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length &gt; 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// Attribute hooks are determined by the lowercase version
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks &amp;&amp; "set" in hooks &amp;&amp;
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks &amp;&amp; "get" in hooks &amp;&amp; ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue &amp;&amp; value === "radio" &amp;&amp;
					nodeName( elem, "input" ) ) {
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name,
			i = 0,

			// Attribute names can contain non-HTML whitespace characters
			// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
			attrNames = value &amp;&amp; value.match( rnothtmlwhite );

		if ( attrNames &amp;&amp; elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				elem.removeAttribute( name );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			elem.setAttribute( name, name );
		}
		return name;
	}
};

jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = function( elem, name, isXML ) {
		var ret, handle,
			lowercaseName = name.toLowerCase();

		if ( !isXML ) {

			// Avoid an infinite loop by temporarily removing this function from the getter
			handle = attrHandle[ lowercaseName ];
			attrHandle[ lowercaseName ] = ret;
			ret = getter( elem, name, isXML ) != null ?
				lowercaseName :
				null;
			attrHandle[ lowercaseName ] = handle;
		}
		return ret;
	};
} );




var rfocusable = /^(?:input|select|textarea|button)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length &gt; 1 );
	},

	removeProp: function( name ) {
		return this.each( function() {
			delete this[ jQuery.propFix[ name ] || name ];
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks &amp;&amp; "set" in hooks &amp;&amp;
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks &amp;&amp; "get" in hooks &amp;&amp; ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// Support: IE &lt;=9 - 11 only
				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// Use proper attribute retrieval (trac-12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				if ( tabindex ) {
					return parseInt( tabindex, 10 );
				}

				if (
					rfocusable.test( elem.nodeName ) ||
					rclickable.test( elem.nodeName ) &amp;&amp;
					elem.href
				) {
					return 0;
				}

				return -1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Support: IE &lt;=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent &amp;&amp; parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		},
		set: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );




	// Strip and collapse whitespace according to HTML spec
	// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
	function stripAndCollapse( value ) {
		var tokens = value.match( rnothtmlwhite ) || [];
		return tokens.join( " " );
	}


function getClass( elem ) {
	return elem.getAttribute &amp;&amp; elem.getAttribute( "class" ) || "";
}

function classesToArray( value ) {
	if ( Array.isArray( value ) ) {
		return value;
	}
	if ( typeof value === "string" ) {
		return value.match( rnothtmlwhite ) || [];
	}
	return [];
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classNames, cur, curValue, className, i, finalValue;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		classNames = classesToArray( value );

		if ( classNames.length ) {
			return this.each( function() {
				curValue = getClass( this );
				cur = this.nodeType === 1 &amp;&amp; ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					for ( i = 0; i &lt; classNames.length; i++ ) {
						className = classNames[ i ];
						if ( cur.indexOf( " " + className + " " ) &lt; 0 ) {
							cur += className + " ";
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						this.setAttribute( "class", finalValue );
					}
				}
			} );
		}

		return this;
	},

	removeClass: function( value ) {
		var classNames, cur, curValue, className, i, finalValue;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		classNames = classesToArray( value );

		if ( classNames.length ) {
			return this.each( function() {
				curValue = getClass( this );

				// This expression is here for better compressibility (see addClass)
				cur = this.nodeType === 1 &amp;&amp; ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					for ( i = 0; i &lt; classNames.length; i++ ) {
						className = classNames[ i ];

						// Remove *all* instances
						while ( cur.indexOf( " " + className + " " ) &gt; -1 ) {
							cur = cur.replace( " " + className + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						this.setAttribute( "class", finalValue );
					}
				}
			} );
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var classNames, className, i, self,
			type = typeof value,
			isValidValue = type === "string" || Array.isArray( value );

		if ( isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		if ( typeof stateVal === "boolean" &amp;&amp; isValidValue ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		classNames = classesToArray( value );

		return this.each( function() {
			if ( isValidValue ) {

				// Toggle individual class names
				self = jQuery( this );

				for ( i = 0; i &lt; classNames.length; i++ ) {
					className = classNames[ i ];

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// Store className if set
					dataPriv.set( this, "__className__", className );
				}

				// If the element has a class name or if we're passed `false`,
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				if ( this.setAttribute ) {
					this.setAttribute( "class",
						className || value === false ?
							"" :
							dataPriv.get( this, "__className__" ) || ""
					);
				}
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &amp;&amp;
				( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) &gt; -1 ) {
				return true;
			}
		}

		return false;
	}
} );




var rreturn = /\r/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, valueIsFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks &amp;&amp;
					"get" in hooks &amp;&amp;
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				// Handle most common string cases
				if ( typeof ret === "string" ) {
					return ret.replace( rreturn, "" );
				}

				// Handle cases where value is null/undef or number
				return ret == null ? "" : ret;
			}

			return;
		}

		valueIsFunction = isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( valueIsFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";

			} else if ( typeof val === "number" ) {
				val += "";

			} else if ( Array.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {

				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE &lt;=10 - 11 only
					// option.text throws exceptions (trac-14686, trac-14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					stripAndCollapse( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option, i,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one",
					values = one ? null : [],
					max = one ? index + 1 : options.length;

				if ( index &lt; 0 ) {
					i = max;

				} else {
					i = one ? index : 0;
				}

				// Loop through all the selected options
				for ( ; i &lt; max; i++ ) {
					option = options[ i ];

					// Support: IE &lt;=9 only
					// IE8-9 doesn't update selected after form reset (trac-2551)
					if ( ( option.selected || i === index ) &amp;&amp;

							// Don't return options that are disabled or in a disabled optgroup
							!option.disabled &amp;&amp;
							( !option.parentNode.disabled ||
								!nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					/* eslint-disable no-cond-assign */

					if ( option.selected =
						jQuery.inArray( jQuery.valHooks.option.get( option ), values ) &gt; -1
					) {
						optionSet = true;
					}

					/* eslint-enable no-cond-assign */
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( Array.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) &gt; -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




// Return jQuery for attributes-only inclusion


support.focusin = "onfocusin" in window;


var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	stopPropagationCallback = function( e ) {
		e.stopPropagation();
	};

jQuery.extend( jQuery.event, {

	trigger: function( event, data, elem, onlyHandlers ) {

		var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = lastElement = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) &gt; -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) &lt; 0 &amp;&amp; "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" &amp;&amp; event );

		// Trigger bitmask: &amp; 1 for native handlers; &amp; 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers &amp;&amp; special.trigger &amp;&amp; special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (trac-9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724)
		if ( !onlyHandlers &amp;&amp; !special.noBubble &amp;&amp; !isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) &amp;&amp; !event.isPropagationStopped() ) {
			lastElement = cur;
			event.type = i &gt; 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] &amp;&amp;
				dataPriv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype &amp;&amp; cur[ ontype ];
			if ( handle &amp;&amp; handle.apply &amp;&amp; acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers &amp;&amp; !event.isDefaultPrevented() ) {

			if ( ( !special._default ||
				special._default.apply( eventPath.pop(), data ) === false ) &amp;&amp;
				acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name as the event.
				// Don't do default actions on window, that's where global variables be (trac-6170)
				if ( ontype &amp;&amp; isFunction( elem[ type ] ) &amp;&amp; !isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;

					if ( event.isPropagationStopped() ) {
						lastElement.addEventListener( type, stopPropagationCallback );
					}

					elem[ type ]();

					if ( event.isPropagationStopped() ) {
						lastElement.removeEventListener( type, stopPropagationCallback );
					}

					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	// Piggyback on a donor event to simulate a different one
	// Used only for `focus(in | out)` events
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true
			}
		);

		jQuery.event.trigger( e, null, elem );
	}

} );

jQuery.fn.extend( {

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


// Support: Firefox &lt;=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome &lt;=48 - 49, Safari &lt;=9.0 - 9.1
// focus(in | out) events fire after focus &amp; blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
	jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler on the document while someone wants focusin/focusout
		var handler = function( event ) {
			jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
		};

		jQuery.event.special[ fix ] = {
			setup: function() {

				// Handle: regular nodes (via `this.ownerDocument`), window
				// (via `this.document`) &amp; document (via `this`).
				var doc = this.ownerDocument || this.document || this,
					attaches = dataPriv.access( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this.document || this,
					attaches = dataPriv.access( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					dataPriv.remove( doc, fix );

				} else {
					dataPriv.access( doc, fix, attaches );
				}
			}
		};
	} );
}
var location = window.location;

var nonce = { guid: Date.now() };

var rquery = ( /\?/ );



// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml, parserErrorElem;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE 9 - 11 only
	// IE throws on parseFromString with invalid input.
	try {
		xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
	} catch ( e ) {}

	parserErrorElem = xml &amp;&amp; xml.getElementsByTagName( "parsererror" )[ 0 ];
	if ( !xml || parserErrorElem ) {
		jQuery.error( "Invalid XML: " + (
			parserErrorElem ?
				jQuery.map( parserErrorElem.childNodes, function( el ) {
					return el.textContent;
				} ).join( "\n" ) :
				data
		) );
	}
	return xml;
};


var
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( Array.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" &amp;&amp; v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional &amp;&amp; toType( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, valueOrFunction ) {

			// If value is a function, invoke it and use its return value
			var value = isFunction( valueOrFunction ) ?
				valueOrFunction() :
				valueOrFunction;

			s[ s.length ] = encodeURIComponent( key ) + "=" +
				encodeURIComponent( value == null ? "" : value );
		};

	if ( a == null ) {
		return "";
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( Array.isArray( a ) || ( a.jquery &amp;&amp; !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&amp;" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} ).filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name &amp;&amp; !jQuery( this ).is( ":disabled" ) &amp;&amp;
				rsubmittable.test( this.nodeName ) &amp;&amp; !rsubmitterTypes.test( type ) &amp;&amp;
				( this.checked || !rcheckableType.test( type ) );
		} ).map( function( _i, elem ) {
			var val = jQuery( this ).val();

			if ( val == null ) {
				return null;
			}

			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}

			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


var
	r20 = /%20/g,
	rhash = /#.*$/,
	rantiCache = /([?&amp;])_=[^&amp;]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

	// trac-7653, trac-8125, trac-8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Anchor tag for parsing the document origin
	originAnchor = document.createElement( "a" );

originAnchor.href = location.href;

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];

		if ( isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType[ 0 ] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &amp;&amp;
				!seekingTransport &amp;&amp; !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] &amp;&amp; inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes trac-9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] &amp;&amp; contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev &amp;&amp; isSuccess &amp;&amp; s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

			// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" &amp;&amp; prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv &amp;&amp; s.throws ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: location.href,
		type: "GET",
		isLocal: rlocalProtocol.test( location.protocol ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",

		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": JSON.parse,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var transport,

			// URL without anti-cache param
			cacheURL,

			// Response headers
			responseHeadersString,
			responseHeaders,

			// timeout handle
			timeoutTimer,

			// Url cleanup var
			urlAnchor,

			// Request state (becomes false upon send and true upon completion)
			completed,

			// To know if global events are to be dispatched
			fireGlobals,

			// Loop variable
			i,

			// uncached part of the url
			uncached,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &amp;&amp;
				( callbackContext.nodeType || callbackContext.jquery ) ?
				jQuery( callbackContext ) :
				jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( completed ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() + " " ] =
									( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )
										.concat( match[ 2 ] );
							}
						}
						match = responseHeaders[ key.toLowerCase() + " " ];
					}
					return match == null ? null : match.join( ", " );
				},

				// Raw string
				getAllResponseHeaders: function() {
					return completed ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( completed == null ) {
						name = requestHeadersNames[ name.toLowerCase() ] =
							requestHeadersNames[ name.toLowerCase() ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( completed == null ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( completed ) {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						} else {

							// Lazy-add the new callbacks in a way that preserves old ones
							for ( code in map ) {
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR );

		// Add protocol if not provided (prefilters might expect it)
		// Handle falsy url in the settings object (trac-10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || location.href ) + "" )
			.replace( rprotocol, location.protocol + "//" );

		// Alias method option to type as per ticket trac-12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];

		// A cross-domain request is in order when the origin doesn't match the current origin.
		if ( s.crossDomain == null ) {
			urlAnchor = document.createElement( "a" );

			// Support: IE &lt;=8 - 11, Edge 12 - 15
			// IE throws exception on accessing the href property if url is malformed,
			// e.g. http://example.com:80x/
			try {
				urlAnchor.href = s.url;

				// Support: IE &lt;=8 - 11 only
				// Anchor's host property isn't correctly set when s.url is relative
				urlAnchor.href = urlAnchor.href;
				s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
					urlAnchor.protocol + "//" + urlAnchor.host;
			} catch ( e ) {

				// If there is an error parsing the URL, assume it is crossDomain,
				// it can be rejected by the transport if it is invalid
				s.crossDomain = true;
			}
		}

		// Convert data if not already a string
		if ( s.data &amp;&amp; s.processData &amp;&amp; typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( completed ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118)
		fireGlobals = jQuery.event &amp;&amp; s.global;

		// Watch for a new set of requests
		if ( fireGlobals &amp;&amp; jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		// Remove hash to simplify url manipulation
		cacheURL = s.url.replace( rhash, "" );

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// Remember the hash so we can put it back
			uncached = s.url.slice( cacheURL.length );

			// If data is available and should be processed, append data to url
			if ( s.data &amp;&amp; ( s.processData || typeof s.data === "string" ) ) {
				cacheURL += ( rquery.test( cacheURL ) ? "&amp;" : "?" ) + s.data;

				// trac-9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add or update anti-cache param if needed
			if ( s.cache === false ) {
				cacheURL = cacheURL.replace( rantiCache, "$1" );
				uncached = ( rquery.test( cacheURL ) ? "&amp;" : "?" ) + "_=" + ( nonce.guid++ ) +
					uncached;
			}

			// Put hash and anti-cache on the URL that will be requested (gh-1732)
			s.url = cacheURL + uncached;

		// Change '%20' to '+' if this is encoded form body content (gh-2658)
		} else if ( s.data &amp;&amp; s.processData &amp;&amp;
			( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
			s.data = s.data.replace( r20, "+" );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data &amp;&amp; s.hasContent &amp;&amp; s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] &amp;&amp; s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &amp;&amp;
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// Aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		completeDeferred.add( s.complete );
		jqXHR.done( s.success );
		jqXHR.fail( s.error );

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( completed ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async &amp;&amp; s.timeout &gt; 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				completed = false;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Rethrow post-completion exceptions
				if ( completed ) {
					throw e;
				}

				// Propagate others as results
				done( -1, e );
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Ignore repeat invocations
			if ( completed ) {
				return;
			}

			completed = true;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status &gt; 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status &gt;= 200 &amp;&amp; status &lt; 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Use a noop converter for missing script but not if jsonp
			if ( !isSuccess &amp;&amp;
				jQuery.inArray( "script", s.dataTypes ) &gt; -1 &amp;&amp;
				jQuery.inArray( "json", s.dataTypes ) &lt; 0 ) {
				s.converters[ "text script" ] = function() {};
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// Extract error from statusText and normalize for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status &lt; 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( _i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) &amp;&amp; url ) );
	};
} );

jQuery.ajaxPrefilter( function( s ) {
	var i;
	for ( i in s.headers ) {
		if ( i.toLowerCase() === "content-type" ) {
			s.contentType = s.headers[ i ] || "";
		}
	}
} );


jQuery._evalUrl = function( url, options, doc ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (trac-11264)
		type: "GET",
		dataType: "script",
		cache: true,
		async: false,
		global: false,

		// Only evaluate the response if it is successful (gh-4126)
		// dataFilter is not invoked for failure responses, so using it instead
		// of the default converter is kludgy but it works.
		converters: {
			"text script": function() {}
		},
		dataFilter: function( response ) {
			jQuery.globalEval( response, options, doc );
		}
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		var wrap;

		if ( this[ 0 ] ) {
			if ( isFunction( html ) ) {
				html = html.call( this[ 0 ] );
			}

			// The elements to wrap the target around
			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstElementChild ) {
					elem = elem.firstElementChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var htmlIsFunction = isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function( selector ) {
		this.parent( selector ).not( "body" ).each( function() {
			jQuery( this ).replaceWith( this.childNodes );
		} );
		return this;
	}
} );


jQuery.expr.pseudos.hidden = function( elem ) {
	return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
	return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};




jQuery.ajaxSettings.xhr = function() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
};

var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE &lt;=9 only
		// trac-1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	xhrSupported = jQuery.ajaxSettings.xhr();

support.cors = !!xhrSupported &amp;&amp; ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport( function( options ) {
	var callback, errorCallback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported &amp;&amp; !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr();

				xhr.open(
					options.type,
					options.url,
					options.async,
					options.username,
					options.password
				);

				// Apply custom fields if provided
				if ( options.xhrFields ) {
					for ( i in options.xhrFields ) {
						xhr[ i ] = options.xhrFields[ i ];
					}
				}

				// Override mime type if needed
				if ( options.mimeType &amp;&amp; xhr.overrideMimeType ) {
					xhr.overrideMimeType( options.mimeType );
				}

				// X-Requested-With header
				// For cross-domain requests, seeing as conditions for a preflight are
				// akin to a jigsaw puzzle, we simply never set it to be sure.
				// (it can always be set on a per-request basis or even using ajaxSetup)
				// For same-domain requests, won't change header if already provided.
				if ( !options.crossDomain &amp;&amp; !headers[ "X-Requested-With" ] ) {
					headers[ "X-Requested-With" ] = "XMLHttpRequest";
				}

				// Set headers
				for ( i in headers ) {
					xhr.setRequestHeader( i, headers[ i ] );
				}

				// Callback
				callback = function( type ) {
					return function() {
						if ( callback ) {
							callback = errorCallback = xhr.onload =
								xhr.onerror = xhr.onabort = xhr.ontimeout =
									xhr.onreadystatechange = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {

								// Support: IE &lt;=9 only
								// On a manual native abort, IE9 throws
								// errors on any property access that is not readyState
								if ( typeof xhr.status !== "number" ) {
									complete( 0, "error" );
								} else {
									complete(

										// File: protocol always yields status 0; see trac-8605, trac-14207
										xhr.status,
										xhr.statusText
									);
								}
							} else {
								complete(
									xhrSuccessStatus[ xhr.status ] || xhr.status,
									xhr.statusText,

									// Support: IE &lt;=9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									( xhr.responseType || "text" ) !== "text"  ||
									typeof xhr.responseText !== "string" ?
										{ binary: xhr.response } :
										{ text: xhr.responseText },
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );

				// Support: IE 9 only
				// Use onreadystatechange to replace onabort
				// to handle uncaught aborts
				if ( xhr.onabort !== undefined ) {
					xhr.onabort = errorCallback;
				} else {
					xhr.onreadystatechange = function() {

						// Check readyState before timeout as it changes
						if ( xhr.readyState === 4 ) {

							// Allow onerror to be called first,
							// but that will not handle a native abort
							// Also, save errorCallback to a variable
							// as xhr.onerror cannot be accessed
							window.setTimeout( function() {
								if ( callback ) {
									errorCallback();
								}
							} );
						}
					};
				}

				// Create the abort callback
				callback = callback( "abort" );

				try {

					// Do send the request (this may raise an exception)
					xhr.send( options.hasContent &amp;&amp; options.data || null );
				} catch ( e ) {

					// trac-14683: Only rethrow if this hasn't been notified as an error yet
					if ( callback ) {
						throw e;
					}
				}
			},

			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
	if ( s.crossDomain ) {
		s.contents.script = false;
	}
} );

// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain or forced-by-attrs requests
	if ( s.crossDomain || s.scriptAttrs ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "&lt;script&gt;" )
					.attr( s.scriptAttrs || {} )
					.prop( { charset: s.scriptCharset, src: s.url } )
					.on( "load error", callback = function( evt ) {
						script.remove();
						callback = null;
						if ( evt ) {
							complete( evt.type === "error" ? 404 : 200, evt.type );
						}
					} );

				// Use native DOM manipulation to avoid our domManip AJAX trickery
				document.head.appendChild( script[ 0 ] );
			},
			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&amp;|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false &amp;&amp; ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &amp;&amp;
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &amp;&amp;
				rjsonp.test( s.data ) &amp;&amp; "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&amp;" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer &amp;&amp; isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
	var body = document.implementation.createHTMLDocument( "" ).body;
	body.innerHTML = "&lt;form&gt;&lt;/form&gt;&lt;form&gt;&lt;/form&gt;";
	return body.childNodes.length === 2;
} )();


// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( typeof data !== "string" ) {
		return [];
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}

	var base, parsed, scripts;

	if ( !context ) {

		// Stop scripts or inline event handlers from being executed immediately
		// by using document.implementation
		if ( support.createHTMLDocument ) {
			context = document.implementation.createHTMLDocument( "" );

			// Set the base href for the created document
			// so any parsed elements with URLs
			// are based on the document's URL (gh-2965)
			base = context.createElement( "base" );
			base.href = document.location.href;
			context.head.appendChild( base );
		} else {
			context = document;
		}
	}

	parsed = rsingleTag.exec( data );
	scripts = !keepScripts &amp;&amp; [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts &amp;&amp; scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off &gt; -1 ) {
		selector = stripAndCollapse( url.slice( off ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params &amp;&amp; typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length &gt; 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "&lt;div&gt;" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback &amp;&amp; function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




jQuery.expr.pseudos.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};




jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// Set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &amp;&amp;
			( curCSSTop + curCSSLeft ).indexOf( "auto" ) &gt; -1;

		// Need to be able to calculate position if either
		// top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;

		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );

		} else {
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {

	// offset() relates an element's border box to the document origin
	offset: function( options ) {

		// Preserve chaining for setter
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var rect, win,
			elem = this[ 0 ];

		if ( !elem ) {
			return;
		}

		// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
		// Support: IE &lt;=11 only
		// Running getBoundingClientRect on a
		// disconnected node in IE throws an error
		if ( !elem.getClientRects().length ) {
			return { top: 0, left: 0 };
		}

		// Get document-relative position by adding viewport scroll to viewport-relative gBCR
		rect = elem.getBoundingClientRect();
		win = elem.ownerDocument.defaultView;
		return {
			top: rect.top + win.pageYOffset,
			left: rect.left + win.pageXOffset
		};
	},

	// position() relates an element's margin box to its offset parent's padding box
	// This corresponds to the behavior of CSS absolute positioning
	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset, doc,
			elem = this[ 0 ],
			parentOffset = { top: 0, left: 0 };

		// position:fixed elements are offset from the viewport, which itself always has zero offset
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// Assume position:fixed implies availability of getBoundingClientRect
			offset = elem.getBoundingClientRect();

		} else {
			offset = this.offset();

			// Account for the *real* offset parent, which can be the document or its root element
			// when a statically positioned element is identified
			doc = elem.ownerDocument;
			offsetParent = elem.offsetParent || doc.documentElement;
			while ( offsetParent &amp;&amp;
				( offsetParent === doc.body || offsetParent === doc.documentElement ) &amp;&amp;
				jQuery.css( offsetParent, "position" ) === "static" ) {

				offsetParent = offsetParent.parentNode;
			}
			if ( offsetParent &amp;&amp; offsetParent !== elem &amp;&amp; offsetParent.nodeType === 1 ) {

				// Incorporate borders into its offset, since they are outside its content origin
				parentOffset = jQuery( offsetParent ).offset();
				parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
				parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
			}
		}

		// Subtract parent offsets and element margins
		return {
			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	// This method will return documentElement in the following cases:
	// 1) For the element inside the iframe without offsetParent, this method will return
	//    documentElement of the parent window
	// 2) For the hidden or detached element
	// 3) For body or html element, i.e. in case of the html node - it will return itself
	//
	// but those exceptions were never presented as a real life use-cases
	// and might be considered as more preferable results.
	//
	// This logic, however, is not guaranteed and can change at any point in the future
	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent &amp;&amp; jQuery.css( offsetParent, "position" ) === "static" ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = "pageYOffset" === prop;

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {

			// Coalesce documents and windows
			var win;
			if ( isWindow( elem ) ) {
				win = elem;
			} else if ( elem.nodeType === 9 ) {
				win = elem.defaultView;
			}

			if ( val === undefined ) {
				return win ? win[ prop ] : elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : win.pageXOffset,
					top ? val : win.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length );
	};
} );

// Support: Safari &lt;=7 - 9.1, Chrome &lt;=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( _i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( {
		padding: "inner" + name,
		content: type,
		"": "outer" + name
	}, function( defaultExtra, funcName ) {

		// Margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length &amp;&amp; ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( isWindow( elem ) ) {

					// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
					return funcName.indexOf( "outer" ) === 0 ?
						elem[ "inner" + name ] :
						elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable );
		};
	} );
} );


jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( _i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	},

	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );

jQuery.each(
	( "blur focus focusin focusout resize scroll click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup contextmenu" ).split( " " ),
	function( _i, name ) {

		// Handle event binding
		jQuery.fn[ name ] = function( data, fn ) {
			return arguments.length &gt; 0 ?
				this.on( name, null, data, fn ) :
				this.trigger( name );
		};
	}
);




// Support: Android &lt;=4.0 only
// Make sure we trim BOM and NBSP
// Require that the "whitespace run" starts from a non-whitespace
// to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position.
var rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;

// Bind a function to a context, optionally partially applying any
// arguments.
// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
// However, it is not slated for removal any time soon
jQuery.proxy = function( fn, context ) {
	var tmp, args, proxy;

	if ( typeof context === "string" ) {
		tmp = fn[ context ];
		context = fn;
		fn = tmp;
	}

	// Quick check to determine if target is callable, in the spec
	// this throws a TypeError, but we will just return undefined.
	if ( !isFunction( fn ) ) {
		return undefined;
	}

	// Simulated bind
	args = slice.call( arguments, 2 );
	proxy = function() {
		return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
	};

	// Set the guid of unique handler to the same of original handler, so it can be removed
	proxy.guid = fn.guid = fn.guid || jQuery.guid++;

	return proxy;
};

jQuery.holdReady = function( hold ) {
	if ( hold ) {
		jQuery.readyWait++;
	} else {
		jQuery.ready( true );
	}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
jQuery.isFunction = isFunction;
jQuery.isWindow = isWindow;
jQuery.camelCase = camelCase;
jQuery.type = toType;

jQuery.now = Date.now;

jQuery.isNumeric = function( obj ) {

	// As of jQuery 3.0, isNumeric is limited to
	// strings and numbers (primitives or objects)
	// that can be coerced to finite numbers (gh-2662)
	var type = jQuery.type( obj );
	return ( type === "number" || type === "string" ) &amp;&amp;

		// parseFloat NaNs numeric-cast false positives ("")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		!isNaN( obj - parseFloat( obj ) );
};

jQuery.trim = function( text ) {
	return text == null ?
		"" :
		( text + "" ).replace( rtrim, "$1" );
};



// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( typeof define === "function" &amp;&amp; define.amd ) {
	define( "jquery", [], function() {
		return jQuery;
	} );
}




var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep &amp;&amp; window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (trac-7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (trac-13566)
if ( typeof noGlobal === "undefined" ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;
} );
/* jshint node: true */

/**
 * Unobtrusive scripting adapter for jQuery
 * https://github.com/rails/jquery-ujs
 *
 * Requires jQuery 1.8.0 or later.
 *
 * Released under the MIT license
 *
 */

(function() {
  'use strict';

  var jqueryUjsInit = function($, undefined) {

  // Cut down on the number of issues from people inadvertently including jquery_ujs twice
  // by detecting and raising an error when it happens.
  if ( $.rails !== undefined ) {
    $.error('jquery-ujs has already been loaded!');
  }

  // Shorthand to make it a little easier to call public rails functions from within rails.js
  var rails;
  var $document = $(document);

  $.rails = rails = {
    // Link elements bound by jquery-ujs
    linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]',

    // Button elements bound by jquery-ujs
    buttonClickSelector: 'button[data-remote]:not([form]):not(form button), button[data-confirm]:not([form]):not(form button)',

    // Select elements bound by jquery-ujs
    inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',

    // Form elements bound by jquery-ujs
    formSubmitSelector: 'form:not([data-turbo=true])',

    // Form input elements bound by jquery-ujs
    formInputClickSelector: 'form:not([data-turbo=true]) input[type=submit], form:not([data-turbo=true]) input[type=image], form:not([data-turbo=true]) button[type=submit], form:not([data-turbo=true]) button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',

    // Form input elements disabled during form submission
    disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',

    // Form input elements re-enabled after form submission
    enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',

    // Form required input elements
    requiredInputSelector: 'input[name][required]:not([disabled]), textarea[name][required]:not([disabled])',

    // Form file input elements
    fileInputSelector: 'input[name][type=file]:not([disabled])',

    // Link onClick disable selector with possible reenable after remote submission
    linkDisableSelector: 'a[data-disable-with], a[data-disable]',

    // Button onClick disable selector with possible reenable after remote submission
    buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]',

    // Up-to-date Cross-Site Request Forgery token
    csrfToken: function() {
     return $('meta[name=csrf-token]').attr('content');
    },

    // URL param that must contain the CSRF token
    csrfParam: function() {
     return $('meta[name=csrf-param]').attr('content');
    },

    // Make sure that every Ajax request sends the CSRF token
    CSRFProtection: function(xhr) {
      var token = rails.csrfToken();
      if (token) xhr.setRequestHeader('X-CSRF-Token', token);
    },

    // Make sure that all forms have actual up-to-date tokens (cached forms contain old ones)
    refreshCSRFTokens: function(){
      $('form input[name="' + rails.csrfParam() + '"]').val(rails.csrfToken());
    },

    // Triggers an event on an element and returns false if the event result is false
    fire: function(obj, name, data) {
      var event = $.Event(name);
      obj.trigger(event, data);
      return event.result !== false;
    },

    // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
    confirm: function(message) {
      return confirm(message);
    },

    // Default ajax function, may be overridden with custom function in $.rails.ajax
    ajax: function(options) {
      return $.ajax(options);
    },

    // Default way to get an element's href. May be overridden at $.rails.href.
    href: function(element) {
      return element[0].href;
    },

    // Checks "data-remote" if true to handle the request through a XHR request.
    isRemote: function(element) {
      return element.data('remote') !== undefined &amp;&amp; element.data('remote') !== false;
    },

    // Submits "remote" forms and links with ajax
    handleRemote: function(element) {
      var method, url, data, withCredentials, dataType, options;

      if (rails.fire(element, 'ajax:before')) {
        withCredentials = element.data('with-credentials') || null;
        dataType = element.data('type') || ($.ajaxSettings &amp;&amp; $.ajaxSettings.dataType);

        if (element.is('form')) {
          method = element.data('ujs:submit-button-formmethod') || element.attr('method');
          url = element.data('ujs:submit-button-formaction') || element.attr('action');
          data = $(element[0]).serializeArray();
          // memoized value from clicked submit button
          var button = element.data('ujs:submit-button');
          if (button) {
            data.push(button);
            element.data('ujs:submit-button', null);
          }
          element.data('ujs:submit-button-formmethod', null);
          element.data('ujs:submit-button-formaction', null);
        } else if (element.is(rails.inputChangeSelector)) {
          method = element.data('method');
          url = element.data('url');
          data = element.serialize();
          if (element.data('params')) data = data + '&amp;' + element.data('params');
        } else if (element.is(rails.buttonClickSelector)) {
          method = element.data('method') || 'get';
          url = element.data('url');
          data = element.serialize();
          if (element.data('params')) data = data + '&amp;' + element.data('params');
        } else {
          method = element.data('method');
          url = rails.href(element);
          data = element.data('params') || null;
        }

        options = {
          type: method || 'GET', data: data, dataType: dataType,
          // stopping the "ajax:beforeSend" event will cancel the ajax request
          beforeSend: function(xhr, settings) {
            if (settings.dataType === undefined) {
              xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
            }
            if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) {
              element.trigger('ajax:send', xhr);
            } else {
              return false;
            }
          },
          success: function(data, status, xhr) {
            element.trigger('ajax:success', [data, status, xhr]);
          },
          complete: function(xhr, status) {
            element.trigger('ajax:complete', [xhr, status]);
          },
          error: function(xhr, status, error) {
            element.trigger('ajax:error', [xhr, status, error]);
          },
          crossDomain: rails.isCrossDomain(url)
        };

        // There is no withCredentials for IE6-8 when
        // "Enable native XMLHTTP support" is disabled
        if (withCredentials) {
          options.xhrFields = {
            withCredentials: withCredentials
          };
        }

        // Only pass url to `ajax` options if not blank
        if (url) { options.url = url; }

        return rails.ajax(options);
      } else {
        return false;
      }
    },

    // Determines if the request is a cross domain request.
    isCrossDomain: function(url) {
      var originAnchor = document.createElement('a');
      originAnchor.href = location.href;
      var urlAnchor = document.createElement('a');

      try {
        urlAnchor.href = url;
        // This is a workaround to a IE bug.
        urlAnchor.href = urlAnchor.href;

        // If URL protocol is false or is a string containing a single colon
        // *and* host are false, assume it is not a cross-domain request
        // (should only be the case for IE7 and IE compatibility mode).
        // Otherwise, evaluate protocol and host of the URL against the origin
        // protocol and host.
        return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') &amp;&amp; !urlAnchor.host) ||
          (originAnchor.protocol + '//' + originAnchor.host ===
            urlAnchor.protocol + '//' + urlAnchor.host));
      } catch (e) {
        // If there is an error parsing the URL, assume it is crossDomain.
        return true;
      }
    },

    // Handles "data-method" on links such as:
    // &lt;a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?"&gt;Delete&lt;/a&gt;
    handleMethod: function(link) {
      var href = rails.href(link),
        method = link.data('method'),
        target = link.attr('target'),
        csrfToken = rails.csrfToken(),
        csrfParam = rails.csrfParam(),
        form = $('&lt;form method="post" action="' + href + '"&gt;&lt;/form&gt;'),
        metadataInput = '&lt;input name="_method" value="' + method + '" type="hidden" /&gt;';

      if (csrfParam !== undefined &amp;&amp; csrfToken !== undefined &amp;&amp; !rails.isCrossDomain(href)) {
        metadataInput += '&lt;input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" /&gt;';
      }

      if (target) { form.attr('target', target); }

      form.hide().append(metadataInput).appendTo('body');
      form.submit();
    },

    // Helper function that returns form elements that match the specified CSS selector
    // If form is actually a "form" element this will return associated elements outside the from that have
    // the html form attribute set
    formElements: function(form, selector) {
      return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector);
    },

    /* Disables form elements:
      - Caches element value in 'ujs:enable-with' data store
      - Replaces element text with value of 'data-disable-with' attribute
      - Sets disabled property to true
    */
    disableFormElements: function(form) {
      rails.formElements(form, rails.disableSelector).each(function() {
        rails.disableFormElement($(this));
      });
    },

    disableFormElement: function(element) {
      var method, replacement;

      method = element.is('button') ? 'html' : 'val';
      replacement = element.data('disable-with');

      if (replacement !== undefined) {
        element.data('ujs:enable-with', element[method]());
        element[method](replacement);
      }

      element.prop('disabled', true);
      element.data('ujs:disabled', true);
    },

    /* Re-enables disabled form elements:
      - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
      - Sets disabled property to false
    */
    enableFormElements: function(form) {
      rails.formElements(form, rails.enableSelector).each(function() {
        rails.enableFormElement($(this));
      });
    },

    enableFormElement: function(element) {
      var method = element.is('button') ? 'html' : 'val';
      if (element.data('ujs:enable-with') !== undefined) {
        element[method](element.data('ujs:enable-with'));
        element.removeData('ujs:enable-with'); // clean up cache
      }
      element.prop('disabled', false);
      element.removeData('ujs:disabled');
    },

   /* For 'data-confirm' attribute:
      - Fires `confirm` event
      - Shows the confirmation dialog
      - Fires the `confirm:complete` event

      Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
      Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
      Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
      return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
   */
    allowAction: function(element) {
      var message = element.data('confirm'),
          answer = false, callback;
      if (!message) { return true; }

      if (rails.fire(element, 'confirm')) {
        try {
          answer = rails.confirm(message);
        } catch (e) {
          (console.error || console.log).call(console, e.stack || e);
        }
        callback = rails.fire(element, 'confirm:complete', [answer]);
      }
      return answer &amp;&amp; callback;
    },

    // Helper function which checks for blank inputs in a form that match the specified CSS selector
    blankInputs: function(form, specifiedSelector, nonBlank) {
      var foundInputs = $(),
        input,
        valueToCheck,
        radiosForNameWithNoneSelected,
        radioName,
        selector = specifiedSelector || 'input,textarea',
        requiredInputs = form.find(selector),
        checkedRadioButtonNames = {};

      requiredInputs.each(function() {
        input = $(this);
        if (input.is('input[type=radio]')) {

          // Don't count unchecked required radio as blank if other radio with same name is checked,
          // regardless of whether same-name radio input has required attribute or not. The spec
          // states https://www.w3.org/TR/html5/forms.html#the-required-attribute
          radioName = input.attr('name');

          // Skip if we've already seen the radio with this name.
          if (!checkedRadioButtonNames[radioName]) {

            // If none checked
            if (form.find('input[type=radio]:checked[name="' + radioName + '"]').length === 0) {
              radiosForNameWithNoneSelected = form.find(
                'input[type=radio][name="' + radioName + '"]');
              foundInputs = foundInputs.add(radiosForNameWithNoneSelected);
            }

            // We only need to check each name once.
            checkedRadioButtonNames[radioName] = radioName;
          }
        } else {
          valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : !!input.val();
          if (valueToCheck === nonBlank) {
            foundInputs = foundInputs.add(input);
          }
        }
      });
      return foundInputs.length ? foundInputs : false;
    },

    // Helper function which checks for non-blank inputs in a form that match the specified CSS selector
    nonBlankInputs: function(form, specifiedSelector) {
      return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
    },

    // Helper function, needed to provide consistent behavior in IE
    stopEverything: function(e) {
      $(e.target).trigger('ujs:everythingStopped');
      e.stopImmediatePropagation();
      return false;
    },

    //  Replace element's html with the 'data-disable-with' after storing original html
    //  and prevent clicking on it
    disableElement: function(element) {
      var replacement = element.data('disable-with');

      if (replacement !== undefined) {
        element.data('ujs:enable-with', element.html()); // store enabled state
        element.html(replacement);
      }

      element.on('click.railsDisable', function(e) { // prevent further clicking
        return rails.stopEverything(e);
      });
      element.data('ujs:disabled', true);
    },

    // Restore element to its original state which was disabled by 'disableElement' above
    enableElement: function(element) {
      if (element.data('ujs:enable-with') !== undefined) {
        element.html(element.data('ujs:enable-with')); // set to old enabled state
        element.removeData('ujs:enable-with'); // clean up cache
      }
      element.off('click.railsDisable'); // enable element
      element.removeData('ujs:disabled');
    }
  };

  if (rails.fire($document, 'rails:attachBindings')) {

    $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }});

    // This event works the same as the load event, except that it fires every
    // time the page is loaded.
    //
    // See https://github.com/rails/jquery-ujs/issues/357
    // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
    $(window).on('pageshow.rails', function () {
      $($.rails.enableSelector).each(function () {
        var element = $(this);

        if (element.data('ujs:disabled')) {
          $.rails.enableFormElement(element);
        }
      });

      $($.rails.linkDisableSelector).each(function () {
        var element = $(this);

        if (element.data('ujs:disabled')) {
          $.rails.enableElement(element);
        }
      });
    });

    $document.on('ajax:complete', rails.linkDisableSelector, function() {
        rails.enableElement($(this));
    });

    $document.on('ajax:complete', rails.buttonDisableSelector, function() {
        rails.enableFormElement($(this));
    });

    $document.on('click.rails', rails.linkClickSelector, function(e) {
      var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey;
      if (!rails.allowAction(link)) return rails.stopEverything(e);

      if (!metaClick &amp;&amp; link.is(rails.linkDisableSelector)) rails.disableElement(link);

      if (rails.isRemote(link)) {
        if (metaClick &amp;&amp; (!method || method === 'GET') &amp;&amp; !data) { return true; }

        var handleRemote = rails.handleRemote(link);
        // Response from rails.handleRemote() will either be false or a deferred object promise.
        if (handleRemote === false) {
          rails.enableElement(link);
        } else {
          handleRemote.fail( function() { rails.enableElement(link); } );
        }
        return false;

      } else if (method) {
        rails.handleMethod(link);
        return false;
      }
    });

    $document.on('click.rails', rails.buttonClickSelector, function(e) {
      var button = $(this);

      if (!rails.allowAction(button) || !rails.isRemote(button)) return rails.stopEverything(e);

      if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button);

      var handleRemote = rails.handleRemote(button);
      // Response from rails.handleRemote() will either be false or a deferred object promise.
      if (handleRemote === false) {
        rails.enableFormElement(button);
      } else {
        handleRemote.fail( function() { rails.enableFormElement(button); } );
      }
      return false;
    });

    $document.on('change.rails', rails.inputChangeSelector, function(e) {
      var link = $(this);
      if (!rails.allowAction(link) || !rails.isRemote(link)) return rails.stopEverything(e);

      rails.handleRemote(link);
      return false;
    });

    $document.on('submit.rails', rails.formSubmitSelector, function(e) {
      var form = $(this),
        remote = rails.isRemote(form),
        blankRequiredInputs,
        nonBlankFileInputs;

      if (!rails.allowAction(form)) return rails.stopEverything(e);

      // Skip other logic when required values are missing or file upload is present
      if (form.attr('novalidate') === undefined) {
        if (form.data('ujs:formnovalidate-button') === undefined) {
          blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector, false);
          if (blankRequiredInputs &amp;&amp; rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
            return rails.stopEverything(e);
          }
        } else {
          // Clear the formnovalidate in case the next button click is not on a formnovalidate button
          // Not strictly necessary to do here, since it is also reset on each button click, but just to be certain
          form.data('ujs:formnovalidate-button', undefined);
        }
      }

      if (remote) {
        nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
        if (nonBlankFileInputs) {
          // Slight timeout so that the submit button gets properly serialized
          // (make it easy for event handler to serialize form without disabled values)
          setTimeout(function(){ rails.disableFormElements(form); }, 13);
          var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);

          // Re-enable form elements if event bindings return false (canceling normal form submission)
          if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); }

          return aborted;
        }

        rails.handleRemote(form);
        return false;

      } else {
        // Slight timeout so that the submit button gets properly serialized
        setTimeout(function(){ rails.disableFormElements(form); }, 13);
      }
    });

    $document.on('click.rails', rails.formInputClickSelector, function(event) {
      var button = $(this);

      if (!rails.allowAction(button)) return rails.stopEverything(event);

      // Register the pressed submit button
      var name = button.attr('name'),
        data = name ? {name:name, value:button.val()} : null;

      var form = button.closest('form');
      if (form.length === 0) {
        form = $('#' + button.attr('form'));
      }
      form.data('ujs:submit-button', data);

      // Save attributes from button
      form.data('ujs:formnovalidate-button', button.attr('formnovalidate'));
      form.data('ujs:submit-button-formaction', button.attr('formaction'));
      form.data('ujs:submit-button-formmethod', button.attr('formmethod'));
    });

    $document.on('ajax:send.rails', rails.formSubmitSelector, function(event) {
      if (this === event.target) rails.disableFormElements($(this));
    });

    $document.on('ajax:complete.rails', rails.formSubmitSelector, function(event) {
      if (this === event.target) rails.enableFormElements($(this));
    });

    $(function(){
      rails.refreshCSRFTokens();
    });
  }

  };

  if (window.jQuery) {
    jqueryUjsInit(jQuery);
  } else if (typeof exports === 'object' &amp;&amp; typeof module === 'object') {
    module.exports = jqueryUjsInit;
  }
})();
/*
 Copyright (C) Federico Zivolo 2020
 Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
 */(function(e,t){'object'==typeof exports&amp;&amp;'undefined'!=typeof module?module.exports=t():'function'==typeof define&amp;&amp;define.amd?define(t):e.Popper=t()})(this,function(){'use strict';function e(e){return e&amp;&amp;'[object Function]'==={}.toString.call(e)}function t(e,t){if(1!==e.nodeType)return[];var o=e.ownerDocument.defaultView,n=o.getComputedStyle(e,null);return t?n[t]:n}function o(e){return'HTML'===e.nodeName?e:e.parentNode||e.host}function n(e){if(!e)return document.body;switch(e.nodeName){case'HTML':case'BODY':return e.ownerDocument.body;case'#document':return e.body;}var i=t(e),r=i.overflow,p=i.overflowX,s=i.overflowY;return /(auto|scroll|overlay)/.test(r+s+p)?e:n(o(e))}function i(e){return e&amp;&amp;e.referenceNode?e.referenceNode:e}function r(e){return 11===e?re:10===e?pe:re||pe}function p(e){if(!e)return document.documentElement;for(var o=r(10)?document.body:null,n=e.offsetParent||null;n===o&amp;&amp;e.nextElementSibling;)n=(e=e.nextElementSibling).offsetParent;var i=n&amp;&amp;n.nodeName;return i&amp;&amp;'BODY'!==i&amp;&amp;'HTML'!==i?-1!==['TH','TD','TABLE'].indexOf(n.nodeName)&amp;&amp;'static'===t(n,'position')?p(n):n:e?e.ownerDocument.documentElement:document.documentElement}function s(e){var t=e.nodeName;return'BODY'!==t&amp;&amp;('HTML'===t||p(e.firstElementChild)===e)}function d(e){return null===e.parentNode?e:d(e.parentNode)}function a(e,t){if(!e||!e.nodeType||!t||!t.nodeType)return document.documentElement;var o=e.compareDocumentPosition(t)&amp;Node.DOCUMENT_POSITION_FOLLOWING,n=o?e:t,i=o?t:e,r=document.createRange();r.setStart(n,0),r.setEnd(i,0);var l=r.commonAncestorContainer;if(e!==l&amp;&amp;t!==l||n.contains(i))return s(l)?l:p(l);var f=d(e);return f.host?a(f.host,t):a(e,d(t).host)}function l(e){var t=1&lt;arguments.length&amp;&amp;void 0!==arguments[1]?arguments[1]:'top',o='top'===t?'scrollTop':'scrollLeft',n=e.nodeName;if('BODY'===n||'HTML'===n){var i=e.ownerDocument.documentElement,r=e.ownerDocument.scrollingElement||i;return r[o]}return e[o]}function f(e,t){var o=2&lt;arguments.length&amp;&amp;void 0!==arguments[2]&amp;&amp;arguments[2],n=l(t,'top'),i=l(t,'left'),r=o?-1:1;return e.top+=n*r,e.bottom+=n*r,e.left+=i*r,e.right+=i*r,e}function m(e,t){var o='x'===t?'Left':'Top',n='Left'==o?'Right':'Bottom';return parseFloat(e['border'+o+'Width'])+parseFloat(e['border'+n+'Width'])}function h(e,t,o,n){return ee(t['offset'+e],t['scroll'+e],o['client'+e],o['offset'+e],o['scroll'+e],r(10)?parseInt(o['offset'+e])+parseInt(n['margin'+('Height'===e?'Top':'Left')])+parseInt(n['margin'+('Height'===e?'Bottom':'Right')]):0)}function c(e){var t=e.body,o=e.documentElement,n=r(10)&amp;&amp;getComputedStyle(o);return{height:h('Height',t,o,n),width:h('Width',t,o,n)}}function g(e){return le({},e,{right:e.left+e.width,bottom:e.top+e.height})}function u(e){var o={};try{if(r(10)){o=e.getBoundingClientRect();var n=l(e,'top'),i=l(e,'left');o.top+=n,o.left+=i,o.bottom+=n,o.right+=i}else o=e.getBoundingClientRect()}catch(t){}var p={left:o.left,top:o.top,width:o.right-o.left,height:o.bottom-o.top},s='HTML'===e.nodeName?c(e.ownerDocument):{},d=s.width||e.clientWidth||p.width,a=s.height||e.clientHeight||p.height,f=e.offsetWidth-d,h=e.offsetHeight-a;if(f||h){var u=t(e);f-=m(u,'x'),h-=m(u,'y'),p.width-=f,p.height-=h}return g(p)}function b(e,o){var i=2&lt;arguments.length&amp;&amp;void 0!==arguments[2]&amp;&amp;arguments[2],p=r(10),s='HTML'===o.nodeName,d=u(e),a=u(o),l=n(e),m=t(o),h=parseFloat(m.borderTopWidth),c=parseFloat(m.borderLeftWidth);i&amp;&amp;s&amp;&amp;(a.top=ee(a.top,0),a.left=ee(a.left,0));var b=g({top:d.top-a.top-h,left:d.left-a.left-c,width:d.width,height:d.height});if(b.marginTop=0,b.marginLeft=0,!p&amp;&amp;s){var w=parseFloat(m.marginTop),y=parseFloat(m.marginLeft);b.top-=h-w,b.bottom-=h-w,b.left-=c-y,b.right-=c-y,b.marginTop=w,b.marginLeft=y}return(p&amp;&amp;!i?o.contains(l):o===l&amp;&amp;'BODY'!==l.nodeName)&amp;&amp;(b=f(b,o)),b}function w(e){var t=1&lt;arguments.length&amp;&amp;void 0!==arguments[1]&amp;&amp;arguments[1],o=e.ownerDocument.documentElement,n=b(e,o),i=ee(o.clientWidth,window.innerWidth||0),r=ee(o.clientHeight,window.innerHeight||0),p=t?0:l(o),s=t?0:l(o,'left'),d={top:p-n.top+n.marginTop,left:s-n.left+n.marginLeft,width:i,height:r};return g(d)}function y(e){var n=e.nodeName;if('BODY'===n||'HTML'===n)return!1;if('fixed'===t(e,'position'))return!0;var i=o(e);return!!i&amp;&amp;y(i)}function E(e){if(!e||!e.parentElement||r())return document.documentElement;for(var o=e.parentElement;o&amp;&amp;'none'===t(o,'transform');)o=o.parentElement;return o||document.documentElement}function v(e,t,r,p){var s=4&lt;arguments.length&amp;&amp;void 0!==arguments[4]&amp;&amp;arguments[4],d={top:0,left:0},l=s?E(e):a(e,i(t));if('viewport'===p)d=w(l,s);else{var f;'scrollParent'===p?(f=n(o(t)),'BODY'===f.nodeName&amp;&amp;(f=e.ownerDocument.documentElement)):'window'===p?f=e.ownerDocument.documentElement:f=p;var m=b(f,l,s);if('HTML'===f.nodeName&amp;&amp;!y(l)){var h=c(e.ownerDocument),g=h.height,u=h.width;d.top+=m.top-m.marginTop,d.bottom=g+m.top,d.left+=m.left-m.marginLeft,d.right=u+m.left}else d=m}r=r||0;var v='number'==typeof r;return d.left+=v?r:r.left||0,d.top+=v?r:r.top||0,d.right-=v?r:r.right||0,d.bottom-=v?r:r.bottom||0,d}function x(e){var t=e.width,o=e.height;return t*o}function O(e,t,o,n,i){var r=5&lt;arguments.length&amp;&amp;void 0!==arguments[5]?arguments[5]:0;if(-1===e.indexOf('auto'))return e;var p=v(o,n,r,i),s={top:{width:p.width,height:t.top-p.top},right:{width:p.right-t.right,height:p.height},bottom:{width:p.width,height:p.bottom-t.bottom},left:{width:t.left-p.left,height:p.height}},d=Object.keys(s).map(function(e){return le({key:e},s[e],{area:x(s[e])})}).sort(function(e,t){return t.area-e.area}),a=d.filter(function(e){var t=e.width,n=e.height;return t&gt;=o.clientWidth&amp;&amp;n&gt;=o.clientHeight}),l=0&lt;a.length?a[0].key:d[0].key,f=e.split('-')[1];return l+(f?'-'+f:'')}function L(e,t,o){var n=3&lt;arguments.length&amp;&amp;void 0!==arguments[3]?arguments[3]:null,r=n?E(t):a(t,i(o));return b(o,r,n)}function S(e){var t=e.ownerDocument.defaultView,o=t.getComputedStyle(e),n=parseFloat(o.marginTop||0)+parseFloat(o.marginBottom||0),i=parseFloat(o.marginLeft||0)+parseFloat(o.marginRight||0),r={width:e.offsetWidth+i,height:e.offsetHeight+n};return r}function T(e){var t={left:'right',right:'left',bottom:'top',top:'bottom'};return e.replace(/left|right|bottom|top/g,function(e){return t[e]})}function C(e,t,o){o=o.split('-')[0];var n=S(e),i={width:n.width,height:n.height},r=-1!==['right','left'].indexOf(o),p=r?'top':'left',s=r?'left':'top',d=r?'height':'width',a=r?'width':'height';return i[p]=t[p]+t[d]/2-n[d]/2,i[s]=o===s?t[s]-n[a]:t[T(s)],i}function D(e,t){return Array.prototype.find?e.find(t):e.filter(t)[0]}function N(e,t,o){if(Array.prototype.findIndex)return e.findIndex(function(e){return e[t]===o});var n=D(e,function(e){return e[t]===o});return e.indexOf(n)}function P(t,o,n){var i=void 0===n?t:t.slice(0,N(t,'name',n));return i.forEach(function(t){t['function']&amp;&amp;console.warn('`modifier.function` is deprecated, use `modifier.fn`!');var n=t['function']||t.fn;t.enabled&amp;&amp;e(n)&amp;&amp;(o.offsets.popper=g(o.offsets.popper),o.offsets.reference=g(o.offsets.reference),o=n(o,t))}),o}function k(){if(!this.state.isDestroyed){var e={instance:this,styles:{},arrowStyles:{},attributes:{},flipped:!1,offsets:{}};e.offsets.reference=L(this.state,this.popper,this.reference,this.options.positionFixed),e.placement=O(this.options.placement,e.offsets.reference,this.popper,this.reference,this.options.modifiers.flip.boundariesElement,this.options.modifiers.flip.padding),e.originalPlacement=e.placement,e.positionFixed=this.options.positionFixed,e.offsets.popper=C(this.popper,e.offsets.reference,e.placement),e.offsets.popper.position=this.options.positionFixed?'fixed':'absolute',e=P(this.modifiers,e),this.state.isCreated?this.options.onUpdate(e):(this.state.isCreated=!0,this.options.onCreate(e))}}function W(e,t){return e.some(function(e){var o=e.name,n=e.enabled;return n&amp;&amp;o===t})}function B(e){for(var t=[!1,'ms','Webkit','Moz','O'],o=e.charAt(0).toUpperCase()+e.slice(1),n=0;n&lt;t.length;n++){var i=t[n],r=i?''+i+o:e;if('undefined'!=typeof document.body.style[r])return r}return null}function H(){return this.state.isDestroyed=!0,W(this.modifiers,'applyStyle')&amp;&amp;(this.popper.removeAttribute('x-placement'),this.popper.style.position='',this.popper.style.top='',this.popper.style.left='',this.popper.style.right='',this.popper.style.bottom='',this.popper.style.willChange='',this.popper.style[B('transform')]=''),this.disableEventListeners(),this.options.removeOnDestroy&amp;&amp;this.popper.parentNode.removeChild(this.popper),this}function A(e){var t=e.ownerDocument;return t?t.defaultView:window}function M(e,t,o,i){var r='BODY'===e.nodeName,p=r?e.ownerDocument.defaultView:e;p.addEventListener(t,o,{passive:!0}),r||M(n(p.parentNode),t,o,i),i.push(p)}function F(e,t,o,i){o.updateBound=i,A(e).addEventListener('resize',o.updateBound,{passive:!0});var r=n(e);return M(r,'scroll',o.updateBound,o.scrollParents),o.scrollElement=r,o.eventsEnabled=!0,o}function I(){this.state.eventsEnabled||(this.state=F(this.reference,this.options,this.state,this.scheduleUpdate))}function R(e,t){return A(e).removeEventListener('resize',t.updateBound),t.scrollParents.forEach(function(e){e.removeEventListener('scroll',t.updateBound)}),t.updateBound=null,t.scrollParents=[],t.scrollElement=null,t.eventsEnabled=!1,t}function U(){this.state.eventsEnabled&amp;&amp;(cancelAnimationFrame(this.scheduleUpdate),this.state=R(this.reference,this.state))}function Y(e){return''!==e&amp;&amp;!isNaN(parseFloat(e))&amp;&amp;isFinite(e)}function V(e,t){Object.keys(t).forEach(function(o){var n='';-1!==['width','height','top','right','bottom','left'].indexOf(o)&amp;&amp;Y(t[o])&amp;&amp;(n='px'),e.style[o]=t[o]+n})}function j(e,t){Object.keys(t).forEach(function(o){var n=t[o];!1===n?e.removeAttribute(o):e.setAttribute(o,t[o])})}function q(e,t){var o=e.offsets,n=o.popper,i=o.reference,r=$,p=function(e){return e},s=r(i.width),d=r(n.width),a=-1!==['left','right'].indexOf(e.placement),l=-1!==e.placement.indexOf('-'),f=t?a||l||s%2==d%2?r:Z:p,m=t?r:p;return{left:f(1==s%2&amp;&amp;1==d%2&amp;&amp;!l&amp;&amp;t?n.left-1:n.left),top:m(n.top),bottom:m(n.bottom),right:f(n.right)}}function K(e,t,o){var n=D(e,function(e){var o=e.name;return o===t}),i=!!n&amp;&amp;e.some(function(e){return e.name===o&amp;&amp;e.enabled&amp;&amp;e.order&lt;n.order});if(!i){var r='`'+t+'`';console.warn('`'+o+'`'+' modifier is required by '+r+' modifier in order to work, be sure to include it before '+r+'!')}return i}function z(e){return'end'===e?'start':'start'===e?'end':e}function G(e){var t=1&lt;arguments.length&amp;&amp;void 0!==arguments[1]&amp;&amp;arguments[1],o=he.indexOf(e),n=he.slice(o+1).concat(he.slice(0,o));return t?n.reverse():n}function _(e,t,o,n){var i=e.match(/((?:\-|\+)?\d*\.?\d*)(.*)/),r=+i[1],p=i[2];if(!r)return e;if(0===p.indexOf('%')){var s;switch(p){case'%p':s=o;break;case'%':case'%r':default:s=n;}var d=g(s);return d[t]/100*r}if('vh'===p||'vw'===p){var a;return a='vh'===p?ee(document.documentElement.clientHeight,window.innerHeight||0):ee(document.documentElement.clientWidth,window.innerWidth||0),a/100*r}return r}function X(e,t,o,n){var i=[0,0],r=-1!==['right','left'].indexOf(n),p=e.split(/(\+|\-)/).map(function(e){return e.trim()}),s=p.indexOf(D(p,function(e){return-1!==e.search(/,|\s/)}));p[s]&amp;&amp;-1===p[s].indexOf(',')&amp;&amp;console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');var d=/\s*,\s*|\s+/,a=-1===s?[p]:[p.slice(0,s).concat([p[s].split(d)[0]]),[p[s].split(d)[1]].concat(p.slice(s+1))];return a=a.map(function(e,n){var i=(1===n?!r:r)?'height':'width',p=!1;return e.reduce(function(e,t){return''===e[e.length-1]&amp;&amp;-1!==['+','-'].indexOf(t)?(e[e.length-1]=t,p=!0,e):p?(e[e.length-1]+=t,p=!1,e):e.concat(t)},[]).map(function(e){return _(e,i,t,o)})}),a.forEach(function(e,t){e.forEach(function(o,n){Y(o)&amp;&amp;(i[t]+=o*('-'===e[n-1]?-1:1))})}),i}function J(e,t){var o,n=t.offset,i=e.placement,r=e.offsets,p=r.popper,s=r.reference,d=i.split('-')[0];return o=Y(+n)?[+n,0]:X(n,p,s,d),'left'===d?(p.top+=o[0],p.left-=o[1]):'right'===d?(p.top+=o[0],p.left+=o[1]):'top'===d?(p.left+=o[0],p.top-=o[1]):'bottom'===d&amp;&amp;(p.left+=o[0],p.top+=o[1]),e.popper=p,e}var Q=Math.min,Z=Math.floor,$=Math.round,ee=Math.max,te='undefined'!=typeof window&amp;&amp;'undefined'!=typeof document&amp;&amp;'undefined'!=typeof navigator,oe=function(){for(var e=['Edge','Trident','Firefox'],t=0;t&lt;e.length;t+=1)if(te&amp;&amp;0&lt;=navigator.userAgent.indexOf(e[t]))return 1;return 0}(),ne=te&amp;&amp;window.Promise,ie=ne?function(e){var t=!1;return function(){t||(t=!0,window.Promise.resolve().then(function(){t=!1,e()}))}}:function(e){var t=!1;return function(){t||(t=!0,setTimeout(function(){t=!1,e()},oe))}},re=te&amp;&amp;!!(window.MSInputMethodContext&amp;&amp;document.documentMode),pe=te&amp;&amp;/MSIE 10/.test(navigator.userAgent),se=function(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')},de=function(){function e(e,t){for(var o,n=0;n&lt;t.length;n++)o=t[n],o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&amp;&amp;(o.writable=!0),Object.defineProperty(e,o.key,o)}return function(t,o,n){return o&amp;&amp;e(t.prototype,o),n&amp;&amp;e(t,n),t}}(),ae=function(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e},le=Object.assign||function(e){for(var t,o=1;o&lt;arguments.length;o++)for(var n in t=arguments[o],t)Object.prototype.hasOwnProperty.call(t,n)&amp;&amp;(e[n]=t[n]);return e},fe=te&amp;&amp;/Firefox/i.test(navigator.userAgent),me=['auto-start','auto','auto-end','top-start','top','top-end','right-start','right','right-end','bottom-end','bottom','bottom-start','left-end','left','left-start'],he=me.slice(3),ce={FLIP:'flip',CLOCKWISE:'clockwise',COUNTERCLOCKWISE:'counterclockwise'},ge=function(){function t(o,n){var i=this,r=2&lt;arguments.length&amp;&amp;void 0!==arguments[2]?arguments[2]:{};se(this,t),this.scheduleUpdate=function(){return requestAnimationFrame(i.update)},this.update=ie(this.update.bind(this)),this.options=le({},t.Defaults,r),this.state={isDestroyed:!1,isCreated:!1,scrollParents:[]},this.reference=o&amp;&amp;o.jquery?o[0]:o,this.popper=n&amp;&amp;n.jquery?n[0]:n,this.options.modifiers={},Object.keys(le({},t.Defaults.modifiers,r.modifiers)).forEach(function(e){i.options.modifiers[e]=le({},t.Defaults.modifiers[e]||{},r.modifiers?r.modifiers[e]:{})}),this.modifiers=Object.keys(this.options.modifiers).map(function(e){return le({name:e},i.options.modifiers[e])}).sort(function(e,t){return e.order-t.order}),this.modifiers.forEach(function(t){t.enabled&amp;&amp;e(t.onLoad)&amp;&amp;t.onLoad(i.reference,i.popper,i.options,t,i.state)}),this.update();var p=this.options.eventsEnabled;p&amp;&amp;this.enableEventListeners(),this.state.eventsEnabled=p}return de(t,[{key:'update',value:function(){return k.call(this)}},{key:'destroy',value:function(){return H.call(this)}},{key:'enableEventListeners',value:function(){return I.call(this)}},{key:'disableEventListeners',value:function(){return U.call(this)}}]),t}();return ge.Utils=('undefined'==typeof window?global:window).PopperUtils,ge.placements=me,ge.Defaults={placement:'bottom',positionFixed:!1,eventsEnabled:!0,removeOnDestroy:!1,onCreate:function(){},onUpdate:function(){},modifiers:{shift:{order:100,enabled:!0,fn:function(e){var t=e.placement,o=t.split('-')[0],n=t.split('-')[1];if(n){var i=e.offsets,r=i.reference,p=i.popper,s=-1!==['bottom','top'].indexOf(o),d=s?'left':'top',a=s?'width':'height',l={start:ae({},d,r[d]),end:ae({},d,r[d]+r[a]-p[a])};e.offsets.popper=le({},p,l[n])}return e}},offset:{order:200,enabled:!0,fn:J,offset:0},preventOverflow:{order:300,enabled:!0,fn:function(e,t){var o=t.boundariesElement||p(e.instance.popper);e.instance.reference===o&amp;&amp;(o=p(o));var n=B('transform'),i=e.instance.popper.style,r=i.top,s=i.left,d=i[n];i.top='',i.left='',i[n]='';var a=v(e.instance.popper,e.instance.reference,t.padding,o,e.positionFixed);i.top=r,i.left=s,i[n]=d,t.boundaries=a;var l=t.priority,f=e.offsets.popper,m={primary:function(e){var o=f[e];return f[e]&lt;a[e]&amp;&amp;!t.escapeWithReference&amp;&amp;(o=ee(f[e],a[e])),ae({},e,o)},secondary:function(e){var o='right'===e?'left':'top',n=f[o];return f[e]&gt;a[e]&amp;&amp;!t.escapeWithReference&amp;&amp;(n=Q(f[o],a[e]-('right'===e?f.width:f.height))),ae({},o,n)}};return l.forEach(function(e){var t=-1===['left','top'].indexOf(e)?'secondary':'primary';f=le({},f,m[t](e))}),e.offsets.popper=f,e},priority:['left','right','top','bottom'],padding:5,boundariesElement:'scrollParent'},keepTogether:{order:400,enabled:!0,fn:function(e){var t=e.offsets,o=t.popper,n=t.reference,i=e.placement.split('-')[0],r=Z,p=-1!==['top','bottom'].indexOf(i),s=p?'right':'bottom',d=p?'left':'top',a=p?'width':'height';return o[s]&lt;r(n[d])&amp;&amp;(e.offsets.popper[d]=r(n[d])-o[a]),o[d]&gt;r(n[s])&amp;&amp;(e.offsets.popper[d]=r(n[s])),e}},arrow:{order:500,enabled:!0,fn:function(e,o){var n;if(!K(e.instance.modifiers,'arrow','keepTogether'))return e;var i=o.element;if('string'==typeof i){if(i=e.instance.popper.querySelector(i),!i)return e;}else if(!e.instance.popper.contains(i))return console.warn('WARNING: `arrow.element` must be child of its popper element!'),e;var r=e.placement.split('-')[0],p=e.offsets,s=p.popper,d=p.reference,a=-1!==['left','right'].indexOf(r),l=a?'height':'width',f=a?'Top':'Left',m=f.toLowerCase(),h=a?'left':'top',c=a?'bottom':'right',u=S(i)[l];d[c]-u&lt;s[m]&amp;&amp;(e.offsets.popper[m]-=s[m]-(d[c]-u)),d[m]+u&gt;s[c]&amp;&amp;(e.offsets.popper[m]+=d[m]+u-s[c]),e.offsets.popper=g(e.offsets.popper);var b=d[m]+d[l]/2-u/2,w=t(e.instance.popper),y=parseFloat(w['margin'+f]),E=parseFloat(w['border'+f+'Width']),v=b-e.offsets.popper[m]-y-E;return v=ee(Q(s[l]-u,v),0),e.arrowElement=i,e.offsets.arrow=(n={},ae(n,m,$(v)),ae(n,h,''),n),e},element:'[x-arrow]'},flip:{order:600,enabled:!0,fn:function(e,t){if(W(e.instance.modifiers,'inner'))return e;if(e.flipped&amp;&amp;e.placement===e.originalPlacement)return e;var o=v(e.instance.popper,e.instance.reference,t.padding,t.boundariesElement,e.positionFixed),n=e.placement.split('-')[0],i=T(n),r=e.placement.split('-')[1]||'',p=[];switch(t.behavior){case ce.FLIP:p=[n,i];break;case ce.CLOCKWISE:p=G(n);break;case ce.COUNTERCLOCKWISE:p=G(n,!0);break;default:p=t.behavior;}return p.forEach(function(s,d){if(n!==s||p.length===d+1)return e;n=e.placement.split('-')[0],i=T(n);var a=e.offsets.popper,l=e.offsets.reference,f=Z,m='left'===n&amp;&amp;f(a.right)&gt;f(l.left)||'right'===n&amp;&amp;f(a.left)&lt;f(l.right)||'top'===n&amp;&amp;f(a.bottom)&gt;f(l.top)||'bottom'===n&amp;&amp;f(a.top)&lt;f(l.bottom),h=f(a.left)&lt;f(o.left),c=f(a.right)&gt;f(o.right),g=f(a.top)&lt;f(o.top),u=f(a.bottom)&gt;f(o.bottom),b='left'===n&amp;&amp;h||'right'===n&amp;&amp;c||'top'===n&amp;&amp;g||'bottom'===n&amp;&amp;u,w=-1!==['top','bottom'].indexOf(n),y=!!t.flipVariations&amp;&amp;(w&amp;&amp;'start'===r&amp;&amp;h||w&amp;&amp;'end'===r&amp;&amp;c||!w&amp;&amp;'start'===r&amp;&amp;g||!w&amp;&amp;'end'===r&amp;&amp;u),E=!!t.flipVariationsByContent&amp;&amp;(w&amp;&amp;'start'===r&amp;&amp;c||w&amp;&amp;'end'===r&amp;&amp;h||!w&amp;&amp;'start'===r&amp;&amp;u||!w&amp;&amp;'end'===r&amp;&amp;g),v=y||E;(m||b||v)&amp;&amp;(e.flipped=!0,(m||b)&amp;&amp;(n=p[d+1]),v&amp;&amp;(r=z(r)),e.placement=n+(r?'-'+r:''),e.offsets.popper=le({},e.offsets.popper,C(e.instance.popper,e.offsets.reference,e.placement)),e=P(e.instance.modifiers,e,'flip'))}),e},behavior:'flip',padding:5,boundariesElement:'viewport',flipVariations:!1,flipVariationsByContent:!1},inner:{order:700,enabled:!1,fn:function(e){var t=e.placement,o=t.split('-')[0],n=e.offsets,i=n.popper,r=n.reference,p=-1!==['left','right'].indexOf(o),s=-1===['top','left'].indexOf(o);return i[p?'left':'top']=r[o]-(s?i[p?'width':'height']:0),e.placement=T(t),e.offsets.popper=g(i),e}},hide:{order:800,enabled:!0,fn:function(e){if(!K(e.instance.modifiers,'hide','preventOverflow'))return e;var t=e.offsets.reference,o=D(e.instance.modifiers,function(e){return'preventOverflow'===e.name}).boundaries;if(t.bottom&lt;o.top||t.left&gt;o.right||t.top&gt;o.bottom||t.right&lt;o.left){if(!0===e.hide)return e;e.hide=!0,e.attributes['x-out-of-boundaries']=''}else{if(!1===e.hide)return e;e.hide=!1,e.attributes['x-out-of-boundaries']=!1}return e}},computeStyle:{order:850,enabled:!0,fn:function(e,t){var o=t.x,n=t.y,i=e.offsets.popper,r=D(e.instance.modifiers,function(e){return'applyStyle'===e.name}).gpuAcceleration;void 0!==r&amp;&amp;console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');var s,d,a=void 0===r?t.gpuAcceleration:r,l=p(e.instance.popper),f=u(l),m={position:i.position},h=q(e,2&gt;window.devicePixelRatio||!fe),c='bottom'===o?'top':'bottom',g='right'===n?'left':'right',b=B('transform');if(d='bottom'==c?'HTML'===l.nodeName?-l.clientHeight+h.bottom:-f.height+h.bottom:h.top,s='right'==g?'HTML'===l.nodeName?-l.clientWidth+h.right:-f.width+h.right:h.left,a&amp;&amp;b)m[b]='translate3d('+s+'px, '+d+'px, 0)',m[c]=0,m[g]=0,m.willChange='transform';else{var w='bottom'==c?-1:1,y='right'==g?-1:1;m[c]=d*w,m[g]=s*y,m.willChange=c+', '+g}var E={"x-placement":e.placement};return e.attributes=le({},E,e.attributes),e.styles=le({},m,e.styles),e.arrowStyles=le({},e.offsets.arrow,e.arrowStyles),e},gpuAcceleration:!0,x:'bottom',y:'right'},applyStyle:{order:900,enabled:!0,fn:function(e){return V(e.instance.popper,e.styles),j(e.instance.popper,e.attributes),e.arrowElement&amp;&amp;Object.keys(e.arrowStyles).length&amp;&amp;V(e.arrowElement,e.arrowStyles),e},onLoad:function(e,t,o,n,i){var r=L(i,t,e,o.positionFixed),p=O(o.placement,r,t,e,o.modifiers.flip.boundariesElement,o.modifiers.flip.padding);return t.setAttribute('x-placement',p),V(t,{position:o.positionFixed?'fixed':'absolute'}),o},gpuAcceleration:void 0}}},ge});
/*!
  * Bootstrap v4.6.2 (https://getbootstrap.com/)
  * Copyright 2011-2022 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
  */
(function (global, factory) {
  typeof exports === 'object' &amp;&amp; typeof module !== 'undefined' ? factory(exports, require('jquery'), require('popper.js')) :
  typeof define === 'function' &amp;&amp; define.amd ? define(['exports', 'jquery', 'popper.js'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.bootstrap = {}, global.jQuery, global.Popper));
})(this, (function (exports, $, Popper) { 'use strict';

  function _interopDefaultLegacy (e) { return e &amp;&amp; typeof e === 'object' &amp;&amp; 'default' in e ? e : { 'default': e }; }

  var $__default = /*#__PURE__*/_interopDefaultLegacy($);
  var Popper__default = /*#__PURE__*/_interopDefaultLegacy(Popper);

  function _defineProperties(target, props) {
    for (var i = 0; i &lt; props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    Object.defineProperty(Constructor, "prototype", {
      writable: false
    });
    return Constructor;
  }

  function _extends() {
    _extends = Object.assign ? Object.assign.bind() : function (target) {
      for (var i = 1; i &lt; arguments.length; i++) {
        var source = arguments[i];

        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }

      return target;
    };
    return _extends.apply(this, arguments);
  }

  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;

    _setPrototypeOf(subClass, superClass);
  }

  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
      o.__proto__ = p;
      return o;
    };
    return _setPrototypeOf(o, p);
  }

  /**
   * --------------------------------------------------------------------------
   * Bootstrap (v4.6.2): util.js
   * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
   * --------------------------------------------------------------------------
   */
  /**
   * Private TransitionEnd Helpers
   */

  var TRANSITION_END = 'transitionend';
  var MAX_UID = 1000000;
  var MILLISECONDS_MULTIPLIER = 1000; // Shoutout AngusCroll (https://goo.gl/pxwQGp)

  function toType(obj) {
    if (obj === null || typeof obj === 'undefined') {
      return "" + obj;
    }

    return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
  }

  function getSpecialTransitionEndEvent() {
    return {
      bindType: TRANSITION_END,
      delegateType: TRANSITION_END,
      handle: function handle(event) {
        if ($__default["default"](event.target).is(this)) {
          return event.handleObj.handler.apply(this, arguments); // eslint-disable-line prefer-rest-params
        }

        return undefined;
      }
    };
  }

  function transitionEndEmulator(duration) {
    var _this = this;

    var called = false;
    $__default["default"](this).one(Util.TRANSITION_END, function () {
      called = true;
    });
    setTimeout(function () {
      if (!called) {
        Util.triggerTransitionEnd(_this);
      }
    }, duration);
    return this;
  }

  function setTransitionEndSupport() {
    $__default["default"].fn.emulateTransitionEnd = transitionEndEmulator;
    $__default["default"].event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
  }
  /**
   * Public Util API
   */


  var Util = {
    TRANSITION_END: 'bsTransitionEnd',
    getUID: function getUID(prefix) {
      do {
        // eslint-disable-next-line no-bitwise
        prefix += ~~(Math.random() * MAX_UID); // "~~" acts like a faster Math.floor() here
      } while (document.getElementById(prefix));

      return prefix;
    },
    getSelectorFromElement: function getSelectorFromElement(element) {
      var selector = element.getAttribute('data-target');

      if (!selector || selector === '#') {
        var hrefAttr = element.getAttribute('href');
        selector = hrefAttr &amp;&amp; hrefAttr !== '#' ? hrefAttr.trim() : '';
      }

      try {
        return document.querySelector(selector) ? selector : null;
      } catch (_) {
        return null;
      }
    },
    getTransitionDurationFromElement: function getTransitionDurationFromElement(element) {
      if (!element) {
        return 0;
      } // Get transition-duration of the element


      var transitionDuration = $__default["default"](element).css('transition-duration');
      var transitionDelay = $__default["default"](element).css('transition-delay');
      var floatTransitionDuration = parseFloat(transitionDuration);
      var floatTransitionDelay = parseFloat(transitionDelay); // Return 0 if element or transition duration is not found

      if (!floatTransitionDuration &amp;&amp; !floatTransitionDelay) {
        return 0;
      } // If multiple durations are defined, take the first


      transitionDuration = transitionDuration.split(',')[0];
      transitionDelay = transitionDelay.split(',')[0];
      return (parseFloat(transitionDuration) + parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
    },
    reflow: function reflow(element) {
      return element.offsetHeight;
    },
    triggerTransitionEnd: function triggerTransitionEnd(element) {
      $__default["default"](element).trigger(TRANSITION_END);
    },
    supportsTransitionEnd: function supportsTransitionEnd() {
      return Boolean(TRANSITION_END);
    },
    isElement: function isElement(obj) {
      return (obj[0] || obj).nodeType;
    },
    typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) {
      for (var property in configTypes) {
        if (Object.prototype.hasOwnProperty.call(configTypes, property)) {
          var expectedTypes = configTypes[property];
          var value = config[property];
          var valueType = value &amp;&amp; Util.isElement(value) ? 'element' : toType(value);

          if (!new RegExp(expectedTypes).test(valueType)) {
            throw new Error(componentName.toUpperCase() + ": " + ("Option \"" + property + "\" provided type \"" + valueType + "\" ") + ("but expected type \"" + expectedTypes + "\"."));
          }
        }
      }
    },
    findShadowRoot: function findShadowRoot(element) {
      if (!document.documentElement.attachShadow) {
        return null;
      } // Can find the shadow root otherwise it'll return the document


      if (typeof element.getRootNode === 'function') {
        var root = element.getRootNode();
        return root instanceof ShadowRoot ? root : null;
      }

      if (element instanceof ShadowRoot) {
        return element;
      } // when we don't find a shadow root


      if (!element.parentNode) {
        return null;
      }

      return Util.findShadowRoot(element.parentNode);
    },
    jQueryDetection: function jQueryDetection() {
      if (typeof $__default["default"] === 'undefined') {
        throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.');
      }

      var version = $__default["default"].fn.jquery.split(' ')[0].split('.');
      var minMajor = 1;
      var ltMajor = 2;
      var minMinor = 9;
      var minPatch = 1;
      var maxMajor = 4;

      if (version[0] &lt; ltMajor &amp;&amp; version[1] &lt; minMinor || version[0] === minMajor &amp;&amp; version[1] === minMinor &amp;&amp; version[2] &lt; minPatch || version[0] &gt;= maxMajor) {
        throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0');
      }
    }
  };
  Util.jQueryDetection();
  setTransitionEndSupport();

  /**
   * Constants
   */

  var NAME$a = 'alert';
  var VERSION$a = '4.6.2';
  var DATA_KEY$a = 'bs.alert';
  var EVENT_KEY$a = "." + DATA_KEY$a;
  var DATA_API_KEY$7 = '.data-api';
  var JQUERY_NO_CONFLICT$a = $__default["default"].fn[NAME$a];
  var CLASS_NAME_ALERT = 'alert';
  var CLASS_NAME_FADE$5 = 'fade';
  var CLASS_NAME_SHOW$7 = 'show';
  var EVENT_CLOSE = "close" + EVENT_KEY$a;
  var EVENT_CLOSED = "closed" + EVENT_KEY$a;
  var EVENT_CLICK_DATA_API$6 = "click" + EVENT_KEY$a + DATA_API_KEY$7;
  var SELECTOR_DISMISS = '[data-dismiss="alert"]';
  /**
   * Class definition
   */

  var Alert = /*#__PURE__*/function () {
    function Alert(element) {
      this._element = element;
    } // Getters


    var _proto = Alert.prototype;

    // Public
    _proto.close = function close(element) {
      var rootElement = this._element;

      if (element) {
        rootElement = this._getRootElement(element);
      }

      var customEvent = this._triggerCloseEvent(rootElement);

      if (customEvent.isDefaultPrevented()) {
        return;
      }

      this._removeElement(rootElement);
    };

    _proto.dispose = function dispose() {
      $__default["default"].removeData(this._element, DATA_KEY$a);
      this._element = null;
    } // Private
    ;

    _proto._getRootElement = function _getRootElement(element) {
      var selector = Util.getSelectorFromElement(element);
      var parent = false;

      if (selector) {
        parent = document.querySelector(selector);
      }

      if (!parent) {
        parent = $__default["default"](element).closest("." + CLASS_NAME_ALERT)[0];
      }

      return parent;
    };

    _proto._triggerCloseEvent = function _triggerCloseEvent(element) {
      var closeEvent = $__default["default"].Event(EVENT_CLOSE);
      $__default["default"](element).trigger(closeEvent);
      return closeEvent;
    };

    _proto._removeElement = function _removeElement(element) {
      var _this = this;

      $__default["default"](element).removeClass(CLASS_NAME_SHOW$7);

      if (!$__default["default"](element).hasClass(CLASS_NAME_FADE$5)) {
        this._destroyElement(element);

        return;
      }

      var transitionDuration = Util.getTransitionDurationFromElement(element);
      $__default["default"](element).one(Util.TRANSITION_END, function (event) {
        return _this._destroyElement(element, event);
      }).emulateTransitionEnd(transitionDuration);
    };

    _proto._destroyElement = function _destroyElement(element) {
      $__default["default"](element).detach().trigger(EVENT_CLOSED).remove();
    } // Static
    ;

    Alert._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var $element = $__default["default"](this);
        var data = $element.data(DATA_KEY$a);

        if (!data) {
          data = new Alert(this);
          $element.data(DATA_KEY$a, data);
        }

        if (config === 'close') {
          data[config](this);
        }
      });
    };

    Alert._handleDismiss = function _handleDismiss(alertInstance) {
      return function (event) {
        if (event) {
          event.preventDefault();
        }

        alertInstance.close(this);
      };
    };

    _createClass(Alert, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$a;
      }
    }]);

    return Alert;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_CLICK_DATA_API$6, SELECTOR_DISMISS, Alert._handleDismiss(new Alert()));
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$a] = Alert._jQueryInterface;
  $__default["default"].fn[NAME$a].Constructor = Alert;

  $__default["default"].fn[NAME$a].noConflict = function () {
    $__default["default"].fn[NAME$a] = JQUERY_NO_CONFLICT$a;
    return Alert._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$9 = 'button';
  var VERSION$9 = '4.6.2';
  var DATA_KEY$9 = 'bs.button';
  var EVENT_KEY$9 = "." + DATA_KEY$9;
  var DATA_API_KEY$6 = '.data-api';
  var JQUERY_NO_CONFLICT$9 = $__default["default"].fn[NAME$9];
  var CLASS_NAME_ACTIVE$3 = 'active';
  var CLASS_NAME_BUTTON = 'btn';
  var CLASS_NAME_FOCUS = 'focus';
  var EVENT_CLICK_DATA_API$5 = "click" + EVENT_KEY$9 + DATA_API_KEY$6;
  var EVENT_FOCUS_BLUR_DATA_API = "focus" + EVENT_KEY$9 + DATA_API_KEY$6 + " " + ("blur" + EVENT_KEY$9 + DATA_API_KEY$6);
  var EVENT_LOAD_DATA_API$2 = "load" + EVENT_KEY$9 + DATA_API_KEY$6;
  var SELECTOR_DATA_TOGGLE_CARROT = '[data-toggle^="button"]';
  var SELECTOR_DATA_TOGGLES = '[data-toggle="buttons"]';
  var SELECTOR_DATA_TOGGLE$4 = '[data-toggle="button"]';
  var SELECTOR_DATA_TOGGLES_BUTTONS = '[data-toggle="buttons"] .btn';
  var SELECTOR_INPUT = 'input:not([type="hidden"])';
  var SELECTOR_ACTIVE$2 = '.active';
  var SELECTOR_BUTTON = '.btn';
  /**
   * Class definition
   */

  var Button = /*#__PURE__*/function () {
    function Button(element) {
      this._element = element;
      this.shouldAvoidTriggerChange = false;
    } // Getters


    var _proto = Button.prototype;

    // Public
    _proto.toggle = function toggle() {
      var triggerChangeEvent = true;
      var addAriaPressed = true;
      var rootElement = $__default["default"](this._element).closest(SELECTOR_DATA_TOGGLES)[0];

      if (rootElement) {
        var input = this._element.querySelector(SELECTOR_INPUT);

        if (input) {
          if (input.type === 'radio') {
            if (input.checked &amp;&amp; this._element.classList.contains(CLASS_NAME_ACTIVE$3)) {
              triggerChangeEvent = false;
            } else {
              var activeElement = rootElement.querySelector(SELECTOR_ACTIVE$2);

              if (activeElement) {
                $__default["default"](activeElement).removeClass(CLASS_NAME_ACTIVE$3);
              }
            }
          }

          if (triggerChangeEvent) {
            // if it's not a radio button or checkbox don't add a pointless/invalid checked property to the input
            if (input.type === 'checkbox' || input.type === 'radio') {
              input.checked = !this._element.classList.contains(CLASS_NAME_ACTIVE$3);
            }

            if (!this.shouldAvoidTriggerChange) {
              $__default["default"](input).trigger('change');
            }
          }

          input.focus();
          addAriaPressed = false;
        }
      }

      if (!(this._element.hasAttribute('disabled') || this._element.classList.contains('disabled'))) {
        if (addAriaPressed) {
          this._element.setAttribute('aria-pressed', !this._element.classList.contains(CLASS_NAME_ACTIVE$3));
        }

        if (triggerChangeEvent) {
          $__default["default"](this._element).toggleClass(CLASS_NAME_ACTIVE$3);
        }
      }
    };

    _proto.dispose = function dispose() {
      $__default["default"].removeData(this._element, DATA_KEY$9);
      this._element = null;
    } // Static
    ;

    Button._jQueryInterface = function _jQueryInterface(config, avoidTriggerChange) {
      return this.each(function () {
        var $element = $__default["default"](this);
        var data = $element.data(DATA_KEY$9);

        if (!data) {
          data = new Button(this);
          $element.data(DATA_KEY$9, data);
        }

        data.shouldAvoidTriggerChange = avoidTriggerChange;

        if (config === 'toggle') {
          data[config]();
        }
      });
    };

    _createClass(Button, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$9;
      }
    }]);

    return Button;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_CLICK_DATA_API$5, SELECTOR_DATA_TOGGLE_CARROT, function (event) {
    var button = event.target;
    var initialButton = button;

    if (!$__default["default"](button).hasClass(CLASS_NAME_BUTTON)) {
      button = $__default["default"](button).closest(SELECTOR_BUTTON)[0];
    }

    if (!button || button.hasAttribute('disabled') || button.classList.contains('disabled')) {
      event.preventDefault(); // work around Firefox bug #1540995
    } else {
      var inputBtn = button.querySelector(SELECTOR_INPUT);

      if (inputBtn &amp;&amp; (inputBtn.hasAttribute('disabled') || inputBtn.classList.contains('disabled'))) {
        event.preventDefault(); // work around Firefox bug #1540995

        return;
      }

      if (initialButton.tagName === 'INPUT' || button.tagName !== 'LABEL') {
        Button._jQueryInterface.call($__default["default"](button), 'toggle', initialButton.tagName === 'INPUT');
      }
    }
  }).on(EVENT_FOCUS_BLUR_DATA_API, SELECTOR_DATA_TOGGLE_CARROT, function (event) {
    var button = $__default["default"](event.target).closest(SELECTOR_BUTTON)[0];
    $__default["default"](button).toggleClass(CLASS_NAME_FOCUS, /^focus(in)?$/.test(event.type));
  });
  $__default["default"](window).on(EVENT_LOAD_DATA_API$2, function () {
    // ensure correct active class is set to match the controls' actual values/states
    // find all checkboxes/readio buttons inside data-toggle groups
    var buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLES_BUTTONS));

    for (var i = 0, len = buttons.length; i &lt; len; i++) {
      var button = buttons[i];
      var input = button.querySelector(SELECTOR_INPUT);

      if (input.checked || input.hasAttribute('checked')) {
        button.classList.add(CLASS_NAME_ACTIVE$3);
      } else {
        button.classList.remove(CLASS_NAME_ACTIVE$3);
      }
    } // find all button toggles


    buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE$4));

    for (var _i = 0, _len = buttons.length; _i &lt; _len; _i++) {
      var _button = buttons[_i];

      if (_button.getAttribute('aria-pressed') === 'true') {
        _button.classList.add(CLASS_NAME_ACTIVE$3);
      } else {
        _button.classList.remove(CLASS_NAME_ACTIVE$3);
      }
    }
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$9] = Button._jQueryInterface;
  $__default["default"].fn[NAME$9].Constructor = Button;

  $__default["default"].fn[NAME$9].noConflict = function () {
    $__default["default"].fn[NAME$9] = JQUERY_NO_CONFLICT$9;
    return Button._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$8 = 'carousel';
  var VERSION$8 = '4.6.2';
  var DATA_KEY$8 = 'bs.carousel';
  var EVENT_KEY$8 = "." + DATA_KEY$8;
  var DATA_API_KEY$5 = '.data-api';
  var JQUERY_NO_CONFLICT$8 = $__default["default"].fn[NAME$8];
  var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key

  var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key

  var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch

  var SWIPE_THRESHOLD = 40;
  var CLASS_NAME_CAROUSEL = 'carousel';
  var CLASS_NAME_ACTIVE$2 = 'active';
  var CLASS_NAME_SLIDE = 'slide';
  var CLASS_NAME_RIGHT = 'carousel-item-right';
  var CLASS_NAME_LEFT = 'carousel-item-left';
  var CLASS_NAME_NEXT = 'carousel-item-next';
  var CLASS_NAME_PREV = 'carousel-item-prev';
  var CLASS_NAME_POINTER_EVENT = 'pointer-event';
  var DIRECTION_NEXT = 'next';
  var DIRECTION_PREV = 'prev';
  var DIRECTION_LEFT = 'left';
  var DIRECTION_RIGHT = 'right';
  var EVENT_SLIDE = "slide" + EVENT_KEY$8;
  var EVENT_SLID = "slid" + EVENT_KEY$8;
  var EVENT_KEYDOWN = "keydown" + EVENT_KEY$8;
  var EVENT_MOUSEENTER = "mouseenter" + EVENT_KEY$8;
  var EVENT_MOUSELEAVE = "mouseleave" + EVENT_KEY$8;
  var EVENT_TOUCHSTART = "touchstart" + EVENT_KEY$8;
  var EVENT_TOUCHMOVE = "touchmove" + EVENT_KEY$8;
  var EVENT_TOUCHEND = "touchend" + EVENT_KEY$8;
  var EVENT_POINTERDOWN = "pointerdown" + EVENT_KEY$8;
  var EVENT_POINTERUP = "pointerup" + EVENT_KEY$8;
  var EVENT_DRAG_START = "dragstart" + EVENT_KEY$8;
  var EVENT_LOAD_DATA_API$1 = "load" + EVENT_KEY$8 + DATA_API_KEY$5;
  var EVENT_CLICK_DATA_API$4 = "click" + EVENT_KEY$8 + DATA_API_KEY$5;
  var SELECTOR_ACTIVE$1 = '.active';
  var SELECTOR_ACTIVE_ITEM = '.active.carousel-item';
  var SELECTOR_ITEM = '.carousel-item';
  var SELECTOR_ITEM_IMG = '.carousel-item img';
  var SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev';
  var SELECTOR_INDICATORS = '.carousel-indicators';
  var SELECTOR_DATA_SLIDE = '[data-slide], [data-slide-to]';
  var SELECTOR_DATA_RIDE = '[data-ride="carousel"]';
  var Default$7 = {
    interval: 5000,
    keyboard: true,
    slide: false,
    pause: 'hover',
    wrap: true,
    touch: true
  };
  var DefaultType$7 = {
    interval: '(number|boolean)',
    keyboard: 'boolean',
    slide: '(boolean|string)',
    pause: '(string|boolean)',
    wrap: 'boolean',
    touch: 'boolean'
  };
  var PointerType = {
    TOUCH: 'touch',
    PEN: 'pen'
  };
  /**
   * Class definition
   */

  var Carousel = /*#__PURE__*/function () {
    function Carousel(element, config) {
      this._items = null;
      this._interval = null;
      this._activeElement = null;
      this._isPaused = false;
      this._isSliding = false;
      this.touchTimeout = null;
      this.touchStartX = 0;
      this.touchDeltaX = 0;
      this._config = this._getConfig(config);
      this._element = element;
      this._indicatorsElement = this._element.querySelector(SELECTOR_INDICATORS);
      this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints &gt; 0;
      this._pointerEvent = Boolean(window.PointerEvent || window.MSPointerEvent);

      this._addEventListeners();
    } // Getters


    var _proto = Carousel.prototype;

    // Public
    _proto.next = function next() {
      if (!this._isSliding) {
        this._slide(DIRECTION_NEXT);
      }
    };

    _proto.nextWhenVisible = function nextWhenVisible() {
      var $element = $__default["default"](this._element); // Don't call next when the page isn't visible
      // or the carousel or its parent isn't visible

      if (!document.hidden &amp;&amp; $element.is(':visible') &amp;&amp; $element.css('visibility') !== 'hidden') {
        this.next();
      }
    };

    _proto.prev = function prev() {
      if (!this._isSliding) {
        this._slide(DIRECTION_PREV);
      }
    };

    _proto.pause = function pause(event) {
      if (!event) {
        this._isPaused = true;
      }

      if (this._element.querySelector(SELECTOR_NEXT_PREV)) {
        Util.triggerTransitionEnd(this._element);
        this.cycle(true);
      }

      clearInterval(this._interval);
      this._interval = null;
    };

    _proto.cycle = function cycle(event) {
      if (!event) {
        this._isPaused = false;
      }

      if (this._interval) {
        clearInterval(this._interval);
        this._interval = null;
      }

      if (this._config.interval &amp;&amp; !this._isPaused) {
        this._updateInterval();

        this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
      }
    };

    _proto.to = function to(index) {
      var _this = this;

      this._activeElement = this._element.querySelector(SELECTOR_ACTIVE_ITEM);

      var activeIndex = this._getItemIndex(this._activeElement);

      if (index &gt; this._items.length - 1 || index &lt; 0) {
        return;
      }

      if (this._isSliding) {
        $__default["default"](this._element).one(EVENT_SLID, function () {
          return _this.to(index);
        });
        return;
      }

      if (activeIndex === index) {
        this.pause();
        this.cycle();
        return;
      }

      var direction = index &gt; activeIndex ? DIRECTION_NEXT : DIRECTION_PREV;

      this._slide(direction, this._items[index]);
    };

    _proto.dispose = function dispose() {
      $__default["default"](this._element).off(EVENT_KEY$8);
      $__default["default"].removeData(this._element, DATA_KEY$8);
      this._items = null;
      this._config = null;
      this._element = null;
      this._interval = null;
      this._isPaused = null;
      this._isSliding = null;
      this._activeElement = null;
      this._indicatorsElement = null;
    } // Private
    ;

    _proto._getConfig = function _getConfig(config) {
      config = _extends({}, Default$7, config);
      Util.typeCheckConfig(NAME$8, config, DefaultType$7);
      return config;
    };

    _proto._handleSwipe = function _handleSwipe() {
      var absDeltax = Math.abs(this.touchDeltaX);

      if (absDeltax &lt;= SWIPE_THRESHOLD) {
        return;
      }

      var direction = absDeltax / this.touchDeltaX;
      this.touchDeltaX = 0; // swipe left

      if (direction &gt; 0) {
        this.prev();
      } // swipe right


      if (direction &lt; 0) {
        this.next();
      }
    };

    _proto._addEventListeners = function _addEventListeners() {
      var _this2 = this;

      if (this._config.keyboard) {
        $__default["default"](this._element).on(EVENT_KEYDOWN, function (event) {
          return _this2._keydown(event);
        });
      }

      if (this._config.pause === 'hover') {
        $__default["default"](this._element).on(EVENT_MOUSEENTER, function (event) {
          return _this2.pause(event);
        }).on(EVENT_MOUSELEAVE, function (event) {
          return _this2.cycle(event);
        });
      }

      if (this._config.touch) {
        this._addTouchEventListeners();
      }
    };

    _proto._addTouchEventListeners = function _addTouchEventListeners() {
      var _this3 = this;

      if (!this._touchSupported) {
        return;
      }

      var start = function start(event) {
        if (_this3._pointerEvent &amp;&amp; PointerType[event.originalEvent.pointerType.toUpperCase()]) {
          _this3.touchStartX = event.originalEvent.clientX;
        } else if (!_this3._pointerEvent) {
          _this3.touchStartX = event.originalEvent.touches[0].clientX;
        }
      };

      var move = function move(event) {
        // ensure swiping with one touch and not pinching
        _this3.touchDeltaX = event.originalEvent.touches &amp;&amp; event.originalEvent.touches.length &gt; 1 ? 0 : event.originalEvent.touches[0].clientX - _this3.touchStartX;
      };

      var end = function end(event) {
        if (_this3._pointerEvent &amp;&amp; PointerType[event.originalEvent.pointerType.toUpperCase()]) {
          _this3.touchDeltaX = event.originalEvent.clientX - _this3.touchStartX;
        }

        _this3._handleSwipe();

        if (_this3._config.pause === 'hover') {
          // If it's a touch-enabled device, mouseenter/leave are fired as
          // part of the mouse compatibility events on first tap - the carousel
          // would stop cycling until user tapped out of it;
          // here, we listen for touchend, explicitly pause the carousel
          // (as if it's the second time we tap on it, mouseenter compat event
          // is NOT fired) and after a timeout (to allow for mouse compatibility
          // events to fire) we explicitly restart cycling
          _this3.pause();

          if (_this3.touchTimeout) {
            clearTimeout(_this3.touchTimeout);
          }

          _this3.touchTimeout = setTimeout(function (event) {
            return _this3.cycle(event);
          }, TOUCHEVENT_COMPAT_WAIT + _this3._config.interval);
        }
      };

      $__default["default"](this._element.querySelectorAll(SELECTOR_ITEM_IMG)).on(EVENT_DRAG_START, function (e) {
        return e.preventDefault();
      });

      if (this._pointerEvent) {
        $__default["default"](this._element).on(EVENT_POINTERDOWN, function (event) {
          return start(event);
        });
        $__default["default"](this._element).on(EVENT_POINTERUP, function (event) {
          return end(event);
        });

        this._element.classList.add(CLASS_NAME_POINTER_EVENT);
      } else {
        $__default["default"](this._element).on(EVENT_TOUCHSTART, function (event) {
          return start(event);
        });
        $__default["default"](this._element).on(EVENT_TOUCHMOVE, function (event) {
          return move(event);
        });
        $__default["default"](this._element).on(EVENT_TOUCHEND, function (event) {
          return end(event);
        });
      }
    };

    _proto._keydown = function _keydown(event) {
      if (/input|textarea/i.test(event.target.tagName)) {
        return;
      }

      switch (event.which) {
        case ARROW_LEFT_KEYCODE:
          event.preventDefault();
          this.prev();
          break;

        case ARROW_RIGHT_KEYCODE:
          event.preventDefault();
          this.next();
          break;
      }
    };

    _proto._getItemIndex = function _getItemIndex(element) {
      this._items = element &amp;&amp; element.parentNode ? [].slice.call(element.parentNode.querySelectorAll(SELECTOR_ITEM)) : [];
      return this._items.indexOf(element);
    };

    _proto._getItemByDirection = function _getItemByDirection(direction, activeElement) {
      var isNextDirection = direction === DIRECTION_NEXT;
      var isPrevDirection = direction === DIRECTION_PREV;

      var activeIndex = this._getItemIndex(activeElement);

      var lastItemIndex = this._items.length - 1;
      var isGoingToWrap = isPrevDirection &amp;&amp; activeIndex === 0 || isNextDirection &amp;&amp; activeIndex === lastItemIndex;

      if (isGoingToWrap &amp;&amp; !this._config.wrap) {
        return activeElement;
      }

      var delta = direction === DIRECTION_PREV ? -1 : 1;
      var itemIndex = (activeIndex + delta) % this._items.length;
      return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
    };

    _proto._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) {
      var targetIndex = this._getItemIndex(relatedTarget);

      var fromIndex = this._getItemIndex(this._element.querySelector(SELECTOR_ACTIVE_ITEM));

      var slideEvent = $__default["default"].Event(EVENT_SLIDE, {
        relatedTarget: relatedTarget,
        direction: eventDirectionName,
        from: fromIndex,
        to: targetIndex
      });
      $__default["default"](this._element).trigger(slideEvent);
      return slideEvent;
    };

    _proto._setActiveIndicatorElement = function _setActiveIndicatorElement(element) {
      if (this._indicatorsElement) {
        var indicators = [].slice.call(this._indicatorsElement.querySelectorAll(SELECTOR_ACTIVE$1));
        $__default["default"](indicators).removeClass(CLASS_NAME_ACTIVE$2);

        var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];

        if (nextIndicator) {
          $__default["default"](nextIndicator).addClass(CLASS_NAME_ACTIVE$2);
        }
      }
    };

    _proto._updateInterval = function _updateInterval() {
      var element = this._activeElement || this._element.querySelector(SELECTOR_ACTIVE_ITEM);

      if (!element) {
        return;
      }

      var elementInterval = parseInt(element.getAttribute('data-interval'), 10);

      if (elementInterval) {
        this._config.defaultInterval = this._config.defaultInterval || this._config.interval;
        this._config.interval = elementInterval;
      } else {
        this._config.interval = this._config.defaultInterval || this._config.interval;
      }
    };

    _proto._slide = function _slide(direction, element) {
      var _this4 = this;

      var activeElement = this._element.querySelector(SELECTOR_ACTIVE_ITEM);

      var activeElementIndex = this._getItemIndex(activeElement);

      var nextElement = element || activeElement &amp;&amp; this._getItemByDirection(direction, activeElement);

      var nextElementIndex = this._getItemIndex(nextElement);

      var isCycling = Boolean(this._interval);
      var directionalClassName;
      var orderClassName;
      var eventDirectionName;

      if (direction === DIRECTION_NEXT) {
        directionalClassName = CLASS_NAME_LEFT;
        orderClassName = CLASS_NAME_NEXT;
        eventDirectionName = DIRECTION_LEFT;
      } else {
        directionalClassName = CLASS_NAME_RIGHT;
        orderClassName = CLASS_NAME_PREV;
        eventDirectionName = DIRECTION_RIGHT;
      }

      if (nextElement &amp;&amp; $__default["default"](nextElement).hasClass(CLASS_NAME_ACTIVE$2)) {
        this._isSliding = false;
        return;
      }

      var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);

      if (slideEvent.isDefaultPrevented()) {
        return;
      }

      if (!activeElement || !nextElement) {
        // Some weirdness is happening, so we bail
        return;
      }

      this._isSliding = true;

      if (isCycling) {
        this.pause();
      }

      this._setActiveIndicatorElement(nextElement);

      this._activeElement = nextElement;
      var slidEvent = $__default["default"].Event(EVENT_SLID, {
        relatedTarget: nextElement,
        direction: eventDirectionName,
        from: activeElementIndex,
        to: nextElementIndex
      });

      if ($__default["default"](this._element).hasClass(CLASS_NAME_SLIDE)) {
        $__default["default"](nextElement).addClass(orderClassName);
        Util.reflow(nextElement);
        $__default["default"](activeElement).addClass(directionalClassName);
        $__default["default"](nextElement).addClass(directionalClassName);
        var transitionDuration = Util.getTransitionDurationFromElement(activeElement);
        $__default["default"](activeElement).one(Util.TRANSITION_END, function () {
          $__default["default"](nextElement).removeClass(directionalClassName + " " + orderClassName).addClass(CLASS_NAME_ACTIVE$2);
          $__default["default"](activeElement).removeClass(CLASS_NAME_ACTIVE$2 + " " + orderClassName + " " + directionalClassName);
          _this4._isSliding = false;
          setTimeout(function () {
            return $__default["default"](_this4._element).trigger(slidEvent);
          }, 0);
        }).emulateTransitionEnd(transitionDuration);
      } else {
        $__default["default"](activeElement).removeClass(CLASS_NAME_ACTIVE$2);
        $__default["default"](nextElement).addClass(CLASS_NAME_ACTIVE$2);
        this._isSliding = false;
        $__default["default"](this._element).trigger(slidEvent);
      }

      if (isCycling) {
        this.cycle();
      }
    } // Static
    ;

    Carousel._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var data = $__default["default"](this).data(DATA_KEY$8);

        var _config = _extends({}, Default$7, $__default["default"](this).data());

        if (typeof config === 'object') {
          _config = _extends({}, _config, config);
        }

        var action = typeof config === 'string' ? config : _config.slide;

        if (!data) {
          data = new Carousel(this, _config);
          $__default["default"](this).data(DATA_KEY$8, data);
        }

        if (typeof config === 'number') {
          data.to(config);
        } else if (typeof action === 'string') {
          if (typeof data[action] === 'undefined') {
            throw new TypeError("No method named \"" + action + "\"");
          }

          data[action]();
        } else if (_config.interval &amp;&amp; _config.ride) {
          data.pause();
          data.cycle();
        }
      });
    };

    Carousel._dataApiClickHandler = function _dataApiClickHandler(event) {
      var selector = Util.getSelectorFromElement(this);

      if (!selector) {
        return;
      }

      var target = $__default["default"](selector)[0];

      if (!target || !$__default["default"](target).hasClass(CLASS_NAME_CAROUSEL)) {
        return;
      }

      var config = _extends({}, $__default["default"](target).data(), $__default["default"](this).data());

      var slideIndex = this.getAttribute('data-slide-to');

      if (slideIndex) {
        config.interval = false;
      }

      Carousel._jQueryInterface.call($__default["default"](target), config);

      if (slideIndex) {
        $__default["default"](target).data(DATA_KEY$8).to(slideIndex);
      }

      event.preventDefault();
    };

    _createClass(Carousel, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$8;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$7;
      }
    }]);

    return Carousel;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_CLICK_DATA_API$4, SELECTOR_DATA_SLIDE, Carousel._dataApiClickHandler);
  $__default["default"](window).on(EVENT_LOAD_DATA_API$1, function () {
    var carousels = [].slice.call(document.querySelectorAll(SELECTOR_DATA_RIDE));

    for (var i = 0, len = carousels.length; i &lt; len; i++) {
      var $carousel = $__default["default"](carousels[i]);

      Carousel._jQueryInterface.call($carousel, $carousel.data());
    }
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$8] = Carousel._jQueryInterface;
  $__default["default"].fn[NAME$8].Constructor = Carousel;

  $__default["default"].fn[NAME$8].noConflict = function () {
    $__default["default"].fn[NAME$8] = JQUERY_NO_CONFLICT$8;
    return Carousel._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$7 = 'collapse';
  var VERSION$7 = '4.6.2';
  var DATA_KEY$7 = 'bs.collapse';
  var EVENT_KEY$7 = "." + DATA_KEY$7;
  var DATA_API_KEY$4 = '.data-api';
  var JQUERY_NO_CONFLICT$7 = $__default["default"].fn[NAME$7];
  var CLASS_NAME_SHOW$6 = 'show';
  var CLASS_NAME_COLLAPSE = 'collapse';
  var CLASS_NAME_COLLAPSING = 'collapsing';
  var CLASS_NAME_COLLAPSED = 'collapsed';
  var DIMENSION_WIDTH = 'width';
  var DIMENSION_HEIGHT = 'height';
  var EVENT_SHOW$4 = "show" + EVENT_KEY$7;
  var EVENT_SHOWN$4 = "shown" + EVENT_KEY$7;
  var EVENT_HIDE$4 = "hide" + EVENT_KEY$7;
  var EVENT_HIDDEN$4 = "hidden" + EVENT_KEY$7;
  var EVENT_CLICK_DATA_API$3 = "click" + EVENT_KEY$7 + DATA_API_KEY$4;
  var SELECTOR_ACTIVES = '.show, .collapsing';
  var SELECTOR_DATA_TOGGLE$3 = '[data-toggle="collapse"]';
  var Default$6 = {
    toggle: true,
    parent: ''
  };
  var DefaultType$6 = {
    toggle: 'boolean',
    parent: '(string|element)'
  };
  /**
   * Class definition
   */

  var Collapse = /*#__PURE__*/function () {
    function Collapse(element, config) {
      this._isTransitioning = false;
      this._element = element;
      this._config = this._getConfig(config);
      this._triggerArray = [].slice.call(document.querySelectorAll("[data-toggle=\"collapse\"][href=\"#" + element.id + "\"]," + ("[data-toggle=\"collapse\"][data-target=\"#" + element.id + "\"]")));
      var toggleList = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE$3));

      for (var i = 0, len = toggleList.length; i &lt; len; i++) {
        var elem = toggleList[i];
        var selector = Util.getSelectorFromElement(elem);
        var filterElement = [].slice.call(document.querySelectorAll(selector)).filter(function (foundElem) {
          return foundElem === element;
        });

        if (selector !== null &amp;&amp; filterElement.length &gt; 0) {
          this._selector = selector;

          this._triggerArray.push(elem);
        }
      }

      this._parent = this._config.parent ? this._getParent() : null;

      if (!this._config.parent) {
        this._addAriaAndCollapsedClass(this._element, this._triggerArray);
      }

      if (this._config.toggle) {
        this.toggle();
      }
    } // Getters


    var _proto = Collapse.prototype;

    // Public
    _proto.toggle = function toggle() {
      if ($__default["default"](this._element).hasClass(CLASS_NAME_SHOW$6)) {
        this.hide();
      } else {
        this.show();
      }
    };

    _proto.show = function show() {
      var _this = this;

      if (this._isTransitioning || $__default["default"](this._element).hasClass(CLASS_NAME_SHOW$6)) {
        return;
      }

      var actives;
      var activesData;

      if (this._parent) {
        actives = [].slice.call(this._parent.querySelectorAll(SELECTOR_ACTIVES)).filter(function (elem) {
          if (typeof _this._config.parent === 'string') {
            return elem.getAttribute('data-parent') === _this._config.parent;
          }

          return elem.classList.contains(CLASS_NAME_COLLAPSE);
        });

        if (actives.length === 0) {
          actives = null;
        }
      }

      if (actives) {
        activesData = $__default["default"](actives).not(this._selector).data(DATA_KEY$7);

        if (activesData &amp;&amp; activesData._isTransitioning) {
          return;
        }
      }

      var startEvent = $__default["default"].Event(EVENT_SHOW$4);
      $__default["default"](this._element).trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      if (actives) {
        Collapse._jQueryInterface.call($__default["default"](actives).not(this._selector), 'hide');

        if (!activesData) {
          $__default["default"](actives).data(DATA_KEY$7, null);
        }
      }

      var dimension = this._getDimension();

      $__default["default"](this._element).removeClass(CLASS_NAME_COLLAPSE).addClass(CLASS_NAME_COLLAPSING);
      this._element.style[dimension] = 0;

      if (this._triggerArray.length) {
        $__default["default"](this._triggerArray).removeClass(CLASS_NAME_COLLAPSED).attr('aria-expanded', true);
      }

      this.setTransitioning(true);

      var complete = function complete() {
        $__default["default"](_this._element).removeClass(CLASS_NAME_COLLAPSING).addClass(CLASS_NAME_COLLAPSE + " " + CLASS_NAME_SHOW$6);
        _this._element.style[dimension] = '';

        _this.setTransitioning(false);

        $__default["default"](_this._element).trigger(EVENT_SHOWN$4);
      };

      var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
      var scrollSize = "scroll" + capitalizedDimension;
      var transitionDuration = Util.getTransitionDurationFromElement(this._element);
      $__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
      this._element.style[dimension] = this._element[scrollSize] + "px";
    };

    _proto.hide = function hide() {
      var _this2 = this;

      if (this._isTransitioning || !$__default["default"](this._element).hasClass(CLASS_NAME_SHOW$6)) {
        return;
      }

      var startEvent = $__default["default"].Event(EVENT_HIDE$4);
      $__default["default"](this._element).trigger(startEvent);

      if (startEvent.isDefaultPrevented()) {
        return;
      }

      var dimension = this._getDimension();

      this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px";
      Util.reflow(this._element);
      $__default["default"](this._element).addClass(CLASS_NAME_COLLAPSING).removeClass(CLASS_NAME_COLLAPSE + " " + CLASS_NAME_SHOW$6);
      var triggerArrayLength = this._triggerArray.length;

      if (triggerArrayLength &gt; 0) {
        for (var i = 0; i &lt; triggerArrayLength; i++) {
          var trigger = this._triggerArray[i];
          var selector = Util.getSelectorFromElement(trigger);

          if (selector !== null) {
            var $elem = $__default["default"]([].slice.call(document.querySelectorAll(selector)));

            if (!$elem.hasClass(CLASS_NAME_SHOW$6)) {
              $__default["default"](trigger).addClass(CLASS_NAME_COLLAPSED).attr('aria-expanded', false);
            }
          }
        }
      }

      this.setTransitioning(true);

      var complete = function complete() {
        _this2.setTransitioning(false);

        $__default["default"](_this2._element).removeClass(CLASS_NAME_COLLAPSING).addClass(CLASS_NAME_COLLAPSE).trigger(EVENT_HIDDEN$4);
      };

      this._element.style[dimension] = '';
      var transitionDuration = Util.getTransitionDurationFromElement(this._element);
      $__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
    };

    _proto.setTransitioning = function setTransitioning(isTransitioning) {
      this._isTransitioning = isTransitioning;
    };

    _proto.dispose = function dispose() {
      $__default["default"].removeData(this._element, DATA_KEY$7);
      this._config = null;
      this._parent = null;
      this._element = null;
      this._triggerArray = null;
      this._isTransitioning = null;
    } // Private
    ;

    _proto._getConfig = function _getConfig(config) {
      config = _extends({}, Default$6, config);
      config.toggle = Boolean(config.toggle); // Coerce string values

      Util.typeCheckConfig(NAME$7, config, DefaultType$6);
      return config;
    };

    _proto._getDimension = function _getDimension() {
      var hasWidth = $__default["default"](this._element).hasClass(DIMENSION_WIDTH);
      return hasWidth ? DIMENSION_WIDTH : DIMENSION_HEIGHT;
    };

    _proto._getParent = function _getParent() {
      var _this3 = this;

      var parent;

      if (Util.isElement(this._config.parent)) {
        parent = this._config.parent; // It's a jQuery object

        if (typeof this._config.parent.jquery !== 'undefined') {
          parent = this._config.parent[0];
        }
      } else {
        parent = document.querySelector(this._config.parent);
      }

      var selector = "[data-toggle=\"collapse\"][data-parent=\"" + this._config.parent + "\"]";
      var children = [].slice.call(parent.querySelectorAll(selector));
      $__default["default"](children).each(function (i, element) {
        _this3._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
      });
      return parent;
    };

    _proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
      var isOpen = $__default["default"](element).hasClass(CLASS_NAME_SHOW$6);

      if (triggerArray.length) {
        $__default["default"](triggerArray).toggleClass(CLASS_NAME_COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
      }
    } // Static
    ;

    Collapse._getTargetFromElement = function _getTargetFromElement(element) {
      var selector = Util.getSelectorFromElement(element);
      return selector ? document.querySelector(selector) : null;
    };

    Collapse._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var $element = $__default["default"](this);
        var data = $element.data(DATA_KEY$7);

        var _config = _extends({}, Default$6, $element.data(), typeof config === 'object' &amp;&amp; config ? config : {});

        if (!data &amp;&amp; _config.toggle &amp;&amp; typeof config === 'string' &amp;&amp; /show|hide/.test(config)) {
          _config.toggle = false;
        }

        if (!data) {
          data = new Collapse(this, _config);
          $element.data(DATA_KEY$7, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    _createClass(Collapse, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$7;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$6;
      }
    }]);

    return Collapse;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) {
    // preventDefault only for &lt;a&gt; elements (which change the URL) not inside the collapsible element
    if (event.currentTarget.tagName === 'A') {
      event.preventDefault();
    }

    var $trigger = $__default["default"](this);
    var selector = Util.getSelectorFromElement(this);
    var selectors = [].slice.call(document.querySelectorAll(selector));
    $__default["default"](selectors).each(function () {
      var $target = $__default["default"](this);
      var data = $target.data(DATA_KEY$7);
      var config = data ? 'toggle' : $trigger.data();

      Collapse._jQueryInterface.call($target, config);
    });
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$7] = Collapse._jQueryInterface;
  $__default["default"].fn[NAME$7].Constructor = Collapse;

  $__default["default"].fn[NAME$7].noConflict = function () {
    $__default["default"].fn[NAME$7] = JQUERY_NO_CONFLICT$7;
    return Collapse._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$6 = 'dropdown';
  var VERSION$6 = '4.6.2';
  var DATA_KEY$6 = 'bs.dropdown';
  var EVENT_KEY$6 = "." + DATA_KEY$6;
  var DATA_API_KEY$3 = '.data-api';
  var JQUERY_NO_CONFLICT$6 = $__default["default"].fn[NAME$6];
  var ESCAPE_KEYCODE$1 = 27; // KeyboardEvent.which value for Escape (Esc) key

  var SPACE_KEYCODE = 32; // KeyboardEvent.which value for space key

  var TAB_KEYCODE = 9; // KeyboardEvent.which value for tab key

  var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key

  var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key

  var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse)

  var REGEXP_KEYDOWN = new RegExp(ARROW_UP_KEYCODE + "|" + ARROW_DOWN_KEYCODE + "|" + ESCAPE_KEYCODE$1);
  var CLASS_NAME_DISABLED$1 = 'disabled';
  var CLASS_NAME_SHOW$5 = 'show';
  var CLASS_NAME_DROPUP = 'dropup';
  var CLASS_NAME_DROPRIGHT = 'dropright';
  var CLASS_NAME_DROPLEFT = 'dropleft';
  var CLASS_NAME_MENURIGHT = 'dropdown-menu-right';
  var CLASS_NAME_POSITION_STATIC = 'position-static';
  var EVENT_HIDE$3 = "hide" + EVENT_KEY$6;
  var EVENT_HIDDEN$3 = "hidden" + EVENT_KEY$6;
  var EVENT_SHOW$3 = "show" + EVENT_KEY$6;
  var EVENT_SHOWN$3 = "shown" + EVENT_KEY$6;
  var EVENT_CLICK = "click" + EVENT_KEY$6;
  var EVENT_CLICK_DATA_API$2 = "click" + EVENT_KEY$6 + DATA_API_KEY$3;
  var EVENT_KEYDOWN_DATA_API = "keydown" + EVENT_KEY$6 + DATA_API_KEY$3;
  var EVENT_KEYUP_DATA_API = "keyup" + EVENT_KEY$6 + DATA_API_KEY$3;
  var SELECTOR_DATA_TOGGLE$2 = '[data-toggle="dropdown"]';
  var SELECTOR_FORM_CHILD = '.dropdown form';
  var SELECTOR_MENU = '.dropdown-menu';
  var SELECTOR_NAVBAR_NAV = '.navbar-nav';
  var SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)';
  var PLACEMENT_TOP = 'top-start';
  var PLACEMENT_TOPEND = 'top-end';
  var PLACEMENT_BOTTOM = 'bottom-start';
  var PLACEMENT_BOTTOMEND = 'bottom-end';
  var PLACEMENT_RIGHT = 'right-start';
  var PLACEMENT_LEFT = 'left-start';
  var Default$5 = {
    offset: 0,
    flip: true,
    boundary: 'scrollParent',
    reference: 'toggle',
    display: 'dynamic',
    popperConfig: null
  };
  var DefaultType$5 = {
    offset: '(number|string|function)',
    flip: 'boolean',
    boundary: '(string|element)',
    reference: '(string|element)',
    display: 'string',
    popperConfig: '(null|object)'
  };
  /**
   * Class definition
   */

  var Dropdown = /*#__PURE__*/function () {
    function Dropdown(element, config) {
      this._element = element;
      this._popper = null;
      this._config = this._getConfig(config);
      this._menu = this._getMenuElement();
      this._inNavbar = this._detectNavbar();

      this._addEventListeners();
    } // Getters


    var _proto = Dropdown.prototype;

    // Public
    _proto.toggle = function toggle() {
      if (this._element.disabled || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED$1)) {
        return;
      }

      var isActive = $__default["default"](this._menu).hasClass(CLASS_NAME_SHOW$5);

      Dropdown._clearMenus();

      if (isActive) {
        return;
      }

      this.show(true);
    };

    _proto.show = function show(usePopper) {
      if (usePopper === void 0) {
        usePopper = false;
      }

      if (this._element.disabled || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED$1) || $__default["default"](this._menu).hasClass(CLASS_NAME_SHOW$5)) {
        return;
      }

      var relatedTarget = {
        relatedTarget: this._element
      };
      var showEvent = $__default["default"].Event(EVENT_SHOW$3, relatedTarget);

      var parent = Dropdown._getParentFromElement(this._element);

      $__default["default"](parent).trigger(showEvent);

      if (showEvent.isDefaultPrevented()) {
        return;
      } // Totally disable Popper for Dropdowns in Navbar


      if (!this._inNavbar &amp;&amp; usePopper) {
        // Check for Popper dependency
        if (typeof Popper__default["default"] === 'undefined') {
          throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)');
        }

        var referenceElement = this._element;

        if (this._config.reference === 'parent') {
          referenceElement = parent;
        } else if (Util.isElement(this._config.reference)) {
          referenceElement = this._config.reference; // Check if it's jQuery element

          if (typeof this._config.reference.jquery !== 'undefined') {
            referenceElement = this._config.reference[0];
          }
        } // If boundary is not `scrollParent`, then set position to `static`
        // to allow the menu to "escape" the scroll parent's boundaries
        // https://github.com/twbs/bootstrap/issues/24251


        if (this._config.boundary !== 'scrollParent') {
          $__default["default"](parent).addClass(CLASS_NAME_POSITION_STATIC);
        }

        this._popper = new Popper__default["default"](referenceElement, this._menu, this._getPopperConfig());
      } // If this is a touch-enabled device we add extra
      // empty mouseover listeners to the body's immediate children;
      // only needed because of broken event delegation on iOS
      // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html


      if ('ontouchstart' in document.documentElement &amp;&amp; $__default["default"](parent).closest(SELECTOR_NAVBAR_NAV).length === 0) {
        $__default["default"](document.body).children().on('mouseover', null, $__default["default"].noop);
      }

      this._element.focus();

      this._element.setAttribute('aria-expanded', true);

      $__default["default"](this._menu).toggleClass(CLASS_NAME_SHOW$5);
      $__default["default"](parent).toggleClass(CLASS_NAME_SHOW$5).trigger($__default["default"].Event(EVENT_SHOWN$3, relatedTarget));
    };

    _proto.hide = function hide() {
      if (this._element.disabled || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED$1) || !$__default["default"](this._menu).hasClass(CLASS_NAME_SHOW$5)) {
        return;
      }

      var relatedTarget = {
        relatedTarget: this._element
      };
      var hideEvent = $__default["default"].Event(EVENT_HIDE$3, relatedTarget);

      var parent = Dropdown._getParentFromElement(this._element);

      $__default["default"](parent).trigger(hideEvent);

      if (hideEvent.isDefaultPrevented()) {
        return;
      }

      if (this._popper) {
        this._popper.destroy();
      }

      $__default["default"](this._menu).toggleClass(CLASS_NAME_SHOW$5);
      $__default["default"](parent).toggleClass(CLASS_NAME_SHOW$5).trigger($__default["default"].Event(EVENT_HIDDEN$3, relatedTarget));
    };

    _proto.dispose = function dispose() {
      $__default["default"].removeData(this._element, DATA_KEY$6);
      $__default["default"](this._element).off(EVENT_KEY$6);
      this._element = null;
      this._menu = null;

      if (this._popper !== null) {
        this._popper.destroy();

        this._popper = null;
      }
    };

    _proto.update = function update() {
      this._inNavbar = this._detectNavbar();

      if (this._popper !== null) {
        this._popper.scheduleUpdate();
      }
    } // Private
    ;

    _proto._addEventListeners = function _addEventListeners() {
      var _this = this;

      $__default["default"](this._element).on(EVENT_CLICK, function (event) {
        event.preventDefault();
        event.stopPropagation();

        _this.toggle();
      });
    };

    _proto._getConfig = function _getConfig(config) {
      config = _extends({}, this.constructor.Default, $__default["default"](this._element).data(), config);
      Util.typeCheckConfig(NAME$6, config, this.constructor.DefaultType);
      return config;
    };

    _proto._getMenuElement = function _getMenuElement() {
      if (!this._menu) {
        var parent = Dropdown._getParentFromElement(this._element);

        if (parent) {
          this._menu = parent.querySelector(SELECTOR_MENU);
        }
      }

      return this._menu;
    };

    _proto._getPlacement = function _getPlacement() {
      var $parentDropdown = $__default["default"](this._element.parentNode);
      var placement = PLACEMENT_BOTTOM; // Handle dropup

      if ($parentDropdown.hasClass(CLASS_NAME_DROPUP)) {
        placement = $__default["default"](this._menu).hasClass(CLASS_NAME_MENURIGHT) ? PLACEMENT_TOPEND : PLACEMENT_TOP;
      } else if ($parentDropdown.hasClass(CLASS_NAME_DROPRIGHT)) {
        placement = PLACEMENT_RIGHT;
      } else if ($parentDropdown.hasClass(CLASS_NAME_DROPLEFT)) {
        placement = PLACEMENT_LEFT;
      } else if ($__default["default"](this._menu).hasClass(CLASS_NAME_MENURIGHT)) {
        placement = PLACEMENT_BOTTOMEND;
      }

      return placement;
    };

    _proto._detectNavbar = function _detectNavbar() {
      return $__default["default"](this._element).closest('.navbar').length &gt; 0;
    };

    _proto._getOffset = function _getOffset() {
      var _this2 = this;

      var offset = {};

      if (typeof this._config.offset === 'function') {
        offset.fn = function (data) {
          data.offsets = _extends({}, data.offsets, _this2._config.offset(data.offsets, _this2._element));
          return data;
        };
      } else {
        offset.offset = this._config.offset;
      }

      return offset;
    };

    _proto._getPopperConfig = function _getPopperConfig() {
      var popperConfig = {
        placement: this._getPlacement(),
        modifiers: {
          offset: this._getOffset(),
          flip: {
            enabled: this._config.flip
          },
          preventOverflow: {
            boundariesElement: this._config.boundary
          }
        }
      }; // Disable Popper if we have a static display

      if (this._config.display === 'static') {
        popperConfig.modifiers.applyStyle = {
          enabled: false
        };
      }

      return _extends({}, popperConfig, this._config.popperConfig);
    } // Static
    ;

    Dropdown._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var data = $__default["default"](this).data(DATA_KEY$6);

        var _config = typeof config === 'object' ? config : null;

        if (!data) {
          data = new Dropdown(this, _config);
          $__default["default"](this).data(DATA_KEY$6, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    Dropdown._clearMenus = function _clearMenus(event) {
      if (event &amp;&amp; (event.which === RIGHT_MOUSE_BUTTON_WHICH || event.type === 'keyup' &amp;&amp; event.which !== TAB_KEYCODE)) {
        return;
      }

      var toggles = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE$2));

      for (var i = 0, len = toggles.length; i &lt; len; i++) {
        var parent = Dropdown._getParentFromElement(toggles[i]);

        var context = $__default["default"](toggles[i]).data(DATA_KEY$6);
        var relatedTarget = {
          relatedTarget: toggles[i]
        };

        if (event &amp;&amp; event.type === 'click') {
          relatedTarget.clickEvent = event;
        }

        if (!context) {
          continue;
        }

        var dropdownMenu = context._menu;

        if (!$__default["default"](parent).hasClass(CLASS_NAME_SHOW$5)) {
          continue;
        }

        if (event &amp;&amp; (event.type === 'click' &amp;&amp; /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' &amp;&amp; event.which === TAB_KEYCODE) &amp;&amp; $__default["default"].contains(parent, event.target)) {
          continue;
        }

        var hideEvent = $__default["default"].Event(EVENT_HIDE$3, relatedTarget);
        $__default["default"](parent).trigger(hideEvent);

        if (hideEvent.isDefaultPrevented()) {
          continue;
        } // If this is a touch-enabled device we remove the extra
        // empty mouseover listeners we added for iOS support


        if ('ontouchstart' in document.documentElement) {
          $__default["default"](document.body).children().off('mouseover', null, $__default["default"].noop);
        }

        toggles[i].setAttribute('aria-expanded', 'false');

        if (context._popper) {
          context._popper.destroy();
        }

        $__default["default"](dropdownMenu).removeClass(CLASS_NAME_SHOW$5);
        $__default["default"](parent).removeClass(CLASS_NAME_SHOW$5).trigger($__default["default"].Event(EVENT_HIDDEN$3, relatedTarget));
      }
    };

    Dropdown._getParentFromElement = function _getParentFromElement(element) {
      var parent;
      var selector = Util.getSelectorFromElement(element);

      if (selector) {
        parent = document.querySelector(selector);
      }

      return parent || element.parentNode;
    } // eslint-disable-next-line complexity
    ;

    Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) {
      // If not input/textarea:
      //  - And not a key in REGEXP_KEYDOWN =&gt; not a dropdown command
      // If input/textarea:
      //  - If space key =&gt; not a dropdown command
      //  - If key is other than escape
      //    - If key is not up or down =&gt; not a dropdown command
      //    - If trigger inside the menu =&gt; not a dropdown command
      if (/input|textarea/i.test(event.target.tagName) ? event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE$1 &amp;&amp; (event.which !== ARROW_DOWN_KEYCODE &amp;&amp; event.which !== ARROW_UP_KEYCODE || $__default["default"](event.target).closest(SELECTOR_MENU).length) : !REGEXP_KEYDOWN.test(event.which)) {
        return;
      }

      if (this.disabled || $__default["default"](this).hasClass(CLASS_NAME_DISABLED$1)) {
        return;
      }

      var parent = Dropdown._getParentFromElement(this);

      var isActive = $__default["default"](parent).hasClass(CLASS_NAME_SHOW$5);

      if (!isActive &amp;&amp; event.which === ESCAPE_KEYCODE$1) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();

      if (!isActive || event.which === ESCAPE_KEYCODE$1 || event.which === SPACE_KEYCODE) {
        if (event.which === ESCAPE_KEYCODE$1) {
          $__default["default"](parent.querySelector(SELECTOR_DATA_TOGGLE$2)).trigger('focus');
        }

        $__default["default"](this).trigger('click');
        return;
      }

      var items = [].slice.call(parent.querySelectorAll(SELECTOR_VISIBLE_ITEMS)).filter(function (item) {
        return $__default["default"](item).is(':visible');
      });

      if (items.length === 0) {
        return;
      }

      var index = items.indexOf(event.target);

      if (event.which === ARROW_UP_KEYCODE &amp;&amp; index &gt; 0) {
        // Up
        index--;
      }

      if (event.which === ARROW_DOWN_KEYCODE &amp;&amp; index &lt; items.length - 1) {
        // Down
        index++;
      }

      if (index &lt; 0) {
        index = 0;
      }

      items[index].focus();
    };

    _createClass(Dropdown, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$6;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$5;
      }
    }, {
      key: "DefaultType",
      get: function get() {
        return DefaultType$5;
      }
    }]);

    return Dropdown;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$2, Dropdown._dataApiKeydownHandler).on(EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown._dataApiKeydownHandler).on(EVENT_CLICK_DATA_API$2 + " " + EVENT_KEYUP_DATA_API, Dropdown._clearMenus).on(EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) {
    event.preventDefault();
    event.stopPropagation();

    Dropdown._jQueryInterface.call($__default["default"](this), 'toggle');
  }).on(EVENT_CLICK_DATA_API$2, SELECTOR_FORM_CHILD, function (e) {
    e.stopPropagation();
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$6] = Dropdown._jQueryInterface;
  $__default["default"].fn[NAME$6].Constructor = Dropdown;

  $__default["default"].fn[NAME$6].noConflict = function () {
    $__default["default"].fn[NAME$6] = JQUERY_NO_CONFLICT$6;
    return Dropdown._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$5 = 'modal';
  var VERSION$5 = '4.6.2';
  var DATA_KEY$5 = 'bs.modal';
  var EVENT_KEY$5 = "." + DATA_KEY$5;
  var DATA_API_KEY$2 = '.data-api';
  var JQUERY_NO_CONFLICT$5 = $__default["default"].fn[NAME$5];
  var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key

  var CLASS_NAME_SCROLLABLE = 'modal-dialog-scrollable';
  var CLASS_NAME_SCROLLBAR_MEASURER = 'modal-scrollbar-measure';
  var CLASS_NAME_BACKDROP = 'modal-backdrop';
  var CLASS_NAME_OPEN = 'modal-open';
  var CLASS_NAME_FADE$4 = 'fade';
  var CLASS_NAME_SHOW$4 = 'show';
  var CLASS_NAME_STATIC = 'modal-static';
  var EVENT_HIDE$2 = "hide" + EVENT_KEY$5;
  var EVENT_HIDE_PREVENTED = "hidePrevented" + EVENT_KEY$5;
  var EVENT_HIDDEN$2 = "hidden" + EVENT_KEY$5;
  var EVENT_SHOW$2 = "show" + EVENT_KEY$5;
  var EVENT_SHOWN$2 = "shown" + EVENT_KEY$5;
  var EVENT_FOCUSIN = "focusin" + EVENT_KEY$5;
  var EVENT_RESIZE = "resize" + EVENT_KEY$5;
  var EVENT_CLICK_DISMISS$1 = "click.dismiss" + EVENT_KEY$5;
  var EVENT_KEYDOWN_DISMISS = "keydown.dismiss" + EVENT_KEY$5;
  var EVENT_MOUSEUP_DISMISS = "mouseup.dismiss" + EVENT_KEY$5;
  var EVENT_MOUSEDOWN_DISMISS = "mousedown.dismiss" + EVENT_KEY$5;
  var EVENT_CLICK_DATA_API$1 = "click" + EVENT_KEY$5 + DATA_API_KEY$2;
  var SELECTOR_DIALOG = '.modal-dialog';
  var SELECTOR_MODAL_BODY = '.modal-body';
  var SELECTOR_DATA_TOGGLE$1 = '[data-toggle="modal"]';
  var SELECTOR_DATA_DISMISS$1 = '[data-dismiss="modal"]';
  var SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top';
  var SELECTOR_STICKY_CONTENT = '.sticky-top';
  var Default$4 = {
    backdrop: true,
    keyboard: true,
    focus: true,
    show: true
  };
  var DefaultType$4 = {
    backdrop: '(boolean|string)',
    keyboard: 'boolean',
    focus: 'boolean',
    show: 'boolean'
  };
  /**
   * Class definition
   */

  var Modal = /*#__PURE__*/function () {
    function Modal(element, config) {
      this._config = this._getConfig(config);
      this._element = element;
      this._dialog = element.querySelector(SELECTOR_DIALOG);
      this._backdrop = null;
      this._isShown = false;
      this._isBodyOverflowing = false;
      this._ignoreBackdropClick = false;
      this._isTransitioning = false;
      this._scrollbarWidth = 0;
    } // Getters


    var _proto = Modal.prototype;

    // Public
    _proto.toggle = function toggle(relatedTarget) {
      return this._isShown ? this.hide() : this.show(relatedTarget);
    };

    _proto.show = function show(relatedTarget) {
      var _this = this;

      if (this._isShown || this._isTransitioning) {
        return;
      }

      var showEvent = $__default["default"].Event(EVENT_SHOW$2, {
        relatedTarget: relatedTarget
      });
      $__default["default"](this._element).trigger(showEvent);

      if (showEvent.isDefaultPrevented()) {
        return;
      }

      this._isShown = true;

      if ($__default["default"](this._element).hasClass(CLASS_NAME_FADE$4)) {
        this._isTransitioning = true;
      }

      this._checkScrollbar();

      this._setScrollbar();

      this._adjustDialog();

      this._setEscapeEvent();

      this._setResizeEvent();

      $__default["default"](this._element).on(EVENT_CLICK_DISMISS$1, SELECTOR_DATA_DISMISS$1, function (event) {
        return _this.hide(event);
      });
      $__default["default"](this._dialog).on(EVENT_MOUSEDOWN_DISMISS, function () {
        $__default["default"](_this._element).one(EVENT_MOUSEUP_DISMISS, function (event) {
          if ($__default["default"](event.target).is(_this._element)) {
            _this._ignoreBackdropClick = true;
          }
        });
      });

      this._showBackdrop(function () {
        return _this._showElement(relatedTarget);
      });
    };

    _proto.hide = function hide(event) {
      var _this2 = this;

      if (event) {
        event.preventDefault();
      }

      if (!this._isShown || this._isTransitioning) {
        return;
      }

      var hideEvent = $__default["default"].Event(EVENT_HIDE$2);
      $__default["default"](this._element).trigger(hideEvent);

      if (!this._isShown || hideEvent.isDefaultPrevented()) {
        return;
      }

      this._isShown = false;
      var transition = $__default["default"](this._element).hasClass(CLASS_NAME_FADE$4);

      if (transition) {
        this._isTransitioning = true;
      }

      this._setEscapeEvent();

      this._setResizeEvent();

      $__default["default"](document).off(EVENT_FOCUSIN);
      $__default["default"](this._element).removeClass(CLASS_NAME_SHOW$4);
      $__default["default"](this._element).off(EVENT_CLICK_DISMISS$1);
      $__default["default"](this._dialog).off(EVENT_MOUSEDOWN_DISMISS);

      if (transition) {
        var transitionDuration = Util.getTransitionDurationFromElement(this._element);
        $__default["default"](this._element).one(Util.TRANSITION_END, function (event) {
          return _this2._hideModal(event);
        }).emulateTransitionEnd(transitionDuration);
      } else {
        this._hideModal();
      }
    };

    _proto.dispose = function dispose() {
      [window, this._element, this._dialog].forEach(function (htmlElement) {
        return $__default["default"](htmlElement).off(EVENT_KEY$5);
      });
      /**
       * `document` has 2 events `EVENT_FOCUSIN` and `EVENT_CLICK_DATA_API`
       * Do not move `document` in `htmlElements` array
       * It will remove `EVENT_CLICK_DATA_API` event that should remain
       */

      $__default["default"](document).off(EVENT_FOCUSIN);
      $__default["default"].removeData(this._element, DATA_KEY$5);
      this._config = null;
      this._element = null;
      this._dialog = null;
      this._backdrop = null;
      this._isShown = null;
      this._isBodyOverflowing = null;
      this._ignoreBackdropClick = null;
      this._isTransitioning = null;
      this._scrollbarWidth = null;
    };

    _proto.handleUpdate = function handleUpdate() {
      this._adjustDialog();
    } // Private
    ;

    _proto._getConfig = function _getConfig(config) {
      config = _extends({}, Default$4, config);
      Util.typeCheckConfig(NAME$5, config, DefaultType$4);
      return config;
    };

    _proto._triggerBackdropTransition = function _triggerBackdropTransition() {
      var _this3 = this;

      var hideEventPrevented = $__default["default"].Event(EVENT_HIDE_PREVENTED);
      $__default["default"](this._element).trigger(hideEventPrevented);

      if (hideEventPrevented.isDefaultPrevented()) {
        return;
      }

      var isModalOverflowing = this._element.scrollHeight &gt; document.documentElement.clientHeight;

      if (!isModalOverflowing) {
        this._element.style.overflowY = 'hidden';
      }

      this._element.classList.add(CLASS_NAME_STATIC);

      var modalTransitionDuration = Util.getTransitionDurationFromElement(this._dialog);
      $__default["default"](this._element).off(Util.TRANSITION_END);
      $__default["default"](this._element).one(Util.TRANSITION_END, function () {
        _this3._element.classList.remove(CLASS_NAME_STATIC);

        if (!isModalOverflowing) {
          $__default["default"](_this3._element).one(Util.TRANSITION_END, function () {
            _this3._element.style.overflowY = '';
          }).emulateTransitionEnd(_this3._element, modalTransitionDuration);
        }
      }).emulateTransitionEnd(modalTransitionDuration);

      this._element.focus();
    };

    _proto._showElement = function _showElement(relatedTarget) {
      var _this4 = this;

      var transition = $__default["default"](this._element).hasClass(CLASS_NAME_FADE$4);
      var modalBody = this._dialog ? this._dialog.querySelector(SELECTOR_MODAL_BODY) : null;

      if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
        // Don't move modal's DOM position
        document.body.appendChild(this._element);
      }

      this._element.style.display = 'block';

      this._element.removeAttribute('aria-hidden');

      this._element.setAttribute('aria-modal', true);

      this._element.setAttribute('role', 'dialog');

      if ($__default["default"](this._dialog).hasClass(CLASS_NAME_SCROLLABLE) &amp;&amp; modalBody) {
        modalBody.scrollTop = 0;
      } else {
        this._element.scrollTop = 0;
      }

      if (transition) {
        Util.reflow(this._element);
      }

      $__default["default"](this._element).addClass(CLASS_NAME_SHOW$4);

      if (this._config.focus) {
        this._enforceFocus();
      }

      var shownEvent = $__default["default"].Event(EVENT_SHOWN$2, {
        relatedTarget: relatedTarget
      });

      var transitionComplete = function transitionComplete() {
        if (_this4._config.focus) {
          _this4._element.focus();
        }

        _this4._isTransitioning = false;
        $__default["default"](_this4._element).trigger(shownEvent);
      };

      if (transition) {
        var transitionDuration = Util.getTransitionDurationFromElement(this._dialog);
        $__default["default"](this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(transitionDuration);
      } else {
        transitionComplete();
      }
    };

    _proto._enforceFocus = function _enforceFocus() {
      var _this5 = this;

      $__default["default"](document).off(EVENT_FOCUSIN) // Guard against infinite focus loop
      .on(EVENT_FOCUSIN, function (event) {
        if (document !== event.target &amp;&amp; _this5._element !== event.target &amp;&amp; $__default["default"](_this5._element).has(event.target).length === 0) {
          _this5._element.focus();
        }
      });
    };

    _proto._setEscapeEvent = function _setEscapeEvent() {
      var _this6 = this;

      if (this._isShown) {
        $__default["default"](this._element).on(EVENT_KEYDOWN_DISMISS, function (event) {
          if (_this6._config.keyboard &amp;&amp; event.which === ESCAPE_KEYCODE) {
            event.preventDefault();

            _this6.hide();
          } else if (!_this6._config.keyboard &amp;&amp; event.which === ESCAPE_KEYCODE) {
            _this6._triggerBackdropTransition();
          }
        });
      } else if (!this._isShown) {
        $__default["default"](this._element).off(EVENT_KEYDOWN_DISMISS);
      }
    };

    _proto._setResizeEvent = function _setResizeEvent() {
      var _this7 = this;

      if (this._isShown) {
        $__default["default"](window).on(EVENT_RESIZE, function (event) {
          return _this7.handleUpdate(event);
        });
      } else {
        $__default["default"](window).off(EVENT_RESIZE);
      }
    };

    _proto._hideModal = function _hideModal() {
      var _this8 = this;

      this._element.style.display = 'none';

      this._element.setAttribute('aria-hidden', true);

      this._element.removeAttribute('aria-modal');

      this._element.removeAttribute('role');

      this._isTransitioning = false;

      this._showBackdrop(function () {
        $__default["default"](document.body).removeClass(CLASS_NAME_OPEN);

        _this8._resetAdjustments();

        _this8._resetScrollbar();

        $__default["default"](_this8._element).trigger(EVENT_HIDDEN$2);
      });
    };

    _proto._removeBackdrop = function _removeBackdrop() {
      if (this._backdrop) {
        $__default["default"](this._backdrop).remove();
        this._backdrop = null;
      }
    };

    _proto._showBackdrop = function _showBackdrop(callback) {
      var _this9 = this;

      var animate = $__default["default"](this._element).hasClass(CLASS_NAME_FADE$4) ? CLASS_NAME_FADE$4 : '';

      if (this._isShown &amp;&amp; this._config.backdrop) {
        this._backdrop = document.createElement('div');
        this._backdrop.className = CLASS_NAME_BACKDROP;

        if (animate) {
          this._backdrop.classList.add(animate);
        }

        $__default["default"](this._backdrop).appendTo(document.body);
        $__default["default"](this._element).on(EVENT_CLICK_DISMISS$1, function (event) {
          if (_this9._ignoreBackdropClick) {
            _this9._ignoreBackdropClick = false;
            return;
          }

          if (event.target !== event.currentTarget) {
            return;
          }

          if (_this9._config.backdrop === 'static') {
            _this9._triggerBackdropTransition();
          } else {
            _this9.hide();
          }
        });

        if (animate) {
          Util.reflow(this._backdrop);
        }

        $__default["default"](this._backdrop).addClass(CLASS_NAME_SHOW$4);

        if (!callback) {
          return;
        }

        if (!animate) {
          callback();
          return;
        }

        var backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop);
        $__default["default"](this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(backdropTransitionDuration);
      } else if (!this._isShown &amp;&amp; this._backdrop) {
        $__default["default"](this._backdrop).removeClass(CLASS_NAME_SHOW$4);

        var callbackRemove = function callbackRemove() {
          _this9._removeBackdrop();

          if (callback) {
            callback();
          }
        };

        if ($__default["default"](this._element).hasClass(CLASS_NAME_FADE$4)) {
          var _backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop);

          $__default["default"](this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(_backdropTransitionDuration);
        } else {
          callbackRemove();
        }
      } else if (callback) {
        callback();
      }
    } // ----------------------------------------------------------------------
    // the following methods are used to handle overflowing modals
    // todo (fat): these should probably be refactored out of modal.js
    // ----------------------------------------------------------------------
    ;

    _proto._adjustDialog = function _adjustDialog() {
      var isModalOverflowing = this._element.scrollHeight &gt; document.documentElement.clientHeight;

      if (!this._isBodyOverflowing &amp;&amp; isModalOverflowing) {
        this._element.style.paddingLeft = this._scrollbarWidth + "px";
      }

      if (this._isBodyOverflowing &amp;&amp; !isModalOverflowing) {
        this._element.style.paddingRight = this._scrollbarWidth + "px";
      }
    };

    _proto._resetAdjustments = function _resetAdjustments() {
      this._element.style.paddingLeft = '';
      this._element.style.paddingRight = '';
    };

    _proto._checkScrollbar = function _checkScrollbar() {
      var rect = document.body.getBoundingClientRect();
      this._isBodyOverflowing = Math.round(rect.left + rect.right) &lt; window.innerWidth;
      this._scrollbarWidth = this._getScrollbarWidth();
    };

    _proto._setScrollbar = function _setScrollbar() {
      var _this10 = this;

      if (this._isBodyOverflowing) {
        // Note: DOMNode.style.paddingRight returns the actual value or '' if not set
        //   while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set
        var fixedContent = [].slice.call(document.querySelectorAll(SELECTOR_FIXED_CONTENT));
        var stickyContent = [].slice.call(document.querySelectorAll(SELECTOR_STICKY_CONTENT)); // Adjust fixed content padding

        $__default["default"](fixedContent).each(function (index, element) {
          var actualPadding = element.style.paddingRight;
          var calculatedPadding = $__default["default"](element).css('padding-right');
          $__default["default"](element).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + _this10._scrollbarWidth + "px");
        }); // Adjust sticky content margin

        $__default["default"](stickyContent).each(function (index, element) {
          var actualMargin = element.style.marginRight;
          var calculatedMargin = $__default["default"](element).css('margin-right');
          $__default["default"](element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) - _this10._scrollbarWidth + "px");
        }); // Adjust body padding

        var actualPadding = document.body.style.paddingRight;
        var calculatedPadding = $__default["default"](document.body).css('padding-right');
        $__default["default"](document.body).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + this._scrollbarWidth + "px");
      }

      $__default["default"](document.body).addClass(CLASS_NAME_OPEN);
    };

    _proto._resetScrollbar = function _resetScrollbar() {
      // Restore fixed content padding
      var fixedContent = [].slice.call(document.querySelectorAll(SELECTOR_FIXED_CONTENT));
      $__default["default"](fixedContent).each(function (index, element) {
        var padding = $__default["default"](element).data('padding-right');
        $__default["default"](element).removeData('padding-right');
        element.style.paddingRight = padding ? padding : '';
      }); // Restore sticky content

      var elements = [].slice.call(document.querySelectorAll("" + SELECTOR_STICKY_CONTENT));
      $__default["default"](elements).each(function (index, element) {
        var margin = $__default["default"](element).data('margin-right');

        if (typeof margin !== 'undefined') {
          $__default["default"](element).css('margin-right', margin).removeData('margin-right');
        }
      }); // Restore body padding

      var padding = $__default["default"](document.body).data('padding-right');
      $__default["default"](document.body).removeData('padding-right');
      document.body.style.paddingRight = padding ? padding : '';
    };

    _proto._getScrollbarWidth = function _getScrollbarWidth() {
      // thx d.walsh
      var scrollDiv = document.createElement('div');
      scrollDiv.className = CLASS_NAME_SCROLLBAR_MEASURER;
      document.body.appendChild(scrollDiv);
      var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
      document.body.removeChild(scrollDiv);
      return scrollbarWidth;
    } // Static
    ;

    Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) {
      return this.each(function () {
        var data = $__default["default"](this).data(DATA_KEY$5);

        var _config = _extends({}, Default$4, $__default["default"](this).data(), typeof config === 'object' &amp;&amp; config ? config : {});

        if (!data) {
          data = new Modal(this, _config);
          $__default["default"](this).data(DATA_KEY$5, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config](relatedTarget);
        } else if (_config.show) {
          data.show(relatedTarget);
        }
      });
    };

    _createClass(Modal, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$5;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$4;
      }
    }]);

    return Modal;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) {
    var _this11 = this;

    var target;
    var selector = Util.getSelectorFromElement(this);

    if (selector) {
      target = document.querySelector(selector);
    }

    var config = $__default["default"](target).data(DATA_KEY$5) ? 'toggle' : _extends({}, $__default["default"](target).data(), $__default["default"](this).data());

    if (this.tagName === 'A' || this.tagName === 'AREA') {
      event.preventDefault();
    }

    var $target = $__default["default"](target).one(EVENT_SHOW$2, function (showEvent) {
      if (showEvent.isDefaultPrevented()) {
        // Only register focus restorer if modal will actually get shown
        return;
      }

      $target.one(EVENT_HIDDEN$2, function () {
        if ($__default["default"](_this11).is(':visible')) {
          _this11.focus();
        }
      });
    });

    Modal._jQueryInterface.call($__default["default"](target), config, this);
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$5] = Modal._jQueryInterface;
  $__default["default"].fn[NAME$5].Constructor = Modal;

  $__default["default"].fn[NAME$5].noConflict = function () {
    $__default["default"].fn[NAME$5] = JQUERY_NO_CONFLICT$5;
    return Modal._jQueryInterface;
  };

  /**
   * --------------------------------------------------------------------------
   * Bootstrap (v4.6.2): tools/sanitizer.js
   * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
   * --------------------------------------------------------------------------
   */
  var uriAttrs = ['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href'];
  var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
  var DefaultWhitelist = {
    // Global attributes allowed on any supplied element below.
    '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],
    a: ['target', 'href', 'title', 'rel'],
    area: [],
    b: [],
    br: [],
    col: [],
    code: [],
    div: [],
    em: [],
    hr: [],
    h1: [],
    h2: [],
    h3: [],
    h4: [],
    h5: [],
    h6: [],
    i: [],
    img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],
    li: [],
    ol: [],
    p: [],
    pre: [],
    s: [],
    small: [],
    span: [],
    sub: [],
    sup: [],
    strong: [],
    u: [],
    ul: []
  };
  /**
   * A pattern that recognizes a commonly useful subset of URLs that are safe.
   *
   * Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts
   */

  var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&amp;/:?]*(?:[#/?]|$))/i;
  /**
   * A pattern that matches safe data URLs. Only matches image, video and audio types.
   *
   * Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts
   */

  var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i;

  function allowedAttribute(attr, allowedAttributeList) {
    var attrName = attr.nodeName.toLowerCase();

    if (allowedAttributeList.indexOf(attrName) !== -1) {
      if (uriAttrs.indexOf(attrName) !== -1) {
        return Boolean(SAFE_URL_PATTERN.test(attr.nodeValue) || DATA_URL_PATTERN.test(attr.nodeValue));
      }

      return true;
    }

    var regExp = allowedAttributeList.filter(function (attrRegex) {
      return attrRegex instanceof RegExp;
    }); // Check if a regular expression validates the attribute.

    for (var i = 0, len = regExp.length; i &lt; len; i++) {
      if (regExp[i].test(attrName)) {
        return true;
      }
    }

    return false;
  }

  function sanitizeHtml(unsafeHtml, whiteList, sanitizeFn) {
    if (unsafeHtml.length === 0) {
      return unsafeHtml;
    }

    if (sanitizeFn &amp;&amp; typeof sanitizeFn === 'function') {
      return sanitizeFn(unsafeHtml);
    }

    var domParser = new window.DOMParser();
    var createdDocument = domParser.parseFromString(unsafeHtml, 'text/html');
    var whitelistKeys = Object.keys(whiteList);
    var elements = [].slice.call(createdDocument.body.querySelectorAll('*'));

    var _loop = function _loop(i, len) {
      var el = elements[i];
      var elName = el.nodeName.toLowerCase();

      if (whitelistKeys.indexOf(el.nodeName.toLowerCase()) === -1) {
        el.parentNode.removeChild(el);
        return "continue";
      }

      var attributeList = [].slice.call(el.attributes); // eslint-disable-next-line unicorn/prefer-spread

      var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
      attributeList.forEach(function (attr) {
        if (!allowedAttribute(attr, whitelistedAttributes)) {
          el.removeAttribute(attr.nodeName);
        }
      });
    };

    for (var i = 0, len = elements.length; i &lt; len; i++) {
      var _ret = _loop(i);

      if (_ret === "continue") continue;
    }

    return createdDocument.body.innerHTML;
  }

  /**
   * Constants
   */

  var NAME$4 = 'tooltip';
  var VERSION$4 = '4.6.2';
  var DATA_KEY$4 = 'bs.tooltip';
  var EVENT_KEY$4 = "." + DATA_KEY$4;
  var JQUERY_NO_CONFLICT$4 = $__default["default"].fn[NAME$4];
  var CLASS_PREFIX$1 = 'bs-tooltip';
  var BSCLS_PREFIX_REGEX$1 = new RegExp("(^|\\s)" + CLASS_PREFIX$1 + "\\S+", 'g');
  var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
  var CLASS_NAME_FADE$3 = 'fade';
  var CLASS_NAME_SHOW$3 = 'show';
  var HOVER_STATE_SHOW = 'show';
  var HOVER_STATE_OUT = 'out';
  var SELECTOR_TOOLTIP_INNER = '.tooltip-inner';
  var SELECTOR_ARROW = '.arrow';
  var TRIGGER_HOVER = 'hover';
  var TRIGGER_FOCUS = 'focus';
  var TRIGGER_CLICK = 'click';
  var TRIGGER_MANUAL = 'manual';
  var AttachmentMap = {
    AUTO: 'auto',
    TOP: 'top',
    RIGHT: 'right',
    BOTTOM: 'bottom',
    LEFT: 'left'
  };
  var Default$3 = {
    animation: true,
    template: '&lt;div class="tooltip" role="tooltip"&gt;' + '&lt;div class="arrow"&gt;&lt;/div&gt;' + '&lt;div class="tooltip-inner"&gt;&lt;/div&gt;&lt;/div&gt;',
    trigger: 'hover focus',
    title: '',
    delay: 0,
    html: false,
    selector: false,
    placement: 'top',
    offset: 0,
    container: false,
    fallbackPlacement: 'flip',
    boundary: 'scrollParent',
    customClass: '',
    sanitize: true,
    sanitizeFn: null,
    whiteList: DefaultWhitelist,
    popperConfig: null
  };
  var DefaultType$3 = {
    animation: 'boolean',
    template: 'string',
    title: '(string|element|function)',
    trigger: 'string',
    delay: '(number|object)',
    html: 'boolean',
    selector: '(string|boolean)',
    placement: '(string|function)',
    offset: '(number|string|function)',
    container: '(string|element|boolean)',
    fallbackPlacement: '(string|array)',
    boundary: '(string|element)',
    customClass: '(string|function)',
    sanitize: 'boolean',
    sanitizeFn: '(null|function)',
    whiteList: 'object',
    popperConfig: '(null|object)'
  };
  var Event$1 = {
    HIDE: "hide" + EVENT_KEY$4,
    HIDDEN: "hidden" + EVENT_KEY$4,
    SHOW: "show" + EVENT_KEY$4,
    SHOWN: "shown" + EVENT_KEY$4,
    INSERTED: "inserted" + EVENT_KEY$4,
    CLICK: "click" + EVENT_KEY$4,
    FOCUSIN: "focusin" + EVENT_KEY$4,
    FOCUSOUT: "focusout" + EVENT_KEY$4,
    MOUSEENTER: "mouseenter" + EVENT_KEY$4,
    MOUSELEAVE: "mouseleave" + EVENT_KEY$4
  };
  /**
   * Class definition
   */

  var Tooltip = /*#__PURE__*/function () {
    function Tooltip(element, config) {
      if (typeof Popper__default["default"] === 'undefined') {
        throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)');
      } // Private


      this._isEnabled = true;
      this._timeout = 0;
      this._hoverState = '';
      this._activeTrigger = {};
      this._popper = null; // Protected

      this.element = element;
      this.config = this._getConfig(config);
      this.tip = null;

      this._setListeners();
    } // Getters


    var _proto = Tooltip.prototype;

    // Public
    _proto.enable = function enable() {
      this._isEnabled = true;
    };

    _proto.disable = function disable() {
      this._isEnabled = false;
    };

    _proto.toggleEnabled = function toggleEnabled() {
      this._isEnabled = !this._isEnabled;
    };

    _proto.toggle = function toggle(event) {
      if (!this._isEnabled) {
        return;
      }

      if (event) {
        var dataKey = this.constructor.DATA_KEY;
        var context = $__default["default"](event.currentTarget).data(dataKey);

        if (!context) {
          context = new this.constructor(event.currentTarget, this._getDelegateConfig());
          $__default["default"](event.currentTarget).data(dataKey, context);
        }

        context._activeTrigger.click = !context._activeTrigger.click;

        if (context._isWithActiveTrigger()) {
          context._enter(null, context);
        } else {
          context._leave(null, context);
        }
      } else {
        if ($__default["default"](this.getTipElement()).hasClass(CLASS_NAME_SHOW$3)) {
          this._leave(null, this);

          return;
        }

        this._enter(null, this);
      }
    };

    _proto.dispose = function dispose() {
      clearTimeout(this._timeout);
      $__default["default"].removeData(this.element, this.constructor.DATA_KEY);
      $__default["default"](this.element).off(this.constructor.EVENT_KEY);
      $__default["default"](this.element).closest('.modal').off('hide.bs.modal', this._hideModalHandler);

      if (this.tip) {
        $__default["default"](this.tip).remove();
      }

      this._isEnabled = null;
      this._timeout = null;
      this._hoverState = null;
      this._activeTrigger = null;

      if (this._popper) {
        this._popper.destroy();
      }

      this._popper = null;
      this.element = null;
      this.config = null;
      this.tip = null;
    };

    _proto.show = function show() {
      var _this = this;

      if ($__default["default"](this.element).css('display') === 'none') {
        throw new Error('Please use show on visible elements');
      }

      var showEvent = $__default["default"].Event(this.constructor.Event.SHOW);

      if (this.isWithContent() &amp;&amp; this._isEnabled) {
        $__default["default"](this.element).trigger(showEvent);
        var shadowRoot = Util.findShadowRoot(this.element);
        var isInTheDom = $__default["default"].contains(shadowRoot !== null ? shadowRoot : this.element.ownerDocument.documentElement, this.element);

        if (showEvent.isDefaultPrevented() || !isInTheDom) {
          return;
        }

        var tip = this.getTipElement();
        var tipId = Util.getUID(this.constructor.NAME);
        tip.setAttribute('id', tipId);
        this.element.setAttribute('aria-describedby', tipId);
        this.setContent();

        if (this.config.animation) {
          $__default["default"](tip).addClass(CLASS_NAME_FADE$3);
        }

        var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement;

        var attachment = this._getAttachment(placement);

        this.addAttachmentClass(attachment);

        var container = this._getContainer();

        $__default["default"](tip).data(this.constructor.DATA_KEY, this);

        if (!$__default["default"].contains(this.element.ownerDocument.documentElement, this.tip)) {
          $__default["default"](tip).appendTo(container);
        }

        $__default["default"](this.element).trigger(this.constructor.Event.INSERTED);
        this._popper = new Popper__default["default"](this.element, tip, this._getPopperConfig(attachment));
        $__default["default"](tip).addClass(CLASS_NAME_SHOW$3);
        $__default["default"](tip).addClass(this.config.customClass); // If this is a touch-enabled device we add extra
        // empty mouseover listeners to the body's immediate children;
        // only needed because of broken event delegation on iOS
        // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html

        if ('ontouchstart' in document.documentElement) {
          $__default["default"](document.body).children().on('mouseover', null, $__default["default"].noop);
        }

        var complete = function complete() {
          if (_this.config.animation) {
            _this._fixTransition();
          }

          var prevHoverState = _this._hoverState;
          _this._hoverState = null;
          $__default["default"](_this.element).trigger(_this.constructor.Event.SHOWN);

          if (prevHoverState === HOVER_STATE_OUT) {
            _this._leave(null, _this);
          }
        };

        if ($__default["default"](this.tip).hasClass(CLASS_NAME_FADE$3)) {
          var transitionDuration = Util.getTransitionDurationFromElement(this.tip);
          $__default["default"](this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
        } else {
          complete();
        }
      }
    };

    _proto.hide = function hide(callback) {
      var _this2 = this;

      var tip = this.getTipElement();
      var hideEvent = $__default["default"].Event(this.constructor.Event.HIDE);

      var complete = function complete() {
        if (_this2._hoverState !== HOVER_STATE_SHOW &amp;&amp; tip.parentNode) {
          tip.parentNode.removeChild(tip);
        }

        _this2._cleanTipClass();

        _this2.element.removeAttribute('aria-describedby');

        $__default["default"](_this2.element).trigger(_this2.constructor.Event.HIDDEN);

        if (_this2._popper !== null) {
          _this2._popper.destroy();
        }

        if (callback) {
          callback();
        }
      };

      $__default["default"](this.element).trigger(hideEvent);

      if (hideEvent.isDefaultPrevented()) {
        return;
      }

      $__default["default"](tip).removeClass(CLASS_NAME_SHOW$3); // If this is a touch-enabled device we remove the extra
      // empty mouseover listeners we added for iOS support

      if ('ontouchstart' in document.documentElement) {
        $__default["default"](document.body).children().off('mouseover', null, $__default["default"].noop);
      }

      this._activeTrigger[TRIGGER_CLICK] = false;
      this._activeTrigger[TRIGGER_FOCUS] = false;
      this._activeTrigger[TRIGGER_HOVER] = false;

      if ($__default["default"](this.tip).hasClass(CLASS_NAME_FADE$3)) {
        var transitionDuration = Util.getTransitionDurationFromElement(tip);
        $__default["default"](tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
      } else {
        complete();
      }

      this._hoverState = '';
    };

    _proto.update = function update() {
      if (this._popper !== null) {
        this._popper.scheduleUpdate();
      }
    } // Protected
    ;

    _proto.isWithContent = function isWithContent() {
      return Boolean(this.getTitle());
    };

    _proto.addAttachmentClass = function addAttachmentClass(attachment) {
      $__default["default"](this.getTipElement()).addClass(CLASS_PREFIX$1 + "-" + attachment);
    };

    _proto.getTipElement = function getTipElement() {
      this.tip = this.tip || $__default["default"](this.config.template)[0];
      return this.tip;
    };

    _proto.setContent = function setContent() {
      var tip = this.getTipElement();
      this.setElementContent($__default["default"](tip.querySelectorAll(SELECTOR_TOOLTIP_INNER)), this.getTitle());
      $__default["default"](tip).removeClass(CLASS_NAME_FADE$3 + " " + CLASS_NAME_SHOW$3);
    };

    _proto.setElementContent = function setElementContent($element, content) {
      if (typeof content === 'object' &amp;&amp; (content.nodeType || content.jquery)) {
        // Content is a DOM node or a jQuery
        if (this.config.html) {
          if (!$__default["default"](content).parent().is($element)) {
            $element.empty().append(content);
          }
        } else {
          $element.text($__default["default"](content).text());
        }

        return;
      }

      if (this.config.html) {
        if (this.config.sanitize) {
          content = sanitizeHtml(content, this.config.whiteList, this.config.sanitizeFn);
        }

        $element.html(content);
      } else {
        $element.text(content);
      }
    };

    _proto.getTitle = function getTitle() {
      var title = this.element.getAttribute('data-original-title');

      if (!title) {
        title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title;
      }

      return title;
    } // Private
    ;

    _proto._getPopperConfig = function _getPopperConfig(attachment) {
      var _this3 = this;

      var defaultBsConfig = {
        placement: attachment,
        modifiers: {
          offset: this._getOffset(),
          flip: {
            behavior: this.config.fallbackPlacement
          },
          arrow: {
            element: SELECTOR_ARROW
          },
          preventOverflow: {
            boundariesElement: this.config.boundary
          }
        },
        onCreate: function onCreate(data) {
          if (data.originalPlacement !== data.placement) {
            _this3._handlePopperPlacementChange(data);
          }
        },
        onUpdate: function onUpdate(data) {
          return _this3._handlePopperPlacementChange(data);
        }
      };
      return _extends({}, defaultBsConfig, this.config.popperConfig);
    };

    _proto._getOffset = function _getOffset() {
      var _this4 = this;

      var offset = {};

      if (typeof this.config.offset === 'function') {
        offset.fn = function (data) {
          data.offsets = _extends({}, data.offsets, _this4.config.offset(data.offsets, _this4.element));
          return data;
        };
      } else {
        offset.offset = this.config.offset;
      }

      return offset;
    };

    _proto._getContainer = function _getContainer() {
      if (this.config.container === false) {
        return document.body;
      }

      if (Util.isElement(this.config.container)) {
        return $__default["default"](this.config.container);
      }

      return $__default["default"](document).find(this.config.container);
    };

    _proto._getAttachment = function _getAttachment(placement) {
      return AttachmentMap[placement.toUpperCase()];
    };

    _proto._setListeners = function _setListeners() {
      var _this5 = this;

      var triggers = this.config.trigger.split(' ');
      triggers.forEach(function (trigger) {
        if (trigger === 'click') {
          $__default["default"](_this5.element).on(_this5.constructor.Event.CLICK, _this5.config.selector, function (event) {
            return _this5.toggle(event);
          });
        } else if (trigger !== TRIGGER_MANUAL) {
          var eventIn = trigger === TRIGGER_HOVER ? _this5.constructor.Event.MOUSEENTER : _this5.constructor.Event.FOCUSIN;
          var eventOut = trigger === TRIGGER_HOVER ? _this5.constructor.Event.MOUSELEAVE : _this5.constructor.Event.FOCUSOUT;
          $__default["default"](_this5.element).on(eventIn, _this5.config.selector, function (event) {
            return _this5._enter(event);
          }).on(eventOut, _this5.config.selector, function (event) {
            return _this5._leave(event);
          });
        }
      });

      this._hideModalHandler = function () {
        if (_this5.element) {
          _this5.hide();
        }
      };

      $__default["default"](this.element).closest('.modal').on('hide.bs.modal', this._hideModalHandler);

      if (this.config.selector) {
        this.config = _extends({}, this.config, {
          trigger: 'manual',
          selector: ''
        });
      } else {
        this._fixTitle();
      }
    };

    _proto._fixTitle = function _fixTitle() {
      var titleType = typeof this.element.getAttribute('data-original-title');

      if (this.element.getAttribute('title') || titleType !== 'string') {
        this.element.setAttribute('data-original-title', this.element.getAttribute('title') || '');
        this.element.setAttribute('title', '');
      }
    };

    _proto._enter = function _enter(event, context) {
      var dataKey = this.constructor.DATA_KEY;
      context = context || $__default["default"](event.currentTarget).data(dataKey);

      if (!context) {
        context = new this.constructor(event.currentTarget, this._getDelegateConfig());
        $__default["default"](event.currentTarget).data(dataKey, context);
      }

      if (event) {
        context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true;
      }

      if ($__default["default"](context.getTipElement()).hasClass(CLASS_NAME_SHOW$3) || context._hoverState === HOVER_STATE_SHOW) {
        context._hoverState = HOVER_STATE_SHOW;
        return;
      }

      clearTimeout(context._timeout);
      context._hoverState = HOVER_STATE_SHOW;

      if (!context.config.delay || !context.config.delay.show) {
        context.show();
        return;
      }

      context._timeout = setTimeout(function () {
        if (context._hoverState === HOVER_STATE_SHOW) {
          context.show();
        }
      }, context.config.delay.show);
    };

    _proto._leave = function _leave(event, context) {
      var dataKey = this.constructor.DATA_KEY;
      context = context || $__default["default"](event.currentTarget).data(dataKey);

      if (!context) {
        context = new this.constructor(event.currentTarget, this._getDelegateConfig());
        $__default["default"](event.currentTarget).data(dataKey, context);
      }

      if (event) {
        context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = false;
      }

      if (context._isWithActiveTrigger()) {
        return;
      }

      clearTimeout(context._timeout);
      context._hoverState = HOVER_STATE_OUT;

      if (!context.config.delay || !context.config.delay.hide) {
        context.hide();
        return;
      }

      context._timeout = setTimeout(function () {
        if (context._hoverState === HOVER_STATE_OUT) {
          context.hide();
        }
      }, context.config.delay.hide);
    };

    _proto._isWithActiveTrigger = function _isWithActiveTrigger() {
      for (var trigger in this._activeTrigger) {
        if (this._activeTrigger[trigger]) {
          return true;
        }
      }

      return false;
    };

    _proto._getConfig = function _getConfig(config) {
      var dataAttributes = $__default["default"](this.element).data();
      Object.keys(dataAttributes).forEach(function (dataAttr) {
        if (DISALLOWED_ATTRIBUTES.indexOf(dataAttr) !== -1) {
          delete dataAttributes[dataAttr];
        }
      });
      config = _extends({}, this.constructor.Default, dataAttributes, typeof config === 'object' &amp;&amp; config ? config : {});

      if (typeof config.delay === 'number') {
        config.delay = {
          show: config.delay,
          hide: config.delay
        };
      }

      if (typeof config.title === 'number') {
        config.title = config.title.toString();
      }

      if (typeof config.content === 'number') {
        config.content = config.content.toString();
      }

      Util.typeCheckConfig(NAME$4, config, this.constructor.DefaultType);

      if (config.sanitize) {
        config.template = sanitizeHtml(config.template, config.whiteList, config.sanitizeFn);
      }

      return config;
    };

    _proto._getDelegateConfig = function _getDelegateConfig() {
      var config = {};

      if (this.config) {
        for (var key in this.config) {
          if (this.constructor.Default[key] !== this.config[key]) {
            config[key] = this.config[key];
          }
        }
      }

      return config;
    };

    _proto._cleanTipClass = function _cleanTipClass() {
      var $tip = $__default["default"](this.getTipElement());
      var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX$1);

      if (tabClass !== null &amp;&amp; tabClass.length) {
        $tip.removeClass(tabClass.join(''));
      }
    };

    _proto._handlePopperPlacementChange = function _handlePopperPlacementChange(popperData) {
      this.tip = popperData.instance.popper;

      this._cleanTipClass();

      this.addAttachmentClass(this._getAttachment(popperData.placement));
    };

    _proto._fixTransition = function _fixTransition() {
      var tip = this.getTipElement();
      var initConfigAnimation = this.config.animation;

      if (tip.getAttribute('x-placement') !== null) {
        return;
      }

      $__default["default"](tip).removeClass(CLASS_NAME_FADE$3);
      this.config.animation = false;
      this.hide();
      this.show();
      this.config.animation = initConfigAnimation;
    } // Static
    ;

    Tooltip._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var $element = $__default["default"](this);
        var data = $element.data(DATA_KEY$4);

        var _config = typeof config === 'object' &amp;&amp; config;

        if (!data &amp;&amp; /dispose|hide/.test(config)) {
          return;
        }

        if (!data) {
          data = new Tooltip(this, _config);
          $element.data(DATA_KEY$4, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    _createClass(Tooltip, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$4;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$3;
      }
    }, {
      key: "NAME",
      get: function get() {
        return NAME$4;
      }
    }, {
      key: "DATA_KEY",
      get: function get() {
        return DATA_KEY$4;
      }
    }, {
      key: "Event",
      get: function get() {
        return Event$1;
      }
    }, {
      key: "EVENT_KEY",
      get: function get() {
        return EVENT_KEY$4;
      }
    }, {
      key: "DefaultType",
      get: function get() {
        return DefaultType$3;
      }
    }]);

    return Tooltip;
  }();
  /**
   * jQuery
   */


  $__default["default"].fn[NAME$4] = Tooltip._jQueryInterface;
  $__default["default"].fn[NAME$4].Constructor = Tooltip;

  $__default["default"].fn[NAME$4].noConflict = function () {
    $__default["default"].fn[NAME$4] = JQUERY_NO_CONFLICT$4;
    return Tooltip._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$3 = 'popover';
  var VERSION$3 = '4.6.2';
  var DATA_KEY$3 = 'bs.popover';
  var EVENT_KEY$3 = "." + DATA_KEY$3;
  var JQUERY_NO_CONFLICT$3 = $__default["default"].fn[NAME$3];
  var CLASS_PREFIX = 'bs-popover';
  var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g');
  var CLASS_NAME_FADE$2 = 'fade';
  var CLASS_NAME_SHOW$2 = 'show';
  var SELECTOR_TITLE = '.popover-header';
  var SELECTOR_CONTENT = '.popover-body';

  var Default$2 = _extends({}, Tooltip.Default, {
    placement: 'right',
    trigger: 'click',
    content: '',
    template: '&lt;div class="popover" role="tooltip"&gt;' + '&lt;div class="arrow"&gt;&lt;/div&gt;' + '&lt;h3 class="popover-header"&gt;&lt;/h3&gt;' + '&lt;div class="popover-body"&gt;&lt;/div&gt;&lt;/div&gt;'
  });

  var DefaultType$2 = _extends({}, Tooltip.DefaultType, {
    content: '(string|element|function)'
  });

  var Event = {
    HIDE: "hide" + EVENT_KEY$3,
    HIDDEN: "hidden" + EVENT_KEY$3,
    SHOW: "show" + EVENT_KEY$3,
    SHOWN: "shown" + EVENT_KEY$3,
    INSERTED: "inserted" + EVENT_KEY$3,
    CLICK: "click" + EVENT_KEY$3,
    FOCUSIN: "focusin" + EVENT_KEY$3,
    FOCUSOUT: "focusout" + EVENT_KEY$3,
    MOUSEENTER: "mouseenter" + EVENT_KEY$3,
    MOUSELEAVE: "mouseleave" + EVENT_KEY$3
  };
  /**
   * Class definition
   */

  var Popover = /*#__PURE__*/function (_Tooltip) {
    _inheritsLoose(Popover, _Tooltip);

    function Popover() {
      return _Tooltip.apply(this, arguments) || this;
    }

    var _proto = Popover.prototype;

    // Overrides
    _proto.isWithContent = function isWithContent() {
      return this.getTitle() || this._getContent();
    };

    _proto.addAttachmentClass = function addAttachmentClass(attachment) {
      $__default["default"](this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment);
    };

    _proto.getTipElement = function getTipElement() {
      this.tip = this.tip || $__default["default"](this.config.template)[0];
      return this.tip;
    };

    _proto.setContent = function setContent() {
      var $tip = $__default["default"](this.getTipElement()); // We use append for html objects to maintain js events

      this.setElementContent($tip.find(SELECTOR_TITLE), this.getTitle());

      var content = this._getContent();

      if (typeof content === 'function') {
        content = content.call(this.element);
      }

      this.setElementContent($tip.find(SELECTOR_CONTENT), content);
      $tip.removeClass(CLASS_NAME_FADE$2 + " " + CLASS_NAME_SHOW$2);
    } // Private
    ;

    _proto._getContent = function _getContent() {
      return this.element.getAttribute('data-content') || this.config.content;
    };

    _proto._cleanTipClass = function _cleanTipClass() {
      var $tip = $__default["default"](this.getTipElement());
      var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX);

      if (tabClass !== null &amp;&amp; tabClass.length &gt; 0) {
        $tip.removeClass(tabClass.join(''));
      }
    } // Static
    ;

    Popover._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var data = $__default["default"](this).data(DATA_KEY$3);

        var _config = typeof config === 'object' ? config : null;

        if (!data &amp;&amp; /dispose|hide/.test(config)) {
          return;
        }

        if (!data) {
          data = new Popover(this, _config);
          $__default["default"](this).data(DATA_KEY$3, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    _createClass(Popover, null, [{
      key: "VERSION",
      get: // Getters
      function get() {
        return VERSION$3;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$2;
      }
    }, {
      key: "NAME",
      get: function get() {
        return NAME$3;
      }
    }, {
      key: "DATA_KEY",
      get: function get() {
        return DATA_KEY$3;
      }
    }, {
      key: "Event",
      get: function get() {
        return Event;
      }
    }, {
      key: "EVENT_KEY",
      get: function get() {
        return EVENT_KEY$3;
      }
    }, {
      key: "DefaultType",
      get: function get() {
        return DefaultType$2;
      }
    }]);

    return Popover;
  }(Tooltip);
  /**
   * jQuery
   */


  $__default["default"].fn[NAME$3] = Popover._jQueryInterface;
  $__default["default"].fn[NAME$3].Constructor = Popover;

  $__default["default"].fn[NAME$3].noConflict = function () {
    $__default["default"].fn[NAME$3] = JQUERY_NO_CONFLICT$3;
    return Popover._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$2 = 'scrollspy';
  var VERSION$2 = '4.6.2';
  var DATA_KEY$2 = 'bs.scrollspy';
  var EVENT_KEY$2 = "." + DATA_KEY$2;
  var DATA_API_KEY$1 = '.data-api';
  var JQUERY_NO_CONFLICT$2 = $__default["default"].fn[NAME$2];
  var CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item';
  var CLASS_NAME_ACTIVE$1 = 'active';
  var EVENT_ACTIVATE = "activate" + EVENT_KEY$2;
  var EVENT_SCROLL = "scroll" + EVENT_KEY$2;
  var EVENT_LOAD_DATA_API = "load" + EVENT_KEY$2 + DATA_API_KEY$1;
  var METHOD_OFFSET = 'offset';
  var METHOD_POSITION = 'position';
  var SELECTOR_DATA_SPY = '[data-spy="scroll"]';
  var SELECTOR_NAV_LIST_GROUP$1 = '.nav, .list-group';
  var SELECTOR_NAV_LINKS = '.nav-link';
  var SELECTOR_NAV_ITEMS = '.nav-item';
  var SELECTOR_LIST_ITEMS = '.list-group-item';
  var SELECTOR_DROPDOWN$1 = '.dropdown';
  var SELECTOR_DROPDOWN_ITEMS = '.dropdown-item';
  var SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle';
  var Default$1 = {
    offset: 10,
    method: 'auto',
    target: ''
  };
  var DefaultType$1 = {
    offset: 'number',
    method: 'string',
    target: '(string|element)'
  };
  /**
   * Class definition
   */

  var ScrollSpy = /*#__PURE__*/function () {
    function ScrollSpy(element, config) {
      var _this = this;

      this._element = element;
      this._scrollElement = element.tagName === 'BODY' ? window : element;
      this._config = this._getConfig(config);
      this._selector = this._config.target + " " + SELECTOR_NAV_LINKS + "," + (this._config.target + " " + SELECTOR_LIST_ITEMS + ",") + (this._config.target + " " + SELECTOR_DROPDOWN_ITEMS);
      this._offsets = [];
      this._targets = [];
      this._activeTarget = null;
      this._scrollHeight = 0;
      $__default["default"](this._scrollElement).on(EVENT_SCROLL, function (event) {
        return _this._process(event);
      });
      this.refresh();

      this._process();
    } // Getters


    var _proto = ScrollSpy.prototype;

    // Public
    _proto.refresh = function refresh() {
      var _this2 = this;

      var autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION;
      var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method;
      var offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0;
      this._offsets = [];
      this._targets = [];
      this._scrollHeight = this._getScrollHeight();
      var targets = [].slice.call(document.querySelectorAll(this._selector));
      targets.map(function (element) {
        var target;
        var targetSelector = Util.getSelectorFromElement(element);

        if (targetSelector) {
          target = document.querySelector(targetSelector);
        }

        if (target) {
          var targetBCR = target.getBoundingClientRect();

          if (targetBCR.width || targetBCR.height) {
            // TODO (fat): remove sketch reliance on jQuery position/offset
            return [$__default["default"](target)[offsetMethod]().top + offsetBase, targetSelector];
          }
        }

        return null;
      }).filter(Boolean).sort(function (a, b) {
        return a[0] - b[0];
      }).forEach(function (item) {
        _this2._offsets.push(item[0]);

        _this2._targets.push(item[1]);
      });
    };

    _proto.dispose = function dispose() {
      $__default["default"].removeData(this._element, DATA_KEY$2);
      $__default["default"](this._scrollElement).off(EVENT_KEY$2);
      this._element = null;
      this._scrollElement = null;
      this._config = null;
      this._selector = null;
      this._offsets = null;
      this._targets = null;
      this._activeTarget = null;
      this._scrollHeight = null;
    } // Private
    ;

    _proto._getConfig = function _getConfig(config) {
      config = _extends({}, Default$1, typeof config === 'object' &amp;&amp; config ? config : {});

      if (typeof config.target !== 'string' &amp;&amp; Util.isElement(config.target)) {
        var id = $__default["default"](config.target).attr('id');

        if (!id) {
          id = Util.getUID(NAME$2);
          $__default["default"](config.target).attr('id', id);
        }

        config.target = "#" + id;
      }

      Util.typeCheckConfig(NAME$2, config, DefaultType$1);
      return config;
    };

    _proto._getScrollTop = function _getScrollTop() {
      return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop;
    };

    _proto._getScrollHeight = function _getScrollHeight() {
      return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    };

    _proto._getOffsetHeight = function _getOffsetHeight() {
      return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height;
    };

    _proto._process = function _process() {
      var scrollTop = this._getScrollTop() + this._config.offset;

      var scrollHeight = this._getScrollHeight();

      var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight();

      if (this._scrollHeight !== scrollHeight) {
        this.refresh();
      }

      if (scrollTop &gt;= maxScroll) {
        var target = this._targets[this._targets.length - 1];

        if (this._activeTarget !== target) {
          this._activate(target);
        }

        return;
      }

      if (this._activeTarget &amp;&amp; scrollTop &lt; this._offsets[0] &amp;&amp; this._offsets[0] &gt; 0) {
        this._activeTarget = null;

        this._clear();

        return;
      }

      for (var i = this._offsets.length; i--;) {
        var isActiveTarget = this._activeTarget !== this._targets[i] &amp;&amp; scrollTop &gt;= this._offsets[i] &amp;&amp; (typeof this._offsets[i + 1] === 'undefined' || scrollTop &lt; this._offsets[i + 1]);

        if (isActiveTarget) {
          this._activate(this._targets[i]);
        }
      }
    };

    _proto._activate = function _activate(target) {
      this._activeTarget = target;

      this._clear();

      var queries = this._selector.split(',').map(function (selector) {
        return selector + "[data-target=\"" + target + "\"]," + selector + "[href=\"" + target + "\"]";
      });

      var $link = $__default["default"]([].slice.call(document.querySelectorAll(queries.join(','))));

      if ($link.hasClass(CLASS_NAME_DROPDOWN_ITEM)) {
        $link.closest(SELECTOR_DROPDOWN$1).find(SELECTOR_DROPDOWN_TOGGLE$1).addClass(CLASS_NAME_ACTIVE$1);
        $link.addClass(CLASS_NAME_ACTIVE$1);
      } else {
        // Set triggered link as active
        $link.addClass(CLASS_NAME_ACTIVE$1); // Set triggered links parents as active
        // With both &lt;ul&gt; and &lt;nav&gt; markup a parent is the previous sibling of any nav ancestor

        $link.parents(SELECTOR_NAV_LIST_GROUP$1).prev(SELECTOR_NAV_LINKS + ", " + SELECTOR_LIST_ITEMS).addClass(CLASS_NAME_ACTIVE$1); // Handle special case when .nav-link is inside .nav-item

        $link.parents(SELECTOR_NAV_LIST_GROUP$1).prev(SELECTOR_NAV_ITEMS).children(SELECTOR_NAV_LINKS).addClass(CLASS_NAME_ACTIVE$1);
      }

      $__default["default"](this._scrollElement).trigger(EVENT_ACTIVATE, {
        relatedTarget: target
      });
    };

    _proto._clear = function _clear() {
      [].slice.call(document.querySelectorAll(this._selector)).filter(function (node) {
        return node.classList.contains(CLASS_NAME_ACTIVE$1);
      }).forEach(function (node) {
        return node.classList.remove(CLASS_NAME_ACTIVE$1);
      });
    } // Static
    ;

    ScrollSpy._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var data = $__default["default"](this).data(DATA_KEY$2);

        var _config = typeof config === 'object' &amp;&amp; config;

        if (!data) {
          data = new ScrollSpy(this, _config);
          $__default["default"](this).data(DATA_KEY$2, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    _createClass(ScrollSpy, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$2;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default$1;
      }
    }]);

    return ScrollSpy;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](window).on(EVENT_LOAD_DATA_API, function () {
    var scrollSpys = [].slice.call(document.querySelectorAll(SELECTOR_DATA_SPY));
    var scrollSpysLength = scrollSpys.length;

    for (var i = scrollSpysLength; i--;) {
      var $spy = $__default["default"](scrollSpys[i]);

      ScrollSpy._jQueryInterface.call($spy, $spy.data());
    }
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$2] = ScrollSpy._jQueryInterface;
  $__default["default"].fn[NAME$2].Constructor = ScrollSpy;

  $__default["default"].fn[NAME$2].noConflict = function () {
    $__default["default"].fn[NAME$2] = JQUERY_NO_CONFLICT$2;
    return ScrollSpy._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME$1 = 'tab';
  var VERSION$1 = '4.6.2';
  var DATA_KEY$1 = 'bs.tab';
  var EVENT_KEY$1 = "." + DATA_KEY$1;
  var DATA_API_KEY = '.data-api';
  var JQUERY_NO_CONFLICT$1 = $__default["default"].fn[NAME$1];
  var CLASS_NAME_DROPDOWN_MENU = 'dropdown-menu';
  var CLASS_NAME_ACTIVE = 'active';
  var CLASS_NAME_DISABLED = 'disabled';
  var CLASS_NAME_FADE$1 = 'fade';
  var CLASS_NAME_SHOW$1 = 'show';
  var EVENT_HIDE$1 = "hide" + EVENT_KEY$1;
  var EVENT_HIDDEN$1 = "hidden" + EVENT_KEY$1;
  var EVENT_SHOW$1 = "show" + EVENT_KEY$1;
  var EVENT_SHOWN$1 = "shown" + EVENT_KEY$1;
  var EVENT_CLICK_DATA_API = "click" + EVENT_KEY$1 + DATA_API_KEY;
  var SELECTOR_DROPDOWN = '.dropdown';
  var SELECTOR_NAV_LIST_GROUP = '.nav, .list-group';
  var SELECTOR_ACTIVE = '.active';
  var SELECTOR_ACTIVE_UL = '&gt; li &gt; .active';
  var SELECTOR_DATA_TOGGLE = '[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]';
  var SELECTOR_DROPDOWN_TOGGLE = '.dropdown-toggle';
  var SELECTOR_DROPDOWN_ACTIVE_CHILD = '&gt; .dropdown-menu .active';
  /**
   * Class definition
   */

  var Tab = /*#__PURE__*/function () {
    function Tab(element) {
      this._element = element;
    } // Getters


    var _proto = Tab.prototype;

    // Public
    _proto.show = function show() {
      var _this = this;

      if (this._element.parentNode &amp;&amp; this._element.parentNode.nodeType === Node.ELEMENT_NODE &amp;&amp; $__default["default"](this._element).hasClass(CLASS_NAME_ACTIVE) || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED) || this._element.hasAttribute('disabled')) {
        return;
      }

      var target;
      var previous;
      var listElement = $__default["default"](this._element).closest(SELECTOR_NAV_LIST_GROUP)[0];
      var selector = Util.getSelectorFromElement(this._element);

      if (listElement) {
        var itemSelector = listElement.nodeName === 'UL' || listElement.nodeName === 'OL' ? SELECTOR_ACTIVE_UL : SELECTOR_ACTIVE;
        previous = $__default["default"].makeArray($__default["default"](listElement).find(itemSelector));
        previous = previous[previous.length - 1];
      }

      var hideEvent = $__default["default"].Event(EVENT_HIDE$1, {
        relatedTarget: this._element
      });
      var showEvent = $__default["default"].Event(EVENT_SHOW$1, {
        relatedTarget: previous
      });

      if (previous) {
        $__default["default"](previous).trigger(hideEvent);
      }

      $__default["default"](this._element).trigger(showEvent);

      if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
        return;
      }

      if (selector) {
        target = document.querySelector(selector);
      }

      this._activate(this._element, listElement);

      var complete = function complete() {
        var hiddenEvent = $__default["default"].Event(EVENT_HIDDEN$1, {
          relatedTarget: _this._element
        });
        var shownEvent = $__default["default"].Event(EVENT_SHOWN$1, {
          relatedTarget: previous
        });
        $__default["default"](previous).trigger(hiddenEvent);
        $__default["default"](_this._element).trigger(shownEvent);
      };

      if (target) {
        this._activate(target, target.parentNode, complete);
      } else {
        complete();
      }
    };

    _proto.dispose = function dispose() {
      $__default["default"].removeData(this._element, DATA_KEY$1);
      this._element = null;
    } // Private
    ;

    _proto._activate = function _activate(element, container, callback) {
      var _this2 = this;

      var activeElements = container &amp;&amp; (container.nodeName === 'UL' || container.nodeName === 'OL') ? $__default["default"](container).find(SELECTOR_ACTIVE_UL) : $__default["default"](container).children(SELECTOR_ACTIVE);
      var active = activeElements[0];
      var isTransitioning = callback &amp;&amp; active &amp;&amp; $__default["default"](active).hasClass(CLASS_NAME_FADE$1);

      var complete = function complete() {
        return _this2._transitionComplete(element, active, callback);
      };

      if (active &amp;&amp; isTransitioning) {
        var transitionDuration = Util.getTransitionDurationFromElement(active);
        $__default["default"](active).removeClass(CLASS_NAME_SHOW$1).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
      } else {
        complete();
      }
    };

    _proto._transitionComplete = function _transitionComplete(element, active, callback) {
      if (active) {
        $__default["default"](active).removeClass(CLASS_NAME_ACTIVE);
        var dropdownChild = $__default["default"](active.parentNode).find(SELECTOR_DROPDOWN_ACTIVE_CHILD)[0];

        if (dropdownChild) {
          $__default["default"](dropdownChild).removeClass(CLASS_NAME_ACTIVE);
        }

        if (active.getAttribute('role') === 'tab') {
          active.setAttribute('aria-selected', false);
        }
      }

      $__default["default"](element).addClass(CLASS_NAME_ACTIVE);

      if (element.getAttribute('role') === 'tab') {
        element.setAttribute('aria-selected', true);
      }

      Util.reflow(element);

      if (element.classList.contains(CLASS_NAME_FADE$1)) {
        element.classList.add(CLASS_NAME_SHOW$1);
      }

      var parent = element.parentNode;

      if (parent &amp;&amp; parent.nodeName === 'LI') {
        parent = parent.parentNode;
      }

      if (parent &amp;&amp; $__default["default"](parent).hasClass(CLASS_NAME_DROPDOWN_MENU)) {
        var dropdownElement = $__default["default"](element).closest(SELECTOR_DROPDOWN)[0];

        if (dropdownElement) {
          var dropdownToggleList = [].slice.call(dropdownElement.querySelectorAll(SELECTOR_DROPDOWN_TOGGLE));
          $__default["default"](dropdownToggleList).addClass(CLASS_NAME_ACTIVE);
        }

        element.setAttribute('aria-expanded', true);
      }

      if (callback) {
        callback();
      }
    } // Static
    ;

    Tab._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var $this = $__default["default"](this);
        var data = $this.data(DATA_KEY$1);

        if (!data) {
          data = new Tab(this);
          $this.data(DATA_KEY$1, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config]();
        }
      });
    };

    _createClass(Tab, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION$1;
      }
    }]);

    return Tab;
  }();
  /**
   * Data API implementation
   */


  $__default["default"](document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
    event.preventDefault();

    Tab._jQueryInterface.call($__default["default"](this), 'show');
  });
  /**
   * jQuery
   */

  $__default["default"].fn[NAME$1] = Tab._jQueryInterface;
  $__default["default"].fn[NAME$1].Constructor = Tab;

  $__default["default"].fn[NAME$1].noConflict = function () {
    $__default["default"].fn[NAME$1] = JQUERY_NO_CONFLICT$1;
    return Tab._jQueryInterface;
  };

  /**
   * Constants
   */

  var NAME = 'toast';
  var VERSION = '4.6.2';
  var DATA_KEY = 'bs.toast';
  var EVENT_KEY = "." + DATA_KEY;
  var JQUERY_NO_CONFLICT = $__default["default"].fn[NAME];
  var CLASS_NAME_FADE = 'fade';
  var CLASS_NAME_HIDE = 'hide';
  var CLASS_NAME_SHOW = 'show';
  var CLASS_NAME_SHOWING = 'showing';
  var EVENT_CLICK_DISMISS = "click.dismiss" + EVENT_KEY;
  var EVENT_HIDE = "hide" + EVENT_KEY;
  var EVENT_HIDDEN = "hidden" + EVENT_KEY;
  var EVENT_SHOW = "show" + EVENT_KEY;
  var EVENT_SHOWN = "shown" + EVENT_KEY;
  var SELECTOR_DATA_DISMISS = '[data-dismiss="toast"]';
  var Default = {
    animation: true,
    autohide: true,
    delay: 500
  };
  var DefaultType = {
    animation: 'boolean',
    autohide: 'boolean',
    delay: 'number'
  };
  /**
   * Class definition
   */

  var Toast = /*#__PURE__*/function () {
    function Toast(element, config) {
      this._element = element;
      this._config = this._getConfig(config);
      this._timeout = null;

      this._setListeners();
    } // Getters


    var _proto = Toast.prototype;

    // Public
    _proto.show = function show() {
      var _this = this;

      var showEvent = $__default["default"].Event(EVENT_SHOW);
      $__default["default"](this._element).trigger(showEvent);

      if (showEvent.isDefaultPrevented()) {
        return;
      }

      this._clearTimeout();

      if (this._config.animation) {
        this._element.classList.add(CLASS_NAME_FADE);
      }

      var complete = function complete() {
        _this._element.classList.remove(CLASS_NAME_SHOWING);

        _this._element.classList.add(CLASS_NAME_SHOW);

        $__default["default"](_this._element).trigger(EVENT_SHOWN);

        if (_this._config.autohide) {
          _this._timeout = setTimeout(function () {
            _this.hide();
          }, _this._config.delay);
        }
      };

      this._element.classList.remove(CLASS_NAME_HIDE);

      Util.reflow(this._element);

      this._element.classList.add(CLASS_NAME_SHOWING);

      if (this._config.animation) {
        var transitionDuration = Util.getTransitionDurationFromElement(this._element);
        $__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
      } else {
        complete();
      }
    };

    _proto.hide = function hide() {
      if (!this._element.classList.contains(CLASS_NAME_SHOW)) {
        return;
      }

      var hideEvent = $__default["default"].Event(EVENT_HIDE);
      $__default["default"](this._element).trigger(hideEvent);

      if (hideEvent.isDefaultPrevented()) {
        return;
      }

      this._close();
    };

    _proto.dispose = function dispose() {
      this._clearTimeout();

      if (this._element.classList.contains(CLASS_NAME_SHOW)) {
        this._element.classList.remove(CLASS_NAME_SHOW);
      }

      $__default["default"](this._element).off(EVENT_CLICK_DISMISS);
      $__default["default"].removeData(this._element, DATA_KEY);
      this._element = null;
      this._config = null;
    } // Private
    ;

    _proto._getConfig = function _getConfig(config) {
      config = _extends({}, Default, $__default["default"](this._element).data(), typeof config === 'object' &amp;&amp; config ? config : {});
      Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
      return config;
    };

    _proto._setListeners = function _setListeners() {
      var _this2 = this;

      $__default["default"](this._element).on(EVENT_CLICK_DISMISS, SELECTOR_DATA_DISMISS, function () {
        return _this2.hide();
      });
    };

    _proto._close = function _close() {
      var _this3 = this;

      var complete = function complete() {
        _this3._element.classList.add(CLASS_NAME_HIDE);

        $__default["default"](_this3._element).trigger(EVENT_HIDDEN);
      };

      this._element.classList.remove(CLASS_NAME_SHOW);

      if (this._config.animation) {
        var transitionDuration = Util.getTransitionDurationFromElement(this._element);
        $__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
      } else {
        complete();
      }
    };

    _proto._clearTimeout = function _clearTimeout() {
      clearTimeout(this._timeout);
      this._timeout = null;
    } // Static
    ;

    Toast._jQueryInterface = function _jQueryInterface(config) {
      return this.each(function () {
        var $element = $__default["default"](this);
        var data = $element.data(DATA_KEY);

        var _config = typeof config === 'object' &amp;&amp; config;

        if (!data) {
          data = new Toast(this, _config);
          $element.data(DATA_KEY, data);
        }

        if (typeof config === 'string') {
          if (typeof data[config] === 'undefined') {
            throw new TypeError("No method named \"" + config + "\"");
          }

          data[config](this);
        }
      });
    };

    _createClass(Toast, null, [{
      key: "VERSION",
      get: function get() {
        return VERSION;
      }
    }, {
      key: "DefaultType",
      get: function get() {
        return DefaultType;
      }
    }, {
      key: "Default",
      get: function get() {
        return Default;
      }
    }]);

    return Toast;
  }();
  /**
   * jQuery
   */


  $__default["default"].fn[NAME] = Toast._jQueryInterface;
  $__default["default"].fn[NAME].Constructor = Toast;

  $__default["default"].fn[NAME].noConflict = function () {
    $__default["default"].fn[NAME] = JQUERY_NO_CONFLICT;
    return Toast._jQueryInterface;
  };

  exports.Alert = Alert;
  exports.Button = Button;
  exports.Carousel = Carousel;
  exports.Collapse = Collapse;
  exports.Dropdown = Dropdown;
  exports.Modal = Modal;
  exports.Popover = Popover;
  exports.Scrollspy = ScrollSpy;
  exports.Tab = Tab;
  exports.Toast = Toast;
  exports.Tooltip = Tooltip;
  exports.Util = Util;

  Object.defineProperty(exports, '__esModule', { value: true });

}));
// Generated by CoffeeScript 1.7.1
(function() {
  var $, cardFromNumber, cardFromType, cards, defaultFormat, formatBackCardNumber, formatBackExpiry, formatCardNumber, formatExpiry, formatForwardExpiry, formatForwardSlashAndSpace, hasTextSelected, luhnCheck, reFormatCVC, reFormatCardNumber, reFormatExpiry, reFormatNumeric, replaceFullWidthChars, restrictCVC, restrictCardNumber, restrictExpiry, restrictNumeric, safeVal, setCardType,
    __slice = [].slice,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i &lt; l; i++) { if (i in this &amp;&amp; this[i] === item) return i; } return -1; };

  $ = window.jQuery || window.Zepto || window.$;

  $.payment = {};

  $.payment.fn = {};

  $.fn.payment = function() {
    var args, method;
    method = arguments[0], args = 2 &lt;= arguments.length ? __slice.call(arguments, 1) : [];
    return $.payment.fn[method].apply(this, args);
  };

  defaultFormat = /(\d{1,4})/g;

  $.payment.cards = cards = [
    {
      type: 'maestro',
      patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
      format: defaultFormat,
      length: [12, 13, 14, 15, 16, 17, 18, 19],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'forbrugsforeningen',
      patterns: [600],
      format: defaultFormat,
      length: [16],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'dankort',
      patterns: [5019],
      format: defaultFormat,
      length: [16],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'visa',
      patterns: [4],
      format: defaultFormat,
      length: [13, 16],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'mastercard',
      patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27],
      format: defaultFormat,
      length: [16],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'amex',
      patterns: [34, 37],
      format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
      length: [15],
      cvcLength: [3, 4],
      luhn: true
    }, {
      type: 'dinersclub',
      patterns: [30, 36, 38, 39],
      format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/,
      length: [14],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'discover',
      patterns: [60, 64, 65, 622],
      format: defaultFormat,
      length: [16],
      cvcLength: [3],
      luhn: true
    }, {
      type: 'unionpay',
      patterns: [62, 88],
      format: defaultFormat,
      length: [16, 17, 18, 19],
      cvcLength: [3],
      luhn: false
    }, {
      type: 'jcb',
      patterns: [35],
      format: defaultFormat,
      length: [16],
      cvcLength: [3],
      luhn: true
    }
  ];

  cardFromNumber = function(num) {
    var card, p, pattern, _i, _j, _len, _len1, _ref;
    num = (num + '').replace(/\D/g, '');
    for (_i = 0, _len = cards.length; _i &lt; _len; _i++) {
      card = cards[_i];
      _ref = card.patterns;
      for (_j = 0, _len1 = _ref.length; _j &lt; _len1; _j++) {
        pattern = _ref[_j];
        p = pattern + '';
        if (num.substr(0, p.length) === p) {
          return card;
        }
      }
    }
  };

  cardFromType = function(type) {
    var card, _i, _len;
    for (_i = 0, _len = cards.length; _i &lt; _len; _i++) {
      card = cards[_i];
      if (card.type === type) {
        return card;
      }
    }
  };

  luhnCheck = function(num) {
    var digit, digits, odd, sum, _i, _len;
    odd = true;
    sum = 0;
    digits = (num + '').split('').reverse();
    for (_i = 0, _len = digits.length; _i &lt; _len; _i++) {
      digit = digits[_i];
      digit = parseInt(digit, 10);
      if ((odd = !odd)) {
        digit *= 2;
      }
      if (digit &gt; 9) {
        digit -= 9;
      }
      sum += digit;
    }
    return sum % 10 === 0;
  };

  hasTextSelected = function($target) {
    var _ref;
    if (($target.prop('selectionStart') != null) &amp;&amp; $target.prop('selectionStart') !== $target.prop('selectionEnd')) {
      return true;
    }
    if ((typeof document !== "undefined" &amp;&amp; document !== null ? (_ref = document.selection) != null ? _ref.createRange : void 0 : void 0) != null) {
      if (document.selection.createRange().text) {
        return true;
      }
    }
    return false;
  };

  safeVal = function(value, $target) {
    var currPair, cursor, digit, error, last, prevPair;
    try {
      cursor = $target.prop('selectionStart');
    } catch (_error) {
      error = _error;
      cursor = null;
    }
    last = $target.val();
    $target.val(value);
    if (cursor !== null &amp;&amp; $target.is(":focus")) {
      if (cursor === last.length) {
        cursor = value.length;
      }
      if (last !== value) {
        prevPair = last.slice(cursor - 1, +cursor + 1 || 9e9);
        currPair = value.slice(cursor - 1, +cursor + 1 || 9e9);
        digit = value[cursor];
        if (/\d/.test(digit) &amp;&amp; prevPair === ("" + digit + " ") &amp;&amp; currPair === (" " + digit)) {
          cursor = cursor + 1;
        }
      }
      $target.prop('selectionStart', cursor);
      return $target.prop('selectionEnd', cursor);
    }
  };

  replaceFullWidthChars = function(str) {
    var chars, chr, fullWidth, halfWidth, idx, value, _i, _len;
    if (str == null) {
      str = '';
    }
    fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19';
    halfWidth = '0123456789';
    value = '';
    chars = str.split('');
    for (_i = 0, _len = chars.length; _i &lt; _len; _i++) {
      chr = chars[_i];
      idx = fullWidth.indexOf(chr);
      if (idx &gt; -1) {
        chr = halfWidth[idx];
      }
      value += chr;
    }
    return value;
  };

  reFormatNumeric = function(e) {
    var $target;
    $target = $(e.currentTarget);
    return setTimeout(function() {
      var value;
      value = $target.val();
      value = replaceFullWidthChars(value);
      value = value.replace(/\D/g, '');
      return safeVal(value, $target);
    });
  };

  reFormatCardNumber = function(e) {
    var $target;
    $target = $(e.currentTarget);
    return setTimeout(function() {
      var value;
      value = $target.val();
      value = replaceFullWidthChars(value);
      value = $.payment.formatCardNumber(value);
      return safeVal(value, $target);
    });
  };

  formatCardNumber = function(e) {
    var $target, card, digit, length, re, upperLength, value;
    digit = String.fromCharCode(e.which);
    if (!/^\d+$/.test(digit)) {
      return;
    }
    $target = $(e.currentTarget);
    value = $target.val();
    card = cardFromNumber(value + digit);
    length = (value.replace(/\D/g, '') + digit).length;
    upperLength = 16;
    if (card) {
      upperLength = card.length[card.length.length - 1];
    }
    if (length &gt;= upperLength) {
      return;
    }
    if (($target.prop('selectionStart') != null) &amp;&amp; $target.prop('selectionStart') !== value.length) {
      return;
    }
    if (card &amp;&amp; card.type === 'amex') {
      re = /^(\d{4}|\d{4}\s\d{6})$/;
    } else {
      re = /(?:^|\s)(\d{4})$/;
    }
    if (re.test(value)) {
      e.preventDefault();
      return setTimeout(function() {
        return $target.val(value + ' ' + digit);
      });
    } else if (re.test(value + digit)) {
      e.preventDefault();
      return setTimeout(function() {
        return $target.val(value + digit + ' ');
      });
    }
  };

  formatBackCardNumber = function(e) {
    var $target, value;
    $target = $(e.currentTarget);
    value = $target.val();
    if (e.which !== 8) {
      return;
    }
    if (($target.prop('selectionStart') != null) &amp;&amp; $target.prop('selectionStart') !== value.length) {
      return;
    }
    if (/\d\s$/.test(value)) {
      e.preventDefault();
      return setTimeout(function() {
        return $target.val(value.replace(/\d\s$/, ''));
      });
    } else if (/\s\d?$/.test(value)) {
      e.preventDefault();
      return setTimeout(function() {
        return $target.val(value.replace(/\d$/, ''));
      });
    }
  };

  reFormatExpiry = function(e) {
    var $target;
    $target = $(e.currentTarget);
    return setTimeout(function() {
      var value;
      value = $target.val();
      value = replaceFullWidthChars(value);
      value = $.payment.formatExpiry(value);
      return safeVal(value, $target);
    });
  };

  formatExpiry = function(e) {
    var $target, digit, val;
    digit = String.fromCharCode(e.which);
    if (!/^\d+$/.test(digit)) {
      return;
    }
    $target = $(e.currentTarget);
    val = $target.val() + digit;
    if (/^\d$/.test(val) &amp;&amp; (val !== '0' &amp;&amp; val !== '1')) {
      e.preventDefault();
      return setTimeout(function() {
        return $target.val("0" + val + " / ");
      });
    } else if (/^\d\d$/.test(val)) {
      e.preventDefault();
      return setTimeout(function() {
        var m1, m2;
        m1 = parseInt(val[0], 10);
        m2 = parseInt(val[1], 10);
        if (m2 &gt; 2 &amp;&amp; m1 !== 0) {
          return $target.val("0" + m1 + " / " + m2);
        } else {
          return $target.val("" + val + " / ");
        }
      });
    }
  };

  formatForwardExpiry = function(e) {
    var $target, digit, val;
    digit = String.fromCharCode(e.which);
    if (!/^\d+$/.test(digit)) {
      return;
    }
    $target = $(e.currentTarget);
    val = $target.val();
    if (/^\d\d$/.test(val)) {
      return $target.val("" + val + " / ");
    }
  };

  formatForwardSlashAndSpace = function(e) {
    var $target, val, which;
    which = String.fromCharCode(e.which);
    if (!(which === '/' || which === ' ')) {
      return;
    }
    $target = $(e.currentTarget);
    val = $target.val();
    if (/^\d$/.test(val) &amp;&amp; val !== '0') {
      return $target.val("0" + val + " / ");
    }
  };

  formatBackExpiry = function(e) {
    var $target, value;
    $target = $(e.currentTarget);
    value = $target.val();
    if (e.which !== 8) {
      return;
    }
    if (($target.prop('selectionStart') != null) &amp;&amp; $target.prop('selectionStart') !== value.length) {
      return;
    }
    if (/\d\s\/\s$/.test(value)) {
      e.preventDefault();
      return setTimeout(function() {
        return $target.val(value.replace(/\d\s\/\s$/, ''));
      });
    }
  };

  reFormatCVC = function(e) {
    var $target;
    $target = $(e.currentTarget);
    return setTimeout(function() {
      var value;
      value = $target.val();
      value = replaceFullWidthChars(value);
      value = value.replace(/\D/g, '').slice(0, 4);
      return safeVal(value, $target);
    });
  };

  restrictNumeric = function(e) {
    var input;
    if (e.metaKey || e.ctrlKey) {
      return true;
    }
    if (e.which === 32) {
      return false;
    }
    if (e.which === 0) {
      return true;
    }
    if (e.which &lt; 33) {
      return true;
    }
    input = String.fromCharCode(e.which);
    return !!/[\d\s]/.test(input);
  };

  restrictCardNumber = function(e) {
    var $target, card, digit, value;
    $target = $(e.currentTarget);
    digit = String.fromCharCode(e.which);
    if (!/^\d+$/.test(digit)) {
      return;
    }
    if (hasTextSelected($target)) {
      return;
    }
    value = ($target.val() + digit).replace(/\D/g, '');
    card = cardFromNumber(value);
    if (card) {
      return value.length &lt;= card.length[card.length.length - 1];
    } else {
      return value.length &lt;= 16;
    }
  };

  restrictExpiry = function(e) {
    var $target, digit, value;
    $target = $(e.currentTarget);
    digit = String.fromCharCode(e.which);
    if (!/^\d+$/.test(digit)) {
      return;
    }
    if (hasTextSelected($target)) {
      return;
    }
    value = $target.val() + digit;
    value = value.replace(/\D/g, '');
    if (value.length &gt; 6) {
      return false;
    }
  };

  restrictCVC = function(e) {
    var $target, digit, val;
    $target = $(e.currentTarget);
    digit = String.fromCharCode(e.which);
    if (!/^\d+$/.test(digit)) {
      return;
    }
    if (hasTextSelected($target)) {
      return;
    }
    val = $target.val() + digit;
    return val.length &lt;= 4;
  };

  setCardType = function(e) {
    var $target, allTypes, card, cardType, val;
    $target = $(e.currentTarget);
    val = $target.val();
    cardType = $.payment.cardType(val) || 'unknown';
    if (!$target.hasClass(cardType)) {
      allTypes = (function() {
        var _i, _len, _results;
        _results = [];
        for (_i = 0, _len = cards.length; _i &lt; _len; _i++) {
          card = cards[_i];
          _results.push(card.type);
        }
        return _results;
      })();
      $target.removeClass('unknown');
      $target.removeClass(allTypes.join(' '));
      $target.addClass(cardType);
      $target.toggleClass('identified', cardType !== 'unknown');
      return $target.trigger('payment.cardType', cardType);
    }
  };

  $.payment.fn.formatCardCVC = function() {
    this.on('keypress', restrictNumeric);
    this.on('keypress', restrictCVC);
    this.on('paste', reFormatCVC);
    this.on('change', reFormatCVC);
    this.on('input', reFormatCVC);
    return this;
  };

  $.payment.fn.formatCardExpiry = function() {
    this.on('keypress', restrictNumeric);
    this.on('keypress', restrictExpiry);
    this.on('keypress', formatExpiry);
    this.on('keypress', formatForwardSlashAndSpace);
    this.on('keypress', formatForwardExpiry);
    this.on('keydown', formatBackExpiry);
    this.on('change', reFormatExpiry);
    this.on('input', reFormatExpiry);
    return this;
  };

  $.payment.fn.formatCardNumber = function() {
    this.on('keypress', restrictNumeric);
    this.on('keypress', restrictCardNumber);
    this.on('keypress', formatCardNumber);
    this.on('keydown', formatBackCardNumber);
    this.on('keyup', setCardType);
    this.on('paste', reFormatCardNumber);
    this.on('change', reFormatCardNumber);
    this.on('input', reFormatCardNumber);
    this.on('input', setCardType);
    return this;
  };

  $.payment.fn.restrictNumeric = function() {
    this.on('keypress', restrictNumeric);
    this.on('paste', reFormatNumeric);
    this.on('change', reFormatNumeric);
    this.on('input', reFormatNumeric);
    return this;
  };

  $.payment.fn.cardExpiryVal = function() {
    return $.payment.cardExpiryVal($(this).val());
  };

  $.payment.cardExpiryVal = function(value) {
    var month, prefix, year, _ref;
    _ref = value.split(/[\s\/]+/, 2), month = _ref[0], year = _ref[1];
    if ((year != null ? year.length : void 0) === 2 &amp;&amp; /^\d+$/.test(year)) {
      prefix = (new Date).getFullYear();
      prefix = prefix.toString().slice(0, 2);
      year = prefix + year;
    }
    month = parseInt(month, 10);
    year = parseInt(year, 10);
    return {
      month: month,
      year: year
    };
  };

  $.payment.validateCardNumber = function(num) {
    var card, _ref;
    num = (num + '').replace(/\s+|-/g, '');
    if (!/^\d+$/.test(num)) {
      return false;
    }
    card = cardFromNumber(num);
    if (!card) {
      return false;
    }
    return (_ref = num.length, __indexOf.call(card.length, _ref) &gt;= 0) &amp;&amp; (card.luhn === false || luhnCheck(num));
  };

  $.payment.validateCardExpiry = function(month, year) {
    var currentTime, expiry, _ref;
    if (typeof month === 'object' &amp;&amp; 'month' in month) {
      _ref = month, month = _ref.month, year = _ref.year;
    }
    if (!(month &amp;&amp; year)) {
      return false;
    }
    month = $.trim(month);
    year = $.trim(year);
    if (!/^\d+$/.test(month)) {
      return false;
    }
    if (!/^\d+$/.test(year)) {
      return false;
    }
    if (!((1 &lt;= month &amp;&amp; month &lt;= 12))) {
      return false;
    }
    if (year.length === 2) {
      if (year &lt; 70) {
        year = "20" + year;
      } else {
        year = "19" + year;
      }
    }
    if (year.length !== 4) {
      return false;
    }
    expiry = new Date(year, month);
    currentTime = new Date;
    expiry.setMonth(expiry.getMonth() - 1);
    expiry.setMonth(expiry.getMonth() + 1, 1);
    return expiry &gt; currentTime;
  };

  $.payment.validateCardCVC = function(cvc, type) {
    var card, _ref;
    cvc = $.trim(cvc);
    if (!/^\d+$/.test(cvc)) {
      return false;
    }
    card = cardFromType(type);
    if (card != null) {
      return _ref = cvc.length, __indexOf.call(card.cvcLength, _ref) &gt;= 0;
    } else {
      return cvc.length &gt;= 3 &amp;&amp; cvc.length &lt;= 4;
    }
  };

  $.payment.cardType = function(num) {
    var _ref;
    if (!num) {
      return null;
    }
    return ((_ref = cardFromNumber(num)) != null ? _ref.type : void 0) || null;
  };

  $.payment.formatCardNumber = function(num) {
    var card, groups, upperLength, _ref;
    num = num.replace(/\D/g, '');
    card = cardFromNumber(num);
    if (!card) {
      return num;
    }
    upperLength = card.length[card.length.length - 1];
    num = num.slice(0, upperLength);
    if (card.format.global) {
      return (_ref = num.match(card.format)) != null ? _ref.join(' ') : void 0;
    } else {
      groups = card.format.exec(num);
      if (groups == null) {
        return;
      }
      groups.shift();
      groups = $.grep(groups, function(n) {
        return n;
      });
      return groups.join(' ');
    }
  };

  $.payment.formatExpiry = function(expiry) {
    var mon, parts, sep, year;
    parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/);
    if (!parts) {
      return '';
    }
    mon = parts[1] || '';
    sep = parts[2] || '';
    year = parts[3] || '';
    if (year.length &gt; 0) {
      sep = ' / ';
    } else if (sep === ' /') {
      mon = mon.substring(0, 1);
      sep = '';
    } else if (mon.length === 2 || sep.length &gt; 0) {
      sep = ' / ';
    } else if (mon.length === 1 &amp;&amp; (mon !== '0' &amp;&amp; mon !== '1')) {
      mon = "0" + mon;
      sep = ' / ';
    }
    return mon + sep + year;
  };

}).call(this);
/*!
 * cleave.js - 1.6.0
 * https://github.com/nosir/cleave.js
 * Apache License Version 2.0
 *
 * Copyright (C) 2012-2020 Max Huang https://github.com/nosir/
 */
!function(e,t){"object"==typeof exports&amp;&amp;"object"==typeof module?module.exports=t():"function"==typeof define&amp;&amp;define.amd?define([],t):"object"==typeof exports?exports.Cleave=t():e.Cleave=t()}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var n=r[i]={exports:{},id:i,loaded:!1};return e[i].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){(function(t){"use strict";var i=function(e,t){var r=this,n=!1;if("string"==typeof e?(r.element=document.querySelector(e),n=document.querySelectorAll(e).length&gt;1):"undefined"!=typeof e.length&amp;&amp;e.length&gt;0?(r.element=e[0],n=e.length&gt;1):r.element=e,!r.element)throw new Error("[cleave.js] Please check the element");if(n)try{console.warn("[cleave.js] Multiple input fields matched, cleave.js will only take the first one.")}catch(a){}t.initValue=r.element.value,r.properties=i.DefaultProperties.assign({},t),r.init()};i.prototype={init:function(){var e=this,t=e.properties;return t.numeral||t.phone||t.creditCard||t.time||t.date||0!==t.blocksLength||t.prefix?(t.maxLength=i.Util.getMaxLength(t.blocks),e.isAndroid=i.Util.isAndroid(),e.lastInputValue="",e.isBackward="",e.onChangeListener=e.onChange.bind(e),e.onKeyDownListener=e.onKeyDown.bind(e),e.onFocusListener=e.onFocus.bind(e),e.onCutListener=e.onCut.bind(e),e.onCopyListener=e.onCopy.bind(e),e.initSwapHiddenInput(),e.element.addEventListener("input",e.onChangeListener),e.element.addEventListener("keydown",e.onKeyDownListener),e.element.addEventListener("focus",e.onFocusListener),e.element.addEventListener("cut",e.onCutListener),e.element.addEventListener("copy",e.onCopyListener),e.initPhoneFormatter(),e.initDateFormatter(),e.initTimeFormatter(),e.initNumeralFormatter(),void((t.initValue||t.prefix&amp;&amp;!t.noImmediatePrefix)&amp;&amp;e.onInput(t.initValue))):void e.onInput(t.initValue)},initSwapHiddenInput:function(){var e=this,t=e.properties;if(t.swapHiddenInput){var r=e.element.cloneNode(!0);e.element.parentNode.insertBefore(r,e.element),e.elementSwapHidden=e.element,e.elementSwapHidden.type="hidden",e.element=r,e.element.id=""}},initNumeralFormatter:function(){var e=this,t=e.properties;t.numeral&amp;&amp;(t.numeralFormatter=new i.NumeralFormatter(t.numeralDecimalMark,t.numeralIntegerScale,t.numeralDecimalScale,t.numeralThousandsGroupStyle,t.numeralPositiveOnly,t.stripLeadingZeroes,t.prefix,t.signBeforePrefix,t.tailPrefix,t.delimiter))},initTimeFormatter:function(){var e=this,t=e.properties;t.time&amp;&amp;(t.timeFormatter=new i.TimeFormatter(t.timePattern,t.timeFormat),t.blocks=t.timeFormatter.getBlocks(),t.blocksLength=t.blocks.length,t.maxLength=i.Util.getMaxLength(t.blocks))},initDateFormatter:function(){var e=this,t=e.properties;t.date&amp;&amp;(t.dateFormatter=new i.DateFormatter(t.datePattern,t.dateMin,t.dateMax),t.blocks=t.dateFormatter.getBlocks(),t.blocksLength=t.blocks.length,t.maxLength=i.Util.getMaxLength(t.blocks))},initPhoneFormatter:function(){var e=this,t=e.properties;if(t.phone)try{t.phoneFormatter=new i.PhoneFormatter(new t.root.Cleave.AsYouTypeFormatter(t.phoneRegionCode),t.delimiter)}catch(r){throw new Error("[cleave.js] Please include phone-type-formatter.{country}.js lib")}},onKeyDown:function(e){var t=this,r=e.which||e.keyCode;t.lastInputValue=t.element.value,t.isBackward=8===r},onChange:function(e){var t=this,r=t.properties,n=i.Util;t.isBackward=t.isBackward||"deleteContentBackward"===e.inputType;var a=n.getPostDelimiter(t.lastInputValue,r.delimiter,r.delimiters);t.isBackward&amp;&amp;a?r.postDelimiterBackspace=a:r.postDelimiterBackspace=!1,this.onInput(this.element.value)},onFocus:function(){var e=this,t=e.properties;e.lastInputValue=e.element.value,t.prefix&amp;&amp;t.noImmediatePrefix&amp;&amp;!e.element.value&amp;&amp;this.onInput(t.prefix),i.Util.fixPrefixCursor(e.element,t.prefix,t.delimiter,t.delimiters)},onCut:function(e){i.Util.checkFullSelection(this.element.value)&amp;&amp;(this.copyClipboardData(e),this.onInput(""))},onCopy:function(e){i.Util.checkFullSelection(this.element.value)&amp;&amp;this.copyClipboardData(e)},copyClipboardData:function(e){var t=this,r=t.properties,n=i.Util,a=t.element.value,o="";o=r.copyDelimiter?a:n.stripDelimiters(a,r.delimiter,r.delimiters);try{e.clipboardData?e.clipboardData.setData("Text",o):window.clipboardData.setData("Text",o),e.preventDefault()}catch(l){}},onInput:function(e){var t=this,r=t.properties,n=i.Util,a=n.getPostDelimiter(e,r.delimiter,r.delimiters);return r.numeral||!r.postDelimiterBackspace||a||(e=n.headStr(e,e.length-r.postDelimiterBackspace.length)),r.phone?(!r.prefix||r.noImmediatePrefix&amp;&amp;!e.length?r.result=r.phoneFormatter.format(e):r.result=r.prefix+r.phoneFormatter.format(e).slice(r.prefix.length),void t.updateValueState()):r.numeral?(r.prefix&amp;&amp;r.noImmediatePrefix&amp;&amp;0===e.length?r.result="":r.result=r.numeralFormatter.format(e),void t.updateValueState()):(r.date&amp;&amp;(e=r.dateFormatter.getValidatedDate(e)),r.time&amp;&amp;(e=r.timeFormatter.getValidatedTime(e)),e=n.stripDelimiters(e,r.delimiter,r.delimiters),e=n.getPrefixStrippedValue(e,r.prefix,r.prefixLength,r.result,r.delimiter,r.delimiters,r.noImmediatePrefix,r.tailPrefix,r.signBeforePrefix),e=r.numericOnly?n.strip(e,/[^\d]/g):e,e=r.uppercase?e.toUpperCase():e,e=r.lowercase?e.toLowerCase():e,r.prefix&amp;&amp;(r.tailPrefix?e+=r.prefix:e=r.prefix+e,0===r.blocksLength)?(r.result=e,void t.updateValueState()):(r.creditCard&amp;&amp;t.updateCreditCardPropsByValue(e),e=n.headStr(e,r.maxLength),r.result=n.getFormattedValue(e,r.blocks,r.blocksLength,r.delimiter,r.delimiters,r.delimiterLazyShow),void t.updateValueState()))},updateCreditCardPropsByValue:function(e){var t,r=this,n=r.properties,a=i.Util;a.headStr(n.result,4)!==a.headStr(e,4)&amp;&amp;(t=i.CreditCardDetector.getInfo(e,n.creditCardStrictMode),n.blocks=t.blocks,n.blocksLength=n.blocks.length,n.maxLength=a.getMaxLength(n.blocks),n.creditCardType!==t.type&amp;&amp;(n.creditCardType=t.type,n.onCreditCardTypeChanged.call(r,n.creditCardType)))},updateValueState:function(){var e=this,t=i.Util,r=e.properties;if(e.element){var n=e.element.selectionEnd,a=e.element.value,o=r.result;if(n=t.getNextCursorPosition(n,a,o,r.delimiter,r.delimiters),e.isAndroid)return void window.setTimeout(function(){e.element.value=o,t.setSelection(e.element,n,r.document,!1),e.callOnValueChanged()},1);e.element.value=o,r.swapHiddenInput&amp;&amp;(e.elementSwapHidden.value=e.getRawValue()),t.setSelection(e.element,n,r.document,!1),e.callOnValueChanged()}},callOnValueChanged:function(){var e=this,t=e.properties;t.onValueChanged.call(e,{target:{name:e.element.name,value:t.result,rawValue:e.getRawValue()}})},setPhoneRegionCode:function(e){var t=this,r=t.properties;r.phoneRegionCode=e,t.initPhoneFormatter(),t.onChange()},setRawValue:function(e){var t=this,r=t.properties;e=void 0!==e&amp;&amp;null!==e?e.toString():"",r.numeral&amp;&amp;(e=e.replace(".",r.numeralDecimalMark)),r.postDelimiterBackspace=!1,t.element.value=e,t.onInput(e)},getRawValue:function(){var e=this,t=e.properties,r=i.Util,n=e.element.value;return t.rawValueTrimPrefix&amp;&amp;(n=r.getPrefixStrippedValue(n,t.prefix,t.prefixLength,t.result,t.delimiter,t.delimiters,t.noImmediatePrefix,t.tailPrefix,t.signBeforePrefix)),n=t.numeral?t.numeralFormatter.getRawValue(n):r.stripDelimiters(n,t.delimiter,t.delimiters)},getISOFormatDate:function(){var e=this,t=e.properties;return t.date?t.dateFormatter.getISOFormatDate():""},getISOFormatTime:function(){var e=this,t=e.properties;return t.time?t.timeFormatter.getISOFormatTime():""},getFormattedValue:function(){return this.element.value},destroy:function(){var e=this;e.element.removeEventListener("input",e.onChangeListener),e.element.removeEventListener("keydown",e.onKeyDownListener),e.element.removeEventListener("focus",e.onFocusListener),e.element.removeEventListener("cut",e.onCutListener),e.element.removeEventListener("copy",e.onCopyListener)},toString:function(){return"[Cleave Object]"}},i.NumeralFormatter=r(1),i.DateFormatter=r(2),i.TimeFormatter=r(3),i.PhoneFormatter=r(4),i.CreditCardDetector=r(5),i.Util=r(6),i.DefaultProperties=r(7),("object"==typeof t&amp;&amp;t?t:window).Cleave=i,e.exports=i}).call(t,function(){return this}())},function(e,t){"use strict";var r=function(e,t,i,n,a,o,l,s,c,u){var d=this;d.numeralDecimalMark=e||".",d.numeralIntegerScale=t&gt;0?t:0,d.numeralDecimalScale=i&gt;=0?i:2,d.numeralThousandsGroupStyle=n||r.groupStyle.thousand,d.numeralPositiveOnly=!!a,d.stripLeadingZeroes=o!==!1,d.prefix=l||""===l?l:"",d.signBeforePrefix=!!s,d.tailPrefix=!!c,d.delimiter=u||""===u?u:",",d.delimiterRE=u?new RegExp("\\"+u,"g"):""};r.groupStyle={thousand:"thousand",lakh:"lakh",wan:"wan",none:"none"},r.prototype={getRawValue:function(e){return e.replace(this.delimiterRE,"").replace(this.numeralDecimalMark,".")},format:function(e){var t,i,n,a,o=this,l="";switch(e=e.replace(/[A-Za-z]/g,"").replace(o.numeralDecimalMark,"M").replace(/[^\dM-]/g,"").replace(/^\-/,"N").replace(/\-/g,"").replace("N",o.numeralPositiveOnly?"":"-").replace("M",o.numeralDecimalMark),o.stripLeadingZeroes&amp;&amp;(e=e.replace(/^(-)?0+(?=\d)/,"$1")),i="-"===e.slice(0,1)?"-":"",n="undefined"!=typeof o.prefix?o.signBeforePrefix?i+o.prefix:o.prefix+i:i,a=e,e.indexOf(o.numeralDecimalMark)&gt;=0&amp;&amp;(t=e.split(o.numeralDecimalMark),a=t[0],l=o.numeralDecimalMark+t[1].slice(0,o.numeralDecimalScale)),"-"===i&amp;&amp;(a=a.slice(1)),o.numeralIntegerScale&gt;0&amp;&amp;(a=a.slice(0,o.numeralIntegerScale)),o.numeralThousandsGroupStyle){case r.groupStyle.lakh:a=a.replace(/(\d)(?=(\d\d)+\d$)/g,"$1"+o.delimiter);break;case r.groupStyle.wan:a=a.replace(/(\d)(?=(\d{4})+$)/g,"$1"+o.delimiter);break;case r.groupStyle.thousand:a=a.replace(/(\d)(?=(\d{3})+$)/g,"$1"+o.delimiter)}return o.tailPrefix?i+a.toString()+(o.numeralDecimalScale&gt;0?l.toString():"")+o.prefix:n+a.toString()+(o.numeralDecimalScale&gt;0?l.toString():"")}},e.exports=r},function(e,t){"use strict";var r=function(e,t,r){var i=this;i.date=[],i.blocks=[],i.datePattern=e,i.dateMin=t.split("-").reverse().map(function(e){return parseInt(e,10)}),2===i.dateMin.length&amp;&amp;i.dateMin.unshift(0),i.dateMax=r.split("-").reverse().map(function(e){return parseInt(e,10)}),2===i.dateMax.length&amp;&amp;i.dateMax.unshift(0),i.initBlocks()};r.prototype={initBlocks:function(){var e=this;e.datePattern.forEach(function(t){"Y"===t?e.blocks.push(4):e.blocks.push(2)})},getISOFormatDate:function(){var e=this,t=e.date;return t[2]?t[2]+"-"+e.addLeadingZero(t[1])+"-"+e.addLeadingZero(t[0]):""},getBlocks:function(){return this.blocks},getValidatedDate:function(e){var t=this,r="";return e=e.replace(/[^\d]/g,""),t.blocks.forEach(function(i,n){if(e.length&gt;0){var a=e.slice(0,i),o=a.slice(0,1),l=e.slice(i);switch(t.datePattern[n]){case"d":"00"===a?a="01":parseInt(o,10)&gt;3?a="0"+o:parseInt(a,10)&gt;31&amp;&amp;(a="31");break;case"m":"00"===a?a="01":parseInt(o,10)&gt;1?a="0"+o:parseInt(a,10)&gt;12&amp;&amp;(a="12")}r+=a,e=l}}),this.getFixedDateString(r)},getFixedDateString:function(e){var t,r,i,n=this,a=n.datePattern,o=[],l=0,s=0,c=0,u=0,d=0,m=0,p=!1;4===e.length&amp;&amp;"y"!==a[0].toLowerCase()&amp;&amp;"y"!==a[1].toLowerCase()&amp;&amp;(u="d"===a[0]?0:2,d=2-u,t=parseInt(e.slice(u,u+2),10),r=parseInt(e.slice(d,d+2),10),o=this.getFixedDate(t,r,0)),8===e.length&amp;&amp;(a.forEach(function(e,t){switch(e){case"d":l=t;break;case"m":s=t;break;default:c=t}}),m=2*c,u=l&lt;=c?2*l:2*l+2,d=s&lt;=c?2*s:2*s+2,t=parseInt(e.slice(u,u+2),10),r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+4),10),p=4===e.slice(m,m+4).length,o=this.getFixedDate(t,r,i)),4!==e.length||"y"!==a[0]&amp;&amp;"y"!==a[1]||(d="m"===a[0]?0:2,m=2-d,r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+2),10),p=2===e.slice(m,m+2).length,o=[0,r,i]),6!==e.length||"Y"!==a[0]&amp;&amp;"Y"!==a[1]||(d="m"===a[0]?0:4,m=2-.5*d,r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+4),10),p=4===e.slice(m,m+4).length,o=[0,r,i]),o=n.getRangeFixedDate(o),n.date=o;var h=0===o.length?e:a.reduce(function(e,t){switch(t){case"d":return e+(0===o[0]?"":n.addLeadingZero(o[0]));case"m":return e+(0===o[1]?"":n.addLeadingZero(o[1]));case"y":return e+(p?n.addLeadingZeroForYear(o[2],!1):"");case"Y":return e+(p?n.addLeadingZeroForYear(o[2],!0):"")}},"");return h},getRangeFixedDate:function(e){var t=this,r=t.datePattern,i=t.dateMin||[],n=t.dateMax||[];return!e.length||i.length&lt;3&amp;&amp;n.length&lt;3?e:r.find(function(e){return"y"===e.toLowerCase()})&amp;&amp;0===e[2]?e:n.length&amp;&amp;(n[2]&lt;e[2]||n[2]===e[2]&amp;&amp;(n[1]&lt;e[1]||n[1]===e[1]&amp;&amp;n[0]&lt;e[0]))?n:i.length&amp;&amp;(i[2]&gt;e[2]||i[2]===e[2]&amp;&amp;(i[1]&gt;e[1]||i[1]===e[1]&amp;&amp;i[0]&gt;e[0]))?i:e},getFixedDate:function(e,t,r){return e=Math.min(e,31),t=Math.min(t,12),r=parseInt(r||0,10),(t&lt;7&amp;&amp;t%2===0||t&gt;8&amp;&amp;t%2===1)&amp;&amp;(e=Math.min(e,2===t?this.isLeapYear(r)?29:28:30)),[e,t,r]},isLeapYear:function(e){return e%4===0&amp;&amp;e%100!==0||e%400===0},addLeadingZero:function(e){return(e&lt;10?"0":"")+e},addLeadingZeroForYear:function(e,t){return t?(e&lt;10?"000":e&lt;100?"00":e&lt;1e3?"0":"")+e:(e&lt;10?"0":"")+e}},e.exports=r},function(e,t){"use strict";var r=function(e,t){var r=this;r.time=[],r.blocks=[],r.timePattern=e,r.timeFormat=t,r.initBlocks()};r.prototype={initBlocks:function(){var e=this;e.timePattern.forEach(function(){e.blocks.push(2)})},getISOFormatTime:function(){var e=this,t=e.time;return t[2]?e.addLeadingZero(t[0])+":"+e.addLeadingZero(t[1])+":"+e.addLeadingZero(t[2]):""},getBlocks:function(){return this.blocks},getTimeFormatOptions:function(){var e=this;return"12"===String(e.timeFormat)?{maxHourFirstDigit:1,maxHours:12,maxMinutesFirstDigit:5,maxMinutes:60}:{maxHourFirstDigit:2,maxHours:23,maxMinutesFirstDigit:5,maxMinutes:60}},getValidatedTime:function(e){var t=this,r="";e=e.replace(/[^\d]/g,"");var i=t.getTimeFormatOptions();return t.blocks.forEach(function(n,a){if(e.length&gt;0){var o=e.slice(0,n),l=o.slice(0,1),s=e.slice(n);switch(t.timePattern[a]){case"h":parseInt(l,10)&gt;i.maxHourFirstDigit?o="0"+l:parseInt(o,10)&gt;i.maxHours&amp;&amp;(o=i.maxHours+"");break;case"m":case"s":parseInt(l,10)&gt;i.maxMinutesFirstDigit?o="0"+l:parseInt(o,10)&gt;i.maxMinutes&amp;&amp;(o=i.maxMinutes+"")}r+=o,e=s}}),this.getFixedTimeString(r)},getFixedTimeString:function(e){var t,r,i,n=this,a=n.timePattern,o=[],l=0,s=0,c=0,u=0,d=0,m=0;return 6===e.length&amp;&amp;(a.forEach(function(e,t){switch(e){case"s":l=2*t;break;case"m":s=2*t;break;case"h":c=2*t}}),m=c,d=s,u=l,t=parseInt(e.slice(u,u+2),10),r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+2),10),o=this.getFixedTime(i,r,t)),4===e.length&amp;&amp;n.timePattern.indexOf("s")&lt;0&amp;&amp;(a.forEach(function(e,t){switch(e){case"m":s=2*t;break;case"h":c=2*t}}),m=c,d=s,t=0,r=parseInt(e.slice(d,d+2),10),i=parseInt(e.slice(m,m+2),10),o=this.getFixedTime(i,r,t)),n.time=o,0===o.length?e:a.reduce(function(e,t){switch(t){case"s":return e+n.addLeadingZero(o[2]);case"m":return e+n.addLeadingZero(o[1]);case"h":return e+n.addLeadingZero(o[0])}},"")},getFixedTime:function(e,t,r){return r=Math.min(parseInt(r||0,10),60),t=Math.min(t,60),e=Math.min(e,60),[e,t,r]},addLeadingZero:function(e){return(e&lt;10?"0":"")+e}},e.exports=r},function(e,t){"use strict";var r=function(e,t){var r=this;r.delimiter=t||""===t?t:" ",r.delimiterRE=t?new RegExp("\\"+t,"g"):"",r.formatter=e};r.prototype={setFormatter:function(e){this.formatter=e},format:function(e){var t=this;t.formatter.clear(),e=e.replace(/[^\d+]/g,""),e=e.replace(/^\+/,"B").replace(/\+/g,"").replace("B","+"),e=e.replace(t.delimiterRE,"");for(var r,i="",n=!1,a=0,o=e.length;a&lt;o;a++)r=t.formatter.inputDigit(e.charAt(a)),/[\s()-]/g.test(r)?(i=r,n=!0):n||(i=r);return i=i.replace(/[()]/g,""),i=i.replace(/[\s-]/g,t.delimiter)}},e.exports=r},function(e,t){"use strict";var r={blocks:{uatp:[4,5,6],amex:[4,6,5],diners:[4,6,4],discover:[4,4,4,4],mastercard:[4,4,4,4],dankort:[4,4,4,4],instapayment:[4,4,4,4],jcb15:[4,6,5],jcb:[4,4,4,4],maestro:[4,4,4,4],visa:[4,4,4,4],mir:[4,4,4,4],unionPay:[4,4,4,4],general:[4,4,4,4]},re:{uatp:/^(?!1800)1\d{0,14}/,amex:/^3[47]\d{0,13}/,discover:/^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/,diners:/^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,mastercard:/^(5[1-5]\d{0,2}|22[2-9]\d{0,1}|2[3-7]\d{0,2})\d{0,12}/,dankort:/^(5019|4175|4571)\d{0,12}/,instapayment:/^63[7-9]\d{0,13}/,jcb15:/^(?:2131|1800)\d{0,11}/,jcb:/^(?:35\d{0,2})\d{0,12}/,maestro:/^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/,mir:/^220[0-4]\d{0,12}/,visa:/^4\d{0,15}/,unionPay:/^(62|81)\d{0,14}/},getStrictBlocks:function(e){var t=e.reduce(function(e,t){return e+t},0);return e.concat(19-t)},getInfo:function(e,t){var i=r.blocks,n=r.re;t=!!t;for(var a in n)if(n[a].test(e)){var o=i[a];return{type:a,blocks:t?this.getStrictBlocks(o):o}}return{type:"unknown",blocks:t?this.getStrictBlocks(i.general):i.general}}};e.exports=r},function(e,t){"use strict";var r={noop:function(){},strip:function(e,t){return e.replace(t,"")},getPostDelimiter:function(e,t,r){if(0===r.length)return e.slice(-t.length)===t?t:"";var i="";return r.forEach(function(t){e.slice(-t.length)===t&amp;&amp;(i=t)}),i},getDelimiterREByDelimiter:function(e){return new RegExp(e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"),"g")},getNextCursorPosition:function(e,t,r,i,n){return t.length===e?r.length:e+this.getPositionOffset(e,t,r,i,n)},getPositionOffset:function(e,t,r,i,n){var a,o,l;return a=this.stripDelimiters(t.slice(0,e),i,n),o=this.stripDelimiters(r.slice(0,e),i,n),l=a.length-o.length,0!==l?l/Math.abs(l):0},stripDelimiters:function(e,t,r){var i=this;if(0===r.length){var n=t?i.getDelimiterREByDelimiter(t):"";return e.replace(n,"")}return r.forEach(function(t){t.split("").forEach(function(t){e=e.replace(i.getDelimiterREByDelimiter(t),"")})}),e},headStr:function(e,t){return e.slice(0,t)},getMaxLength:function(e){return e.reduce(function(e,t){return e+t},0)},getPrefixStrippedValue:function(e,t,r,i,n,a,o,l,s){if(0===r)return e;if(e===t&amp;&amp;""!==e)return"";if(s&amp;&amp;"-"==e.slice(0,1)){var c="-"==i.slice(0,1)?i.slice(1):i;return"-"+this.getPrefixStrippedValue(e.slice(1),t,r,c,n,a,o,l,s)}if(i.slice(0,r)!==t&amp;&amp;!l)return o&amp;&amp;!i&amp;&amp;e?e:"";if(i.slice(-r)!==t&amp;&amp;l)return o&amp;&amp;!i&amp;&amp;e?e:"";var u=this.stripDelimiters(i,n,a);return e.slice(0,r)===t||l?e.slice(-r)!==t&amp;&amp;l?u.slice(0,-r-1):l?e.slice(0,-r):e.slice(r):u.slice(r)},getFirstDiffIndex:function(e,t){for(var r=0;e.charAt(r)===t.charAt(r);)if(""===e.charAt(r++))return-1;return r},getFormattedValue:function(e,t,r,i,n,a){var o="",l=n.length&gt;0,s="";return 0===r?e:(t.forEach(function(t,c){if(e.length&gt;0){var u=e.slice(0,t),d=e.slice(t);s=l?n[a?c-1:c]||s:i,a?(c&gt;0&amp;&amp;(o+=s),o+=u):(o+=u,u.length===t&amp;&amp;c&lt;r-1&amp;&amp;(o+=s)),e=d}}),o)},fixPrefixCursor:function(e,t,r,i){if(e){var n=e.value,a=r||i[0]||" ";if(e.setSelectionRange&amp;&amp;t&amp;&amp;!(t.length+a.length&lt;=n.length)){var o=2*n.length;setTimeout(function(){e.setSelectionRange(o,o)},1)}}},checkFullSelection:function(e){try{var t=window.getSelection()||document.getSelection()||{};return t.toString().length===e.length}catch(r){}return!1},setSelection:function(e,t,r){if(e===this.getActiveElement(r)&amp;&amp;!(e&amp;&amp;e.value.length&lt;=t))if(e.createTextRange){var i=e.createTextRange();i.move("character",t),i.select()}else try{e.setSelectionRange(t,t)}catch(n){console.warn("The input element type does not support selection")}},getActiveElement:function(e){var t=e.activeElement;return t&amp;&amp;t.shadowRoot?this.getActiveElement(t.shadowRoot):t},isAndroid:function(){return navigator&amp;&amp;/android/i.test(navigator.userAgent)},isAndroidBackspaceKeydown:function(e,t){return!!(this.isAndroid()&amp;&amp;e&amp;&amp;t)&amp;&amp;t===e.slice(0,-1)}};e.exports=r},function(e,t){(function(t){"use strict";var r={assign:function(e,r){return e=e||{},r=r||{},e.creditCard=!!r.creditCard,e.creditCardStrictMode=!!r.creditCardStrictMode,e.creditCardType="",e.onCreditCardTypeChanged=r.onCreditCardTypeChanged||function(){},e.phone=!!r.phone,e.phoneRegionCode=r.phoneRegionCode||"AU",e.phoneFormatter={},e.time=!!r.time,e.timePattern=r.timePattern||["h","m","s"],e.timeFormat=r.timeFormat||"24",e.timeFormatter={},e.date=!!r.date,e.datePattern=r.datePattern||["d","m","Y"],e.dateMin=r.dateMin||"",e.dateMax=r.dateMax||"",e.dateFormatter={},e.numeral=!!r.numeral,e.numeralIntegerScale=r.numeralIntegerScale&gt;0?r.numeralIntegerScale:0,e.numeralDecimalScale=r.numeralDecimalScale&gt;=0?r.numeralDecimalScale:2,e.numeralDecimalMark=r.numeralDecimalMark||".",e.numeralThousandsGroupStyle=r.numeralThousandsGroupStyle||"thousand",e.numeralPositiveOnly=!!r.numeralPositiveOnly,e.stripLeadingZeroes=r.stripLeadingZeroes!==!1,e.signBeforePrefix=!!r.signBeforePrefix,e.tailPrefix=!!r.tailPrefix,e.swapHiddenInput=!!r.swapHiddenInput,e.numericOnly=e.creditCard||e.date||!!r.numericOnly,e.uppercase=!!r.uppercase,e.lowercase=!!r.lowercase,e.prefix=e.creditCard||e.date?"":r.prefix||"",e.noImmediatePrefix=!!r.noImmediatePrefix,e.prefixLength=e.prefix.length,e.rawValueTrimPrefix=!!r.rawValueTrimPrefix,e.copyDelimiter=!!r.copyDelimiter,e.initValue=void 0!==r.initValue&amp;&amp;null!==r.initValue?r.initValue.toString():"",e.delimiter=r.delimiter||""===r.delimiter?r.delimiter:r.date?"/":r.time?":":r.numeral?",":(r.phone," "),e.delimiterLength=e.delimiter.length,e.delimiterLazyShow=!!r.delimiterLazyShow,e.delimiters=r.delimiters||[],e.blocks=r.blocks||[],e.blocksLength=e.blocks.length,e.root="object"==typeof t&amp;&amp;t?t:window,e.document=r.document||e.root.document,e.maxLength=0,e.backspace=!1,e.result="",e.onValueChanged=r.onValueChanged||function(){},e}};e.exports=r}).call(t,function(){return this}())}])});
/*!
 * jsUri
 * https://github.com/derek-watson/jsUri
 *
 * Copyright 2013, Derek Watson
 * Released under the MIT license.
 *
 * Includes parseUri regular expressions
 * http://blog.stevenlevithan.com/archives/parseuri
 * Copyright 2007, Steven Levithan
 * Released under the MIT license.
 */

 /*globals define, module */

(function(global) {

  var re = {
    starts_with_slashes: /^\/+/,
    ends_with_slashes: /\/+$/,
    pluses: /\+/g,
    query_separator: /[&amp;;]/,
    uri_parser: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*)(?::([^:@]*))?)?@)?(\[[0-9a-fA-F:.]+\]|[^:\/?#]*)(?::(\d+|(?=:)))?(:)?)((((?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  };

  /**
   * Define forEach for older js environments
   * @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach#Compatibility
   */
  if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(callback, thisArg) {
      var T, k;

      if (this == null) {
        throw new TypeError(' this is null or not defined');
      }

      var O = Object(this);
      var len = O.length &gt;&gt;&gt; 0;

      if (typeof callback !== "function") {
        throw new TypeError(callback + ' is not a function');
      }

      if (arguments.length &gt; 1) {
        T = thisArg;
      }

      k = 0;

      while (k &lt; len) {
        var kValue;
        if (k in O) {
          kValue = O[k];
          callback.call(T, kValue, k, O);
        }
        k++;
      }
    };
  }

  /**
   * unescape a query param value
   * @param  {string} s encoded value
   * @return {string}   decoded value
   */
  function decode(s) {
    if (s) {
        s = s.toString().replace(re.pluses, '%20');
        s = decodeURIComponent(s);
    }
    return s;
  }

  /**
   * Breaks a uri string down into its individual parts
   * @param  {string} str uri
   * @return {object}     parts
   */
  function parseUri(str) {
    var parser = re.uri_parser;
    var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"];
    var m = parser.exec(str || '');
    var parts = {};

    parserKeys.forEach(function(key, i) {
      parts[key] = m[i] || '';
    });

    return parts;
  }

  /**
   * Breaks a query string down into an array of key/value pairs
   * @param  {string} str query
   * @return {array}      array of arrays (key/value pairs)
   */
  function parseQuery(str) {
    var i, ps, p, n, k, v, l;
    var pairs = [];

    if (typeof(str) === 'undefined' || str === null || str === '') {
      return pairs;
    }

    if (str.indexOf('?') === 0) {
      str = str.substring(1);
    }

    ps = str.toString().split(re.query_separator);

    for (i = 0, l = ps.length; i &lt; l; i++) {
      p = ps[i];
      n = p.indexOf('=');

      if (n !== 0) {
        k = decode(p.substring(0, n));
        v = decode(p.substring(n + 1));
        pairs.push(n === -1 ? [p, null] : [k, v]);
      }

    }
    return pairs;
  }

  /**
   * Creates a new Uri object
   * @constructor
   * @param {string} str
   */
  function Uri(str) {
    this.uriParts = parseUri(str);
    this.queryPairs = parseQuery(this.uriParts.query);
    this.hasAuthorityPrefixUserPref = null;
  }

  /**
   * Define getter/setter methods
   */
  ['protocol', 'userInfo', 'host', 'port', 'path', 'anchor'].forEach(function(key) {
    Uri.prototype[key] = function(val) {
      if (typeof val !== 'undefined') {
        this.uriParts[key] = val;
      }
      return this.uriParts[key];
    };
  });

  /**
   * if there is no protocol, the leading // can be enabled or disabled
   * @param  {Boolean}  val
   * @return {Boolean}
   */
  Uri.prototype.hasAuthorityPrefix = function(val) {
    if (typeof val !== 'undefined') {
      this.hasAuthorityPrefixUserPref = val;
    }

    if (this.hasAuthorityPrefixUserPref === null) {
      return (this.uriParts.source.indexOf('//') !== -1);
    } else {
      return this.hasAuthorityPrefixUserPref;
    }
  };

  Uri.prototype.isColonUri = function (val) {
    if (typeof val !== 'undefined') {
      this.uriParts.isColonUri = !!val;
    } else {
      return !!this.uriParts.isColonUri;
    }
  };

  /**
   * Serializes the internal state of the query pairs
   * @param  {string} [val]   set a new query string
   * @return {string}         query string
   */
  Uri.prototype.query = function(val) {
    var s = '', i, param, l;

    if (typeof val !== 'undefined') {
      this.queryPairs = parseQuery(val);
    }

    for (i = 0, l = this.queryPairs.length; i &lt; l; i++) {
      param = this.queryPairs[i];
      if (s.length &gt; 0) {
        s += '&amp;';
      }
      if (param[1] === null) {
        s += param[0];
      } else {
        s += param[0];
        s += '=';
        if (typeof param[1] !== 'undefined') {
          s += encodeURIComponent(param[1]);
        }
      }
    }
    return s.length &gt; 0 ? '?' + s : s;
  };

  /**
   * returns the first query param value found for the key
   * @param  {string} key query key
   * @return {string}     first value found for key
   */
  Uri.prototype.getQueryParamValue = function (key) {
    var param, i, l;
    for (i = 0, l = this.queryPairs.length; i &lt; l; i++) {
      param = this.queryPairs[i];
      if (key === param[0]) {
        return param[1];
      }
    }
  };

  /**
   * returns an array of query param values for the key
   * @param  {string} key query key
   * @return {array}      array of values
   */
  Uri.prototype.getQueryParamValues = function (key) {
    var arr = [], i, param, l;
    for (i = 0, l = this.queryPairs.length; i &lt; l; i++) {
      param = this.queryPairs[i];
      if (key === param[0]) {
        arr.push(param[1]);
      }
    }
    return arr;
  };

  /**
   * removes query parameters
   * @param  {string} key     remove values for key
   * @param  {val}    [val]   remove a specific value, otherwise removes all
   * @return {Uri}            returns self for fluent chaining
   */
  Uri.prototype.deleteQueryParam = function (key, val) {
    var arr = [], i, param, keyMatchesFilter, valMatchesFilter, l;

    for (i = 0, l = this.queryPairs.length; i &lt; l; i++) {

      param = this.queryPairs[i];
      keyMatchesFilter = decode(param[0]) === decode(key);
      valMatchesFilter = param[1] === val;

      if ((arguments.length === 1 &amp;&amp; !keyMatchesFilter) || (arguments.length === 2 &amp;&amp; (!keyMatchesFilter || !valMatchesFilter))) {
        arr.push(param);
      }
    }

    this.queryPairs = arr;

    return this;
  };

  /**
   * adds a query parameter
   * @param  {string}  key        add values for key
   * @param  {string}  val        value to add
   * @param  {integer} [index]    specific index to add the value at
   * @return {Uri}                returns self for fluent chaining
   */
  Uri.prototype.addQueryParam = function (key, val, index) {
    if (arguments.length === 3 &amp;&amp; index !== -1) {
      index = Math.min(index, this.queryPairs.length);
      this.queryPairs.splice(index, 0, [key, val]);
    } else if (arguments.length &gt; 0) {
      this.queryPairs.push([key, val]);
    }
    return this;
  };

  /**
   * test for the existence of a query parameter
   * @param  {string}  key        check values for key
   * @return {Boolean}            true if key exists, otherwise false
   */
  Uri.prototype.hasQueryParam = function (key) {
    var i, len = this.queryPairs.length;
    for (i = 0; i &lt; len; i++) {
      if (this.queryPairs[i][0] == key)
        return true;
    }
    return false;
  };

  /**
   * replaces query param values
   * @param  {string} key         key to replace value for
   * @param  {string} newVal      new value
   * @param  {string} [oldVal]    replace only one specific value (otherwise replaces all)
   * @return {Uri}                returns self for fluent chaining
   */
  Uri.prototype.replaceQueryParam = function (key, newVal, oldVal) {
    var index = -1, len = this.queryPairs.length, i, param;

    if (arguments.length === 3) {
      for (i = 0; i &lt; len; i++) {
        param = this.queryPairs[i];
        if (decode(param[0]) === decode(key) &amp;&amp; decodeURIComponent(param[1]) === decode(oldVal)) {
          index = i;
          break;
        }
      }
      if (index &gt;= 0) {
        this.deleteQueryParam(key, decode(oldVal)).addQueryParam(key, newVal, index);
      }
    } else {
      for (i = 0; i &lt; len; i++) {
        param = this.queryPairs[i];
        if (decode(param[0]) === decode(key)) {
          index = i;
          break;
        }
      }
      this.deleteQueryParam(key);
      this.addQueryParam(key, newVal, index);
    }
    return this;
  };

  /**
   * Define fluent setter methods (setProtocol, setHasAuthorityPrefix, etc)
   */
  ['protocol', 'hasAuthorityPrefix', 'isColonUri', 'userInfo', 'host', 'port', 'path', 'query', 'anchor'].forEach(function(key) {
    var method = 'set' + key.charAt(0).toUpperCase() + key.slice(1);
    Uri.prototype[method] = function(val) {
      this[key](val);
      return this;
    };
  });

  /**
   * Scheme name, colon and doubleslash, as required
   * @return {string} http:// or possibly just //
   */
  Uri.prototype.scheme = function() {
    var s = '';

    if (this.protocol()) {
      s += this.protocol();
      if (this.protocol().indexOf(':') !== this.protocol().length - 1) {
        s += ':';
      }
      s += '//';
    } else {
      if (this.hasAuthorityPrefix() &amp;&amp; this.host()) {
        s += '//';
      }
    }

    return s;
  };

  /**
   * Same as Mozilla nsIURI.prePath
   * @return {string} scheme://user:password@host:port
   * @see  https://developer.mozilla.org/en/nsIURI
   */
  Uri.prototype.origin = function() {
    var s = this.scheme();

    if (this.userInfo() &amp;&amp; this.host()) {
      s += this.userInfo();
      if (this.userInfo().indexOf('@') !== this.userInfo().length - 1) {
        s += '@';
      }
    }

    if (this.host()) {
      s += this.host();
      if (this.port() || (this.path() &amp;&amp; this.path().substr(0, 1).match(/[0-9]/))) {
        s += ':' + this.port();
      }
    }

    return s;
  };

  /**
   * Adds a trailing slash to the path
   */
  Uri.prototype.addTrailingSlash = function() {
    var path = this.path() || '';

    if (path.substr(-1) !== '/') {
      this.path(path + '/');
    }

    return this;
  };

  /**
   * Serializes the internal state of the Uri object
   * @return {string}
   */
  Uri.prototype.toString = function() {
    var path, s = this.origin();

    if (this.isColonUri()) {
      if (this.path()) {
        s += ':'+this.path();
      }
    } else if (this.path()) {
      path = this.path();
      if (!(re.ends_with_slashes.test(s) || re.starts_with_slashes.test(path))) {
        s += '/';
      } else {
        if (s) {
          s.replace(re.ends_with_slashes, '/');
        }
        path = path.replace(re.starts_with_slashes, '/');
      }
      s += path;
    } else {
      if (this.host() &amp;&amp; (this.query().toString() || this.anchor())) {
        s += '/';
      }
    }
    if (this.query().toString()) {
      s += this.query().toString();
    }

    if (this.anchor()) {
      if (this.anchor().indexOf('#') !== 0) {
        s += '#';
      }
      s += this.anchor();
    }

    return s;
  };

  /**
   * Clone a Uri object
   * @return {Uri} duplicate copy of the Uri
   */
  Uri.prototype.clone = function() {
    return new Uri(this.toString());
  };

  /**
   * export via AMD or CommonJS, otherwise leak a global
   */
  if (typeof define === 'function' &amp;&amp; define.amd) {
    define(function() {
      return Uri;
    });
  } else if (typeof module !== 'undefined' &amp;&amp; typeof module.exports !== 'undefined') {
    module.exports = Uri;
  } else {
    global.Uri = Uri;
  }
}(this));
function Spree () {}

Spree.ready = function (callback) {
  return jQuery(document).on('page:load turbolinks:load', function () {
    return callback(jQuery)
  })
}

Spree.mountedAt = function () {
  return window.SpreePaths.mounted_at
}

Spree.adminPath = function () {
  return window.SpreePaths.admin
}

Spree.pathFor = function (path) {
  var locationOrigin = (window.location.protocol + '//' + window.location.hostname) + (window.location.port ? ':' + window.location.port : '')

  return this.url('' + locationOrigin + (this.mountedAt()) + path, this.url_params).toString()
}

Spree.localizedPathFor = function(path) {
  if (typeof (SPREE_LOCALE) !== 'undefined' &amp;&amp; typeof (SPREE_CURRENCY) !== 'undefined') {
    var fullUrl = new URL(Spree.pathFor(path))
    var params = fullUrl.searchParams
    var pathName = fullUrl.pathname

    params.set('currency', SPREE_CURRENCY)

    if (pathName.match(/api\/v/)) {
      params.set('locale', SPREE_LOCALE)
    } else {
      pathName = (this.mountedAt()) + SPREE_LOCALE + '/' + path
    }
    return fullUrl.origin + pathName + '?' + params.toString()
  }
  return Spree.pathFor(path)
}

Spree.adminPathFor = function (path) {
  return this.pathFor('' + (this.adminPath()) + path)
}

Spree.url = function (uri, query) {
  if (uri.path === void 0) {
    // eslint-disable-next-line no-undef
    uri = new Uri(uri)
  }
  if (query) {
    $.each(query, function (key, value) {
      return uri.addQueryParam(key, value)
    })
  }
  return uri
}

Spree.ajax = function (urlOrSettings, settings) {
  var url
  if (typeof urlOrSettings === 'string') {
    return $.ajax(Spree.url(urlOrSettings).toString(), settings)
  } else {
    url = urlOrSettings['url']
    delete urlOrSettings['url']
    return $.ajax(Spree.url(url).toString(), urlOrSettings)
  }
}

Spree.routes = {
  states_search: Spree.pathFor('api/v1/states'),
  apply_coupon_code: function (orderId) {
    return Spree.pathFor('api/v1/orders/' + orderId + '/apply_coupon_code')
  },
  cart: Spree.pathFor('cart')
}

Spree.url_params = {};
!function(e,n){"object"==typeof exports&amp;&amp;"undefined"!=typeof module?n():"function"==typeof define&amp;&amp;define.amd?define(n):n()}(0,function(){"use strict";function e(e){var n=this.constructor;return this.then(function(t){return n.resolve(e()).then(function(){return t})},function(t){return n.resolve(e()).then(function(){return n.reject(t)})})}function n(){}function t(e){if(!(this instanceof t))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=undefined,this._deferreds=[],u(e,this)}function o(e,n){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,t._immediateFn(function(){var t=1===e._state?n.onFulfilled:n.onRejected;if(null!==t){var o;try{o=t(e._value)}catch(f){return void i(n.promise,f)}r(n.promise,o)}else(1===e._state?r:i)(n.promise,e._value)})):e._deferreds.push(n)}function r(e,n){try{if(n===e)throw new TypeError("A promise cannot be resolved with itself.");if(n&amp;&amp;("object"==typeof n||"function"==typeof n)){var o=n.then;if(n instanceof t)return e._state=3,e._value=n,void f(e);if("function"==typeof o)return void u(function(e,n){return function(){e.apply(n,arguments)}}(o,n),e)}e._state=1,e._value=n,f(e)}catch(r){i(e,r)}}function i(e,n){e._state=2,e._value=n,f(e)}function f(e){2===e._state&amp;&amp;0===e._deferreds.length&amp;&amp;t._immediateFn(function(){e._handled||t._unhandledRejectionFn(e._value)});for(var n=0,r=e._deferreds.length;r&gt;n;n++)o(e,e._deferreds[n]);e._deferreds=null}function u(e,n){var t=!1;try{e(function(e){t||(t=!0,r(n,e))},function(e){t||(t=!0,i(n,e))})}catch(o){if(t)return;t=!0,i(n,o)}}var c=setTimeout;t.prototype["catch"]=function(e){return this.then(null,e)},t.prototype.then=function(e,t){var r=new this.constructor(n);return o(this,new function(e,n,t){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof n?n:null,this.promise=t}(e,t,r)),r},t.prototype["finally"]=e,t.all=function(e){return new t(function(n,t){function o(e,f){try{if(f&amp;&amp;("object"==typeof f||"function"==typeof f)){var u=f.then;if("function"==typeof u)return void u.call(f,function(n){o(e,n)},t)}r[e]=f,0==--i&amp;&amp;n(r)}catch(c){t(c)}}if(!e||"undefined"==typeof e.length)throw new TypeError("Promise.all accepts an array");var r=Array.prototype.slice.call(e);if(0===r.length)return n([]);for(var i=r.length,f=0;r.length&gt;f;f++)o(f,r[f])})},t.resolve=function(e){return e&amp;&amp;"object"==typeof e&amp;&amp;e.constructor===t?e:new t(function(n){n(e)})},t.reject=function(e){return new t(function(n,t){t(e)})},t.race=function(e){return new t(function(n,t){for(var o=0,r=e.length;r&gt;o;o++)e[o].then(n,t)})},t._immediateFn="function"==typeof setImmediate&amp;&amp;function(e){setImmediate(e)}||function(e){c(e,0)},t._unhandledRejectionFn=function(e){void 0!==console&amp;&amp;console&amp;&amp;console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype["finally"]||(l.Promise.prototype["finally"]=e):l.Promise=t});
(function (global, factory) {
  typeof exports === 'object' &amp;&amp; typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' &amp;&amp; define.amd ? define(['exports'], factory) :
  (factory((global.WHATWGFetch = {})));
}(this, (function (exports) { 'use strict';

  var support = {
    searchParams: 'URLSearchParams' in self,
    iterable: 'Symbol' in self &amp;&amp; 'iterator' in Symbol,
    blob:
      'FileReader' in self &amp;&amp;
      'Blob' in self &amp;&amp;
      (function() {
        try {
          new Blob();
          return true
        } catch (e) {
          return false
        }
      })(),
    formData: 'FormData' in self,
    arrayBuffer: 'ArrayBuffer' in self
  };

  function isDataView(obj) {
    return obj &amp;&amp; DataView.prototype.isPrototypeOf(obj)
  }

  if (support.arrayBuffer) {
    var viewClasses = [
      '[object Int8Array]',
      '[object Uint8Array]',
      '[object Uint8ClampedArray]',
      '[object Int16Array]',
      '[object Uint16Array]',
      '[object Int32Array]',
      '[object Uint32Array]',
      '[object Float32Array]',
      '[object Float64Array]'
    ];

    var isArrayBufferView =
      ArrayBuffer.isView ||
      function(obj) {
        return obj &amp;&amp; viewClasses.indexOf(Object.prototype.toString.call(obj)) &gt; -1
      };
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = String(name);
    }
    if (/[^a-z0-9\-#$%&amp;'*+.^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = String(value);
    }
    return value
  }

  // Build a destructive iterator for the value list
  function iteratorFor(items) {
    var iterator = {
      next: function() {
        var value = items.shift();
        return {done: value === undefined, value: value}
      }
    };

    if (support.iterable) {
      iterator[Symbol.iterator] = function() {
        return iterator
      };
    }

    return iterator
  }

  function Headers(headers) {
    this.map = {};

    if (headers instanceof Headers) {
      headers.forEach(function(value, name) {
        this.append(name, value);
      }, this);
    } else if (Array.isArray(headers)) {
      headers.forEach(function(header) {
        this.append(header[0], header[1]);
      }, this);
    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        this.append(name, headers[name]);
      }, this);
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name);
    value = normalizeValue(value);
    var oldValue = this.map[name];
    this.map[name] = oldValue ? oldValue + ', ' + value : value;
  };

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)];
  };

  Headers.prototype.get = function(name) {
    name = normalizeName(name);
    return this.has(name) ? this.map[name] : null
  };

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  };

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = normalizeValue(value);
  };

  Headers.prototype.forEach = function(callback, thisArg) {
    for (var name in this.map) {
      if (this.map.hasOwnProperty(name)) {
        callback.call(thisArg, this.map[name], name, this);
      }
    }
  };

  Headers.prototype.keys = function() {
    var items = [];
    this.forEach(function(value, name) {
      items.push(name);
    });
    return iteratorFor(items)
  };

  Headers.prototype.values = function() {
    var items = [];
    this.forEach(function(value) {
      items.push(value);
    });
    return iteratorFor(items)
  };

  Headers.prototype.entries = function() {
    var items = [];
    this.forEach(function(value, name) {
      items.push([name, value]);
    });
    return iteratorFor(items)
  };

  if (support.iterable) {
    Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true;
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result);
      };
      reader.onerror = function() {
        reject(reader.error);
      };
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader();
    var promise = fileReaderReady(reader);
    reader.readAsArrayBuffer(blob);
    return promise
  }

  function readBlobAsText(blob) {
    var reader = new FileReader();
    var promise = fileReaderReady(reader);
    reader.readAsText(blob);
    return promise
  }

  function readArrayBufferAsText(buf) {
    var view = new Uint8Array(buf);
    var chars = new Array(view.length);

    for (var i = 0; i &lt; view.length; i++) {
      chars[i] = String.fromCharCode(view[i]);
    }
    return chars.join('')
  }

  function bufferClone(buf) {
    if (buf.slice) {
      return buf.slice(0)
    } else {
      var view = new Uint8Array(buf.byteLength);
      view.set(new Uint8Array(buf));
      return view.buffer
    }
  }

  function Body() {
    this.bodyUsed = false;

    this._initBody = function(body) {
      this._bodyInit = body;
      if (!body) {
        this._bodyText = '';
      } else if (typeof body === 'string') {
        this._bodyText = body;
      } else if (support.blob &amp;&amp; Blob.prototype.isPrototypeOf(body)) {
        this._bodyBlob = body;
      } else if (support.formData &amp;&amp; FormData.prototype.isPrototypeOf(body)) {
        this._bodyFormData = body;
      } else if (support.searchParams &amp;&amp; URLSearchParams.prototype.isPrototypeOf(body)) {
        this._bodyText = body.toString();
      } else if (support.arrayBuffer &amp;&amp; support.blob &amp;&amp; isDataView(body)) {
        this._bodyArrayBuffer = bufferClone(body.buffer);
        // IE 10-11 can't handle a DataView body.
        this._bodyInit = new Blob([this._bodyArrayBuffer]);
      } else if (support.arrayBuffer &amp;&amp; (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
        this._bodyArrayBuffer = bufferClone(body);
      } else {
        this._bodyText = body = Object.prototype.toString.call(body);
      }

      if (!this.headers.get('content-type')) {
        if (typeof body === 'string') {
          this.headers.set('content-type', 'text/plain;charset=UTF-8');
        } else if (this._bodyBlob &amp;&amp; this._bodyBlob.type) {
          this.headers.set('content-type', this._bodyBlob.type);
        } else if (support.searchParams &amp;&amp; URLSearchParams.prototype.isPrototypeOf(body)) {
          this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
        }
      }
    };

    if (support.blob) {
      this.blob = function() {
        var rejected = consumed(this);
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyArrayBuffer) {
          return Promise.resolve(new Blob([this._bodyArrayBuffer]))
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      };

      this.arrayBuffer = function() {
        if (this._bodyArrayBuffer) {
          return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
        } else {
          return this.blob().then(readBlobAsArrayBuffer)
        }
      };
    }

    this.text = function() {
      var rejected = consumed(this);
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return readBlobAsText(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as text')
      } else {
        return Promise.resolve(this._bodyText)
      }
    };

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      };
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    };

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];

  function normalizeMethod(method) {
    var upcased = method.toUpperCase();
    return methods.indexOf(upcased) &gt; -1 ? upcased : method
  }

  function Request(input, options) {
    options = options || {};
    var body = options.body;

    if (input instanceof Request) {
      if (input.bodyUsed) {
        throw new TypeError('Already read')
      }
      this.url = input.url;
      this.credentials = input.credentials;
      if (!options.headers) {
        this.headers = new Headers(input.headers);
      }
      this.method = input.method;
      this.mode = input.mode;
      this.signal = input.signal;
      if (!body &amp;&amp; input._bodyInit != null) {
        body = input._bodyInit;
        input.bodyUsed = true;
      }
    } else {
      this.url = String(input);
    }

    this.credentials = options.credentials || this.credentials || 'same-origin';
    if (options.headers || !this.headers) {
      this.headers = new Headers(options.headers);
    }
    this.method = normalizeMethod(options.method || this.method || 'GET');
    this.mode = options.mode || this.mode || null;
    this.signal = options.signal || this.signal;
    this.referrer = null;

    if ((this.method === 'GET' || this.method === 'HEAD') &amp;&amp; body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(body);
  }

  Request.prototype.clone = function() {
    return new Request(this, {body: this._bodyInit})
  };

  function decode(body) {
    var form = new FormData();
    body
      .trim()
      .split('&amp;')
      .forEach(function(bytes) {
        if (bytes) {
          var split = bytes.split('=');
          var name = split.shift().replace(/\+/g, ' ');
          var value = split.join('=').replace(/\+/g, ' ');
          form.append(decodeURIComponent(name), decodeURIComponent(value));
        }
      });
    return form
  }

  function parseHeaders(rawHeaders) {
    var headers = new Headers();
    // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
    // https://tools.ietf.org/html/rfc7230#section-3.2
    var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
    preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
      var parts = line.split(':');
      var key = parts.shift().trim();
      if (key) {
        var value = parts.join(':').trim();
        headers.append(key, value);
      }
    });
    return headers
  }

  Body.call(Request.prototype);

  function Response(bodyInit, options) {
    if (!options) {
      options = {};
    }

    this.type = 'default';
    this.status = options.status === undefined ? 200 : options.status;
    this.ok = this.status &gt;= 200 &amp;&amp; this.status &lt; 300;
    this.statusText = 'statusText' in options ? options.statusText : 'OK';
    this.headers = new Headers(options.headers);
    this.url = options.url || '';
    this._initBody(bodyInit);
  }

  Body.call(Response.prototype);

  Response.prototype.clone = function() {
    return new Response(this._bodyInit, {
      status: this.status,
      statusText: this.statusText,
      headers: new Headers(this.headers),
      url: this.url
    })
  };

  Response.error = function() {
    var response = new Response(null, {status: 0, statusText: ''});
    response.type = 'error';
    return response
  };

  var redirectStatuses = [301, 302, 303, 307, 308];

  Response.redirect = function(url, status) {
    if (redirectStatuses.indexOf(status) === -1) {
      throw new RangeError('Invalid status code')
    }

    return new Response(null, {status: status, headers: {location: url}})
  };

  exports.DOMException = self.DOMException;
  try {
    new exports.DOMException();
  } catch (err) {
    exports.DOMException = function(message, name) {
      this.message = message;
      this.name = name;
      var error = Error(message);
      this.stack = error.stack;
    };
    exports.DOMException.prototype = Object.create(Error.prototype);
    exports.DOMException.prototype.constructor = exports.DOMException;
  }

  function fetch(input, init) {
    return new Promise(function(resolve, reject) {
      var request = new Request(input, init);

      if (request.signal &amp;&amp; request.signal.aborted) {
        return reject(new exports.DOMException('Aborted', 'AbortError'))
      }

      var xhr = new XMLHttpRequest();

      function abortXhr() {
        xhr.abort();
      }

      xhr.onload = function() {
        var options = {
          status: xhr.status,
          statusText: xhr.statusText,
          headers: parseHeaders(xhr.getAllResponseHeaders() || '')
        };
        options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options));
      };

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'));
      };

      xhr.ontimeout = function() {
        reject(new TypeError('Network request failed'));
      };

      xhr.onabort = function() {
        reject(new exports.DOMException('Aborted', 'AbortError'));
      };

      xhr.open(request.method, request.url, true);

      if (request.credentials === 'include') {
        xhr.withCredentials = true;
      } else if (request.credentials === 'omit') {
        xhr.withCredentials = false;
      }

      if ('responseType' in xhr &amp;&amp; support.blob) {
        xhr.responseType = 'blob';
      }

      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value);
      });

      if (request.signal) {
        request.signal.addEventListener('abort', abortXhr);

        xhr.onreadystatechange = function() {
          // DONE (success or failure)
          if (xhr.readyState === 4) {
            request.signal.removeEventListener('abort', abortXhr);
          }
        };
      }

      xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
    })
  }

  fetch.polyfill = true;

  if (!self.fetch) {
    self.fetch = fetch;
    self.Headers = Headers;
    self.Request = Request;
    self.Response = Response;
  }

  exports.Headers = Headers;
  exports.Request = Request;
  exports.Response = Response;
  exports.fetch = fetch;

  Object.defineProperty(exports, '__esModule', { value: true });

})));

var SpreeAPI = {
  oauthToken: null, // user Bearer token to authorize operations for the given user
  orderToken: null // order token to authorize operations on current order (cart)
}

SpreeAPI.Storefront = {}
SpreeAPI.Platform = {}

// API routes
Spree.routes.api_v2_storefront_cart_create = Spree.pathFor('api/v2/storefront/cart')
Spree.routes.api_v2_storefront_cart_add_item = Spree.pathFor('api/v2/storefront/cart/add_item')
Spree.routes.api_v2_storefront_cart_apply_coupon_code = Spree.pathFor('api/v2/storefront/cart/apply_coupon_code')

// helpers
SpreeAPI.handle500error = function () {
  alert('Internal Server Error')
}

SpreeAPI.prepareHeaders = function (headers) {
  if (typeof headers === 'undefined') {
    headers = {}
  }

  // if signed in we need to pass the Bearer authorization token
  // so backend will recognize that actions are authorized in scope of this user
  if (SpreeAPI.oauthToken) {
    headers['Authorization'] = 'Bearer ' + SpreeAPI.oauthToken
  }

  // default headers, required for POST/PATCH/DELETE requests
  headers['Accept'] = 'application/json'
  headers['Content-Type'] = 'application/json'
  return headers
};
window.lazySizesConfig = window.lazySizesConfig || {}
window.lazySizesConfig.loadMode = 1
window.lazySizesConfig.init = false
window.lazySizesConfig.loadHidden = false

Spree.ready(function ($) {
  window.lazySizes.init()
});
/*! lazysizes - v5.1.2 */
!function(a,b){var c=b(a,a.document);a.lazySizes=c,"object"==typeof module&amp;&amp;module.exports&amp;&amp;(module.exports=c)}("undefined"!=typeof window?window:{},function(a,b){"use strict";var c,d;if(function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};d=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in d||(d[b]=c[b])}(),!b||!b.getElementsByClassName)return{init:function(){},cfg:d,noSupport:!0};var e=b.documentElement,f=a.Date,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h],k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&amp;&amp;p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&amp;&amp;a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&amp;&amp;u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,d,e,f,g){var h=b.createEvent("Event");return e||(e={}),e.instance=c,h.initEvent(d,!f,!g),h.detail=e,a.dispatchEvent(h),h},w=function(b,c){var e;!g&amp;&amp;(e=a.picturefill||d.pf)?(c&amp;&amp;c.src&amp;&amp;!b[i]("srcset")&amp;&amp;b.setAttribute("srcset",c.src),e({reevaluate:!0,elements:[b]})):c&amp;&amp;c.src&amp;&amp;(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c&lt;d.minSize&amp;&amp;b&amp;&amp;!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&amp;&amp;!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,c=0,e=d.throttleDelay,g=d.ricTimeout,h=function(){b=!1,c=f.now(),a()},i=m&amp;&amp;g&gt;49?function(){m(h,{timeout:g}),g!==d.ricTimeout&amp;&amp;(g=d.ricTimeout)}:A(function(){k(h)},!0);return function(a){var d;(a=!0===a)&amp;&amp;(g=33),b||(b=!0,d=e-(f.now()-c),d&lt;0&amp;&amp;(d=0),a||d&lt;9?i():k(i,d))}},C=function(a){var b,c,d=99,e=function(){b=null,a()},g=function(){var a=f.now()-c;a&lt;d?k(g,d-a):(m||e)(e)};return function(){c=f.now(),b||(b=k(g,d))}},D=function(){var g,l,m,o,p,y,D,F,G,H,I,J,K=/^img$/i,L=/^iframe$/i,M="onscroll"in a&amp;&amp;!/(gle|ing)bot/.test(navigator.userAgent),N=0,O=0,P=0,Q=-1,R=function(a){P--,(!a||P&lt;0||!a.target)&amp;&amp;(P=0)},S=function(a){return null==J&amp;&amp;(J="hidden"==x(b.body,"visibility")),J||!("hidden"==x(a.parentNode,"visibility")&amp;&amp;"hidden"==x(a,"visibility"))},T=function(a,c){var d,f=a,g=S(a);for(F-=c,I+=c,G-=c,H+=c;g&amp;&amp;(f=f.offsetParent)&amp;&amp;f!=b.body&amp;&amp;f!=e;)(g=(x(f,"opacity")||1)&gt;0)&amp;&amp;"visible"!=x(f,"overflow")&amp;&amp;(d=f.getBoundingClientRect(),g=H&gt;d.left&amp;&amp;G&lt;d.right&amp;&amp;I&gt;d.top-1&amp;&amp;F&lt;d.bottom+1);return g},U=function(){var a,f,h,j,k,m,n,p,q,r,s,t,u=c.elements;if((o=d.loadMode)&amp;&amp;P&lt;8&amp;&amp;(a=u.length)){for(f=0,Q++;f&lt;a;f++)if(u[f]&amp;&amp;!u[f]._lazyRace)if(!M||c.prematureUnveil&amp;&amp;c.prematureUnveil(u[f]))aa(u[f]);else if((p=u[f][i]("data-expand"))&amp;&amp;(m=1*p)||(m=O),r||(r=!d.expand||d.expand&lt;1?e.clientHeight&gt;500&amp;&amp;e.clientWidth&gt;500?500:370:d.expand,c._defEx=r,s=r*d.expFactor,t=d.hFac,J=null,O&lt;s&amp;&amp;P&lt;1&amp;&amp;Q&gt;2&amp;&amp;o&gt;2&amp;&amp;!b.hidden?(O=s,Q=0):O=o&gt;1&amp;&amp;Q&gt;1&amp;&amp;P&lt;6?r:N),q!==m&amp;&amp;(y=innerWidth+m*t,D=innerHeight+m,n=-1*m,q=m),h=u[f].getBoundingClientRect(),(I=h.bottom)&gt;=n&amp;&amp;(F=h.top)&lt;=D&amp;&amp;(H=h.right)&gt;=n*t&amp;&amp;(G=h.left)&lt;=y&amp;&amp;(I||H||G||F)&amp;&amp;(d.loadHidden||S(u[f]))&amp;&amp;(l&amp;&amp;P&lt;3&amp;&amp;!p&amp;&amp;(o&lt;3||Q&lt;4)||T(u[f],m))){if(aa(u[f]),k=!0,P&gt;9)break}else!k&amp;&amp;l&amp;&amp;!j&amp;&amp;P&lt;4&amp;&amp;Q&lt;4&amp;&amp;o&gt;2&amp;&amp;(g[0]||d.preloadAfterLoad)&amp;&amp;(g[0]||!p&amp;&amp;(I||H||G||F||"auto"!=u[f][i](d.sizesAttr)))&amp;&amp;(j=g[0]||u[f]);j&amp;&amp;!k&amp;&amp;aa(j)}},V=B(U),W=function(a){var b=a.target;if(b._lazyCache)return void delete b._lazyCache;R(a),s(b,d.loadedClass),t(b,d.loadingClass),u(b,Y),v(b,"lazyloaded")},X=A(W),Y=function(a){X({target:a.target})},Z=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},$=function(a){var b,c=a[i](d.srcsetAttr);(b=d.customMedia[a[i]("data-media")||a[i]("media")])&amp;&amp;a.setAttribute("media",b),c&amp;&amp;a.setAttribute("srcset",c)},_=A(function(a,b,c,e,f){var g,h,j,l,o,p;(o=v(a,"lazybeforeunveil",b)).defaultPrevented||(e&amp;&amp;(c?s(a,d.autosizesClass):a.setAttribute("sizes",e)),h=a[i](d.srcsetAttr),g=a[i](d.srcAttr),f&amp;&amp;(j=a.parentNode,l=j&amp;&amp;n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&amp;&amp;(h||g||l),o={target:a},s(a,d.loadingClass),p&amp;&amp;(clearTimeout(m),m=k(R,2500),u(a,Y,!0)),l&amp;&amp;q.call(j.getElementsByTagName("source"),$),h?a.setAttribute("srcset",h):g&amp;&amp;!l&amp;&amp;(L.test(a.nodeName)?Z(a,g):a.src=g),f&amp;&amp;(h||l)&amp;&amp;w(a,{src:g})),a._lazyRace&amp;&amp;delete a._lazyRace,t(a,d.lazyClass),z(function(){var b=a.complete&amp;&amp;a.naturalWidth&gt;1;p&amp;&amp;!b||(b&amp;&amp;s(a,"ls-is-cached"),W(o),a._lazyCache=!0,k(function(){"_lazyCache"in a&amp;&amp;delete a._lazyCache},9)),"lazy"==a.loading&amp;&amp;P--},!0)}),aa=function(a){if(!a._lazyRace){var b,c=K.test(a.nodeName),e=c&amp;&amp;(a[i](d.sizesAttr)||a[i]("sizes")),f="auto"==e;(!f&amp;&amp;l||!c||!a[i]("src")&amp;&amp;!a.srcset||a.complete||r(a,d.errorClass)||!r(a,d.lazyClass))&amp;&amp;(b=v(a,"lazyunveilread").detail,f&amp;&amp;E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,P++,_(a,b,f,e,c))}},ba=C(function(){d.loadMode=3,V()}),ca=function(){3==d.loadMode&amp;&amp;(d.loadMode=2),ba()},da=function(){if(!l){if(f.now()-p&lt;999)return void k(da,999);l=!0,d.loadMode=3,V(),j("scroll",ca,!0)}};return{_:function(){p=f.now(),c.elements=b.getElementsByClassName(d.lazyClass),g=b.getElementsByClassName(d.lazyClass+" "+d.preloadClass),j("scroll",V,!0),j("resize",V,!0),a.MutationObserver?new MutationObserver(V).observe(e,{childList:!0,subtree:!0,attributes:!0}):(e[h]("DOMNodeInserted",V,!0),e[h]("DOMAttrModified",V,!0),setInterval(V,999)),j("hashchange",V,!0),["focus","mouseover","click","load","transitionend","animationend"].forEach(function(a){b[h](a,V,!0)}),/d$|^c/.test(b.readyState)?da():(j("load",da),b[h]("DOMContentLoaded",V),k(da,2e4)),c.elements.length?(U(),z._lsFlush()):V()},checkElems:V,unveil:aa,_aLSL:ca}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;f&lt;g;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),e=function(a,b,d){var e,f=a.parentNode;f&amp;&amp;(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width)&amp;&amp;d!==a._lazysizesWidth&amp;&amp;c(a,f,e,d))},f=function(){var b,c=a.length;if(c)for(b=0;b&lt;c;b++)e(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(d.autosizesClass),j("resize",g)},checkElems:g,updateElem:e}}(),F=function(){!F.i&amp;&amp;b.getElementsByClassName&amp;&amp;(F.i=!0,E._(),D._())};return k(function(){d.init&amp;&amp;F()}),c={cfg:d,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}});
/*!
 * accounting.js v0.4.2, copyright 2014 Open Exchange Rates, MIT license, http://openexchangerates.github.io/accounting.js
 */
(function(p,z){function q(a){return!!(""===a||a&amp;&amp;a.charCodeAt&amp;&amp;a.substr)}function m(a){return u?u(a):"[object Array]"===v.call(a)}function r(a){return"[object Object]"===v.call(a)}function s(a,b){var d,a=a||{},b=b||{};for(d in b)b.hasOwnProperty(d)&amp;&amp;null==a[d]&amp;&amp;(a[d]=b[d]);return a}function j(a,b,d){var c=[],e,h;if(!a)return c;if(w&amp;&amp;a.map===w)return a.map(b,d);for(e=0,h=a.length;e&lt;h;e++)c[e]=b.call(d,a[e],e,a);return c}function n(a,b){a=Math.round(Math.abs(a));return isNaN(a)?b:a}function x(a){var b=c.settings.currency.format;"function"===typeof a&amp;&amp;(a=a());return q(a)&amp;&amp;a.match("%v")?{pos:a,neg:a.replace("-","").replace("%v","-%v"),zero:a}:!a||!a.pos||!a.pos.match("%v")?!q(b)?b:c.settings.currency.format={pos:b,neg:b.replace("%v","-%v"),zero:b}:a}var c={version:"0.4.1",settings:{currency:{symbol:"$",format:"%s%v",decimal:".",thousand:",",precision:2,grouping:3},number:{precision:0,grouping:3,thousand:",",decimal:"."}}},w=Array.prototype.map,u=Array.isArray,v=Object.prototype.toString,o=c.unformat=c.parse=function(a,b){if(m(a))return j(a,function(a){return o(a,b)});a=a||0;if("number"===typeof a)return a;var b=b||".",c=RegExp("[^0-9-"+b+"]",["g"]),c=parseFloat((""+a).replace(/\((.*)\)/,"-$1").replace(c,"").replace(b,"."));return!isNaN(c)?c:0},y=c.toFixed=function(a,b){var b=n(b,c.settings.number.precision),d=Math.pow(10,b);return(Math.round(c.unformat(a)*d)/d).toFixed(b)},t=c.formatNumber=c.format=function(a,b,d,i){if(m(a))return j(a,function(a){return t(a,b,d,i)});var a=o(a),e=s(r(b)?b:{precision:b,thousand:d,decimal:i},c.settings.number),h=n(e.precision),f=0&gt;a?"-":"",g=parseInt(y(Math.abs(a||0),h),10)+"",l=3&lt;g.length?g.length%3:0;return f+(l?g.substr(0,l)+e.thousand:"")+g.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+e.thousand)+(h?e.decimal+y(Math.abs(a),h).split(".")[1]:"")},A=c.formatMoney=function(a,b,d,i,e,h){if(m(a))return j(a,function(a){return A(a,b,d,i,e,h)});var a=o(a),f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format);return(0&lt;a?g.pos:0&gt;a?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal))};c.formatColumn=function(a,b,d,i,e,h){if(!a)return[];var f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format),l=g.pos.indexOf("%s")&lt;g.pos.indexOf("%v")?!0:!1,k=0,a=j(a,function(a){if(m(a))return c.formatColumn(a,f);a=o(a);a=(0&lt;a?g.pos:0&gt;a?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal));if(a.length&gt;k)k=a.length;return a});return j(a,function(a){return q(a)&amp;&amp;a.length&lt;k?l?a.replace(f.symbol,f.symbol+Array(k-a.length+1).join(" ")):Array(k-a.length+1).join(" ")+a:a})};if("undefined"!==typeof exports){if("undefined"!==typeof module&amp;&amp;module.exports)exports=module.exports=c;exports.accounting=c}else"function"===typeof define&amp;&amp;define.amd?define([],function(){return c}):(c.noConflict=function(a){return function(){p.accounting=a;c.noConflict=z;return c}}(p.accounting),p.accounting=c)})(this);
/*
Turbolinks 5.2.0
Copyright Â© 2018 Basecamp, LLC
 */
(function(){var t=this;(function(){(function(){this.Turbolinks={supported:function(){return null!=window.history.pushState&amp;&amp;null!=window.requestAnimationFrame&amp;&amp;null!=window.addEventListener}(),visit:function(t,r){return e.controller.visit(t,r)},clearCache:function(){return e.controller.clearCache()},setProgressBarDelay:function(t){return e.controller.setProgressBarDelay(t)}}}).call(this)}).call(t);var e=t.Turbolinks;(function(){(function(){var t,r,n,o=[].slice;e.copyObject=function(t){var e,r,n;r={};for(e in t)n=t[e],r[e]=n;return r},e.closest=function(e,r){return t.call(e,r)},t=function(){var t,e;return t=document.documentElement,null!=(e=t.closest)?e:function(t){var e;for(e=this;e;){if(e.nodeType===Node.ELEMENT_NODE&amp;&amp;r.call(e,t))return e;e=e.parentNode}}}(),e.defer=function(t){return setTimeout(t,1)},e.throttle=function(t){var e;return e=null,function(){var r;return r=1&lt;=arguments.length?o.call(arguments,0):[],null!=e?e:e=requestAnimationFrame(function(n){return function(){return e=null,t.apply(n,r)}}(this))}},e.dispatch=function(t,e){var r,o,i,s,a,u;return a=null!=e?e:{},u=a.target,r=a.cancelable,o=a.data,i=document.createEvent("Events"),i.initEvent(t,!0,r===!0),i.data=null!=o?o:{},i.cancelable&amp;&amp;!n&amp;&amp;(s=i.preventDefault,i.preventDefault=function(){return this.defaultPrevented||Object.defineProperty(this,"defaultPrevented",{get:function(){return!0}}),s.call(this)}),(null!=u?u:document).dispatchEvent(i),i},n=function(){var t;return t=document.createEvent("Events"),t.initEvent("test",!0,!0),t.preventDefault(),t.defaultPrevented}(),e.match=function(t,e){return r.call(t,e)},r=function(){var t,e,r,n;return t=document.documentElement,null!=(e=null!=(r=null!=(n=t.matchesSelector)?n:t.webkitMatchesSelector)?r:t.msMatchesSelector)?e:t.mozMatchesSelector}(),e.uuid=function(){var t,e,r;for(r="",t=e=1;36&gt;=e;t=++e)r+=9===t||14===t||19===t||24===t?"-":15===t?"4":20===t?(Math.floor(4*Math.random())+8).toString(16):Math.floor(15*Math.random()).toString(16);return r}}).call(this),function(){e.Location=function(){function t(t){var e,r;null==t&amp;&amp;(t=""),r=document.createElement("a"),r.href=t.toString(),this.absoluteURL=r.href,e=r.hash.length,2&gt;e?this.requestURL=this.absoluteURL:(this.requestURL=this.absoluteURL.slice(0,-e),this.anchor=r.hash.slice(1))}var e,r,n,o;return t.wrap=function(t){return t instanceof this?t:new this(t)},t.prototype.getOrigin=function(){return this.absoluteURL.split("/",3).join("/")},t.prototype.getPath=function(){var t,e;return null!=(t=null!=(e=this.requestURL.match(/\/\/[^\/]*(\/[^?;]*)/))?e[1]:void 0)?t:"/"},t.prototype.getPathComponents=function(){return this.getPath().split("/").slice(1)},t.prototype.getLastPathComponent=function(){return this.getPathComponents().slice(-1)[0]},t.prototype.getExtension=function(){var t,e;return null!=(t=null!=(e=this.getLastPathComponent().match(/\.[^.]*$/))?e[0]:void 0)?t:""},t.prototype.isHTML=function(){return this.getExtension().match(/^(?:|\.(?:htm|html|xhtml))$/)},t.prototype.isPrefixedBy=function(t){var e;return e=r(t),this.isEqualTo(t)||o(this.absoluteURL,e)},t.prototype.isEqualTo=function(t){return this.absoluteURL===(null!=t?t.absoluteURL:void 0)},t.prototype.toCacheKey=function(){return this.requestURL},t.prototype.toJSON=function(){return this.absoluteURL},t.prototype.toString=function(){return this.absoluteURL},t.prototype.valueOf=function(){return this.absoluteURL},r=function(t){return e(t.getOrigin()+t.getPath())},e=function(t){return n(t,"/")?t:t+"/"},o=function(t,e){return t.slice(0,e.length)===e},n=function(t,e){return t.slice(-e.length)===e},t}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.HttpRequest=function(){function r(r,n,o){this.delegate=r,this.requestCanceled=t(this.requestCanceled,this),this.requestTimedOut=t(this.requestTimedOut,this),this.requestFailed=t(this.requestFailed,this),this.requestLoaded=t(this.requestLoaded,this),this.requestProgressed=t(this.requestProgressed,this),this.url=e.Location.wrap(n).requestURL,this.referrer=e.Location.wrap(o).absoluteURL,this.createXHR()}return r.NETWORK_FAILURE=0,r.TIMEOUT_FAILURE=-1,r.timeout=60,r.prototype.send=function(){var t;return this.xhr&amp;&amp;!this.sent?(this.notifyApplicationBeforeRequestStart(),this.setProgress(0),this.xhr.send(),this.sent=!0,"function"==typeof(t=this.delegate).requestStarted?t.requestStarted():void 0):void 0},r.prototype.cancel=function(){return this.xhr&amp;&amp;this.sent?this.xhr.abort():void 0},r.prototype.requestProgressed=function(t){return t.lengthComputable?this.setProgress(t.loaded/t.total):void 0},r.prototype.requestLoaded=function(){return this.endRequest(function(t){return function(){var e;return 200&lt;=(e=t.xhr.status)&amp;&amp;300&gt;e?t.delegate.requestCompletedWithResponse(t.xhr.responseText,t.xhr.getResponseHeader("Turbolinks-Location")):(t.failed=!0,t.delegate.requestFailedWithStatusCode(t.xhr.status,t.xhr.responseText))}}(this))},r.prototype.requestFailed=function(){return this.endRequest(function(t){return function(){return t.failed=!0,t.delegate.requestFailedWithStatusCode(t.constructor.NETWORK_FAILURE)}}(this))},r.prototype.requestTimedOut=function(){return this.endRequest(function(t){return function(){return t.failed=!0,t.delegate.requestFailedWithStatusCode(t.constructor.TIMEOUT_FAILURE)}}(this))},r.prototype.requestCanceled=function(){return this.endRequest()},r.prototype.notifyApplicationBeforeRequestStart=function(){return e.dispatch("turbolinks:request-start",{data:{url:this.url,xhr:this.xhr}})},r.prototype.notifyApplicationAfterRequestEnd=function(){return e.dispatch("turbolinks:request-end",{data:{url:this.url,xhr:this.xhr}})},r.prototype.createXHR=function(){return this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url,!0),this.xhr.timeout=1e3*this.constructor.timeout,this.xhr.setRequestHeader("Accept","text/html, application/xhtml+xml"),this.xhr.setRequestHeader("Turbolinks-Referrer",this.referrer),this.xhr.onprogress=this.requestProgressed,this.xhr.onload=this.requestLoaded,this.xhr.onerror=this.requestFailed,this.xhr.ontimeout=this.requestTimedOut,this.xhr.onabort=this.requestCanceled},r.prototype.endRequest=function(t){return this.xhr?(this.notifyApplicationAfterRequestEnd(),null!=t&amp;&amp;t.call(this),this.destroy()):void 0},r.prototype.setProgress=function(t){var e;return this.progress=t,"function"==typeof(e=this.delegate).requestProgressed?e.requestProgressed(this.progress):void 0},r.prototype.destroy=function(){var t;return this.setProgress(1),"function"==typeof(t=this.delegate).requestFinished&amp;&amp;t.requestFinished(),this.delegate=null,this.xhr=null},r}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.ProgressBar=function(){function e(){this.trickle=t(this.trickle,this),this.stylesheetElement=this.createStylesheetElement(),this.progressElement=this.createProgressElement()}var r;return r=300,e.defaultCSS=".turbolinks-progress-bar {\n  position: fixed;\n  display: block;\n  top: 0;\n  left: 0;\n  height: 3px;\n  background: #0076ff;\n  z-index: 9999;\n  transition: width "+r+"ms ease-out, opacity "+r/2+"ms "+r/2+"ms ease-in;\n  transform: translate3d(0, 0, 0);\n}",e.prototype.show=function(){return this.visible?void 0:(this.visible=!0,this.installStylesheetElement(),this.installProgressElement(),this.startTrickling())},e.prototype.hide=function(){return this.visible&amp;&amp;!this.hiding?(this.hiding=!0,this.fadeProgressElement(function(t){return function(){return t.uninstallProgressElement(),t.stopTrickling(),t.visible=!1,t.hiding=!1}}(this))):void 0},e.prototype.setValue=function(t){return this.value=t,this.refresh()},e.prototype.installStylesheetElement=function(){return document.head.insertBefore(this.stylesheetElement,document.head.firstChild)},e.prototype.installProgressElement=function(){return this.progressElement.style.width=0,this.progressElement.style.opacity=1,document.documentElement.insertBefore(this.progressElement,document.body),this.refresh()},e.prototype.fadeProgressElement=function(t){return this.progressElement.style.opacity=0,setTimeout(t,1.5*r)},e.prototype.uninstallProgressElement=function(){return this.progressElement.parentNode?document.documentElement.removeChild(this.progressElement):void 0},e.prototype.startTrickling=function(){return null!=this.trickleInterval?this.trickleInterval:this.trickleInterval=setInterval(this.trickle,r)},e.prototype.stopTrickling=function(){return clearInterval(this.trickleInterval),this.trickleInterval=null},e.prototype.trickle=function(){return this.setValue(this.value+Math.random()/100)},e.prototype.refresh=function(){return requestAnimationFrame(function(t){return function(){return t.progressElement.style.width=10+90*t.value+"%"}}(this))},e.prototype.createStylesheetElement=function(){var t;return t=document.createElement("style"),t.type="text/css",t.textContent=this.constructor.defaultCSS,t},e.prototype.createProgressElement=function(){var t;return t=document.createElement("div"),t.className="turbolinks-progress-bar",t},e}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.BrowserAdapter=function(){function r(r){this.controller=r,this.showProgressBar=t(this.showProgressBar,this),this.progressBar=new e.ProgressBar}var n,o,i;return i=e.HttpRequest,n=i.NETWORK_FAILURE,o=i.TIMEOUT_FAILURE,r.prototype.visitProposedToLocationWithAction=function(t,e){return this.controller.startVisitToLocationWithAction(t,e)},r.prototype.visitStarted=function(t){return t.issueRequest(),t.changeHistory(),t.loadCachedSnapshot()},r.prototype.visitRequestStarted=function(t){return this.progressBar.setValue(0),t.hasCachedSnapshot()||"restore"!==t.action?this.showProgressBarAfterDelay():this.showProgressBar()},r.prototype.visitRequestProgressed=function(t){return this.progressBar.setValue(t.progress)},r.prototype.visitRequestCompleted=function(t){return t.loadResponse()},r.prototype.visitRequestFailedWithStatusCode=function(t,e){switch(e){case n:case o:return this.reload();default:return t.loadResponse()}},r.prototype.visitRequestFinished=function(t){return this.hideProgressBar()},r.prototype.visitCompleted=function(t){return t.followRedirect()},r.prototype.pageInvalidated=function(){return this.reload()},r.prototype.showProgressBarAfterDelay=function(){return this.progressBarTimeout=setTimeout(this.showProgressBar,this.controller.progressBarDelay)},r.prototype.showProgressBar=function(){return this.progressBar.show()},r.prototype.hideProgressBar=function(){return this.progressBar.hide(),clearTimeout(this.progressBarTimeout)},r.prototype.reload=function(){return window.location.reload()},r}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.History=function(){function r(e){this.delegate=e,this.onPageLoad=t(this.onPageLoad,this),this.onPopState=t(this.onPopState,this)}return r.prototype.start=function(){return this.started?void 0:(addEventListener("popstate",this.onPopState,!1),addEventListener("load",this.onPageLoad,!1),this.started=!0)},r.prototype.stop=function(){return this.started?(removeEventListener("popstate",this.onPopState,!1),removeEventListener("load",this.onPageLoad,!1),this.started=!1):void 0},r.prototype.push=function(t,r){return t=e.Location.wrap(t),this.update("push",t,r)},r.prototype.replace=function(t,r){return t=e.Location.wrap(t),this.update("replace",t,r)},r.prototype.onPopState=function(t){var r,n,o,i;return this.shouldHandlePopState()&amp;&amp;(i=null!=(n=t.state)?n.turbolinks:void 0)?(r=e.Location.wrap(window.location),o=i.restorationIdentifier,this.delegate.historyPoppedToLocationWithRestorationIdentifier(r,o)):void 0},r.prototype.onPageLoad=function(t){return e.defer(function(t){return function(){return t.pageLoaded=!0}}(this))},r.prototype.shouldHandlePopState=function(){return this.pageIsLoaded()},r.prototype.pageIsLoaded=function(){return this.pageLoaded||"complete"===document.readyState},r.prototype.update=function(t,e,r){var n;return n={turbolinks:{restorationIdentifier:r}},history[t+"State"](n,null,e)},r}()}.call(this),function(){e.HeadDetails=function(){function t(t){var e,r,n,s,a,u;for(this.elements={},n=0,a=t.length;a&gt;n;n++)u=t[n],u.nodeType===Node.ELEMENT_NODE&amp;&amp;(s=u.outerHTML,r=null!=(e=this.elements)[s]?e[s]:e[s]={type:i(u),tracked:o(u),elements:[]},r.elements.push(u))}var e,r,n,o,i;return t.fromHeadElement=function(t){var e;return new this(null!=(e=null!=t?t.childNodes:void 0)?e:[])},t.prototype.hasElementWithKey=function(t){return t in this.elements},t.prototype.getTrackedElementSignature=function(){var t,e;return function(){var r,n;r=this.elements,n=[];for(t in r)e=r[t].tracked,e&amp;&amp;n.push(t);return n}.call(this).join("")},t.prototype.getScriptElementsNotInDetails=function(t){return this.getElementsMatchingTypeNotInDetails("script",t)},t.prototype.getStylesheetElementsNotInDetails=function(t){return this.getElementsMatchingTypeNotInDetails("stylesheet",t)},t.prototype.getElementsMatchingTypeNotInDetails=function(t,e){var r,n,o,i,s,a;o=this.elements,s=[];for(n in o)i=o[n],a=i.type,r=i.elements,a!==t||e.hasElementWithKey(n)||s.push(r[0]);return s},t.prototype.getProvisionalElements=function(){var t,e,r,n,o,i,s;r=[],n=this.elements;for(e in n)o=n[e],s=o.type,i=o.tracked,t=o.elements,null!=s||i?t.length&gt;1&amp;&amp;r.push.apply(r,t.slice(1)):r.push.apply(r,t);return r},t.prototype.getMetaValue=function(t){var e;return null!=(e=this.findMetaElementByName(t))?e.getAttribute("content"):void 0},t.prototype.findMetaElementByName=function(t){var r,n,o,i;r=void 0,i=this.elements;for(o in i)n=i[o].elements,e(n[0],t)&amp;&amp;(r=n[0]);return r},i=function(t){return r(t)?"script":n(t)?"stylesheet":void 0},o=function(t){return"reload"===t.getAttribute("data-turbolinks-track")},r=function(t){var e;return e=t.tagName.toLowerCase(),"script"===e},n=function(t){var e;return e=t.tagName.toLowerCase(),"style"===e||"link"===e&amp;&amp;"stylesheet"===t.getAttribute("rel")},e=function(t,e){var r;return r=t.tagName.toLowerCase(),"meta"===r&amp;&amp;t.getAttribute("name")===e},t}()}.call(this),function(){e.Snapshot=function(){function t(t,e){this.headDetails=t,this.bodyElement=e}return t.wrap=function(t){return t instanceof this?t:"string"==typeof t?this.fromHTMLString(t):this.fromHTMLElement(t)},t.fromHTMLString=function(t){var e;return e=document.createElement("html"),e.innerHTML=t,this.fromHTMLElement(e)},t.fromHTMLElement=function(t){var r,n,o,i;return o=t.querySelector("head"),r=null!=(i=t.querySelector("body"))?i:document.createElement("body"),n=e.HeadDetails.fromHeadElement(o),new this(n,r)},t.prototype.clone=function(){return new this.constructor(this.headDetails,this.bodyElement.cloneNode(!0))},t.prototype.getRootLocation=function(){var t,r;return r=null!=(t=this.getSetting("root"))?t:"/",new e.Location(r)},t.prototype.getCacheControlValue=function(){return this.getSetting("cache-control")},t.prototype.getElementForAnchor=function(t){try{return this.bodyElement.querySelector("[id='"+t+"'], a[name='"+t+"']")}catch(e){}},t.prototype.getPermanentElements=function(){return this.bodyElement.querySelectorAll("[id][data-turbolinks-permanent]")},t.prototype.getPermanentElementById=function(t){return this.bodyElement.querySelector("#"+t+"[data-turbolinks-permanent]")},t.prototype.getPermanentElementsPresentInSnapshot=function(t){var e,r,n,o,i;for(o=this.getPermanentElements(),i=[],r=0,n=o.length;n&gt;r;r++)e=o[r],t.getPermanentElementById(e.id)&amp;&amp;i.push(e);return i},t.prototype.findFirstAutofocusableElement=function(){return this.bodyElement.querySelector("[autofocus]")},t.prototype.hasAnchor=function(t){return null!=this.getElementForAnchor(t)},t.prototype.isPreviewable=function(){return"no-preview"!==this.getCacheControlValue()},t.prototype.isCacheable=function(){return"no-cache"!==this.getCacheControlValue()},t.prototype.isVisitable=function(){return"reload"!==this.getSetting("visit-control")},t.prototype.getSetting=function(t){return this.headDetails.getMetaValue("turbolinks-"+t)},t}()}.call(this),function(){var t=[].slice;e.Renderer=function(){function e(){}var r;return e.render=function(){var e,r,n,o;return n=arguments[0],r=arguments[1],e=3&lt;=arguments.length?t.call(arguments,2):[],o=function(t,e,r){r.prototype=t.prototype;var n=new r,o=t.apply(n,e);return Object(o)===o?o:n}(this,e,function(){}),o.delegate=n,o.render(r),o},e.prototype.renderView=function(t){return this.delegate.viewWillRender(this.newBody),t(),this.delegate.viewRendered(this.newBody)},e.prototype.invalidateView=function(){return this.delegate.viewInvalidated()},e.prototype.createScriptElement=function(t){var e;return"false"===t.getAttribute("data-turbolinks-eval")?t:(e=document.createElement("script"),e.textContent=t.textContent,e.async=!1,r(e,t),e)},r=function(t,e){var r,n,o,i,s,a,u;for(i=e.attributes,a=[],r=0,n=i.length;n&gt;r;r++)s=i[r],o=s.name,u=s.value,a.push(t.setAttribute(o,u));return a},e}()}.call(this),function(){var t,r,n=function(t,e){function r(){this.constructor=t}for(var n in e)o.call(e,n)&amp;&amp;(t[n]=e[n]);return r.prototype=e.prototype,t.prototype=new r,t.__super__=e.prototype,t},o={}.hasOwnProperty;e.SnapshotRenderer=function(e){function o(t,e,r){this.currentSnapshot=t,this.newSnapshot=e,this.isPreview=r,this.currentHeadDetails=this.currentSnapshot.headDetails,this.newHeadDetails=this.newSnapshot.headDetails,this.currentBody=this.currentSnapshot.bodyElement,this.newBody=this.newSnapshot.bodyElement}return n(o,e),o.prototype.render=function(t){return this.shouldRender()?(this.mergeHead(),this.renderView(function(e){return function(){return e.replaceBody(),e.isPreview||e.focusFirstAutofocusableElement(),t()}}(this))):this.invalidateView()},o.prototype.mergeHead=function(){return this.copyNewHeadStylesheetElements(),this.copyNewHeadScriptElements(),this.removeCurrentHeadProvisionalElements(),this.copyNewHeadProvisionalElements()},o.prototype.replaceBody=function(){var t;return t=this.relocateCurrentBodyPermanentElements(),this.activateNewBodyScriptElements(),this.assignNewBody(),this.replacePlaceholderElementsWithClonedPermanentElements(t)},o.prototype.shouldRender=function(){return this.newSnapshot.isVisitable()&amp;&amp;this.trackedElementsAreIdentical()},o.prototype.trackedElementsAreIdentical=function(){return this.currentHeadDetails.getTrackedElementSignature()===this.newHeadDetails.getTrackedElementSignature()},o.prototype.copyNewHeadStylesheetElements=function(){var t,e,r,n,o;for(n=this.getNewHeadStylesheetElements(),o=[],e=0,r=n.length;r&gt;e;e++)t=n[e],o.push(document.head.appendChild(t));return o},o.prototype.copyNewHeadScriptElements=function(){var t,e,r,n,o;for(n=this.getNewHeadScriptElements(),o=[],e=0,r=n.length;r&gt;e;e++)t=n[e],o.push(document.head.appendChild(this.createScriptElement(t)));return o},o.prototype.removeCurrentHeadProvisionalElements=function(){var t,e,r,n,o;for(n=this.getCurrentHeadProvisionalElements(),o=[],e=0,r=n.length;r&gt;e;e++)t=n[e],o.push(document.head.removeChild(t));return o},o.prototype.copyNewHeadProvisionalElements=function(){var t,e,r,n,o;for(n=this.getNewHeadProvisionalElements(),o=[],e=0,r=n.length;r&gt;e;e++)t=n[e],o.push(document.head.appendChild(t));return o},o.prototype.relocateCurrentBodyPermanentElements=function(){var e,n,o,i,s,a,u;for(a=this.getCurrentBodyPermanentElements(),u=[],e=0,n=a.length;n&gt;e;e++)i=a[e],s=t(i),o=this.newSnapshot.getPermanentElementById(i.id),r(i,s.element),r(o,i),u.push(s);return u},o.prototype.replacePlaceholderElementsWithClonedPermanentElements=function(t){var e,n,o,i,s,a,u;for(u=[],o=0,i=t.length;i&gt;o;o++)a=t[o],n=a.element,s=a.permanentElement,e=s.cloneNode(!0),u.push(r(n,e));return u},o.prototype.activateNewBodyScriptElements=function(){var t,e,n,o,i,s;for(i=this.getNewBodyScriptElements(),s=[],e=0,o=i.length;o&gt;e;e++)n=i[e],t=this.createScriptElement(n),s.push(r(n,t));return s},o.prototype.assignNewBody=function(){return document.body=this.newBody},o.prototype.focusFirstAutofocusableElement=function(){var t;return null!=(t=this.newSnapshot.findFirstAutofocusableElement())?t.focus():void 0},o.prototype.getNewHeadStylesheetElements=function(){return this.newHeadDetails.getStylesheetElementsNotInDetails(this.currentHeadDetails)},o.prototype.getNewHeadScriptElements=function(){return this.newHeadDetails.getScriptElementsNotInDetails(this.currentHeadDetails)},o.prototype.getCurrentHeadProvisionalElements=function(){return this.currentHeadDetails.getProvisionalElements()},o.prototype.getNewHeadProvisionalElements=function(){return this.newHeadDetails.getProvisionalElements()},o.prototype.getCurrentBodyPermanentElements=function(){return this.currentSnapshot.getPermanentElementsPresentInSnapshot(this.newSnapshot)},o.prototype.getNewBodyScriptElements=function(){return this.newBody.querySelectorAll("script")},o}(e.Renderer),t=function(t){var e;return e=document.createElement("meta"),e.setAttribute("name","turbolinks-permanent-placeholder"),e.setAttribute("content",t.id),{element:e,permanentElement:t}},r=function(t,e){var r;return(r=t.parentNode)?r.replaceChild(e,t):void 0}}.call(this),function(){var t=function(t,e){function n(){this.constructor=t}for(var o in e)r.call(e,o)&amp;&amp;(t[o]=e[o]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},r={}.hasOwnProperty;e.ErrorRenderer=function(e){function r(t){var e;e=document.createElement("html"),e.innerHTML=t,this.newHead=e.querySelector("head"),this.newBody=e.querySelector("body")}return t(r,e),r.prototype.render=function(t){return this.renderView(function(e){return function(){return e.replaceHeadAndBody(),e.activateBodyScriptElements(),t()}}(this))},r.prototype.replaceHeadAndBody=function(){var t,e;return e=document.head,t=document.body,e.parentNode.replaceChild(this.newHead,e),t.parentNode.replaceChild(this.newBody,t)},r.prototype.activateBodyScriptElements=function(){var t,e,r,n,o,i;for(n=this.getScriptElements(),i=[],e=0,r=n.length;r&gt;e;e++)o=n[e],t=this.createScriptElement(o),i.push(o.parentNode.replaceChild(t,o));return i},r.prototype.getScriptElements=function(){return document.documentElement.querySelectorAll("script")},r}(e.Renderer)}.call(this),function(){e.View=function(){function t(t){this.delegate=t,this.htmlElement=document.documentElement}return t.prototype.getRootLocation=function(){return this.getSnapshot().getRootLocation()},t.prototype.getElementForAnchor=function(t){return this.getSnapshot().getElementForAnchor(t)},t.prototype.getSnapshot=function(){return e.Snapshot.fromHTMLElement(this.htmlElement)},t.prototype.render=function(t,e){var r,n,o;return o=t.snapshot,r=t.error,n=t.isPreview,this.markAsPreview(n),null!=o?this.renderSnapshot(o,n,e):this.renderError(r,e)},t.prototype.markAsPreview=function(t){return t?this.htmlElement.setAttribute("data-turbolinks-preview",""):this.htmlElement.removeAttribute("data-turbolinks-preview")},t.prototype.renderSnapshot=function(t,r,n){return e.SnapshotRenderer.render(this.delegate,n,this.getSnapshot(),e.Snapshot.wrap(t),r)},t.prototype.renderError=function(t,r){return e.ErrorRenderer.render(this.delegate,r,t)},t}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.ScrollManager=function(){function r(r){this.delegate=r,this.onScroll=t(this.onScroll,this),this.onScroll=e.throttle(this.onScroll)}return r.prototype.start=function(){return this.started?void 0:(addEventListener("scroll",this.onScroll,!1),this.onScroll(),this.started=!0)},r.prototype.stop=function(){return this.started?(removeEventListener("scroll",this.onScroll,!1),this.started=!1):void 0},r.prototype.scrollToElement=function(t){return t.scrollIntoView()},r.prototype.scrollToPosition=function(t){var e,r;return e=t.x,r=t.y,window.scrollTo(e,r)},r.prototype.onScroll=function(t){return this.updatePosition({x:window.pageXOffset,y:window.pageYOffset})},r.prototype.updatePosition=function(t){var e;return this.position=t,null!=(e=this.delegate)?e.scrollPositionChanged(this.position):void 0},r}()}.call(this),function(){e.SnapshotCache=function(){function t(t){this.size=t,this.keys=[],this.snapshots={}}var r;return t.prototype.has=function(t){var e;return e=r(t),e in this.snapshots},t.prototype.get=function(t){var e;if(this.has(t))return e=this.read(t),this.touch(t),e},t.prototype.put=function(t,e){return this.write(t,e),this.touch(t),e},t.prototype.read=function(t){var e;return e=r(t),this.snapshots[e]},t.prototype.write=function(t,e){var n;return n=r(t),this.snapshots[n]=e},t.prototype.touch=function(t){var e,n;return n=r(t),e=this.keys.indexOf(n),e&gt;-1&amp;&amp;this.keys.splice(e,1),this.keys.unshift(n),this.trim()},t.prototype.trim=function(){var t,e,r,n,o;for(n=this.keys.splice(this.size),o=[],t=0,r=n.length;r&gt;t;t++)e=n[t],o.push(delete this.snapshots[e]);return o},r=function(t){return e.Location.wrap(t).toCacheKey()},t}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.Visit=function(){function r(r,n,o){this.controller=r,this.action=o,this.performScroll=t(this.performScroll,this),this.identifier=e.uuid(),this.location=e.Location.wrap(n),this.adapter=this.controller.adapter,this.state="initialized",this.timingMetrics={}}var n;return r.prototype.start=function(){return"initialized"===this.state?(this.recordTimingMetric("visitStart"),this.state="started",this.adapter.visitStarted(this)):void 0},r.prototype.cancel=function(){var t;return"started"===this.state?(null!=(t=this.request)&amp;&amp;t.cancel(),this.cancelRender(),this.state="canceled"):void 0},r.prototype.complete=function(){var t;return"started"===this.state?(this.recordTimingMetric("visitEnd"),this.state="completed","function"==typeof(t=this.adapter).visitCompleted&amp;&amp;t.visitCompleted(this),this.controller.visitCompleted(this)):void 0},r.prototype.fail=function(){var t;return"started"===this.state?(this.state="failed","function"==typeof(t=this.adapter).visitFailed?t.visitFailed(this):void 0):void 0},r.prototype.changeHistory=function(){var t,e;return this.historyChanged?void 0:(t=this.location.isEqualTo(this.referrer)?"replace":this.action,e=n(t),this.controller[e](this.location,this.restorationIdentifier),this.historyChanged=!0)},r.prototype.issueRequest=function(){return this.shouldIssueRequest()&amp;&amp;null==this.request?(this.progress=0,this.request=new e.HttpRequest(this,this.location,this.referrer),this.request.send()):void 0},r.prototype.getCachedSnapshot=function(){var t;return!(t=this.controller.getCachedSnapshotForLocation(this.location))||null!=this.location.anchor&amp;&amp;!t.hasAnchor(this.location.anchor)||"restore"!==this.action&amp;&amp;!t.isPreviewable()?void 0:t},r.prototype.hasCachedSnapshot=function(){return null!=this.getCachedSnapshot()},r.prototype.loadCachedSnapshot=function(){var t,e;return(e=this.getCachedSnapshot())?(t=this.shouldIssueRequest(),this.render(function(){var r;return this.cacheSnapshot(),this.controller.render({snapshot:e,isPreview:t},this.performScroll),"function"==typeof(r=this.adapter).visitRendered&amp;&amp;r.visitRendered(this),t?void 0:this.complete()})):void 0},r.prototype.loadResponse=function(){return null!=this.response?this.render(function(){var t,e;return this.cacheSnapshot(),this.request.failed?(this.controller.render({error:this.response},this.performScroll),"function"==typeof(t=this.adapter).visitRendered&amp;&amp;t.visitRendered(this),this.fail()):(this.controller.render({snapshot:this.response},this.performScroll),"function"==typeof(e=this.adapter).visitRendered&amp;&amp;e.visitRendered(this),this.complete())}):void 0},r.prototype.followRedirect=function(){return this.redirectedToLocation&amp;&amp;!this.followedRedirect?(this.location=this.redirectedToLocation,this.controller.replaceHistoryWithLocationAndRestorationIdentifier(this.redirectedToLocation,this.restorationIdentifier),this.followedRedirect=!0):void 0},r.prototype.requestStarted=function(){var t;return this.recordTimingMetric("requestStart"),"function"==typeof(t=this.adapter).visitRequestStarted?t.visitRequestStarted(this):void 0},r.prototype.requestProgressed=function(t){var e;return this.progress=t,"function"==typeof(e=this.adapter).visitRequestProgressed?e.visitRequestProgressed(this):void 0},r.prototype.requestCompletedWithResponse=function(t,r){return this.response=t,null!=r&amp;&amp;(this.redirectedToLocation=e.Location.wrap(r)),this.adapter.visitRequestCompleted(this)},r.prototype.requestFailedWithStatusCode=function(t,e){return this.response=e,this.adapter.visitRequestFailedWithStatusCode(this,t)},r.prototype.requestFinished=function(){var t;return this.recordTimingMetric("requestEnd"),"function"==typeof(t=this.adapter).visitRequestFinished?t.visitRequestFinished(this):void 0},r.prototype.performScroll=function(){return this.scrolled?void 0:("restore"===this.action?this.scrollToRestoredPosition()||this.scrollToTop():this.scrollToAnchor()||this.scrollToTop(),this.scrolled=!0)},r.prototype.scrollToRestoredPosition=function(){var t,e;return t=null!=(e=this.restorationData)?e.scrollPosition:void 0,null!=t?(this.controller.scrollToPosition(t),!0):void 0},r.prototype.scrollToAnchor=function(){return null!=this.location.anchor?(this.controller.scrollToAnchor(this.location.anchor),!0):void 0},r.prototype.scrollToTop=function(){return this.controller.scrollToPosition({x:0,y:0})},r.prototype.recordTimingMetric=function(t){var e;return null!=(e=this.timingMetrics)[t]?e[t]:e[t]=(new Date).getTime()},r.prototype.getTimingMetrics=function(){return e.copyObject(this.timingMetrics)},n=function(t){switch(t){case"replace":return"replaceHistoryWithLocationAndRestorationIdentifier";case"advance":case"restore":return"pushHistoryWithLocationAndRestorationIdentifier"}},r.prototype.shouldIssueRequest=function(){return"restore"===this.action?!this.hasCachedSnapshot():!0},r.prototype.cacheSnapshot=function(){return this.snapshotCached?void 0:(this.controller.cacheSnapshot(),this.snapshotCached=!0)},r.prototype.render=function(t){return this.cancelRender(),this.frame=requestAnimationFrame(function(e){return function(){return e.frame=null,t.call(e)}}(this))},r.prototype.cancelRender=function(){return this.frame?cancelAnimationFrame(this.frame):void 0},r}()}.call(this),function(){var t=function(t,e){return function(){return t.apply(e,arguments)}};e.Controller=function(){function r(){this.clickBubbled=t(this.clickBubbled,this),this.clickCaptured=t(this.clickCaptured,this),this.pageLoaded=t(this.pageLoaded,this),this.history=new e.History(this),this.view=new e.View(this),this.scrollManager=new e.ScrollManager(this),this.restorationData={},this.clearCache(),this.setProgressBarDelay(500)}return r.prototype.start=function(){return e.supported&amp;&amp;!this.started?(addEventListener("click",this.clickCaptured,!0),addEventListener("DOMContentLoaded",this.pageLoaded,!1),this.scrollManager.start(),this.startHistory(),this.started=!0,this.enabled=!0):void 0},r.prototype.disable=function(){return this.enabled=!1},r.prototype.stop=function(){return this.started?(removeEventListener("click",this.clickCaptured,!0),removeEventListener("DOMContentLoaded",this.pageLoaded,!1),this.scrollManager.stop(),this.stopHistory(),this.started=!1):void 0},r.prototype.clearCache=function(){return this.cache=new e.SnapshotCache(10)},r.prototype.visit=function(t,r){var n,o;return null==r&amp;&amp;(r={}),t=e.Location.wrap(t),this.applicationAllowsVisitingLocation(t)?this.locationIsVisitable(t)?(n=null!=(o=r.action)?o:"advance",this.adapter.visitProposedToLocationWithAction(t,n)):window.location=t:void 0},r.prototype.startVisitToLocationWithAction=function(t,r,n){var o;return e.supported?(o=this.getRestorationDataForIdentifier(n),this.startVisit(t,r,{restorationData:o})):window.location=t},r.prototype.setProgressBarDelay=function(t){return this.progressBarDelay=t},r.prototype.startHistory=function(){return this.location=e.Location.wrap(window.location),this.restorationIdentifier=e.uuid(),this.history.start(),this.history.replace(this.location,this.restorationIdentifier)},r.prototype.stopHistory=function(){return this.history.stop()},r.prototype.pushHistoryWithLocationAndRestorationIdentifier=function(t,r){return this.restorationIdentifier=r,this.location=e.Location.wrap(t),this.history.push(this.location,this.restorationIdentifier)},r.prototype.replaceHistoryWithLocationAndRestorationIdentifier=function(t,r){return this.restorationIdentifier=r,this.location=e.Location.wrap(t),this.history.replace(this.location,this.restorationIdentifier)},r.prototype.historyPoppedToLocationWithRestorationIdentifier=function(t,r){var n;return this.restorationIdentifier=r,this.enabled?(n=this.getRestorationDataForIdentifier(this.restorationIdentifier),this.startVisit(t,"restore",{restorationIdentifier:this.restorationIdentifier,restorationData:n,historyChanged:!0}),this.location=e.Location.wrap(t)):this.adapter.pageInvalidated()},r.prototype.getCachedSnapshotForLocation=function(t){var e;return null!=(e=this.cache.get(t))?e.clone():void 0},r.prototype.shouldCacheSnapshot=function(){return this.view.getSnapshot().isCacheable();
},r.prototype.cacheSnapshot=function(){var t,r;return this.shouldCacheSnapshot()?(this.notifyApplicationBeforeCachingSnapshot(),r=this.view.getSnapshot(),t=this.lastRenderedLocation,e.defer(function(e){return function(){return e.cache.put(t,r.clone())}}(this))):void 0},r.prototype.scrollToAnchor=function(t){var e;return(e=this.view.getElementForAnchor(t))?this.scrollToElement(e):this.scrollToPosition({x:0,y:0})},r.prototype.scrollToElement=function(t){return this.scrollManager.scrollToElement(t)},r.prototype.scrollToPosition=function(t){return this.scrollManager.scrollToPosition(t)},r.prototype.scrollPositionChanged=function(t){var e;return e=this.getCurrentRestorationData(),e.scrollPosition=t},r.prototype.render=function(t,e){return this.view.render(t,e)},r.prototype.viewInvalidated=function(){return this.adapter.pageInvalidated()},r.prototype.viewWillRender=function(t){return this.notifyApplicationBeforeRender(t)},r.prototype.viewRendered=function(){return this.lastRenderedLocation=this.currentVisit.location,this.notifyApplicationAfterRender()},r.prototype.pageLoaded=function(){return this.lastRenderedLocation=this.location,this.notifyApplicationAfterPageLoad()},r.prototype.clickCaptured=function(){return removeEventListener("click",this.clickBubbled,!1),addEventListener("click",this.clickBubbled,!1)},r.prototype.clickBubbled=function(t){var e,r,n;return this.enabled&amp;&amp;this.clickEventIsSignificant(t)&amp;&amp;(r=this.getVisitableLinkForNode(t.target))&amp;&amp;(n=this.getVisitableLocationForLink(r))&amp;&amp;this.applicationAllowsFollowingLinkToLocation(r,n)?(t.preventDefault(),e=this.getActionForLink(r),this.visit(n,{action:e})):void 0},r.prototype.applicationAllowsFollowingLinkToLocation=function(t,e){var r;return r=this.notifyApplicationAfterClickingLinkToLocation(t,e),!r.defaultPrevented},r.prototype.applicationAllowsVisitingLocation=function(t){var e;return e=this.notifyApplicationBeforeVisitingLocation(t),!e.defaultPrevented},r.prototype.notifyApplicationAfterClickingLinkToLocation=function(t,r){return e.dispatch("turbolinks:click",{target:t,data:{url:r.absoluteURL},cancelable:!0})},r.prototype.notifyApplicationBeforeVisitingLocation=function(t){return e.dispatch("turbolinks:before-visit",{data:{url:t.absoluteURL},cancelable:!0})},r.prototype.notifyApplicationAfterVisitingLocation=function(t){return e.dispatch("turbolinks:visit",{data:{url:t.absoluteURL}})},r.prototype.notifyApplicationBeforeCachingSnapshot=function(){return e.dispatch("turbolinks:before-cache")},r.prototype.notifyApplicationBeforeRender=function(t){return e.dispatch("turbolinks:before-render",{data:{newBody:t}})},r.prototype.notifyApplicationAfterRender=function(){return e.dispatch("turbolinks:render")},r.prototype.notifyApplicationAfterPageLoad=function(t){return null==t&amp;&amp;(t={}),e.dispatch("turbolinks:load",{data:{url:this.location.absoluteURL,timing:t}})},r.prototype.startVisit=function(t,e,r){var n;return null!=(n=this.currentVisit)&amp;&amp;n.cancel(),this.currentVisit=this.createVisit(t,e,r),this.currentVisit.start(),this.notifyApplicationAfterVisitingLocation(t)},r.prototype.createVisit=function(t,r,n){var o,i,s,a,u;return i=null!=n?n:{},a=i.restorationIdentifier,s=i.restorationData,o=i.historyChanged,u=new e.Visit(this,t,r),u.restorationIdentifier=null!=a?a:e.uuid(),u.restorationData=e.copyObject(s),u.historyChanged=o,u.referrer=this.location,u},r.prototype.visitCompleted=function(t){return this.notifyApplicationAfterPageLoad(t.getTimingMetrics())},r.prototype.clickEventIsSignificant=function(t){return!(t.defaultPrevented||t.target.isContentEditable||t.which&gt;1||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey)},r.prototype.getVisitableLinkForNode=function(t){return this.nodeIsVisitable(t)?e.closest(t,"a[href]:not([target]):not([download])"):void 0},r.prototype.getVisitableLocationForLink=function(t){var r;return r=new e.Location(t.getAttribute("href")),this.locationIsVisitable(r)?r:void 0},r.prototype.getActionForLink=function(t){var e;return null!=(e=t.getAttribute("data-turbolinks-action"))?e:"advance"},r.prototype.nodeIsVisitable=function(t){var r;return(r=e.closest(t,"[data-turbolinks]"))?"false"!==r.getAttribute("data-turbolinks"):!0},r.prototype.locationIsVisitable=function(t){return t.isPrefixedBy(this.view.getRootLocation())&amp;&amp;t.isHTML()},r.prototype.getCurrentRestorationData=function(){return this.getRestorationDataForIdentifier(this.restorationIdentifier)},r.prototype.getRestorationDataForIdentifier=function(t){var e;return null!=(e=this.restorationData)[t]?e[t]:e[t]={}},r}()}.call(this),function(){!function(){var t,e;if((t=e=document.currentScript)&amp;&amp;!e.hasAttribute("data-turbolinks-suppress-warning"))for(;t=t.parentNode;)if(t===document.body)return console.warn("You are loading Turbolinks from a &lt;script&gt; element inside the &lt;body&gt; element. This is probably not what you meant to do!\n\nLoad your application\u2019s JavaScript bundle inside the &lt;head&gt; element instead. &lt;script&gt; elements in &lt;body&gt; are evaluated with each page change.\n\nFor more information, see: https://github.com/turbolinks/turbolinks#working-with-script-elements\n\n\u2014\u2014\nSuppress this warning by adding a `data-turbolinks-suppress-warning` attribute to: %s",e.outerHTML)}()}.call(this),function(){var t,r,n;e.start=function(){return r()?(null==e.controller&amp;&amp;(e.controller=t()),e.controller.start()):void 0},r=function(){return null==window.Turbolinks&amp;&amp;(window.Turbolinks=e),n()},t=function(){var t;return t=new e.Controller,t.adapter=new e.BrowserAdapter(t),t},n=function(){return window.Turbolinks===e},n()&amp;&amp;e.start()}.call(this)}).call(this),"object"==typeof module&amp;&amp;module.exports?module.exports=e:"function"==typeof define&amp;&amp;define.amd&amp;&amp;define(e)}).call(this);
Spree.fetchAccount = function () {
  return $.ajax({
    url: Spree.localizedPathFor('account_link')
  }).done(function (data) {
    Spree.accountFetched = true
    return $('#link-to-account').html(data)
  })
}

Spree.ready(function () {
  if (!Spree.accountFetched) Spree.fetchAccount()
});
Spree.fetchApiTokens = function () {
  fetch(Spree.routes.api_tokens, {
    method: 'GET',
    credentials: 'same-origin'
  }).then(function (response) {
    switch (response.status) {
      case 200:
        response.json().then(function (json) {
          SpreeAPI.orderToken = json.order_token
          SpreeAPI.oauthToken = json.oauth_token
          Spree.apiTokensFetched = true
        })
        break
    }
  })
}

Spree.ready(function () {
  if (!Spree.apiTokensFetched) Spree.fetchApiTokens()
});
// $.fn.carousel already occupied by legacy plugin. Need to use a different name for Bootstrap 4's carousel.
var carouselBootstrap4 = $.fn.carousel.noConflict()
$.fn.carouselBootstrap4 = carouselBootstrap4;
function CouponManager (input) {
  this.input = input
  this.appliedCouponCodeField = this.input.appliedCouponCodeField
  this.couponCodeField = this.input.couponCodeField
  this.couponApplied = false
  this.couponRemoved = false
  this.couponStatus = this.input.couponStatus
  this.couponButton = this.input.couponButton
  this.removeCouponButton = this.input.removeCouponButton
  this.couponErrorIcon = document.createElement("img")
  this.couponErrorIcon.src = Spree.translations.coupon_code_error_icon
}

CouponManager.prototype.applyCoupon = function () {
  this.couponCode = $.trim($(this.couponCodeField).val())
  if (this.couponCode !== '') {
    if (this.couponStatus.length === 0) {
      this.couponStatus = $('&lt;div/&gt;', {
        id: 'coupon_status'
      })
      this.couponCodeField.parent().append(this.couponStatus)
    }
    this.couponStatus.removeClass()
    this.sendRequest()
    return this.couponApplied
  } else {
    return true
  }
}

CouponManager.prototype.removeCoupon = function () {
  this.couponCode = $.trim($(this.appliedCouponCodeField).attr('data-code'))
  if (this.couponCode !== '') {
    if (this.couponStatus.length === 0) {
      this.couponStatus = $('&lt;div/&gt;', {
        id: 'coupon_status'
      })
      this.appliedCouponCodeField.parent().append(this.couponStatus)
    }
    this.couponStatus.removeClass()
    this.sendRemoveRequest()
    return this.couponRemoved
  } else {
    return true
  }
}

CouponManager.prototype.sendRequest = function () {
  return $.ajax({
    async: false,
    method: 'PATCH',
    url: Spree.routes.api_v2_storefront_cart_apply_coupon_code,
    dataType: 'json',
    headers: {
      'X-Spree-Order-Token': SpreeAPI.orderToken
    },
    data: {
      coupon_code: this.couponCode
    }
  }).done(function () {
    this.couponCodeField.val('')
    this.couponStatus.addClass('alert-success').html(Spree.translations.coupon_code_applied)
    this.couponApplied = true
  }.bind(this)).fail(function (xhr) {
    var handler = xhr.responseJSON
    this.couponCodeField.addClass('error')
    this.couponButton.addClass('error')
    this.couponStatus.addClass('alert-error').html(handler['error'])
    this.couponStatus.prepend(this.couponErrorIcon)
  }.bind(this))
}

CouponManager.prototype.sendRemoveRequest = function () {
  return $.ajax({
    async: false,
    method: 'DELETE',
    url: Spree.routes.api_v2_storefront_cart_remove_coupon_code(this.couponCode),
    dataType: 'json',
    headers: {
      'X-Spree-Order-Token': SpreeAPI.orderToken
    }
  }).done(function () {
    this.appliedCouponCodeField.val('')
    this.couponStatus.addClass('alert-success').html(Spree.translations.coupon_code_removed)
    this.couponRemoved = true
  }.bind(this)).fail(function (xhr) {
    var handler = xhr.responseJSON
    this.appliedCouponCodeField.addClass('error')
    this.removeCouponButton.addClass('error')
    this.couponStatus.addClass('alert-error').html(handler['error'])
    this.couponStatus.prepend(this.couponErrorIcon)
  }.bind(this))
};

Spree.ready(function ($) {
  var formUpdateCart = $('form#update-cart')

  function buildEventTriggerObject(dataset, quantity) {
    if (!dataset || !quantity) return false

    var triggerObject = {
      type: 'product_remove_from_cart',
      variant_sku: dataset.variantSku,
      variant_name: dataset.variantName,
      variant_price: dataset.variantPrice,
      variant_options: dataset.variantOptions,
      variant_quantity: quantity
    }

    return triggerObject
  }

  if (formUpdateCart.length) {
    var clearInvalidCouponField = function() {
      var couponCodeField = $('#order_coupon_code');
      var couponStatus = $('#coupon_status');
      if (!!couponCodeField.val() &amp;&amp; couponStatus.hasClass('alert-error')) {
        couponCodeField.val('')
      }
    }

    formUpdateCart.find('a.delete').show().one('click', function (event) {
      var itemId = $(this).attr('data-id')
      var link = $(event.currentTarget);
      var quantityInputs = $("form#update-cart input.shopping-cart-item-quantity-input[data-id='" + itemId + "']")
      var quantity = $(quantityInputs).val()
      $(this).parents('.shopping-cart-item').first().find('input.shopping-cart-item-quantity-input').val(0)
      clearInvalidCouponField()
      if (link[0] &amp;&amp; link[0].dataset &amp;&amp; quantity) {
        link.trigger(buildEventTriggerObject(link[0].dataset, quantity))
      }
      formUpdateCart.submit()
      return false
    })
    formUpdateCart.find('input.shopping-cart-item-quantity-input').on('keyup', function(e) {
      var itemId = $(this).attr('data-id')
      var value = $(this).val()
      var newValue = isNaN(value) || value === '' ? value : parseInt(value, 10)
      var targetInputs = $("form#update-cart input.shopping-cart-item-quantity-input[data-id='" + itemId + "']")
      $(targetInputs).val(newValue)
    })
    formUpdateCart.find('input.shopping-cart-item-quantity-input').on('change', function(e) {
      clearInvalidCouponField()
      formUpdateCart.submit()
    })
    formUpdateCart.find('button.shopping-cart-item-quantity-decrease-btn').off('click').on('click', function() {
      var itemId = $(this).attr('data-id')
      var input = $("input[data-id='" + itemId + "']")
      var inputValue = parseInt($(input).val(), 10)

      if (inputValue &gt; 1) {
        $(input).val(inputValue - 1)
        clearInvalidCouponField()
        formUpdateCart.submit()
      }
    })
    formUpdateCart.find('button.shopping-cart-item-quantity-increase-btn').off('click').on('click', function() {
      var itemId = $(this).attr('data-id')
      var input = $("input[data-id='" + itemId + "']")
      var inputValue = parseInt($(input).val(), 10)

      $(input).val(inputValue + 1)
      clearInvalidCouponField()
      formUpdateCart.submit()
    })
    formUpdateCart.find('button#shopping-cart-coupon-code-button').off('click').on('click', function(event) {
      var couponCodeField = $('#order_coupon_code');

      if (!$.trim(couponCodeField.val()).length) {
        event.preventDefault()
        return false
      }
    })

    formUpdateCart.find('button#shopping-cart-remove-coupon-code-button').off('click').on('click', function(event) {
      var input = {
        appliedCouponCodeField: $('#order_applied_coupon_code'),
        couponCodeField: $('#order_coupon_code'),
        couponStatus: $('#coupon_status'),
        couponButton: $('#shopping-cart-coupon-code-button'),
        removeCouponButton: $('#shopping-cart-remove-coupon-code-button')
      }

      if (new CouponManager(input).removeCoupon()) {
        return true
      } else {
        event.preventDefault()
        return false
      }
    })
  }
  formUpdateCart.submit(function (event) {
    var input = {
      couponCodeField: $('#order_coupon_code'),
      couponStatus: $('#coupon_status'),
      couponButton: $('#shopping-cart-coupon-code-button')
    }
    var updateButton = formUpdateCart.find('#update-button')
    updateButton.attr('disabled', true)
    if ($.trim(input.couponCodeField.val()).length &gt; 0) {
      // eslint-disable-next-line no-undef
      if (new CouponManager(input).applyCoupon()) {
        this.submit()
        return true
      } else {
        updateButton.attr('disabled', false)
        event.preventDefault()
        return false
      }
    }
  })

  if (!Spree.cartFetched) Spree.fetchCart()
})

Spree.fetchCart = function () {
  return $.ajax({
    url: Spree.localizedPathFor('cart_link')
  }).done(function (data) {
    Spree.cartFetched = true
    return $('#link-to-cart').html(data)
  })
}

Spree.ensureCart = function (successCallback) {
  if (SpreeAPI.orderToken) {
    successCallback()
  } else {
    fetch(Spree.routes.ensure_cart, {
      method: 'POST',
      credentials: 'same-origin'
    }).then(function (response) {
      switch (response.status) {
        case 200:
          response.json().then(function (json) {
            SpreeAPI.orderToken = json.token
            successCallback()
          })
          break
      }
    })
  }
};
document.addEventListener('turbolinks:load', function () {
  var localeSelect = document.querySelectorAll('select[name=switch_to_locale]');

  if (localeSelect.length) {
    localeSelect.forEach(function (element) {
      element.addEventListener('change', function () {
        Spree.clearCache();
        Spree.showProgressBar();
        element.form.submit();
      });
    });
  }
});
document.addEventListener('turbolinks:load', function(event) {
  // this condition checks if this is the first initial load of turbolinks application
  if (!event.data.timing.visitStart) {
    var currencySelect = document.querySelectorAll('select[name=switch_to_currency]')

    if (currencySelect.length) {
      currencySelect.forEach(function (element) {
        element.addEventListener('change', function () {
          Spree.showProgressBar()
          var newCurrency = this.value

          // we need to make AJAX call here to the backend to set currency in session
          fetch(Spree.routes.set_currency(newCurrency), {
            method: 'GET'
          }).then(function (response) {
            switch (response.status) {
              case 200:
                Spree.setCurrency(newCurrency)
                document.getElementById('internationalization-options-desktop').classList.remove('show')
                break
            }
          })
        })
      })
    }
  }
})

// fix back button issue with different currency set
// invalidate page if cached page has different currency then the current one
document.addEventListener('turbolinks:load', function(event) {
  if (typeof (SPREE_DEFAULT_CURRENCY) !== 'undefined' &amp;&amp; typeof (SPREE_CURRENCY) !== 'undefined') {
    if (SPREE_CURRENCY === SPREE_DEFAULT_CURRENCY) {
      var regexAnyCurrency = new RegExp('currency=')
      if (event.data.url.match(regexAnyCurrency) &amp;&amp; !event.data.url.match(SPREE_CURRENCY)) {
        Spree.setCurrency(SPREE_CURRENCY)
      }
    } else {
      var regex = new RegExp('currency=' + SPREE_CURRENCY)
      if (!event.data.url.match(regex)) {
        Spree.setCurrency(SPREE_CURRENCY)
      }
    }
  }
});

Spree.disableSaveOnClick = function () {
  $('form.edit_order').on('submit', function (event) {
    if ($(this).data('submitted') === true) {
      event.preventDefault()
    } else {
      $(this).data('submitted', true)
      $(this).find(':submit, :image').removeClass('primary').addClass('disabled')
    }
  })
}

Spree.enableSave = function () {
  $('#checkout form').data('submitted', false).find(':submit, :image').attr('disabled', false).addClass('primary').removeClass('disabled')
}

Spree.ready(function () {
  Spree.Checkout = {}

  var formCheckoutConfirm = $('form#checkout_form_confirm')
  if (formCheckoutConfirm.length) {
    $('form#checkout_form_confirm button#shopping-cart-coupon-code-button').off('click').on('click', function(event) {
      event.preventDefault()

      var input = {
        appliedCouponCodeField: $('#order_applied_coupon_code'),
        couponCodeField: $('#order_coupon_code'),
        couponStatus: $('#coupon_status'),
        couponButton: $('#shopping-cart-coupon-code-button'),
        removeCouponButton: $('#shopping-cart-remove-coupon-code-button')
      }

      if ($.trim(input.couponCodeField.val()).length &amp;&amp; new CouponManager(input).applyCoupon()) {
        location.reload();
        return true
      } else {
        return false
      }
    })

    $('form#checkout_form_confirm button#shopping-cart-remove-coupon-code-button').off('click').on('click', function(event) {
      var input = {
        appliedCouponCodeField: $('#order_applied_coupon_code'),
        couponCodeField: $('#order_coupon_code'),
        couponStatus: $('#coupon_status'),
        couponButton: $('#shopping-cart-coupon-code-button'),
        removeCouponButton: $('#shopping-cart-remove-coupon-code-button')
      }

      if (new CouponManager(input).removeCoupon()) {
        return true
      } else {
        event.preventDefault()
        return false
      }
    })
  }

  return Spree.Checkout
})

$('.js-remove-credit-card').click(function() {
  if (confirm(Spree.translations.credit_card_remove_confirmation)) {
    return $.ajax({
      async: false,
      method: 'DELETE',
      url: Spree.routes.api_v2_storefront_destroy_credit_card(this.dataset.id),
      dataType: 'json',
      headers: {
        'Authorization': 'Bearer ' + SpreeAPI.oauthToken
      }
    }).done(function() {
      location.reload();
    })
  }
});
Spree.ready(function($) {
  Spree.onAddress = function() {
    if ($('#checkout_form_address').length) {
      Spree.updateState = function(region) {
        var countryId = getCountryId(region)
        if (countryId != null) {
          if (Spree.Checkout[countryId] == null) {
            $.ajax({
              async: false,
              method: 'GET',
              url: Spree.localizedPathFor('/api/v2/storefront/countries/' + countryId + '?include=checkout_zone_applicable_states'),
              dataType: 'json'
            }).done(function(data) {
              var json = data.included;
              var xStates = [];
              for (var i = 0; i &lt; json.length; i++) {
                var obj = json[i];
                xStates.push({
                  id: obj.id,
                  name: obj.attributes.name
                })
              }
              Spree.Checkout[countryId] = {
                states: xStates,
                states_required: data.data.attributes.states_required,
                zipcode_required: data.data.attributes.zipcode_required
              }
              Spree.fillStates(Spree.Checkout[countryId], region)
              Spree.toggleZipcode(Spree.Checkout[countryId], region)
            })
          } else {
            Spree.fillStates(Spree.Checkout[countryId], region)
            Spree.toggleZipcode(Spree.Checkout[countryId], region)
          }
        }
      }

      Spree.toggleZipcode = function(data, region) {
        var requiredIndicator = $('span#required_marker').first().text()
        var zipcodeRequired = data.zipcode_required
        var zipcodePara = $('#' + region + 'zipcode')
        var zipcodeInput = zipcodePara.find('input')
        var zipcodeLabel = zipcodePara.find('label')
        var zipcodeLabelText = zipcodeInput.attr('aria-label')

        if (zipcodeRequired) {
          var zipText = zipcodeLabelText + ' ' + requiredIndicator
          zipcodeInput.prop('required', true).attr('placeholder', zipText)
          zipcodeLabel.text('')
          zipcodeLabel.text(zipText)
          zipcodeInput.addClass('required')
        } else {
          zipcodeInput.prop('required', false).attr('placeholder', zipcodeLabelText)
          zipcodeLabel.text('')
          zipcodeLabel.text(zipcodeLabelText)
          zipcodeInput.removeClass('required')
        }
      }

      Spree.fillStates = function(data, region) {
        var selected
        var statesRequired = data.states_required
        var states = data.states
        var statePara = $('#' + region + 'state')
        var stateSelect = statePara.find('select')
        var stateInput = statePara.find('input')
        var stateLabel = statePara.find('label')
        var stateSelectImg = statePara.find('img')
        var stateSpanRequired = statePara.find('abbr')

        if (states.length &gt; 0) {
          selected = parseInt(stateSelect.val())
          stateSelect.html('')
          $.each(states, function(idx, state) {
            var opt = $(document.createElement('option')).attr('value', state.id).html(state.name)
            if (selected.toString(10) === state.id.toString(10)) {
              opt.prop('selected', true)
            }
            stateSelect.append(opt)
          })
          // If States are listed for the Country selected kill the input field
          stateInput.hide()
            .prop('disabled', true)
            .prop('required', false)
            .val('')

          // Activate the State select dropdown.
          statePara.show()
          stateSelect.prop('required', statesRequired)
            .prop('disabled', false)
            .show()
          stateSelectImg.show()
          stateLabel.addClass('state-select-label')
          stateSpanRequired.toggle(statesRequired)
        } else {
          // If no States are listed in the database for the country selected
          // and a State is not required =&gt; (United Kingdom).
          // Kill the State selector and input field.
          stateSelectImg.hide()
          stateSelect.hide()
            .prop('disabled', true)
            .prop('required', false)
            .find('option').remove()

          stateInput.prop('disabled', true)
            .prop('required', false)
            .hide()

          // Toggle visibility of States parent element based on State required.
          statePara.toggle(statesRequired)

          if (statesRequired) {
            // If a State is required, but none are listed in the database
            // for the country selected =&gt; (Hong Kong)
            // Enable the State input field, set it to required.
            stateInput.show()
              .prop('disabled', false)
              .prop('required', true)
            stateSpanRequired.show()
            stateLabel.removeClass('state-select-label') // required for floating label
          }
        }
      }
      $('#bcountry select').change(function() {
        Spree.updateState('b')
      })
      $('#scountry select').change(function() {
        Spree.updateState('s')
      })
      Spree.updateState('b')

      var orderUseBilling = $('input#order_use_billing')
      orderUseBilling.change(function() {
        updateShippingFormState(orderUseBilling)
      })
      updateShippingFormState(orderUseBilling)
    }

    function updateShippingFormState(orderUseBilling) {
      if (orderUseBilling.is(':checked')) {
        $('#shipping .inner').hide()
        $('#shipping .inner input, #shipping .inner select').prop('disabled', true)
      } else {
        $('#shipping .inner').show()
        $('#shipping .inner input, #shipping .inner select').prop('disabled', false)
        Spree.updateState('s')
      }
    }

    function getCountryId(region) {
      return $('#' + region + 'country select').val()
    }
  }
  Spree.onAddress()
});
Spree.ready(function ($) {
  if ($('.select_address').length &gt; 0) {
    $('input#order_use_billing').unbind('change');

    hide_address_form('billing');
    hide_address_form('shipping');

    if ($('input#order_use_billing').is(':checked')) {
      $('#shipping .select_address').hide()
    }

    $('input#order_use_billing').click(function () {
      if ($(this).is(':checked')) {
        $('#shipping .select_address').hide()
        hide_address_form('shipping')
      } else {
        $('#shipping .select_address').show()
        if ($("input[name='order[ship_address_id]']:checked").val() == '0') {
          show_address_form('shipping')
        } else {
          hide_address_form('shipping')
        }
      }
    });

    $("input[name='order[bill_address_id]']:radio").change(function () {
      if ($("input[name='order[bill_address_id]']:checked").val() == '0') {
        show_address_form('billing')
      } else {
        hide_address_form('billing')
      }
    });

    $("input[name='order[ship_address_id]']:radio").change(function () {
      if ($("input[name='order[ship_address_id]']:checked").val() == '0') {
        show_address_form('shipping')
      } else {
        hide_address_form('shipping')
      }
    })
  }

  function hide_address_form(address_type) {
    $('#' + address_type + ' .inner').hide();
    $('#' + address_type + ' .inner input').prop('disabled', true)
    $('#' + address_type + ' .inner select').prop('disabled', true)
  }

  function show_address_form(address_type) {
    $('#' + address_type + ' .inner').show();
    $('#' + address_type + ' .inner input').prop('disabled', false)
    $('#' + address_type + ' .inner select').prop('disabled', false)
  }
});
/* global Cleave */
var CARD_NUMBER_SELECTOR = '.cardNumber'
var CARD_EXPIRATION_SELECTOR = '.cardExpiry'
var CARD_CODE_SELECTOR = '.cardCode'

//= require spree/frontend/coupon_manager
Spree.ready(function ($) {
  Spree.onPayment = function () {
    if ($('#checkout_form_payment').length) {
      if ($('#existing_cards').length) {
        $('#payment-methods').hide()
        $('.existing-cc-radio').click(function () {
          $(this).prop('checked', true)
          $('#use_existing_card_no').prop('checked', false)
          $('#use_existing_card_yes').prop('checked', true)
          $('#payment-methods').hide()
          Spree.enableSave()
        })
        $('#use_existing_card_no').click(function () {
          $('#payment-methods').show()
          $('.existing-cc-radio').prop('checked', false)
          $('#use_existing_card_yes').prop('checked', false)
          Spree.enableSave()
        })
      }

      if ($(CARD_NUMBER_SELECTOR).length &gt; 0 &amp;&amp;
          $(CARD_EXPIRATION_SELECTOR).length &gt; 0 &amp;&amp;
          $(CARD_CODE_SELECTOR).length &gt; 0) {
        var cardCodeCleave;
        var updateCardCodeCleave = function (length) {
          if (cardCodeCleave) cardCodeCleave.destroy()

          cardCodeCleave = new Cleave(CARD_CODE_SELECTOR, {
            numericOnly: true,
            blocks: [length]
          })
        }

        updateCardCodeCleave(3)

        /* eslint-disable no-new */
        new Cleave(CARD_NUMBER_SELECTOR, {
          creditCard: true,
          onCreditCardTypeChanged: function (type) {
            $('.ccType').val(type)

            if (type === 'amex') {
              updateCardCodeCleave(4)
            } else {
              updateCardCodeCleave(3)
            }
          }
        })
        /* eslint-disable no-new */
        new Cleave(CARD_EXPIRATION_SELECTOR, {
          date: true,
          datePattern: ['m', 'Y']
        })
      }

      $('input[type="radio"][name="order[payments_attributes][][payment_method_id]"]').click(function () {
        $('#payment-methods').hide()
        $('.payment-sources').hide()
        Spree.enableSave()
        if ($('#payment_method_' + this.value).find('fieldset').children().length !== 0) {
          if (this.closest('label').dataset.type === 'card') {
            if ($('#existing_cards').length) {
              $('.existing-cc-radio').first().prop('checked', true);
              $('#use_existing_card_no').prop('checked', false)
              $('#use_existing_card_yes').prop('checked', true)
              $('#existing_cards').show();
              $('#payment-methods').hide();
              $('.payment-sources').show()
            }
          } else {
            $('.existing-cc-radio').prop('checked', false);
            $('#use_existing_card_no').prop('checked', false);
            $('#existing_cards').hide();
            $('#payment-methods').show();
            $('.payment-sources').show()
          }
        }
        $('#payment-methods li').hide()
        if (this.checked) {
          $('#payment_method_' + this.value).show()
        }
      })
      $(document).on('click', '#cvv_link', function (event) {
        var windowName = 'cvv_info'
        var windowOptions = 'left=20,top=20,width=500,height=500,toolbar=0,resizable=0,scrollbars=1'
        window.open($(this).attr('href'), windowName, windowOptions)
        event.preventDefault()
      })
      $('input[type="radio"]:checked').click()
      $('#checkout_form_payment').submit(function (event) {
        var input = {
          couponCodeField: $('#order_coupon_code'),
          couponStatus: $('#coupon_status')
        }
        if ($.trim(input.couponCodeField.val()).length &gt; 0) {
          // eslint-disable-next-line no-undef
          if (new CouponManager(input).applyCoupon()) {
            return true
          } else {
            Spree.enableSave()
            event.preventDefault()
            return false
          }
        }
      })
    }
  }
  Spree.onPayment()
});
/* global accounting */
function ShippingTotalManager (input1) {
  this.input = input1
  this.shippingMethods = this.input.shippingMethods
  this.shipmentTotal = this.input.shipmentTotal
  this.isFreeShipping = this.input.isFreeShipping
  this.taxTotal = this.input.taxTotal
  this.nonShipmentTax = $(this.taxTotal).data('non-shipment-tax')
  this.orderTotal = this.input.orderTotal
  this.formatOptions = {
    symbol: this.shipmentTotal.data('currency'),
    decimal: this.shipmentTotal.attr('decimal-mark'),
    thousand: this.shipmentTotal.attr('thousands-separator'),
    precision: this.shipmentTotal.attr('precision')
  }
}

ShippingTotalManager.prototype.calculateShipmentTotal = function () {
  var checked = $(this.shippingMethods).filter(':checked')
  this.sum = 0
  this.tax = this.parseCurrencyToFloat(this.nonShipmentTax)
  $.each(checked, function (idx, shippingMethod) {
    this.sum += this.parseCurrencyToFloat($(shippingMethod).data('cost'))
    this.tax += this.parseCurrencyToFloat($(shippingMethod).data('tax'))
  }.bind(this))
  return this.readjustSummarySection(
    this.parseCurrencyToFloat(this.orderTotal.html()),
    this.sum,
    this.parseCurrencyToFloat(this.shipmentTotal.html()),
    this.tax,
    this.parseCurrencyToFloat(this.taxTotal.html())
  )
}

ShippingTotalManager.prototype.parseCurrencyToFloat = function (input) {
  return accounting.unformat(input, this.formatOptions.decimal)
}

ShippingTotalManager.prototype.totalShipmentAmount = function (newShipmentTotal, oldShipmentTotal) {
  var totalShipmentAmount = 0;
  if (!this.isFreeShipping.html()) {
    totalShipmentAmount = newShipmentTotal - oldShipmentTotal

    return totalShipmentAmount
  } else {
    return totalShipmentAmount
  }
}

ShippingTotalManager.prototype.readjustSummarySection = function (orderTotal, newShipmentTotal, oldShipmentTotal, newTaxTotal, oldTaxTotal) {
  var newOrderTotal = orderTotal + this.totalShipmentAmount(newShipmentTotal, oldShipmentTotal) + (newTaxTotal - oldTaxTotal)
  this.taxTotal.html(accounting.formatMoney(newTaxTotal, this.formatOptions))
  this.shipmentTotal.html(accounting.formatMoney(newShipmentTotal, this.formatOptions))
  return this.orderTotal.html(accounting.formatMoney(accounting.toFixed(newOrderTotal, 10), this.formatOptions))
}

ShippingTotalManager.prototype.bindEvent = function () {
  this.shippingMethods.change(function () {
    return this.calculateShipmentTotal()
  }.bind(this))
}

Spree.ready(function ($) {
  var input = {
    orderTotal: $('#summary-order-total'),
    taxTotal: $('[data-hook="tax-total"]'),
    shipmentTotal: $('[data-hook="shipping-total"]'),
    shippingMethods: $('input[data-behavior="shipping-method-selector"]'),
    isFreeShipping: $('[data-hook="is-free-shipping"]')
  }
  return new ShippingTotalManager(input).bindEvent()
});
$.fn.isInViewport = function () {
  var elementTop = $(this).offset().top
  var elementBottom = elementTop + $(this).outerHeight()
  var viewportTop = $(window).scrollTop()
  var viewportBottom = viewportTop + $(window).height()
  return elementBottom &gt; viewportTop &amp;&amp; elementTop &lt; viewportBottom
};

Spree.fetchProductCarousel = function (taxonId, htmlContainer) {
  return $.ajax({
    url: Spree.routes.product_carousel(taxonId)
  }).done(function (data) {
    htmlContainer.html(data);
    htmlContainer.find('.carousel').carouselBootstrap4()
  })
}

Spree.loadCarousel = function (element, div) {
  var container = $(element)
  var productCarousel = $(div)
  var carouselLoaded = productCarousel.attr('data-product-carousel-loaded')

  if (container.length &amp;&amp; !carouselLoaded &amp;&amp; container.isInViewport()) {
    var taxonId = productCarousel.attr('data-product-carousel-taxon-id')
    productCarousel.attr('data-product-carousel-loaded', 'true')

    Spree.fetchProductCarousel(taxonId, container)
  }
}

Spree.loadsCarouselElements = function () {
  $('div[data-product-carousel-taxon-id]').each(function (_index, element) { Spree.loadCarousel(element, this) })
}

document.addEventListener('turbolinks:load', function () {
  var carouselPresent = $('div[data-product-carousel-taxon-id]')

  if (carouselPresent.length) {
    // load Carousels straight away if they are in the viewport
    Spree.loadsCarouselElements()

    // load additional Carousels when scrolling down
    $(window).on('resize scroll', function () {
      Spree.loadsCarouselElements()
    })
  }
});
Spree.ready(function ($) {
  document.getElementById('overlay').addEventListener('click', function () {
    var noProductElement = document.getElementById('no-product-available')
    document.getElementById("overlay").classList.remove('shown');
    document.getElementById("search-dropdown").classList.remove('shown');
    document.querySelector('.header-spree').classList.remove('above-overlay')
    if (noProductElement) noProductElement.classList.remove('shown');
  }, false);

  document.onkeydown = function(evt) {
    var searchMenuElement = document.getElementsByClassName("navbar-right-search-menu")

    if (searchMenuElement.length === 1) {
      evt = evt || window.event;
      var isEscape = false;
      var isOpenSearchInput = searchMenuElement[0].classList.contains("shown")

      if (isOpenSearchInput)
        return;

      if ("key" in evt) {
        isEscape = (evt.key === "Escape" || evt.key === "Esc");
      } else {
        isEscape = (evt.keyCode === 27);
      }
      if (isEscape) {
        document.querySelector(".navbar-right-dropdown-toggle").blur();
        document.getElementById("overlay").classList.remove('shown');
        document.querySelector('.header-spree').classList.remove('above-overlay')
        document.getElementById("search-dropdown").classList.remove('shown');
        $('.hide-on-esc').toggleClass('shown', false)
      }
    }
  };

  var searchDropdown = document.getElementById('search-dropdown')
  var navBarCategoryLinks = document.getElementsByClassName('main-nav-bar-category-links')
  var navBarCategoryButtons = document.getElementsByClassName('main-nav-bar-category-button')
  var navBarCategoryImages = document.getElementsByClassName('category-image')
  var navBarAccountIcon = [document.getElementById('account-button')]
  var navBarCartIcon = [document.getElementById('link-to-cart')]
  var spreeLogoImage = document.getElementsByClassName('header-spree-fluid-logo')
  var spreeMobileNavs = document.getElementsByClassName('mobile-navigation-list-item')
  var navbarLinks = [
    navBarCategoryLinks,
    navBarCategoryButtons,
    navBarCategoryImages,
    navBarAccountIcon,
    navBarCartIcon,
    spreeLogoImage,
    spreeMobileNavs
  ]

  if (searchDropdown !== null) {
    $.each(navbarLinks, function(index, navbarElements) {
      $.each(navbarElements, function(index, navBarCategoryLink) {
        navBarCategoryLink.addEventListener('click', function () {
          document.getElementById('overlay').classList.remove('shown');
          searchDropdown.classList.remove('shown');
          document.querySelector('.header-spree').classList.remove('above-overlay')
        });
      });
    });
  };
});

Spree.fetchRelatedProducts = function (id, htmlContainer) {
  return $.ajax({
    url: Spree.routes.product_related(id)
  }).done(function (data) {
    htmlContainer.html(data)
    htmlContainer.find('.carousel').carouselBootstrap4()
  })
}

document.addEventListener('turbolinks:load', function () {
  var productDetailsPage = $('body#product-details')

  if (productDetailsPage.length) {
    var productId = $('div[data-related-products]').attr('data-related-products-id')
    var relatedProductsEnabled = $('div[data-related-products]').attr('data-related-products-enabled')
    var relatedProductsFetched = false
    var relatedProductsContainer = $('#related-products')

    if (!relatedProductsFetched &amp;&amp; relatedProductsContainer.length &amp;&amp; relatedProductsEnabled &amp;&amp; relatedProductsEnabled === 'true' &amp;&amp; productId !== '') {
      $(window).on('resize scroll', function () {
        if (!relatedProductsFetched &amp;&amp; relatedProductsContainer.isInViewport()) {
          Spree.fetchRelatedProducts(productId, relatedProductsContainer)
          relatedProductsFetched = true
        }
      })
    }
  }
});

SpreeAPI.Storefront.createCart = function (successCallback, failureCallback) {
  fetch(Spree.routes.api_v2_storefront_cart_create, {
    method: 'POST',
    headers: SpreeAPI.prepareHeaders()
  }).then(function (response) {
    switch (response.status) {
      case 422:
        response.json().then(function (json) { failureCallback(json.error) })
        break
      case 500:
        SpreeAPI.handle500error()
        break
      case 201:
        response.json().then(function (json) {
          SpreeAPI.orderToken = json.data.attributes.token
          successCallback()
        })
        break
    }
  })
}

SpreeAPI.Storefront.addToCart = function (variantId, quantity, options, successCallback, failureCallback) {
  fetch(Spree.routes.api_v2_storefront_cart_add_item, {
    method: 'POST',
    headers: SpreeAPI.prepareHeaders({ 'X-Spree-Order-Token': SpreeAPI.orderToken }),
    body: JSON.stringify({
      variant_id: variantId,
      quantity: quantity,
      options: options
    })
  }).then(function (response) {
    switch (response.status) {
      case 422:
        response.json().then(function (json) { failureCallback(json.error) })
        break
      case 500:
        SpreeAPI.handle500error()
        break
      case 200:
        response.json().then(function (json) {
          successCallback(json.data)
        })
        break
    }
  })
};
Spree.showProductAddedModal = function(product, variant) {
  var modalSelector = '.product-added-modal'
  var nameSelector = '.product-added-modal-product-details-name'
  var priceSelector = '.product-added-modal-product-details-price'
  var imageSelector = '.product-added-modal-product-image-container-image'
  var modalNoImageClass = 'product-added-modal--no-image'

  var price = variant.display_price
  var images = variant &amp;&amp; variant.images.length &gt; 0 ? variant.images : product.images
  var name = product.name
  var leadImage = images.length === 0 ? null : images[0]
  var $modal = $(modalSelector)

  $modal.find(nameSelector).text(name)
  $modal.find(priceSelector).html(price)

  if (leadImage !== null) {
    $modal
      .removeClass(modalNoImageClass)
      .find(imageSelector)
      .attr('src', leadImage.url_product)
      .attr('alt', leadImage.alt || name)
  } else {
    $modal.addClass(modalNoImageClass)
  }

  $modal.modal()
}

Spree.hideProductAddedModal = function() {
  var modalSelector = '.product-added-modal'
  var $modal = $(modalSelector)

  $modal.modal('hide')
};
var getQueryString = window.location.search
var urlParams = new URLSearchParams(getQueryString)
var variantIdFromUrl = urlParams.get('variant')

this.initializeQueryParamsCheck = function () {
  if (urlParams.has('variant')) verifyVariantIdMatch()
}

function verifyVariantIdMatch() {
  this.variants.forEach(function(variant) {
    if (parseInt(variant.id) === parseInt(variantIdFromUrl)) this.urlQueryMatchFound = true
  })
}

this.setSelectedVariantFromUrl = function () {
  this.selectedOptions = []

  this.getVariantOptionsById(variantIdFromUrl)
  this.sortArrayByOptionTypeIndex(this.selectedOptions)
  this.clickListOptions(this.selectedOptions)
  this.updateStructuredData()
}

this.getVariantOptionsById = function(variantIdFromUrl) {
  this.variants.forEach(function(variant) {
    if (parseInt(variant.id) === parseInt(variantIdFromUrl)) this.sortOptionValues(variant.option_values)
  })
}

this.sortOptionValues = function(optVals) {
  optVals.forEach(buildArray)
}

function buildArray(item) {
  var container = document.querySelector('ul#product-variants')
  var target = container.querySelectorAll('.product-variants-variant-values-radio')

  target.forEach(function(inputTag) {
    if (parseInt(inputTag.value) === item.id &amp;&amp; inputTag.dataset.presentation === item.presentation) {
      this.selectedOptions.push(inputTag)
    }
  })
}

this.sortArrayByOptionTypeIndex = function (arrayOfOptions) {
  arrayOfOptions.sort(function (a, b) {
    return a.dataset.optionTypeIndex &gt; b.dataset.optionTypeIndex ? 1 : -1;
  })
}

this.clickListOptions = function(list) {
  list.forEach(function (item) {
    item.checked = true
    var $optionListItem = $(item)
    this.applyCheckedOptionValue($optionListItem)
  })
}

this.updateStructuredData = function() {
  var variant = this.selectedVariant()
  var host = window.location.host
  var schemaData = document.body.querySelector("script[type='application/ld+json']")
  var obj = JSON.parse(schemaData.firstChild.nodeValue)
  var firstLayer = obj[0]
  var offers = obj[0].offers

  if (variant.purchasable) {
    offers.availability = 'InStock'
  } else {
    offers.availability = 'OutOfStock'
  }

  if (variant.sku.length &gt; 1) {
    firstLayer.sku = variant.sku
  }

  firstLayer.url = window.location.href
  offers.url = window.location.href
  offers.price = variant.price.amount

  if (Array.isArray(variant.images) &amp;&amp; (variant.images.length)) {
    firstLayer.image = host + variant.images[0].url_product
  }

  schemaData.firstChild.nodeValue = JSON.stringify(obj)
}

this.initializeColorVarianTooltip = function() {
  var colorVariants = $('.color-select-label[data-toggle="tooltip"]')
  colorVariants.tooltip({
    placement: 'bottom'
  })
};




var ADD_TO_CART_FORM_SELECTOR = '.add-to-cart-form'
var VARIANT_ID_SELECTOR = '[name="variant_id"]'
var OPTION_VALUE_SELECTOR = '.product-variants-variant-values-radio'
var ADD_TO_CART_SELECTOR = '.add-to-cart-button'

var AVAILABILITY_TEMPLATES = {
  notAvailableInCurrency: '.availability-template-not-available-in-currency',
  inStock: '.availability-template-in-stock',
  backorderable: '.availability-template-backorderable',
  outOfStock: '.availability-template-out-of-stock'
}

function CartForm($, $cartForm) {
  this.constructor = function() {
    this.initialize()
    this.bindEventHandlers()
  }

  this.initialize = function() {
    this.urlQueryMatchFound = false
    this.selectedOptionValueIds = []
    this.variants = JSON.parse($cartForm.attr('data-variants'))
    this.withOptionValues = Boolean($cartForm.find(OPTION_VALUE_SELECTOR).length)

    this.$addToCart = $cartForm.find(ADD_TO_CART_SELECTOR)
    this.$price = $cartForm.find('.price.selling')
    this.$compareAtPrice = $cartForm.find('.compare-at-price')
    this.$variantIdInput = $cartForm.find(VARIANT_ID_SELECTOR)

    this.initializeQueryParamsCheck()
    this.initializeColorVarianTooltip()

    if (this.urlQueryMatchFound) {
      this.setSelectedVariantFromUrl()
    } else {
      this.initializeForm()
    }
  }

  this.initializeForm = function() {
    if (this.withOptionValues) {
      var $optionValue = this.firstCheckedOptionValue()
      this.applyCheckedOptionValue($optionValue, true)
      var singleOptionValues = this.getSingleOptionValuesFromEachOptionType()
      if (singleOptionValues.length) {
        singleOptionValues.forEach(function($value) {
          this.applyCheckedOptionValue($value, true)
        })
      }
    } else {
      this.updateAddToCart()
      this.triggerVariantImages()
    }
  }

  this.bindEventHandlers = function() {
    $cartForm.on('click', OPTION_VALUE_SELECTOR, this.handleOptionValueClick)
  }

  this.handleOptionValueClick = function(event) {
    var currentTarget = $(event.currentTarget)
    this.applyCheckedOptionValue(currentTarget)
    currentTarget.blur()
  }.bind(this)

  this.applyCheckedOptionValue = function($optionValue, initialUpdate) {
    this.saveCheckedOptionValue($optionValue)
    this.showAvailableVariants()
    this.updateAddToCart()
    // we don't want to remove availability status on initial page load
    if (!initialUpdate) this.updateVariantAvailability()
    this.updateVariantPrice()
    this.updateVariantId()

    if (this.shouldTriggerVariantImage($optionValue)) {
      this.triggerVariantImages()
    }

    if (initialUpdate) $optionValue.prop('checked', true)
  }

  this.saveCheckedOptionValue = function($optionValue) {
    var optionTypeIndex = $optionValue.data('option-type-index')

    this.selectedOptionValueIds.splice(
      optionTypeIndex,
      this.selectedOptionValueIds.length,
      parseInt($optionValue.val())
    )
  }

  this.showAvailableVariants = function() {
    var availableOptionValueIds = this.availableOptionValueIds()
    var selectedOptionValueIdsCount = this.selectedOptionValueIds.length

    this.optionTypes().each(function(index, optionType) {
      if (index &lt; selectedOptionValueIdsCount) return

      $(optionType)
        .find(OPTION_VALUE_SELECTOR)
        .each(function(_index, ov) {
          var $ov = $(ov)
          var id = parseInt($ov.val())

          $ov.prop('checked', false)
          $ov.prop('disabled', !availableOptionValueIds.includes(id))
        })
    })
  }

  this.optionTypes = function() {
    return $cartForm.find('.product-variants-variant')
  }

  this.availableOptionValueIds = function() {
    var selectedOptionValueIds = this.selectedOptionValueIds

    return this.variants.reduce(function(acc, variant) {
      var optionValues = variant.option_values.map(function(ov) {
        return ov.id
      })

      var isPossibleVariantFound = selectedOptionValueIds.every(function(ov) {
        return optionValues.includes(ov)
      })

      if (isPossibleVariantFound) {
        return acc.concat(optionValues)
      }

      return acc
    }, [])
  }

  this.firstCheckedOptionValue = function() {
    return $cartForm.find(OPTION_VALUE_SELECTOR + '[data-option-type-index=0]' + ':checked')
  }

  this.getSingleOptionValuesFromEachOptionType = function() {
    var singleOptionValues = []
    this.optionTypes().each(function(_, optionType) {
      var $optionValues = $(optionType).find(OPTION_VALUE_SELECTOR)
      if ($optionValues.length === 1) {
        singleOptionValues.push($optionValues.first())
      }
    })
    return singleOptionValues
  }

  this.shouldTriggerVariantImage = function($optionValue) {
    return $optionValue.data('is-color') || !this.firstCheckedOptionValue().data('is-color')
  }

  this.triggerVariantImages = function() {
    var checkedVariantId
    var variant = this.selectedVariant()

    if (variant) {
      checkedVariantId = variant.id
    } else {
      checkedVariantId = this.firstCheckedOptionValue().data('variant-id')
    }

    // Wait for listeners to attach.
    setTimeout(function() {
      $cartForm.trigger({
        type: 'variant_id_change',
        triggerId: $cartForm.attr('data-variant-change-trigger-identifier'),
        variantId: checkedVariantId + ''
      })
    })
  }

  this.selectedVariant = function() {
    var self = this

    if (!this.withOptionValues) {
      return this.variants.find(function(variant) {
        return variant.id === parseInt(self.$variantIdInput.val())
      })
    }

    if (this.variants.length === 1 &amp;&amp; this.variants[0].is_master) {
      return this.variants[0]
    }

    return this.variants.find(function(variant) {
      var optionValueIds = variant.option_values.map(function(ov) {
        return ov.id
      })

      return self.areArraysEqual(optionValueIds, self.selectedOptionValueIds)
    })
  }

  this.areArraysEqual = function(array1, array2) {
    return this.sortArray(array1).join(',') === this.sortArray(array2).join(',')
  }

  this.sortArray = function(array) {
    return array.concat().sort(function(a, b) {
      if (a &lt; b) return -1
      if (a &gt; b) return 1

      return 0
    })
  }

  this.updateAddToCart = function() {
    var variant = this.selectedVariant()

    this.$addToCart.prop('disabled', variant ? !variant.purchasable : true)
  }

  this.availabilityMessage = function(variant) {
    if (!variant.is_product_available_in_currency) {
      return $(AVAILABILITY_TEMPLATES.notAvailableInCurrency).html()
    }

    if (variant.in_stock) {
      return $(AVAILABILITY_TEMPLATES.inStock).html()
    }

    if (variant.backorderable) {
      return $(AVAILABILITY_TEMPLATES.backorderable).html()
    }

    return $(AVAILABILITY_TEMPLATES.outOfStock).html()
  }

  this.updateVariantAvailability = function() {
    var variant = this.selectedVariant()

    if (!variant) {
      return $cartForm
        .find('.add-to-cart-form-general-availability .add-to-cart-form-general-availability-value')
        .html('')
    }

    return $cartForm
      .find('.add-to-cart-form-general-availability .add-to-cart-form-general-availability-value')
      .html(this.availabilityMessage(variant))
  }

  this.updateVariantPrice = function() {
    var variant = this.selectedVariant()

    if (!variant) return

    var shouldDisplayCompareAtPrice = variant.should_display_compare_at_price

    this.$price.html(variant.display_price)

    var compareAtPriceContent = shouldDisplayCompareAtPrice ? variant.display_compare_at_price : ''
    this.$compareAtPrice.html(compareAtPriceContent)
  }

  this.updateVariantId = function() {
    var variant = this.selectedVariant()
    var variantId = (variant &amp;&amp; variant.id) || ''

    this.$variantIdInput.val(variantId)
  }

  this.constructor()
}

Spree.ready(function($) {
  Spree.variantById = function($cartForm, variantId) {
    var cartFormVariants = JSON.parse($cartForm.attr('data-variants'))
    return (
      cartFormVariants.find(function(variant) {
        return variant.id.toString() === variantId
      }) || null
    )
  }

  Spree.addToCartFormSubmissionOptions = function() {
    return {};
  }

  $('#product-details').on('submit', ADD_TO_CART_FORM_SELECTOR, function(event) {
    var $cartForm = $(event.currentTarget);
    var $addToCart = $cartForm.find(ADD_TO_CART_SELECTOR);
    var variantId = $cartForm.find(VARIANT_ID_SELECTOR).val();
    var quantity = parseInt($cartForm.find('[name="quantity"]').val());
    var options = Spree.addToCartFormSubmissionOptions();

    event.preventDefault()
    $addToCart.prop('disabled', true);
    Spree.ensureCart(function() {
      SpreeAPI.Storefront.addToCart(
        variantId,
        quantity,
        options, // options hash - you can pass additional parameters here, your backend
        // needs to be aware of those, see API docs:
        // https://github.com/spree/spree/blob/master/api/docs/v2/storefront/index.yaml#L42
        function(response) {
          $addToCart.prop('disabled', false)
          Spree.fetchCart()
          Spree.showProductAddedModal(JSON.parse(
            $cartForm.attr('data-product-summary')
          ), Spree.variantById($cartForm, variantId))
          $cartForm.trigger({
            type: 'product_add_to_cart',
            variant: Spree.variantById($cartForm, variantId),
            quantity_increment: quantity,
            cart: response.attributes
          })
        },
        function(error) {
          if (typeof error === 'string' &amp;&amp; error !== '') {
            document.querySelector('#no-product-available .no-product-available-text').innerText = error
          }
          document.getElementById('overlay').classList.add('shown')
          document.getElementById('no-product-available').classList.add('shown')
          window.scrollTo(0, 0)
          $addToCart.prop('disabled', false)
        } // failure callback for 422 and 50x errors
      )
    })
  })

  $(ADD_TO_CART_FORM_SELECTOR).each(function(_cartFormIndex, cartFormElement) {
    var $cartForm = $(cartFormElement)

    CartForm($, $cartForm)
  })

  document.addEventListener('turbolinks:request-start', function () {
    Spree.hideProductAddedModal()
  })
});
/*
	jQuery Extended Mag(nify)
	Author: Caleb O'Leary
	Site: http://caleboleary.com
	Current Version: https://github.com/caleboleary/jQuery-Extended-Mag
	MIT License
*/
(function($){
	"use strict";
	$.fn.extend({
		extm: function extm(userOptions) {
			//merge default and user options to 'options' var
			var defaultOptions = {
				zoomElement: false,
				imageSrc: $(this).attr('src'),
				squareOverlay: false,
				position: false,
				rightPad:0,
				lazy: false,
				zoomLevel:1,
				zoomSize:false,
				loadingText:false,
				loadingImage:false
			};
			var options = $.extend({},defaultOptions,userOptions || {});
			function extmInit(options, imageElement) {
				var smallWidth = imageElement.width();
				var smallHeight = imageElement.height();
				var offset = imageElement.offset();
				var zoomElement;
				if (!options.zoomElement) {
					zoomElement = $( "&lt;div style='overflow:hidden;pointer-events:none;height:"+smallHeight+"px;width:"+smallWidth+"px;' class='extm'&gt;&lt;/div&gt;" );
					if (options.position === 'right') {
						zoomElement.appendTo( $('body') );
						zoomElement.css("position","absolute");
						zoomElement.css("top",offset.top);
						zoomElement.css("left",offset.left+smallWidth+options.rightPad);
					}
					else if (options.position === 'overlay') {
						zoomElement.appendTo( $('body') );
						zoomElement.css("position","absolute");
						zoomElement.css("top",offset.top);
						zoomElement.css("left",offset.left);
					}				
					else{
						zoomElement.insertAfter( imageElement );
					}
				}
				else {
					zoomElement = options.zoomElement;
				}
        		var overlayElement;
        		var innerOverlayElement;
				if (options.squareOverlay) {
					overlayElement = $( "&lt;div class='overlayElement' style='pointer-events:none;height:"+smallHeight+"px;width:"+smallWidth+"px;position:absolute;top:"+offset.top+"px;left:"+offset.left+"px;'&gt;&lt;/div&gt;" );
					$('body').append( overlayElement );
					innerOverlayElement = $("&lt;div style='background-color:rgba(0,0,0,0.2);position:absolute;' class='innerOverlay'&gt;&lt;/div&gt;");
					overlayElement.append(innerOverlayElement);
				}
				if (!options.lazy) {
					zoomElement.css("visibility","hidden"); //hide zoom holder
					if (options.squareOverlay) {
						innerOverlayElement.css("visibility","hidden"); //hide zoom holder
					}
				}
				if (options.zoomSize) {
					var fullSizeImage = $('&lt;img style="position:relative;max-width:none;width:'+options.zoomSize+'px;"&gt;'); //make a large clone and insert it
				}
				else if (options.zoomLevel !== 1) {
					var fullSizeImage = $('&lt;img style="position:relative;max-width:none;width:'+(100*options.zoomLevel)+'%;"&gt;'); //make a large clone and insert it
				}
				else {
					var fullSizeImage = $('&lt;img style="position:relative;max-width:none;"&gt;'); //make a large clone and insert it
				}
				if (options.imageSrc) {
					fullSizeImage.attr('src', options.imageSrc);
				}
				else {
					fullSizeImage.attr('src', imageElement.attr('src'));
				}

				fullSizeImage.appendTo(zoomElement);			
				//using this closure to make sure the function gets the right 'imageElement' - in case there are many zooms per page
				(function(imageElement,zoomElement,fullSizeImage,overlayElement,smallHeight,smallWidth,offset, innerOverlayElement,options) {

					//while we wait for fullsize to load...
					if (options.loadingText){
						var loadingElement = $( "&lt;div class='loadingElement' style='pointer-events:none;height:"+smallHeight+"px;width:"+smallWidth+"px;font-family:sans-serif;position:absolute;top:"+offset.top+"px;left:"+offset.left+"px;visibility:hidden;background:rgba(255,255,255,0.5);color:black;font-size:2em;font-weight:bold;text-align:center;'&gt;&lt;p style='position: absolute; left: 50%;top: 50%;transform: translate(-50%, -50%);'&gt;"+options.loadingText+"&lt;/p&gt;&lt;/div&gt;" );
						$('body').append( loadingElement );
						imageElement.on('mouseenter', function(){
							loadingElement.css("visibility","visible");
						});
						imageElement.on('mouseleave', function(){
							loadingElement.css("visibility","hidden");
						});
						if (imageElement.is(':hover')) {
							imageElement.trigger("mouseenter");
						}
					}
					else if (options.loadingImage) {
						var loadingElement = $( "&lt;div class='loadingElement' style='pointer-events:none;height:"+smallHeight+"px;width:"+smallWidth+"px;font-family:sans-serif;position:absolute;top:"+offset.top+"px;left:"+offset.left+"px;visibility:hidden;background:rgba(255,255,255,0.5);color:black;font-size:2em;font-weight:bold;text-align:center;'&gt;&lt;img style='position: absolute; left: 50%;top: 50%;transform: translate(-50%, -50%);' src='"+options.loadingImage+"'/&gt;&lt;/div&gt;" );
						$('body').append( loadingElement );
						imageElement.on('mouseenter', function(){
							loadingElement.css("visibility","visible");
						});
						imageElement.on('mouseleave', function(){
							loadingElement.css("visibility","hidden");
						});
						if (imageElement.is(':hover')) {
							imageElement.trigger("mouseenter");
						}
					}

					fullSizeImage.on('load', function(){

						if (options.loadingText || options.loadingImage){
							//remove our loading stuff
							imageElement.trigger("mouseleave");
							imageElement.unbind('mouseenter mouseleave');
							loadingElement.remove();
						}

						imageElement.on('mouseenter', function(){ //show/hide functionality
							//before we show the zoom element, lets make sure everything is still lined up 
							//this is here in case things have moved since init, like if the user changed their browser width and things shuffled
							offset = imageElement.offset();
							if (options.position === 'right') {
								zoomElement.css("top",offset.top);
								zoomElement.css("left",offset.left+smallWidth+options.rightPad);
							}
							else if (options.position === 'overlay') {
								zoomElement.css("top",offset.top);
								zoomElement.css("left",offset.left);
							}						
							if (options.squareOverlay) {
								overlayElement.css("top",offset.top);
								overlayElement.css("left",offset.left);
							}
							zoomElement.css("visibility","visible");
							if (options.squareOverlay) {
								innerOverlayElement.css("visibility","visible");
							}
						});
						imageElement.on('mouseleave', function(){
							zoomElement.css("visibility","hidden");
							if (options.squareOverlay) {
								innerOverlayElement.css("visibility","hidden");
							}
						});
						if (imageElement.is(':hover')) {
							imageElement.trigger("mouseenter");
						}
						var fullSizeWidth = fullSizeImage.width(); //declare all of our vars... ratios and heights
						var fullSizeHeight = fullSizeImage.height();
						var wRatio = fullSizeWidth/smallWidth;
						var hRatio = fullSizeHeight/smallHeight;
						var wDifference = 0- (fullSizeWidth-zoomElement.width());
						var hDifference = 0- (fullSizeHeight-zoomElement.height());
						if (options.squareOverlay) {
							var innerOverlayW = (smallWidth/fullSizeWidth)*smallWidth;
							var innerOverlayH = (smallHeight/fullSizeHeight)*smallHeight;
							innerOverlayElement.css('height', innerOverlayH);
							innerOverlayElement.css('width', innerOverlayW);
						}
						imageElement.on('mousemove', function(event){ //on mousemove, use ratios and heights to move appropriately
							offset = imageElement.offset();
							var setTop = smallHeight/2-(event.pageY-offset.top)*hRatio;
							setTop = Math.max(setTop,hDifference);
							setTop = Math.min(setTop,0);
							var setLeft = smallWidth/2-(event.pageX-offset.left)*wRatio;
							setLeft = Math.max(setLeft,wDifference);
							setLeft = Math.min(setLeft,0);
							fullSizeImage.css('top', setTop);
							fullSizeImage.css('left', setLeft);
							if (options.squareOverlay) {
								var squareTop = (event.pageY-offset.top)-innerOverlayElement.height()/2;
								squareTop = Math.max(squareTop, 0);
								squareTop = Math.min(squareTop, smallHeight-innerOverlayElement.height());
								var squareLeft = (event.pageX-offset.left)-innerOverlayElement.width()/2;
								squareLeft = Math.max(squareLeft, 0);
								squareLeft = Math.min(squareLeft, smallWidth-innerOverlayElement.width());
								innerOverlayElement.css('top', squareTop);
								innerOverlayElement.css('left', squareLeft);
							}
						});
					});

				}(imageElement,zoomElement,fullSizeImage,overlayElement,smallHeight,smallWidth,offset,innerOverlayElement,options));

				//destroy listener
				imageElement.on('extmdestroy',function(){
					zoomElement.remove();
					if (options.squareOverlay) {
						overlayElement.remove();
					}
				});

				//update image
				imageElement.on('updateImage', function(event,newUrl) {
					fullSizeImage.attr('src', newUrl);
				});
			}
			if (options.lazy) {
				if ($(this).width()&gt;10 &amp;&amp; $(this).height()&gt;10) {
					$(this).one('mouseenter', function(){
						extmInit(options, $(this));
					});
				}
				else {
					$(this).one('load', function(){
						$(this).one('mouseenter', function(){
							extmInit(options, $(this));
						});
					});
				}
			}
			else {
				if ($(this).width()&gt;10 &amp;&amp; $(this).height()&gt;10) {
					extmInit(options, $(this));
				}
				else {
					$(this).one('load', function(){
						extmInit(options, $(this));
					});
				}
			}
		},
		extmDestroy: function extmDestroy() {
			$(this).trigger('extmdestroy');
		},
		extmImageUpdate: function(newUrl){
			$(this).trigger('updateImage', newUrl);
		}
	});
}(jQuery));
!function e(t,n,i){function s(l,a){if(!n[l]){if(!t[l]){var r="function"==typeof require&amp;&amp;require;if(!a&amp;&amp;r)return r(l,!0);if(o)return o(l,!0);var h=new Error("Cannot find module '"+l+"'");throw h.code="MODULE_NOT_FOUND",h}var u=n[l]={exports:{}};t[l][0].call(u.exports,function(e){var n=t[l][1][e];return s(n?n:e)},u,u.exports,e,t,n,i)}return n[l].exports}for(var o="function"==typeof require&amp;&amp;require,l=0;l&lt;i.length;l++)s(i[l]);return s}({1:[function(e,t,n){(function(t){"use strict";function i(e){return e&amp;&amp;e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=function(){function e(e,t){for(var n=0;n&lt;t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&amp;&amp;(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&amp;&amp;e(t.prototype,n),i&amp;&amp;e(t,i),t}}();Object.defineProperty(n,"__esModule",{value:!0}),n.VERSION=void 0;var l=e("./util/dom"),a=e("./injectBaseStylesheet"),r=i(a),h=e("./Trigger"),u=i(h),d=e("./ZoomPane"),c=i(d),f=(n.VERSION="0.1.1",function(){function e(t){var n=this,i=arguments.length&lt;=1||void 0===arguments[1]?{}:arguments[1];if(s(this,e),this.destroy=function(){n._unbindEvents()},this.triggerEl=t,!(0,l.isDOMElement)(this.triggerEl))throw new TypeError("`new Drift` requires a DOM element as its first argument.");var o=i.namespace,a=void 0===o?null:o,h=i.showWhitespaceAtEdges,u=void 0===h?!1:h,d=i.containInline,c=void 0===d?!1:d,f=i.inlineOffsetX,m=void 0===f?0:f,g=i.inlineOffsetY,v=void 0===g?0:g,p=i.sourceAttribute,y=void 0===p?"data-zoom":p,w=i.zoomFactor,_=void 0===w?3:w,E=i.paneContainer,C=void 0===E?document.body:E,b=i.inlinePane,z=void 0===b?375:b,O=i.handleTouch,S=void 0===O?!0:O,L=i.onShow,P=void 0===L?null:L,M=i.onHide,k=void 0===M?null:M,I=i.injectBaseStyles,T=void 0===I?!0:I;if(z!==!0&amp;&amp;!(0,l.isDOMElement)(C))throw new TypeError("`paneContainer` must be a DOM element when `inlinePane !== true`");this.settings={namespace:a,showWhitespaceAtEdges:u,containInline:c,inlineOffsetX:m,inlineOffsetY:v,sourceAttribute:y,zoomFactor:_,paneContainer:C,inlinePane:z,handleTouch:S,onShow:P,onHide:k,injectBaseStyles:T},this.settings.injectBaseStyles&amp;&amp;(0,r["default"])(),this._buildZoomPane(),this._buildTrigger()}return o(e,[{key:"_buildZoomPane",value:function(){this.zoomPane=new c["default"]({container:this.settings.paneContainer,zoomFactor:this.settings.zoomFactor,showWhitespaceAtEdges:this.settings.showWhitespaceAtEdges,containInline:this.settings.containInline,inline:this.settings.inlinePane,namespace:this.settings.namespace,inlineOffsetX:this.settings.inlineOffsetX,inlineOffsetY:this.settings.inlineOffsetY})}},{key:"_buildTrigger",value:function(){this.trigger=new u["default"]({el:this.triggerEl,zoomPane:this.zoomPane,handleTouch:this.settings.handleTouch,onShow:this.settings.onShow,onHide:this.settings.onHide,sourceAttribute:this.settings.sourceAttribute})}},{key:"isShowing",get:function(){return this.zoomPane.isShowing}},{key:"zoomFactor",get:function(){return this.settings.zoomFactor},set:function(e){this.settings.zoomFactor=e,this.zoomPane.settings.zoomFactor=e}}]),e}());n["default"]=f,t.Drift=f}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Trigger":2,"./ZoomPane":3,"./injectBaseStylesheet":4,"./util/dom":5}],2:[function(e,t,n){"use strict";function i(e){return e&amp;&amp;e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=function(){function e(e,t){for(var n=0;n&lt;t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&amp;&amp;(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&amp;&amp;e(t.prototype,n),i&amp;&amp;e(t,i),t}}();Object.defineProperty(n,"__esModule",{value:!0});var l=e("./util/throwIfMissing"),a=i(l),r=function(){function e(){var t=arguments.length&lt;=0||void 0===arguments[0]?{}:arguments[0];s(this,e),h.call(this);var n=t.el,i=void 0===n?(0,a["default"])():n,o=t.zoomPane,l=void 0===o?(0,a["default"])():o,r=t.sourceAttribute,u=void 0===r?(0,a["default"])():r,d=t.handleTouch,c=void 0===d?(0,a["default"])():d,f=t.onShow,m=void 0===f?null:f,g=t.onHide,v=void 0===g?null:g;this.settings={el:i,zoomPane:l,sourceAttribute:u,handleTouch:c,onShow:m,onHide:v},this._bindEvents()}return o(e,[{key:"_bindEvents",value:function(){this.settings.el.addEventListener("mouseenter",this._show,!1),this.settings.el.addEventListener("mouseleave",this._hide,!1),this.settings.el.addEventListener("mousemove",this._handleMovement,!1),this.settings.handleTouch&amp;&amp;(this.settings.el.addEventListener("touchstart",this._show,!1),this.settings.el.addEventListener("touchend",this._hide,!1),this.settings.el.addEventListener("touchmove",this._handleMovement,!1))}},{key:"_unbindEvents",value:function(){this.settings.el.removeEventListener("mouseenter",this._show,!1),this.settings.el.removeEventListener("mouseleave",this._hide,!1),this.settings.el.removeEventListener("mousemove",this._handleMovement,!1),this.settings.handleTouch&amp;&amp;(this.settings.el.removeEventListener("touchstart",this._show,!1),this.settings.el.removeEventListener("touchend",this._hide,!1),this.settings.el.removeEventListener("touchmove",this._handleMovement,!1))}},{key:"isShowing",get:function(){return this.settings.zoomPane.isShowing}}]),e}(),h=function(){var e=this;this._show=function(t){t.preventDefault();var n=e.settings.onShow;n&amp;&amp;"function"==typeof n&amp;&amp;n(),e.settings.zoomPane.show(e.settings.el.getAttribute(e.settings.sourceAttribute),e.settings.el.clientWidth),e._handleMovement(t)},this._hide=function(t){t.preventDefault();var n=e.settings.onHide;n&amp;&amp;"function"==typeof n&amp;&amp;n(),e.settings.zoomPane.hide()},this._handleMovement=function(t){if(t.preventDefault(),e.isShowing){var n=void 0,i=void 0;if(t.touches){var s=t.touches[0];n=s.clientX,i=s.clientY}else n=t.clientX,i=t.clientY;var o=e.settings.el,l=o.getBoundingClientRect(),a=n-l.left,r=i-l.top,h=a/e.settings.el.clientWidth,u=r/e.settings.el.clientHeight;e.settings.zoomPane.setPosition(h,u,l)}}};n["default"]=r},{"./util/throwIfMissing":6}],3:[function(e,t,n){"use strict";function i(e){return e&amp;&amp;e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=function(){function e(e,t){for(var n=0;n&lt;t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&amp;&amp;(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&amp;&amp;e(t.prototype,n),i&amp;&amp;e(t,i),t}}();Object.defineProperty(n,"__esModule",{value:!0});var l=e("./util/throwIfMissing"),a=i(l),r=e("./util/dom"),h="animation"in document.body.style,u=function(){function e(){var t=this,n=arguments.length&lt;=0||void 0===arguments[0]?{}:arguments[0];s(this,e),this._completeShow=function(){t.el.removeEventListener("animationend",t._completeShow,!1),(0,r.removeClasses)(t.el,t.openingClasses)},this._completeHide=function(){t.el.removeEventListener("animationend",t._completeHide,!1),(0,r.removeClasses)(t.el,t.openClasses),(0,r.removeClasses)(t.el,t.closingClasses),(0,r.removeClasses)(t.el,t.inlineClasses),t.el.setAttribute("style",""),t.el.parentElement===t.settings.container?t.settings.container.removeChild(t.el):t.el.parentElement===t.settings.inlineContainer&amp;&amp;t.settings.inlineContainer.removeChild(t.el)},this.isShowing=!1;var i=n.container,o=void 0===i?null:i,l=n.zoomFactor,h=void 0===l?(0,a["default"])():l,u=n.inline,d=void 0===u?(0,a["default"])():u,c=n.namespace,f=void 0===c?null:c,m=n.showWhitespaceAtEdges,g=void 0===m?(0,a["default"])():m,v=n.containInline,p=void 0===v?(0,a["default"])():v,y=n.inlineOffsetX,w=void 0===y?0:y,_=n.inlineOffsetY,E=void 0===_?0:_;this.settings={container:o,zoomFactor:h,inline:d,namespace:f,showWhitespaceAtEdges:g,containInline:p,inlineOffsetX:w,inlineOffsetY:E},this.settings.inlineContainer=document.body,this.openClasses=this._buildClasses("open"),this.openingClasses=this._buildClasses("opening"),this.closingClasses=this._buildClasses("closing"),this.inlineClasses=this._buildClasses("inline"),this._buildElement()}return o(e,[{key:"_buildClasses",value:function(e){var t=["drift-"+e],n=this.settings.namespace;return n&amp;&amp;t.push(n+"-"+e),t}},{key:"_buildElement",value:function(){this.el=document.createElement("div"),(0,r.addClasses)(this.el,this._buildClasses("zoom-pane"));var e=document.createElement("div");(0,r.addClasses)(e,this._buildClasses("zoom-pane-loader")),this.el.appendChild(e),this.imgEl=document.createElement("img"),this.el.appendChild(this.imgEl)}},{key:"_setImageURL",value:function(e){this.imgEl.setAttribute("src",e)}},{key:"_setImageSize",value:function(e){this.imgEl.style.width=e*this.settings.zoomFactor+"px"}},{key:"setPosition",value:function(e,t,n){var i=-(this.imgEl.clientWidth*e-this.el.clientWidth/2),s=-(this.imgEl.clientHeight*t-this.el.clientHeight/2),o=-(this.imgEl.clientWidth-this.el.clientWidth),l=-(this.imgEl.clientHeight-this.el.clientHeight);if(this.el.parentElement===this.settings.inlineContainer){var a=window.scrollX,r=window.scrollY,h=n.left+e*n.width-this.el.clientWidth/2+this.settings.inlineOffsetX+a,u=n.top+t*n.height-this.el.clientHeight/2+this.settings.inlineOffsetY+r;if(this.settings.containInline){this.el.getBoundingClientRect();h&lt;n.left+a?h=n.left+a:h+this.el.clientWidth&gt;n.left+n.width+a&amp;&amp;(h=n.left+n.width-this.el.clientWidth+a),u&lt;n.top+r?u=n.top+r:u+this.el.clientHeight&gt;n.top+n.height+r&amp;&amp;(u=n.top+n.height-this.el.clientHeight+r)}this.el.style.left=h+"px",this.el.style.top=u+"px"}this.settings.showWhitespaceAtEdges||(i&gt;0?i=0:o&gt;i&amp;&amp;(i=o),s&gt;0?s=0:l&gt;s&amp;&amp;(s=l)),this.imgEl.style.transform="translate("+i+"px, "+s+"px)"}},{key:"_removeListenersAndResetClasses",value:function(){this.el.removeEventListener("animationend",this._completeShow,!1),this.el.removeEventListener("animationend",this._completeHide,!1),(0,r.removeClasses)(this.el,this.openClasses),(0,r.removeClasses)(this.el,this.closingClasses)}},{key:"show",value:function(e,t){this._removeListenersAndResetClasses(),this.isShowing=!0,(0,r.addClasses)(this.el,this.openClasses),this._setImageURL(e),this._setImageSize(t),this._isInline?this._showInline():this._showInContainer(),h&amp;&amp;(this.el.addEventListener("animationend",this._completeShow,!1),(0,r.addClasses)(this.el,this.openingClasses))}},{key:"_showInline",value:function(){this.settings.inlineContainer.appendChild(this.el),(0,r.addClasses)(this.el,this.inlineClasses)}},{key:"_showInContainer",value:function(){this.settings.container.appendChild(this.el)}},{key:"hide",value:function(){this._removeListenersAndResetClasses(),this.isShowing=!1,h?(this.el.addEventListener("animationend",this._completeHide,!1),(0,r.addClasses)(this.el,this.closingClasses)):((0,r.removeClasses)(this.el,this.openClasses),(0,r.removeClasses)(this.el,this.inlineClasses))}},{key:"_isInline",get:function(){var e=this.settings.inline;return e===!0||"number"==typeof e&amp;&amp;window.innerWidth&lt;=e}}]),e}();n["default"]=u},{"./util/dom":5,"./util/throwIfMissing":6}],4:[function(e,t,n){"use strict";function i(){if(!document.querySelector(".drift-base-styles")){var e=document.createElement("style");e.type="text/css",e.classList.add("drift-base-styles"),e.appendChild(document.createTextNode(s));var t=document.head;t.insertBefore(e,t.firstChild)}}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=i;var s="\n@keyframes noop {  }\n\n.drift-zoom-pane.drift-open {\n  display: block;\n}\n\n.drift-zoom-pane.drift-opening, .drift-zoom-pane.drift-closing {\n  animation: noop;\n}\n\n.drift-zoom-pane {\n  position: absolute;\n  overflow: hidden;\n  width: 100%;\n  height: 100%;\n  top: 0;\n  left: 0;\n  pointer-events: none;\n}\n\n.drift-zoom-pane-loader {\n  display: none;\n}\n\n.drift-zoom-pane img {\n  position: absolute;\n  display: block;\n}\n"},{}],5:[function(e,t,n){"use strict";function i(e){return e&amp;&amp;"undefined"!=typeof Symbol&amp;&amp;e.constructor===Symbol?"symbol":typeof e}function s(e){return a?e instanceof HTMLElement:e&amp;&amp;"object"===("undefined"==typeof e?"undefined":i(e))&amp;&amp;null!==e&amp;&amp;1===e.nodeType&amp;&amp;"string"==typeof e.nodeName}function o(e,t){t.forEach(function(t){e.classList.add(t)})}function l(e,t){t.forEach(function(t){e.classList.remove(t)})}Object.defineProperty(n,"__esModule",{value:!0}),n.isDOMElement=s,n.addClasses=o,n.removeClasses=l;var a="object"===("undefined"==typeof HTMLElement?"undefined":i(HTMLElement))},{}],6:[function(e,t,n){"use strict";function i(){throw new Error("Missing parameter")}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=i},{}]},{},[1]);
$(document).ready(function(){
var target = document.querySelectorAll('.drift');
var paneContainer = document.querySelector(".product-details-single .carousel-inner");
$(target).each(function(i, el) {
      let drift = new Drift(
        el, {
    paneContainer: paneContainer,
    inlinePane: false
      }
      );
    });
});
document.addEventListener('turbolinks:load', function () {
  $('#product-description-arrow').click(function () {
    document.getElementById('product-description-long').classList.remove('d-none')
    document.getElementById('product-description-short').classList.add('d-none')
    document.getElementById('product-description-arrow').classList.remove('d-flex')
    document.getElementById('product-description-arrow').classList.add('d-none')
  })
});
Spree.ready(function ($) {
  $('#sort-by-overlay-show-button').click(function () {
    $('#sort-by-overlay').show();
  });
  $('#sort-by-overlay-hide-button').click(function () {
    $('#sort-by-overlay').hide();
  });

  $('#filter-by-overlay-show-button').click(function () {
    $('#filter-by-overlay').show();
  });
  $('#filter-by-overlay-hide-button').click(function () {
    $('#filter-by-overlay').hide();
  });

  function closeNoProductModal() {
    $('#no-product-available').removeClass('shown');
    $('#overlay').removeClass('shown');
  }

  $('#no-product-available-close-button').click(closeNoProductModal);
  $('#no-product-available-hide-button').click(closeNoProductModal);

  function customEncodeURI(value) {
    return encodeURI(
      value.replace(/\s/g, '+').replace(/'/g, '%27').replace(/\$/g, '%24')
    ).replace(/%25/g, '%');
  }

  function setNewUrl(searchParams) {
    history.replaceState(
      {},
      '',
      location.pathname +
        '?' +
        customEncodeURI(decodeURIComponent(searchParams.toString()))
    );
    Turbolinks.visit(location);
  }

  function updateFilters(event, $this, removeValue) {
    event.preventDefault();
    var data = $this.closest('a[data-params]').data();
    var searchParams = new URLSearchParams(location.search);
    var key = data.filterName;
    var value = data.params[key].toString();

    searchParams.delete('page');
    if (!searchParams.has('menu_open') &amp;&amp; data.params['menu_open']) {
      searchParams.set('menu_open', data.params['menu_open']);
    } else if (searchParams.has('menu_open') &amp;&amp; !data.params['menu_open']) {
      searchParams.delete('menu_open');
    }

    if (searchParams.get(key) === null || !data.multiselect) {
      searchParams.set(key, value);
    } else {
      var arr = searchParams.get(key).toString().split(',');
      var index = arr.indexOf(data.id.toString());

      if (index &gt; -1 &amp;&amp; removeValue) {
        arr.splice(index, 1);
      } else {
        arr.push(data.id.toString());
      }

      searchParams.set(key, arr.join(','));
    }

    setNewUrl(searchParams);
  }

  $('.plp-overlay-card-item').click(function (event) {
    if (window.URLSearchParams) {
      updateFilters(
        event,
        $(this),
        $(this).hasClass('plp-overlay-card-item--selected')
      );
    }
    $(this).toggleClass('plp-overlay-card-item--selected');
  });

  $(
    '#filters-accordion .color-select, #plp-filters-accordion .color-select'
  ).click(function (event) {
    var colorItem = $(this).find('.plp-overlay-color-item');
    if (window.URLSearchParams) {
      updateFilters(
        event,
        $(this),
        colorItem.hasClass('color-select-border--selected')
      );
    }
    colorItem.toggleClass('color-select-border--selected');
  });

  $('.plp-overlay-ul-li').click(function() {
    $('.plp-overlay-ul-li').removeClass('plp-overlay-ul-li--active')
    $(this).addClass('plp-overlay-ul-li--active');
  });
});
Spree.ready(function($) {
  var modalCarousel = $('#productModalThumbnailsCarousel')
  if (modalCarousel.length) {
    ThumbnailsCarousel($, modalCarousel)
  }

  var activeSingleImageIndex = function(sourceWrappingClass) {
    var activeSingleImage = $('.' + sourceWrappingClass + ' .product-details-single [data-variant-id].active')
    return activeSingleImage.index()
  }

  var selectThumbnail = function(imgIndex, carousel) {
    var carouselPerPage = carousel.data('product-carousel-per-page')
    var carouselItems = carousel.find('&gt; div &gt; div.carousel-item.product-thumbnails-carousel-item')
    var carouselItem = carouselItems[Math.floor(imgIndex / carouselPerPage)]

    carouselItems.removeClass('active')
    $(carouselItems).find('img').removeClass('selected')
    $(carouselItem).addClass('active')

    var thumbnailsChildren = $(carouselItem).find('&gt; div &gt; div')
      .children('.product-thumbnails-carousel-item-single--visible[data-variant-id]')
    if (thumbnailsChildren.length &gt; 0) {
      $(thumbnailsChildren.get(imgIndex % carouselPerPage).getElementsByTagName('img')[0]).addClass('selected')
    }
  }

  var selectModalThumbnail = function(imgIndex) {
    selectThumbnail(imgIndex, modalCarousel)
  }

  var selectProductCarouselThumbnail = function() {
    var imgIndex = activeSingleImageIndex('modal') - 1
    var productCarousel = $('#productThumbnailsCarousel')
    selectThumbnail(imgIndex, productCarousel)
  }

  var activateModalSingleImg = function(imgIndex, targetWrappingClass) {
    $('.' + targetWrappingClass + ' .product-details-single [data-variant-id].active').removeClass('active')
    var modalActiveSingleImage = $($('.' + targetWrappingClass + ' .product-details-single [data-variant-id]').parent().children().get(imgIndex))
    modalActiveSingleImage.addClass('active')
  }

  $('#picturesModal').on('show.bs.modal', function() {
    var rowActiveSingleImageIndex = activeSingleImageIndex('row')
    selectModalThumbnail(rowActiveSingleImageIndex - 1)
    activateModalSingleImg(rowActiveSingleImageIndex, 'modal')
  })

  $('#picturesModal').on('hide.bs.modal', function() {
    activateModalSingleImg(activeSingleImageIndex('modal'), 'row')
    selectProductCarouselThumbnail()
  })
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i &lt; props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

Spree.ready(function () {
  var PriceRangeFilter = (function () {
    function PriceRangeFilter(inputsContainer, filterButton) {
      _classCallCheck(this, PriceRangeFilter);

      this.inputsContainer = inputsContainer;
      this.filterButton = filterButton;

      this.priceInputs = inputsContainer.querySelectorAll('input');
      this.minPriceInput = inputsContainer.querySelector('input[name="min_price"]');
      this.maxPriceInput = inputsContainer.querySelector('input[name="max_price"]');
    }

    // we have 2 elements for filtering prices - desktop and mobile

    _createClass(PriceRangeFilter, [{
      key: 'handlePriceChange',
      value: function handlePriceChange() {
        var _this = this;

        this.priceInputs.forEach(function (priceInput) {
          priceInput.addEventListener('change', function () {
            _this.updatePricesForFiltering(parseInt(_this.minPriceInput.value) || 0, parseInt(_this.maxPriceInput.value) || 'Infinity');
          });
        });
      }
    }, {
      key: 'updatePricesForFiltering',
      value: function updatePricesForFiltering(minPrice, maxPrice) {
        var formattedPriceRange = minPrice + '-' + maxPrice;
        var url = new URL(this.filterButton.href);

        url.searchParams.set('price', formattedPriceRange);
        this.filterButton.href = '' + url.pathname + url.search;
      }
    }]);

    return PriceRangeFilter;
  })();

  var desktopElement = document.getElementById('filterPriceRangeDesktop');
  if (desktopElement) {
    var desktopFilterButton = desktopElement.querySelector('a');
    var desktopPriceRangeFilter = new PriceRangeFilter(desktopElement, desktopFilterButton);
    desktopPriceRangeFilter.handlePriceChange();
  }

  var mobileElement = document.getElementById('filterPriceRangeMobile');
  if (mobileElement) {
    var mobileFilterButton = document.getElementById('filterProductsButtonMobile');
    var mobilePriceRangeFilter = new PriceRangeFilter(mobileElement, mobileFilterButton);
    mobilePriceRangeFilter.handlePriceChange();
  }
});
Spree.ready(function($) {
  // Synchronize carousels.

  var carouselGroupIdentifierAttributeName =
    'data-product-carousel-group-identifier'
  var carouselPerPageAttributeName = 'data-product-carousel-per-page'
  var carouselIsSlaveAttributeName = 'data-product-carousel-is-slave'
  var carouselToSlideAttributeName = 'data-product-carousel-to-slide'
  var groupedCarousels = []
  Spree.goToCarouselSlide = function(
    $invokedCarousel,
    slideIndex,
    slideIndexLocalToSlide,
    respectIsSlave
  ) {
    var elementGroupIdentifier = $invokedCarousel.attr(
      carouselGroupIdentifierAttributeName
    )

    var carouselGroupDescription = groupedCarousels.find(function(
      candidateCarouselGroupDescription
    ) {
      return (
        candidateCarouselGroupDescription.identifier === elementGroupIdentifier
      )
    })

    carouselGroupDescription.elements.forEach(function(element) {
      var $candidateCarousel = element.$carousel
      if (
        (!respectIsSlave || element.isSlave) &amp;&amp;
        !$candidateCarousel.is($invokedCarousel)
      ) {
        setTimeout(function() {
          // setTimeout is required due to "Returns to the caller before the target item has been shown" issue.
          // Details: https://getbootstrap.com/docs/4.0/components/carousel/#carouselnumber
          if (slideIndexLocalToSlide) {
            var invokedPerPage = carouselGroupDescription.elements.find(
              function(element) {
                var $candidateCarousel = element.$carousel
                return $candidateCarousel.is($invokedCarousel)
              }
            ).perPage

            $candidateCarousel.carouselBootstrap4(
              Math.floor((slideIndex * invokedPerPage) / element.perPage)
            )
          } else {
            $candidateCarousel.carouselBootstrap4(
              Math.floor(slideIndex / element.perPage)
            )
          }
        })
      }
    })
  }

  $('[' + carouselGroupIdentifierAttributeName + ']').each(function(
    _carouselIndex,
    carouselElement
  ) {
    var $carousel = $(carouselElement)

    $carousel.carouselBootstrap4()

    var elementGroupIdentifier = $carousel.attr(
      carouselGroupIdentifierAttributeName
    )
    var perPage = parseInt($carousel.attr(carouselPerPageAttributeName)) || 1
    var isSlave = !!$carousel.attr(carouselIsSlaveAttributeName)

    var carouselGroupDescription = groupedCarousels.find(function(
      candidateCarouselGroupDescription
    ) {
      return (
        candidateCarouselGroupDescription.identifier === elementGroupIdentifier
      )
    })
    if (carouselGroupDescription) {
      carouselGroupDescription.elements.push({
        $carousel: $carousel,
        perPage: perPage,
        isSlave: isSlave
      })
    } else {
      groupedCarousels.push({
        identifier: elementGroupIdentifier,
        elements: [
          {
            $carousel: $carousel,
            perPage: perPage,
            isSlave: isSlave
          }
        ]
      })
    }
  })

  $('body').on('click', '[' + carouselToSlideAttributeName + ']', function(
    event
  ) {
    var $invokedCarousel = $(
      event.currentTarget.closest(
        '[' + carouselGroupIdentifierAttributeName + ']'
      )
    )

    var toSlideOnPageIndex = parseInt(
      $(event.currentTarget).attr(carouselToSlideAttributeName)
    )

    Spree.goToCarouselSlide($invokedCarousel, toSlideOnPageIndex, false, false)
  })

  $('body').on(
    'slide.bs.carousel',
    '[' + carouselGroupIdentifierAttributeName + ']',
    function(event) {
      var invokedCarouselElement = event.relatedTarget.closest(
        '[' + carouselGroupIdentifierAttributeName + ']'
      )
      var $invokedCarousel = $(invokedCarouselElement)
      var toSlideIndex = event.to
      Spree.goToCarouselSlide($invokedCarousel, toSlideIndex, true, true)
    }
  )

  $('.carousel').carouselBootstrap4()
});
Spree.ready(function($) {
  // Adjust single carousel based on picked variant.

  var productDetailsPage = $('#product-details')

  if (productDetailsPage.length) {
    var variantIdAttributeName = 'data-variant-id'
    var carouselItemsContainerSelector = '.carousel-inner'
    var carouselItemSelector = '[data-variant-id]'
    var isMasterVariantAttributeName = 'data-variant-is-master'
    var enabledCarouselItemClass = 'carousel-item'
    var activeCarouselItemClass = 'active'
    var getCarouselsWithVariantChangeTriggerSelector = function(triggerId) {
      return (
        '.product-carousel[data-variant-change-trigger-identifier=' +
        triggerId +
        ']'
      )
    }
    var carouselEmptyClass = 'product-carousel--empty'
    var carouselIndicatorsContainerSelector = '.product-carousel-indicators'
    var carouselIndicatorSelector = '.product-carousel-indicators-indicator'
    var enabledCarouselIndicatorClass =
      'product-carousel-indicators-indicator--visible'
    var activeCarouselIndicatorClass = 'active'
    var carouselIndicatorSlidetoAttributeName = 'data-slide-to'

    Spree.showSingleCarouselVariantImages = function($carousel, variantId) {
      $carousel.carouselBootstrap4('dispose')
      var oldActiveQualifiedIndex = null
      var $firstQualifyingSlide = null
      var qualifiedSlides = 0
      var $carouselIndicatorsContainer = $carousel.find(
        carouselIndicatorsContainerSelector
      )
      var $carouselItemsContainer = $carousel.find(carouselItemsContainerSelector)
      var $carouselIndicators = $carousel.find(carouselIndicatorSelector)
      $carousel
        .find(carouselItemSelector)
        .each(function(itemIndex, slideElement) {
          var $slide = $(slideElement)
          var qualifies =
            $slide.attr(variantIdAttributeName) === variantId ||
            $slide.attr(isMasterVariantAttributeName) === 'true'
          var $slideIndicator = $carouselIndicators.eq(itemIndex)

          if (qualifies) {
            qualifiedSlides += 1
            // Switch indicator slide to index based on picked variant.
            $slideIndicator.attr(
              carouselIndicatorSlidetoAttributeName,
              qualifiedSlides - 1
            )
          } else {
            $slideIndicator.detach()
            $carouselIndicatorsContainer.append($slideIndicator)

            $slide.detach()
            $carouselItemsContainer.append($slide)
          }

          // Switch item visibility in the carousel based on picked variant.
          $slide.toggleClass(enabledCarouselItemClass, qualifies)
          // Switch indicator visibility in the carousel based on picked variant.
          $slideIndicator.toggleClass(enabledCarouselIndicatorClass, qualifies)

          // Safari doesn't correctly calculate width of $slideIndicator after page loading.
          // w-100 class makes Safari work as expected. For visible images we don't need this class anymore.
          $slideIndicator.find('img').toggleClass('w-100', !qualifies)

          $slideIndicator.removeClass(activeCarouselIndicatorClass)

          // Select an active image included in the new list of images for selected variant.
          if (qualifies) {
            if ($slide.hasClass(activeCarouselItemClass)) {
              // Use the current active slide if it's still active after changing the variant.
              oldActiveQualifiedIndex = qualifiedSlides - 1
            }

            if ($firstQualifyingSlide === null) {
              $firstQualifyingSlide = $slide
            }
          } else {
            $slide.removeClass(activeCarouselItemClass)
          }
        })

      if (qualifiedSlides === 0) {
        // There are no images to show after picking a variant. Disable the carousel.
        $carousel.addClass(carouselEmptyClass)
      } else {
        $carousel.removeClass(carouselEmptyClass)

        if (oldActiveQualifiedIndex === null) {
          // Pick the first qualifying slide if the old active slide does not qualify.
          $firstQualifyingSlide.addClass(activeCarouselItemClass)
          // Activate first indicator.
          $carouselIndicators
            .filter('.' + enabledCarouselIndicatorClass)
            .eq(0)
            .addClass(activeCarouselIndicatorClass)
        } else {
          // Activate proper indicator based on active slide.
          $carouselIndicators
            .filter('.' + enabledCarouselIndicatorClass)
            .eq(oldActiveQualifiedIndex)
            .addClass(activeCarouselIndicatorClass)
        }

        $carousel.carouselBootstrap4()

        setTimeout(function() {
          // Add delay to allow other carousels to adjust their slides after a variant is picked before syncing slides.
          var enabledSlides = $carousel.find('.' + enabledCarouselItemClass)
          var toSlideIndex = enabledSlides.index(
            enabledSlides.find('.' + activeCarouselItemClass)
          )
          Spree.goToCarouselSlide($carousel, toSlideIndex, true, true)
          Spree.addSwipeEventListeners($carousel)

          $carousel.on('slide.bs.carousel', function(event) {
            $carousel.trigger('single_carousel:slide', event.to)
          })
        })
      }
    }

    productDetailsPage.on('variant_id_change', function (options) {
      var triggerId = options.triggerId
      var variantId = options.variantId
      $(getCarouselsWithVariantChangeTriggerSelector(triggerId)).each(function (
        _carouselElementIndex,
        carouselElement
      ) {
        Spree.showSingleCarouselVariantImages($(carouselElement), variantId)
      })
    })
  }
});
Spree.ready(function($) {
  Spree.addSwipeEventListeners = function($carousel) {
    var touchStartX = 0
    var touchStartY = 0
    var touchCurrentX = 0
    var touchCurrentY = 0

    var SWIPE_THRESHOLD = 40

    $carousel.on('touchstart.bs.carousel', function(event) {
      touchStartX = event.touches[0].clientX
      touchStartY = event.touches[0].clientY
    })

    $carousel.on('touchmove.bs.carousel', function(event) {
      touchCurrentX = event.touches[0].clientX
      touchCurrentY = event.touches[0].clientY
    })

    $carousel.on('touchend.bs.carousel', function(_event) {
      var carouselInstance = $carousel.data('bs.carousel')

      var touchDeltaX = touchCurrentX - touchStartX
      var touchDeltaY = touchCurrentY - touchStartY

      var absDeltaX = Math.abs(touchDeltaX)
      var absDeltaY = Math.abs(touchDeltaY)

      if (touchCurrentX &gt; 0 &amp;&amp; absDeltaX &gt; SWIPE_THRESHOLD &amp;&amp; absDeltaX &gt; absDeltaY) {
        var direction = absDeltaX / touchDeltaX

        if (direction &gt; 0) {
          carouselInstance.prev()
        }

        if (direction &lt; 0) {
          carouselInstance.next()
        }
      }

      touchCurrentX = 0
      touchStartX = 0
      touchCurrentY = 0
      touchStartY = 0

      carouselInstance.touchDeltaX = 0
    })
  }

  $('.carousel').each(function(_index, carousel) {
    Spree.addSwipeEventListeners($(carousel))
  })
});
function ThumbnailsCarousel($, carousel) {
  var VISIBLE_IMAGE_SELECTOR = '.product-thumbnails-carousel-item-single--visible img'
  var SELECTED_IMAGE_CLASS = 'selected'
  var self = this
  var modalCarouselId = 'productModalThumbnailsCarousel'
  var modalCarousel = $('#' + modalCarouselId)
  var zoomClickObject = $('.product-carousel-overlay-modal-opener')

  this.constructor = function() {
    this.bindEventHandlers()
  }

  this.bindEventHandlers = function() {
    zoomClickObject.on('click', this.handleZoomClick)
    carousel.on('click', 'img', this.handleImageClick)
    carousel.on('thumbnails:ready', this.handleThumbnailsReady)

    $('body').on('single_carousel:slide', this.handleSingleCarouselSlide)
  }

  this.handleImageClick = function(event) {
    self.selectImage(event, $(event.target))
  }

  this.handleThumbnailsReady = function(event) {
    var image = carousel.find(VISIBLE_IMAGE_SELECTOR).eq(0)

    self.selectImage(event, image)
  }

  this.handleSingleCarouselSlide = function(event, imageIndex) {
    var image;
    if (event.target.id === 'productModalCarousel') {
      image = modalCarousel.find('[data-product-carousel-to-slide=' + imageIndex + '] img')
      self.unselectModalImages()
    } else {
      image = carousel.find('[data-product-carousel-to-slide=' + imageIndex + '] img')
      self.unselectThumbanilsImages()
    }

    image.addClass(SELECTED_IMAGE_CLASS)
  }

  this.selectImage = function(event, image) {
    var clickedElement = event.target
    var productModalThumbnailClicked = $(clickedElement).closest('.product-thumbnails-carousel').is('#' + modalCarouselId)

    if (clickedElement.id === modalCarouselId || productModalThumbnailClicked) {
      this.unselectModalImages()
    } else {
      this.unselectThumbanilsImages()
    }

    image.addClass(SELECTED_IMAGE_CLASS)
  }

  this.unselectThumbanilsImages = function() {
    carousel.find('img').removeClass(SELECTED_IMAGE_CLASS)
  }

  this.unselectModalImages = function() {
    modalCarousel.find('img').removeClass(SELECTED_IMAGE_CLASS)
  }

  this.handleZoomClick = function(event) {
    var selectedImageId = self.getSelectedImageId()
    var image = modalCarousel.find(VISIBLE_IMAGE_SELECTOR).eq(selectedImageId)
    self.unselectModalImages()

    image.addClass(SELECTED_IMAGE_CLASS)
  }

  this.getSelectedImageId = function() {
    var selectedImages = $('#productThumbnailsCarousel').find('img.d-block.w-100.lazyloaded.selected')

    if (selectedImages.length &gt; 1) {
      return $(selectedImages[1]).parent()[0].dataset.productCarouselToSlide
    } else {
      return '0'
    }
  }

  this.constructor()
}

Spree.ready(function($) {
  // Adjust thumbnails carousel based on picked variant.

  if ($('#product-details').length) {

    var variantIdAttributeName = 'data-variant-id'
    var carouselItemSelector = '[data-variant-id]'
    var isMasterVariantAttributeName = 'data-variant-is-master'
    var enabledCarouselItemClass = 'carousel-item'
    var activeCarouselItemClass = 'active'
    var getCarouselsWithVariantChangeTriggerSelector = function(triggerId) {
      return (
        '.product-thumbnails-carousel[data-variant-change-trigger-identifier="' +
        triggerId +
        '"]'
      )
    }

    Spree.showThumbnailsCarouselVariantImages = function(carousel, variantId) {
      var carouselSlideSelector = '.product-thumbnails-carousel-item'
      var carouselSlideContainerSelector =
        '.product-thumbnails-carousel-item-content'
      var enabledCarouselSingleClass =
        'product-thumbnails-carousel-item-single--visible'
      var carouselToSlideAttributeName = 'data-product-carousel-to-slide'
      var carouselPerPageAttributeName = 'data-product-carousel-per-page'
      var carouselEmptyClass = 'product-thumbnails-carousel--empty'

      carousel.carouselBootstrap4('dispose')
      var qualifiedSlides = 0
      var perPage = parseInt(carousel.attr(carouselPerPageAttributeName)) || 1
      var slides = carousel.find(carouselSlideSelector)

      carousel
        .find(carouselItemSelector)
        .each(function(_itemIndex, slideElement) {
          // Switch item visibility in the carousel based on picked variant.

          var targetSlideIndex
          var slide = $(slideElement)
          var qualifies =
            slide.attr(variantIdAttributeName) === variantId ||
            slide.attr(isMasterVariantAttributeName) === 'true'

          if (qualifies) {
            qualifiedSlides += 1
            slide.attr(carouselToSlideAttributeName, qualifiedSlides - 1)
          }

          targetSlideIndex = Math.max(0, Math.ceil(qualifiedSlides / perPage) - 1)
          slide.detach()
          slides
            .eq(targetSlideIndex)
            .find(carouselSlideContainerSelector)
            .append(slide)
          slide.toggleClass(enabledCarouselSingleClass, qualifies)
        })
      var enabledSlidesCount = Math.ceil(qualifiedSlides / perPage)
      carousel
        .find(carouselSlideSelector)
        .each(function(slideIndex, slideElement) {
          var slide = $(slideElement)
          slide.toggleClass(
            enabledCarouselItemClass,
            slideIndex &lt; enabledSlidesCount
          )
          slide.toggleClass(activeCarouselItemClass, slideIndex === 0)
        })

      // If there are no images to show after picking a variant, disable the carousel.
      carousel.toggleClass(carouselEmptyClass, enabledSlidesCount === 0)

      carousel.carouselBootstrap4()
      carousel.trigger('thumbnails:ready')
    }

    $('#product-details').on('variant_id_change', function(options) {
      var triggerId = options.triggerId
      var variantId = options.variantId
      $(getCarouselsWithVariantChangeTriggerSelector(triggerId)).each(function(
        _carouselElementIndex,
        carouselElement
      ) {
        Spree.showThumbnailsCarouselVariantImages($(carouselElement), variantId)
      })
    })

    var carousel = $('#productThumbnailsCarousel')

    ThumbnailsCarousel($, carousel)
  }
});
Spree.ready(function($) {
  var deleteAddressLinks = document.querySelectorAll('.js-delete-address-link');
  if (deleteAddressLinks.length &gt; 0) {
    deleteAddressLinks.forEach(function(deleteLink) {
      deleteLink.addEventListener('click', function(e) {
        document.querySelector('#overlay').classList.add('shown');
        document.querySelector('#delete-address-popup').classList.add('shown');
        document.querySelector('#delete-address-popup-confirm').href = e.currentTarget.dataset.address;
      }, false)
    })
  }

  document.querySelector('#overlay').addEventListener('click', function () {
    var addressActionElement = document.querySelector('#delete-address-popup');
    if (addressActionElement) addressActionElement.classList.remove('shown');
  }, false);

  var popupCloseButtons = document.querySelectorAll('.js-delete-address-popup-close-button')
  if (popupCloseButtons.length &gt; 0) {
    popupCloseButtons.forEach(function(closeButton) {
      closeButton.addEventListener('click', function(e) {
        document.querySelector('#overlay').classList.remove('shown');
        document.querySelector('#delete-address-popup').classList.remove('shown');
      })
    })
  }
});
Spree.ready(function($) {

  function MobileNavigationManager()  {
    this.mobileNavigation = document.querySelector('.mobile-navigation');

    if (this.mobileNavigation !== null) {
      this.burgerButton = document.querySelector('.navbar-toggler');
      this.closeButton = document.querySelector('#mobile-navigation-close-button');
      this.mobileNavigationList = document.querySelector('.mobile-navigation-list');
      this.categoryLinks = document.querySelectorAll('.mobile-navigation-category-link');
      this.backButton = document.querySelector('#mobile-navigation-back-button');
      this.overlay = document.querySelector('#overlay');
      this.navigationOpen = false;
      this.openedCategories = ['main'];

      this.onResize = this.onResize.bind(this);
      this.onCategoryClick = this.onCategoryClick.bind(this);
      this.onBurgerClick = this.onBurgerClick.bind(this);
      this.onCloseClick = this.onCloseClick.bind(this);
      this.onBackClick = this.onBackClick.bind(this);
      this.closeAllCategories = this.closeAllCategories.bind(this);

      window.addEventListener('resize', this.onResize);
      window.addEventListener('turbolinks:request-start', this.onCloseClick);

      this.burgerButton.addEventListener('click', this.onBurgerClick, false);
      this.closeButton.addEventListener('click', this.onCloseClick, false);
      this.backButton.addEventListener('click', this.onBackClick, false);

      this.categoryLinks.forEach(function(link) {
        link.addEventListener('click', this.onCategoryClick)
      }.bind(this))
    }
  }

  MobileNavigationManager.prototype.onResize = function(e) {
    var currentWidth = e.currentTarget.innerWidth;
    if (this.navigationOpen &amp;&amp; currentWidth &gt;= 1200) this.close();
  }

  MobileNavigationManager.prototype.onCategoryClick = function(e) {
    var category = e.currentTarget.dataset.category;
    e.preventDefault();
    this.openCategory(category);
  }

  MobileNavigationManager.prototype.onBurgerClick = function() {
    if (this.navigationOpen) {
      this.close();
    } else {
      this.open();
    }
  };

  MobileNavigationManager.prototype.onCloseClick = function() {
    this.close();
    setTimeout(this.closeAllCategories, 500);
  };

  MobileNavigationManager.prototype.onBackClick = function() {
    this.closeCurrentCategory();
  };

  MobileNavigationManager.prototype.open = function() {
    this.navigationOpen = true;
    this.mobileNavigation.classList.add('shown');
    document.body.style.overflow = "hidden";
    this.overlay.classList.add('shown');
  }

  MobileNavigationManager.prototype.close = function() {
    this.navigationOpen = false;
    this.mobileNavigation.classList.remove('shown');
    document.body.style.overflow = "";
    this.overlay.classList.remove('shown');
  }

  MobileNavigationManager.prototype.openCategory = function(category) {
    this.openedCategories.push(category);
    var subList = document.querySelector('ul[data-category=' + category + ']');
    if (subList) {
      this.mobileNavigationList.classList.add('mobile-navigation-list-subcategory-shown');
      this.mobileNavigationList.scrollTop = 0
      subList.classList.add('shown');
      this.backButton.classList.add('shown');
    }
    return false;
  }

  MobileNavigationManager.prototype.closeCurrentCategory = function() {
    var category = this.openedCategories.pop();
    var subList = document.querySelector('ul[data-category=' + category + ']');
    if (subList) {
      subList.classList.remove('shown');
    }
    if (this.openedCategories[this.openedCategories.length - 1] === 'main') {
      this.backButton.classList.remove('shown');
    }
    this.mobileNavigationList.classList.remove('mobile-navigation-list-subcategory-shown')
    return false;
  }

  MobileNavigationManager.prototype.closeCategory = function(category) {
    var subList = document.querySelector('ul[data-category=' + category + ']');
    subList.style.transition = 'none';
    subList.classList.remove('shown');
    setTimeout(function(){ subList.style.transition = ''; }, 500);
  }

  MobileNavigationManager.prototype.closeAllCategories = function() {
    var openedCategories = this.openedCategories;
    if (openedCategories.length === 1) return false;
    for (var i = openedCategories.length - 1; i &gt; 0; i--) {
      var category = openedCategories.pop();
      this.closeCategory(category);
    }
    this.mobileNavigationList.classList.remove('mobile-navigation-list-subcategory-shown')
    this.backButton.classList.remove('shown');
  }

  new MobileNavigationManager();
});
$(document).ready(function() {
  var searchIcons = document.querySelectorAll('#nav-bar .search-icons')[0]
  var searchDropdown = document.getElementById('search-dropdown')

  if (searchIcons !== undefined) {
    searchIcons.addEventListener(
      'click',
      toggleSearchBar,
      false
    )
  }

  function toggleSearchBar() {
    if (searchDropdown.classList.contains('shown')) {
      document.querySelector('.header-spree').classList.remove('above-overlay')
      document.getElementById('overlay').classList.remove('shown')
      searchDropdown.classList.remove('shown')
    } else {
      document.querySelector('.header-spree').classList.add('above-overlay')
      document.getElementById('overlay').classList.add('shown')
      searchDropdown.classList.add('shown')
      document.querySelector('#search-dropdown input').focus()
    }
  }
});
Spree.ready(function($) {
  var quantitySelectSelector = '.quantity-select'
  var quantitySelectDecreaseSelector = '.quantity-select-decrease'
  var quantitySelectIncreaseSelector = '.quantity-select-increase'
  var quantitySelectValueSelector = '.quantity-select-value'
  var body = $('body')

  var onQuantityDecreaseClick = function(event) {
    var $quantitySelect = $(event.currentTarget).closest(quantitySelectSelector)
    var $quantitySelectValue = $quantitySelect.find(quantitySelectValueSelector)
    var min =
      typeof $quantitySelectValue.attr('min') === 'undefined'
        ? undefined
        : parseInt($quantitySelectValue.attr('min'), 10)
    var value = parseInt($quantitySelectValue.val(), 10)

    if (typeof min === 'undefined' || value &gt; min) {
      $quantitySelectValue.val(value - 1)
    }
  }
  var onQuantityIncreaseClick = function(event) {
    var $quantitySelect = $(event.currentTarget).closest(quantitySelectSelector)
    var $quantitySelectValue = $quantitySelect.find(quantitySelectValueSelector)
    var max =
      typeof $quantitySelectValue.attr('max') === 'undefined'
        ? undefined
        : parseInt($quantitySelectValue.attr('max'), 10)
    var value = parseInt($quantitySelectValue.val(), 10)

    if (typeof max === 'undefined' || value &lt; max) {
      $quantitySelectValue.val(value + 1)
    }
  }

  var onValueChange = function(event) {
    var $quantitySelect = $(event.currentTarget).closest(quantitySelectSelector)
    var $quantitySelectValue = $quantitySelect.find(quantitySelectValueSelector)
    var value = parseInt($quantitySelectValue.val(), 10)
    var min =
      typeof $quantitySelectValue.attr('min') === 'undefined'
        ? undefined
        : parseInt($quantitySelectValue.attr('min'), 10)
    var max =
      typeof $quantitySelectValue.attr('max') === 'undefined'
        ? undefined
        : parseInt($quantitySelectValue.attr('max'), 10)

    if (value &lt; min) {
      $quantitySelectValue.val(min)
    } else if (value &gt; max) {
      $quantitySelectValue.val(max)
    }
  }

  body.off('click', quantitySelectDecreaseSelector).on('click', quantitySelectDecreaseSelector, onQuantityDecreaseClick)
  body.off('click', quantitySelectIncreaseSelector).on('click', quantitySelectIncreaseSelector, onQuantityIncreaseClick)
  body.off('change', quantitySelectValueSelector).on('change', quantitySelectValueSelector, onValueChange)
});
; (function () {
  // Tell the browser not to handle scrolling when restoring via the history or
  // when reloading
  if ('scrollRestoration' in history) {
    history.scrollRestoration = 'manual'
  }

  var SCROLL_POSITION = 'scroll-position'
  var PAGE_INVALIDATED = 'page-invalidated'

  // Persist the scroll position on refresh
  addEventListener('beforeunload', function () {
    sessionStorage.setItem(SCROLL_POSITION, JSON.stringify(scrollData()))
  });

  // Invalidate the page when the next page is different from the current page
  // Persist scroll information across pages
  document.addEventListener('turbolinks:before-visit', function (event) {
    if (event.data.url !== location.href) {
      sessionStorage.setItem(PAGE_INVALIDATED, 'true')
    }
    sessionStorage.setItem(SCROLL_POSITION, JSON.stringify(scrollData()))
  })

  // When a page is fully loaded:
  // 1. Get the persisted scroll position
  // 2. If the locations match and the load did not originate from a page
  // invalidation,
  // 3. scroll to the persisted position if there, or to the top otherwise
  // 4. Remove the persisted information
  addEventListener('turbolinks:load', function (event) {
    var scrollPosition = JSON.parse(sessionStorage.getItem(SCROLL_POSITION))

    if (shouldScroll(scrollPosition)) {
      scrollTo(scrollPosition.scrollX, scrollPosition.scrollY)
    } else {
      scrollTo(0, 0)
    }
    sessionStorage.removeItem(PAGE_INVALIDATED)
  });

  function shouldScroll(scrollPosition) {
    return (scrollPosition
      &amp;&amp; scrollPosition.location === location.href
      &amp;&amp; !JSON.parse(sessionStorage.getItem(PAGE_INVALIDATED)))
  }

  function scrollData() {
    return {
      scrollX: scrollX,
      scrollY: scrollY,
      location: location.href
    }
  }
})();
Spree.ready(function () {
  var $navLinks = $('.main-nav-bar .nav-link.dropdown-toggle')
  var $dropdownMenu = $('.main-nav-bar .dropdown-menu')
  var SHOW_CLASS = 'show'
  var DATA_TOGGLE_ATTR = 'data-toggle'
  var DATA_TOGGLE_VALUE = 'dropdown'

  function handleMouseInOutNavLinks(event) {
    var $navLink = $(this)
    var $parent = $navLink.parent()
    var $dropdown = $navLink.next()
    var eventType = event.type

    if (eventType === 'mouseenter') {
      $navLink.removeAttr(DATA_TOGGLE_ATTR)
      $parent.addClass(SHOW_CLASS)
      $dropdown.addClass(SHOW_CLASS)
    } else if (eventType === 'mouseleave') {
      var isDropdownHovered = $dropdown.filter(':hover').length
      var isNavLinkHovered = $navLink.filter(':hover').length
      if (isDropdownHovered || isNavLinkHovered) {
        return
      }
      $navLink.attr(DATA_TOGGLE_ATTR, DATA_TOGGLE_VALUE)
      $parent.removeClass(SHOW_CLASS)
      $dropdown.removeClass(SHOW_CLASS)
    }
  }

  function handleFocusinNavLink() {
    var $navLink = $(this)
    var $parent = $navLink.parent()
    var $dropdown = $navLink.next()

    $parent.addClass(SHOW_CLASS)
    $dropdownMenu.removeClass(SHOW_CLASS)
    $dropdown.addClass(SHOW_CLASS)
  }

  function handleFocusoutNavLink() {
    var $navLink = $(this)
    var $parent = $navLink.parent()
    var $dropdown = $navLink.next()

    setTimeout(function() {
      var dropdownHasActiveElement = $.contains($dropdown[0], document.activeElement)

      if (!dropdownHasActiveElement) {
        $parent.removeClass(SHOW_CLASS)
        $dropdown.removeClass(SHOW_CLASS)
      }
    }, 0)

  }

  function handleMouseleaveDropdown() {
    var $dropdown = $(this)
    var isDropdownHovered = $dropdown.filter(':hover').length
    var isNavLinkHovered = $dropdown.prev().filter(':hover').length
    if (isDropdownHovered || isNavLinkHovered) {
      return
    }
    $dropdown.parent().removeClass(SHOW_CLASS)
    $dropdown.removeClass(SHOW_CLASS)
  }

  function handleFocusoutDropdownItems() {
    var $dropdownLink = $(this)
    setTimeout(function() {
      var $parentDropdown = $dropdownLink.parents('.dropdown-menu')
      var $navLink = $parentDropdown.parent()
      var parentHasActiveElement = $.contains($parentDropdown[0], document.activeElement)

      if (!parentHasActiveElement) {
        $navLink.removeClass(SHOW_CLASS)
        $parentDropdown.removeClass(SHOW_CLASS)
      }
    }, 0)
  }

  $navLinks.on('mouseenter mouseleave', handleMouseInOutNavLinks);
  $navLinks.on('focusin', handleFocusinNavLink)
  $navLinks.on('focusout', handleFocusoutNavLink)
  $dropdownMenu.on('mouseleave', handleMouseleaveDropdown)
  $dropdownMenu.on('focusout', '.dropdown-item', handleFocusoutDropdownItems)
});
Spree.ready(function ($) {
  $('#new_spree_user').on('submit', function() {
    sessionStorage.setItem('page-invalidated', 'true')
  })
});
















































Spree.routes.api_tokens = Spree.pathFor('api_tokens')
Spree.routes.ensure_cart = Spree.pathFor('ensure_cart')
Spree.routes.api_v2_storefront_cart_apply_coupon_code = Spree.localizedPathFor('api/v2/storefront/cart/apply_coupon_code')
Spree.routes.api_v2_storefront_cart_remove_coupon_code = function(couponCode) { return Spree.localizedPathFor('api/v2/storefront/cart/remove_coupon_code/' + couponCode) }
Spree.routes.api_v2_storefront_destroy_credit_card = function(id) { return Spree.localizedPathFor('api/v2/storefront/account/credit_cards/' + id) }
Spree.routes.product = function(id) { return Spree.localizedPathFor('products/' + id) }
Spree.routes.product_related = function(id) { return Spree.localizedPathFor('products/' + id + '/related') }
Spree.routes.product_carousel = function (taxonId) { return Spree.localizedPathFor('product_carousel/' + taxonId) }
Spree.routes.set_locale = function(locale) { return Spree.pathFor('locale/set?switch_to_locale=' + locale) }
Spree.routes.set_currency = function(currency) { return Spree.pathFor('currency/set?switch_to_currency=' + currency) }

Spree.showProgressBar = function () {
  if (!Turbolinks.supported) { return }
  Turbolinks.controller.adapter.progressBar.setValue(0)
  Turbolinks.controller.adapter.progressBar.show()
}

Spree.clearCache = function () {
  if (!Turbolinks.supported) { return }

  Turbolinks.clearCache()
}

Spree.setCurrency = function (currency) {
  Spree.clearCache()

  var params = (new URL(window.location)).searchParams
  if (currency === SPREE_DEFAULT_CURRENCY) {
    params.delete('currency')
  } else {
    params.set('currency', currency)
  }
  var queryString = params.toString()
  if (queryString !== '') { queryString = '?' + queryString }

  SPREE_CURRENCY = currency

  Turbolinks.visit(window.location.pathname + queryString, { action: 'replace' })
};
// Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/backend/all.js';
/*
 ### jQuery Star Rating Plugin v4.11 - 2013-03-14 ###
 * Home: http://www.fyneworks.com/jquery/star-rating/
 * Code: http://code.google.com/p/jquery-star-rating-plugin/
 *
	* Licensed under http://en.wikipedia.org/wiki/MIT_License
 ###
*/

/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
	
	// IE6 Background Image Fix
	if ((!$.support.opacity &amp;&amp; !$.support.style)) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
	// Thanks to http://www.visualjquery.com/rating/rating_redux.html
	
	// plugin initialization
	$.fn.rating = function(options){
		if(this.length==0) return this; // quick fail
		
		// Handle API methods
		if(typeof arguments[0]=='string'){
			// Perform API methods on individual elements
			if(this.length&gt;1){
				var args = arguments;
				return this.each(function(){
					$.fn.rating.apply($(this), args);
    });
			};
			// Invoke API method handler
			$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.rating.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Allow multiple controls with the same name by making each call unique
		$.fn.rating.calls++;
		
		// loop through each matched element
		this
		 .not('.star-rating-applied')
			.addClass('star-rating-applied')
		.each(function(){
			
			// Load control parameters / find context / etc
			var control, input = $(this);
			var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
			var context = $(this.form || document.body);
			
			// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
			var raters = context.data('rating');
			if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls };
			var rater = raters[eid] || context.data('rating'+eid);
			
			// if rater is available, verify that the control still exists
			if(rater) control = rater.data('rating');
			
			if(rater &amp;&amp; control)//{// save a byte!
				// add star to control if rater is available and the same control still exists
				control.count++;
				
			//}// save a byte!
			else{
				// create new control if first star or control element was removed/replaced
				
				// Initialize options for this rater
				control = $.extend(
					{}/* new object */,
					options || {} /* current call options */,
					($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
					{ count:0, stars: [], inputs: [] }
				);
				
				// increment number of rating controls
				control.serial = raters.count++;
				
				// create rating element
				rater = $('&lt;span class="star-rating-control"/&gt;');
				input.before(rater);
				
				// Mark element for initialization (once all stars are ready)
				rater.addClass('rating-to-be-drawn');
				
				// Accept readOnly setting from 'disabled' property
				if(input.attr('disabled') || input.hasClass('disabled')) control.readOnly = true;
				
				// Accept required setting from class property (class='required')
				if(input.hasClass('required')) control.required = true;
				
				// Create 'cancel' button
				rater.append(
					control.cancel = $('&lt;div class="rating-cancel"&gt;&lt;a title="' + control.cancel + '"&gt;' + control.cancelValue + '&lt;/a&gt;&lt;/div&gt;')
					.on('mouseover',function(){
						$(this).rating('drain');
						$(this).addClass('star-rating-hover');
						//$(this).rating('focus');
					})
					.on('mouseout',function(){
						$(this).rating('draw');
						$(this).removeClass('star-rating-hover');
						//$(this).rating('blur');
					})
					.on('click',function(){
					 $(this).rating('select');
					})
					.data('rating', control)
				);
				
			}; // first element of group
			
			// insert rating star (thanks Jan Fanslau rev125 for blind support https://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=125)
			var star = $('&lt;div role="text" aria-label="'+ this.title +'" class="star-rating rater-'+ control.serial +'"&gt;&lt;a title="' + (this.title || this.value) + '"&gt;' + this.value + '&lt;/a&gt;&lt;/div&gt;');
			rater.append(star);
			
			// inherit attributes from input element
			if(this.id) star.attr('id', this.id);
			if(this.className) star.addClass(this.className);
			
			// Half-stars?
			if(control.half) control.split = 2;
			
			// Prepare division control
			if(typeof control.split=='number' &amp;&amp; control.split&gt;0){
				var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
				var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
				star
				// restrict star's width and hide overflow (already in CSS)
				.width(spw)
				// move the star left by using a negative margin
				// this is work-around to IE's stupid box model (position:relative doesn't work)
				.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
			};
			
			// readOnly?
			if(control.readOnly)//{ //save a byte!
				// Mark star as readOnly so user can customize display
				star.addClass('star-rating-readonly');
			//}  //save a byte!
			else//{ //save a byte!
			 // Enable hover css effects
				star.addClass('star-rating-live')
				 // Attach mouse events
					.on('mouseover',function(){
						$(this).rating('fill');
						$(this).rating('focus');
					})
					.on('mouseout',function(){
						$(this).rating('draw');
						$(this).rating('blur');
					})
					.on('click',function(){
						$(this).rating('select');
					})
				;
			//}; //save a byte!
			
			// set current selection
			if(this.checked)	control.current = star;
			
			// set current select for links
			if(this.nodeName=="A"){
    if($(this).hasClass('selected'))
     control.current = star;
   };
			
			// hide input element
			input.hide();
			
			// backward compatibility, form element to plugin
			input.on('change.rating',function(event){
				if(event.selfTriggered) return false;
    $(this).rating('select');
   });
			
			// attach reference to star to input element and vice-versa
			star.data('rating.input', input.data('rating.star', star));
			
			// store control information in form (or body when form not available)
			control.stars[control.stars.length] = star[0];
			control.inputs[control.inputs.length] = input[0];
			control.rater = raters[eid] = rater;
			control.context = context;
			
			input.data('rating', control);
			rater.data('rating', control);
			star.data('rating', control);
			context.data('rating', raters);
			context.data('rating'+eid, rater); // required for ajax forms
  }); // each element
		
		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
		
		return this; // don't break the chain...
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.rating, {
		// Used to append a unique serial number to internal control ID
		// each time the plugin is invoked so same name controls can co-exist
		calls: 0,
		
		focus: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.focus) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // focus handler, as requested by focusdigital.co.uk
			if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.focus
		
		blur: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.blur) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // blur handler, as requested by focusdigital.co.uk
			if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.blur
		
		fill: function(){ // fill to the current mouse position.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars and highlight them up to this element
			this.rating('drain');
			this.prevAll().addBack().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.rating.fill
		
		drain: function() { // drain all the stars.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars
			control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
		},// $.fn.rating.drain
		
		draw: function(){ // set value and stars to reflect current selection
			var control = this.data('rating'); if(!control) return this;
			// Clear all stars
			this.rating('drain');
			// Set control value
			var current = $( control.current );//? control.current.data('rating.input') : null );
			var starson = current.length ? current.prevAll().addBack().filter('.rater-'+ control.serial) : null;
			if(starson)	starson.addClass('star-rating-on');
			// Show/hide 'cancel' button
			control.cancel[control.readOnly || control.required?'hide':'show']();
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
		},// $.fn.rating.draw
		
		
		
		
		
		select: function(value,wantCallBack){ // select a value
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// clear selection
			control.current = null;
			// programmatically (based on user input)
			if(typeof value!='undefined' || this.length&gt;1){
			 // select by index (0 based)
				if(typeof value=='number')
 			 return $(control.stars[value]).rating('select',undefined,wantCallBack);
				// select by literal value (must be passed as a string
				if(typeof value=='string'){
					//return
					$.each(control.stars, function(){
 					//console.log($(this).data('rating.input'), $(this).data('rating.input').val(), value, $(this).data('rating.input').val()==value?'BINGO!':'');
						if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack);
					});
					// don't break the chain
  			return this;
				};
			}
			else{
				control.current = this[0].tagName=='INPUT' ?
				 this.data('rating.star') :
					(this.is('.rater-'+ control.serial) ? this : null);
			};
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
			// find current input and its sibblings
			var current = $( control.current ? control.current.data('rating.input') : null );
			var lastipt = $( control.inputs ).filter(':checked');
			var deadipt = $( control.inputs ).not(current);
			// check and uncheck elements as required
			deadipt.prop('checked',false);//.removeAttr('checked');
			current.prop('checked',true);//.attr('checked','checked');
			// trigger change on current or last selected input
			$(current.length? current : lastipt ).trigger({ type:'change', selfTriggered:true });
			// click callback, as requested here: http://plugins.jquery.com/node/1655
			if((wantCallBack || wantCallBack == undefined) &amp;&amp; control.callback) control.callback.apply(current[0], [current.val(), $('a', control.current)[0]]);// callback event
			// don't break the chain
			return this;
  },// $.fn.rating.select
		
		
		
		
		
		readOnly: function(toggle, disable){ // make the control read-only (still submits value)
			var control = this.data('rating'); if(!control) return this;
			// setread-only status
			control.readOnly = toggle || toggle==undefined ? true : false;
			// enable/disable control value submission
			if(disable) $(control.inputs).attr("disabled", "disabled");
			else     			$(control.inputs).removeAttr("disabled");
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
		},// $.fn.rating.readOnly
		
		disable: function(){ // make read-only and never submit value
			this.rating('readOnly', true, true);
		},// $.fn.rating.disable
		
		enable: function(){ // make read/write and submit value
			this.rating('readOnly', false, false);
		}// $.fn.rating.select
		
 });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.rating.options.cancel = 'Clear';
	*/
	$.fn.rating.options = { //$.extend($.fn.rating, { options: {
			cancel: 'Cancel Rating',   // advisory title for the 'cancel' link
			cancelValue: '',           // value to submit when user click the 'cancel' link
			split: 0,                  // split the star into how many parts?
			
			// Width of star image in case the plugin can't work it out. This can happen if
			// the jQuery.dimensions plugin is not available OR the image is hidden at installation
			starWidth: 16//,
			
			//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
			//half:     false,         // just a shortcut to control.split = 2
			//required: false,         // disables the 'cancel' button so user can only select one of the specified values
			//readOnly: false,         // disable rating plugin interaction/ values cannot be.one('change',		//focus:    function(){},  // executed when stars are focused
			//blur:     function(){},  // executed when stars are focused
			//callback: function(){},  // executed when a star is clicked
 }; //} });
	
	/*--------------------------------------------------------*/
	
	
	  // auto-initialize plugin
				$(function(){
				 $('input[type=radio].star').rating();
				});
	
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/;


// Navigating to a page with ratings via TurboLinks shows the radio buttons
$(document).on('page:load', function () {
  $('input[type=radio].star').rating();
});
/*! @license DOMPurify | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.0.8/LICENSE */

(function (global, factory) {
  typeof exports === 'object' &amp;&amp; typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' &amp;&amp; define.amd ? define(factory) :
  (global = global || self, global.DOMPurify = factory());
}(this, function () { 'use strict';

  function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i &lt; arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

  var hasOwnProperty = Object.hasOwnProperty,
      setPrototypeOf = Object.setPrototypeOf,
      isFrozen = Object.isFrozen,
      objectKeys = Object.keys;
  var freeze = Object.freeze,
      seal = Object.seal; // eslint-disable-line import/no-mutable-exports

  var _ref = typeof Reflect !== 'undefined' &amp;&amp; Reflect,
      apply = _ref.apply,
      construct = _ref.construct;

  if (!apply) {
    apply = function apply(fun, thisValue, args) {
      return fun.apply(thisValue, args);
    };
  }

  if (!freeze) {
    freeze = function freeze(x) {
      return x;
    };
  }

  if (!seal) {
    seal = function seal(x) {
      return x;
    };
  }

  if (!construct) {
    construct = function construct(Func, args) {
      return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
    };
  }

  var arrayForEach = unapply(Array.prototype.forEach);
  var arrayIndexOf = unapply(Array.prototype.indexOf);
  var arrayJoin = unapply(Array.prototype.join);
  var arrayPop = unapply(Array.prototype.pop);
  var arrayPush = unapply(Array.prototype.push);
  var arraySlice = unapply(Array.prototype.slice);

  var stringToLowerCase = unapply(String.prototype.toLowerCase);
  var stringMatch = unapply(String.prototype.match);
  var stringReplace = unapply(String.prototype.replace);
  var stringIndexOf = unapply(String.prototype.indexOf);
  var stringTrim = unapply(String.prototype.trim);

  var regExpTest = unapply(RegExp.prototype.test);
  var regExpCreate = unconstruct(RegExp);

  var typeErrorCreate = unconstruct(TypeError);

  function unapply(func) {
    return function (thisArg) {
      for (var _len = arguments.length, args = Array(_len &gt; 1 ? _len - 1 : 0), _key = 1; _key &lt; _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      return apply(func, thisArg, args);
    };
  }

  function unconstruct(func) {
    return function () {
      for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 &lt; _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      return construct(func, args);
    };
  }

  /* Add properties to a lookup table */
  function addToSet(set, array) {
    if (setPrototypeOf) {
      // Make 'in' and truthy checks like Boolean(set.constructor)
      // independent of any properties defined on Object.prototype.
      // Prevent prototype setters from intercepting set as a this value.
      setPrototypeOf(set, null);
    }

    var l = array.length;
    while (l--) {
      var element = array[l];
      if (typeof element === 'string') {
        var lcElement = stringToLowerCase(element);
        if (lcElement !== element) {
          // Config presets (e.g. tags.js, attrs.js) are immutable.
          if (!isFrozen(array)) {
            array[l] = lcElement;
          }

          element = lcElement;
        }
      }

      set[element] = true;
    }

    return set;
  }

  /* Shallow clone an object */
  function clone(object) {
    var newObject = {};

    var property = void 0;
    for (property in object) {
      if (apply(hasOwnProperty, object, [property])) {
        newObject[property] = object[property];
      }
    }

    return newObject;
  }

  var html = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);

  // SVG
  var svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'audio', 'canvas', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'video', 'view', 'vkern']);

  var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);

  var mathMl = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']);

  var text = freeze(['#text']);

  var html$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns']);

  var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);

  var mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);

  var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);

  // eslint-disable-next-line unicorn/better-regex
  var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
  var ERB_EXPR = seal(/&lt;%[\s\S]*|[\s\S]*%&gt;/gm);
  var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
  var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
  var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
  );
  var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g // eslint-disable-line no-control-regex
  );

  var _typeof = typeof Symbol === "function" &amp;&amp; typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj &amp;&amp; typeof Symbol === "function" &amp;&amp; obj.constructor === Symbol &amp;&amp; obj !== Symbol.prototype ? "symbol" : typeof obj; };

  function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i &lt; arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

  var getGlobal = function getGlobal() {
    return typeof window === 'undefined' ? null : window;
  };

  /**
   * Creates a no-op policy for internal use only.
   * Don't export this function outside this module!
   * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
   * @param {Document} document The document object (to determine policy name suffix)
   * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
   * are not supported).
   */
  var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
    if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
      return null;
    }

    // Allow the callers to control the unique policy name
    // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
    // Policy creation with duplicate names throws in Trusted Types.
    var suffix = null;
    var ATTR_NAME = 'data-tt-policy-suffix';
    if (document.currentScript &amp;&amp; document.currentScript.hasAttribute(ATTR_NAME)) {
      suffix = document.currentScript.getAttribute(ATTR_NAME);
    }

    var policyName = 'dompurify' + (suffix ? '#' + suffix : '');

    try {
      return trustedTypes.createPolicy(policyName, {
        createHTML: function createHTML(html$$1) {
          return html$$1;
        }
      });
    } catch (_) {
      // Policy creation failed (most likely another DOMPurify script has
      // already run). Skip creating the policy, as this will only cause errors
      // if TT are enforced.
      console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
      return null;
    }
  };

  function createDOMPurify() {
    var window = arguments.length &gt; 0 &amp;&amp; arguments[0] !== undefined ? arguments[0] : getGlobal();

    var DOMPurify = function DOMPurify(root) {
      return createDOMPurify(root);
    };

    /**
     * Version label, exposed for easier checks
     * if DOMPurify is up to date or not
     */
    DOMPurify.version = '2.0.12';

    /**
     * Array of elements that DOMPurify removed during sanitation.
     * Empty if nothing was removed.
     */
    DOMPurify.removed = [];

    if (!window || !window.document || window.document.nodeType !== 9) {
      // Not running in a browser, provide a factory function
      // so that you can pass your own Window
      DOMPurify.isSupported = false;

      return DOMPurify;
    }

    var originalDocument = window.document;
    var removeTitle = false;

    var document = window.document;
    var DocumentFragment = window.DocumentFragment,
        HTMLTemplateElement = window.HTMLTemplateElement,
        Node = window.Node,
        NodeFilter = window.NodeFilter,
        _window$NamedNodeMap = window.NamedNodeMap,
        NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
        Text = window.Text,
        Comment = window.Comment,
        DOMParser = window.DOMParser,
        trustedTypes = window.trustedTypes;

    // As per issue #47, the web-components registry is inherited by a
    // new document created via createHTMLDocument. As per the spec
    // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
    // a new empty registry is used when creating a template contents owner
    // document, so we use that as our parent document to ensure nothing
    // is inherited.

    if (typeof HTMLTemplateElement === 'function') {
      var template = document.createElement('template');
      if (template.content &amp;&amp; template.content.ownerDocument) {
        document = template.content.ownerDocument;
      }
    }

    var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
    var emptyHTML = trustedTypesPolicy &amp;&amp; RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : '';

    var _document = document,
        implementation = _document.implementation,
        createNodeIterator = _document.createNodeIterator,
        getElementsByTagName = _document.getElementsByTagName,
        createDocumentFragment = _document.createDocumentFragment;
    var importNode = originalDocument.importNode;


    var hooks = {};

    /**
     * Expose whether this browser supports running the full DOMPurify.
     */
    DOMPurify.isSupported = implementation &amp;&amp; typeof implementation.createHTMLDocument !== 'undefined' &amp;&amp; document.documentMode !== 9;

    var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,
        ERB_EXPR$$1 = ERB_EXPR,
        DATA_ATTR$$1 = DATA_ATTR,
        ARIA_ATTR$$1 = ARIA_ATTR,
        IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,
        ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
    var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;

    /**
     * We consider the elements and attributes below to be safe. Ideally
     * don't add any new ones but feel free to remove unwanted ones.
     */

    /* allowed element names */

    var ALLOWED_TAGS = null;
    var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));

    /* Allowed attribute names */
    var ALLOWED_ATTR = null;
    var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));

    /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
    var FORBID_TAGS = null;

    /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
    var FORBID_ATTR = null;

    /* Decide if ARIA attributes are okay */
    var ALLOW_ARIA_ATTR = true;

    /* Decide if custom data attributes are okay */
    var ALLOW_DATA_ATTR = true;

    /* Decide if unknown protocols are okay */
    var ALLOW_UNKNOWN_PROTOCOLS = false;

    /* Output should be safe for jQuery's $() factory? */
    var SAFE_FOR_JQUERY = false;

    /* Output should be safe for common template engines.
     * This means, DOMPurify removes data attributes, mustaches and ERB
     */
    var SAFE_FOR_TEMPLATES = false;

    /* Decide if document with &lt;html&gt;... should be returned */
    var WHOLE_DOCUMENT = false;

    /* Track whether config is already set on this instance of DOMPurify. */
    var SET_CONFIG = false;

    /* Decide if all elements (e.g. style, script) must be children of
     * document.body. By default, browsers might move them to document.head */
    var FORCE_BODY = false;

    /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
     * string (or a TrustedHTML object if Trusted Types are supported).
     * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
     */
    var RETURN_DOM = false;

    /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
     * string  (or a TrustedHTML object if Trusted Types are supported) */
    var RETURN_DOM_FRAGMENT = false;

    /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM
     * `Node` is imported into the current `Document`. If this flag is not enabled the
     * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by
     * DOMPurify. */
    var RETURN_DOM_IMPORT = false;

    /* Try to return a Trusted Type object instead of a string, return a string in
     * case Trusted Types are not supported  */
    var RETURN_TRUSTED_TYPE = false;

    /* Output should be free from DOM clobbering attacks? */
    var SANITIZE_DOM = true;

    /* Keep element content when removing element? */
    var KEEP_CONTENT = true;

    /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
     * of importing it into a new Document and returning a sanitized copy */
    var IN_PLACE = false;

    /* Allow usage of profiles like html, svg and mathMl */
    var USE_PROFILES = {};

    /* Tags to ignore content of when KEEP_CONTENT is true */
    var FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);

    /* Tags that are safe for data: URIs */
    var DATA_URI_TAGS = null;
    var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);

    /* Attributes safe for values like "javascript:" */
    var URI_SAFE_ATTRIBUTES = null;
    var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'summary', 'title', 'value', 'style', 'xmlns']);

    /* Keep a reference to config to pass to hooks */
    var CONFIG = null;

    /* Ideally, do not touch anything below this line */
    /* ______________________________________________ */

    var formElement = document.createElement('form');

    /**
     * _parseConfig
     *
     * @param  {Object} cfg optional config literal
     */
    // eslint-disable-next-line complexity
    var _parseConfig = function _parseConfig(cfg) {
      if (CONFIG &amp;&amp; CONFIG === cfg) {
        return;
      }

      /* Shield configuration object from tampering */
      if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
        cfg = {};
      }

      /* Set configuration parameters */
      ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
      ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
      URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
      DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
      FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
      FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
      USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
      ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
      ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
      ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
      SAFE_FOR_JQUERY = cfg.SAFE_FOR_JQUERY || false; // Default false
      SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
      WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
      RETURN_DOM = cfg.RETURN_DOM || false; // Default false
      RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
      RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT || false; // Default false
      RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
      FORCE_BODY = cfg.FORCE_BODY || false; // Default false
      SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
      KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
      IN_PLACE = cfg.IN_PLACE || false; // Default false
      IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
      if (SAFE_FOR_TEMPLATES) {
        ALLOW_DATA_ATTR = false;
      }

      if (RETURN_DOM_FRAGMENT) {
        RETURN_DOM = true;
      }

      /* Parse profile info */
      if (USE_PROFILES) {
        ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
        ALLOWED_ATTR = [];
        if (USE_PROFILES.html === true) {
          addToSet(ALLOWED_TAGS, html);
          addToSet(ALLOWED_ATTR, html$1);
        }

        if (USE_PROFILES.svg === true) {
          addToSet(ALLOWED_TAGS, svg);
          addToSet(ALLOWED_ATTR, svg$1);
          addToSet(ALLOWED_ATTR, xml);
        }

        if (USE_PROFILES.svgFilters === true) {
          addToSet(ALLOWED_TAGS, svgFilters);
          addToSet(ALLOWED_ATTR, svg$1);
          addToSet(ALLOWED_ATTR, xml);
        }

        if (USE_PROFILES.mathMl === true) {
          addToSet(ALLOWED_TAGS, mathMl);
          addToSet(ALLOWED_ATTR, mathMl$1);
          addToSet(ALLOWED_ATTR, xml);
        }
      }

      /* Merge configuration parameters */
      if (cfg.ADD_TAGS) {
        if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
          ALLOWED_TAGS = clone(ALLOWED_TAGS);
        }

        addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
      }

      if (cfg.ADD_ATTR) {
        if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
          ALLOWED_ATTR = clone(ALLOWED_ATTR);
        }

        addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
      }

      if (cfg.ADD_URI_SAFE_ATTR) {
        addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
      }

      /* Add #text in case KEEP_CONTENT is set to true */
      if (KEEP_CONTENT) {
        ALLOWED_TAGS['#text'] = true;
      }

      /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
      if (WHOLE_DOCUMENT) {
        addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
      }

      /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
      if (ALLOWED_TAGS.table) {
        addToSet(ALLOWED_TAGS, ['tbody']);
        delete FORBID_TAGS.tbody;
      }

      // Prevent further manipulation of configuration.
      // Not available in IE8, Safari 5, etc.
      if (freeze) {
        freeze(cfg);
      }

      CONFIG = cfg;
    };

    /**
     * _forceRemove
     *
     * @param  {Node} node a DOM node
     */
    var _forceRemove = function _forceRemove(node) {
      arrayPush(DOMPurify.removed, { element: node });
      try {
        // eslint-disable-next-line unicorn/prefer-node-remove
        node.parentNode.removeChild(node);
      } catch (_) {
        node.outerHTML = emptyHTML;
      }
    };

    /**
     * _removeAttribute
     *
     * @param  {String} name an Attribute name
     * @param  {Node} node a DOM node
     */
    var _removeAttribute = function _removeAttribute(name, node) {
      try {
        arrayPush(DOMPurify.removed, {
          attribute: node.getAttributeNode(name),
          from: node
        });
      } catch (_) {
        arrayPush(DOMPurify.removed, {
          attribute: null,
          from: node
        });
      }

      node.removeAttribute(name);
    };

    /**
     * _initDocument
     *
     * @param  {String} dirty a string of dirty markup
     * @return {Document} a DOM, filled with the dirty markup
     */
    var _initDocument = function _initDocument(dirty) {
      /* Create a HTML document */
      var doc = void 0;
      var leadingWhitespace = void 0;

      if (FORCE_BODY) {
        dirty = '&lt;remove&gt;&lt;/remove&gt;' + dirty;
      } else {
        /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
        var matches = stringMatch(dirty, /^[\r\n\t ]+/);
        leadingWhitespace = matches &amp;&amp; matches[0];
      }

      var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
      /* Use the DOMParser API by default, fallback later if needs be */
      try {
        doc = new DOMParser().parseFromString(dirtyPayload, 'text/html');
      } catch (_) {}

      /* Remove title to fix a mXSS bug in older MS Edge */
      if (removeTitle) {
        addToSet(FORBID_TAGS, ['title']);
      }

      /* Use createHTMLDocument in case DOMParser is not available */
      if (!doc || !doc.documentElement) {
        doc = implementation.createHTMLDocument('');
        var _doc = doc,
            body = _doc.body;

        body.parentNode.removeChild(body.parentNode.firstElementChild);
        body.outerHTML = dirtyPayload;
      }

      if (dirty &amp;&amp; leadingWhitespace) {
        doc.body.insertBefore(document.createTextNode(leadingWhitespace), doc.body.childNodes[0] || null);
      }

      /* Work on whole document or just its body */
      return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
    };

    /* Here we test for a broken feature in Edge that might cause mXSS */
    if (DOMPurify.isSupported) {
      (function () {
        try {
          var doc = _initDocument('&lt;x/&gt;&lt;title&gt;&amp;lt;/title&amp;gt;&amp;lt;img&amp;gt;');
          if (regExpTest(/&lt;\/title/, doc.querySelector('title').innerHTML)) {
            removeTitle = true;
          }
        } catch (_) {}
      })();
    }

    /**
     * _createIterator
     *
     * @param  {Document} root document/fragment to create iterator for
     * @return {Iterator} iterator instance
     */
    var _createIterator = function _createIterator(root) {
      return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, function () {
        return NodeFilter.FILTER_ACCEPT;
      }, false);
    };

    /**
     * _isClobbered
     *
     * @param  {Node} elm element to check for clobbering attacks
     * @return {Boolean} true if clobbered, false if safe
     */
    var _isClobbered = function _isClobbered(elm) {
      if (elm instanceof Text || elm instanceof Comment) {
        return false;
      }

      if (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string') {
        return true;
      }

      return false;
    };

    /**
     * _isNode
     *
     * @param  {Node} obj object to check whether it's a DOM node
     * @return {Boolean} true is object is a DOM node
     */
    var _isNode = function _isNode(object) {
      return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object &amp;&amp; (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' &amp;&amp; typeof object.nodeType === 'number' &amp;&amp; typeof object.nodeName === 'string';
    };

    /**
     * _executeHook
     * Execute user configurable hooks
     *
     * @param  {String} entryPoint  Name of the hook's entry point
     * @param  {Node} currentNode node to work on with the hook
     * @param  {Object} data additional hook parameters
     */
    var _executeHook = function _executeHook(entryPoint, currentNode, data) {
      if (!hooks[entryPoint]) {
        return;
      }

      arrayForEach(hooks[entryPoint], function (hook) {
        hook.call(DOMPurify, currentNode, data, CONFIG);
      });
    };

    /**
     * _sanitizeElements
     *
     * @protect nodeName
     * @protect textContent
     * @protect removeChild
     *
     * @param   {Node} currentNode to check for permission to exist
     * @return  {Boolean} true if node was killed, false if left alive
     */
    // eslint-disable-next-line complexity
    var _sanitizeElements = function _sanitizeElements(currentNode) {
      var content = void 0;

      /* Execute a hook if present */
      _executeHook('beforeSanitizeElements', currentNode, null);

      /* Check if element is clobbered or can clobber */
      if (_isClobbered(currentNode)) {
        _forceRemove(currentNode);
        return true;
      }

      /* Now let's check the element's type and name */
      var tagName = stringToLowerCase(currentNode.nodeName);

      /* Execute a hook if present */
      _executeHook('uponSanitizeElement', currentNode, {
        tagName: tagName,
        allowedTags: ALLOWED_TAGS
      });

      /* Take care of an mXSS pattern using p, br inside svg, math */
      if ((tagName === 'svg' || tagName === 'math') &amp;&amp; currentNode.querySelectorAll('p, br').length !== 0) {
        _forceRemove(currentNode);
        return true;
      }

      /* Remove element if anything forbids its presence */
      if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
        /* Keep content except for bad-listed elements */
        if (KEEP_CONTENT &amp;&amp; !FORBID_CONTENTS[tagName] &amp;&amp; typeof currentNode.insertAdjacentHTML === 'function') {
          try {
            var htmlToInsert = currentNode.innerHTML;
            currentNode.insertAdjacentHTML('AfterEnd', trustedTypesPolicy ? trustedTypesPolicy.createHTML(htmlToInsert) : htmlToInsert);
          } catch (_) {}
        }

        _forceRemove(currentNode);
        return true;
      }

      /* Remove in case a noscript/noembed XSS is suspected */
      if (tagName === 'noscript' &amp;&amp; regExpTest(/&lt;\/noscript/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);
        return true;
      }

      if (tagName === 'noembed' &amp;&amp; regExpTest(/&lt;\/noembed/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);
        return true;
      }

      /* Convert markup to cover jQuery behavior */
      if (SAFE_FOR_JQUERY &amp;&amp; !currentNode.firstElementChild &amp;&amp; (!currentNode.content || !currentNode.content.firstElementChild) &amp;&amp; regExpTest(/&lt;/g, currentNode.textContent)) {
        arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
        if (currentNode.innerHTML) {
          currentNode.innerHTML = stringReplace(currentNode.innerHTML, /&lt;/g, '&amp;lt;');
        } else {
          currentNode.innerHTML = stringReplace(currentNode.textContent, /&lt;/g, '&amp;lt;');
        }
      }

      /* Sanitize element content to be template-safe */
      if (SAFE_FOR_TEMPLATES &amp;&amp; currentNode.nodeType === 3) {
        /* Get the element's text content */
        content = currentNode.textContent;
        content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');
        content = stringReplace(content, ERB_EXPR$$1, ' ');
        if (currentNode.textContent !== content) {
          arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
          currentNode.textContent = content;
        }
      }

      /* Execute a hook if present */
      _executeHook('afterSanitizeElements', currentNode, null);

      return false;
    };

    /**
     * _isValidAttribute
     *
     * @param  {string} lcTag Lowercase tag name of containing element.
     * @param  {string} lcName Lowercase attribute name.
     * @param  {string} value Attribute value.
     * @return {Boolean} Returns true if `value` is valid, otherwise false.
     */
    // eslint-disable-next-line complexity
    var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
      /* Make sure attribute cannot clobber */
      if (SANITIZE_DOM &amp;&amp; (lcName === 'id' || lcName === 'name') &amp;&amp; (value in document || value in formElement)) {
        return false;
      }

      /* Allow valid data-* attributes: At least one character after "-"
          (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
          XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
          We don't need to check the value; it's always URI safe. */
      if (ALLOW_DATA_ATTR &amp;&amp; regExpTest(DATA_ATTR$$1, lcName)) ; else if (ALLOW_ARIA_ATTR &amp;&amp; regExpTest(ARIA_ATTR$$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
        return false;

        /* Check value is safe. First, is attr inert? If so, is safe */
      } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &amp;&amp; lcTag !== 'script' &amp;&amp; stringIndexOf(value, 'data:') === 0 &amp;&amp; DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS &amp;&amp; !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if (!value) ; else {
        return false;
      }

      return true;
    };

    /**
     * _sanitizeAttributes
     *
     * @protect attributes
     * @protect nodeName
     * @protect removeAttribute
     * @protect setAttribute
     *
     * @param  {Node} currentNode to sanitize
     */
    // eslint-disable-next-line complexity
    var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
      var attr = void 0;
      var value = void 0;
      var lcName = void 0;
      var idAttr = void 0;
      var l = void 0;
      /* Execute a hook if present */
      _executeHook('beforeSanitizeAttributes', currentNode, null);

      var attributes = currentNode.attributes;

      /* Check if we have attributes; if not we might have a text node */

      if (!attributes) {
        return;
      }

      var hookEvent = {
        attrName: '',
        attrValue: '',
        keepAttr: true,
        allowedAttributes: ALLOWED_ATTR
      };
      l = attributes.length;

      /* Go backwards over all attributes; safely remove bad ones */
      while (l--) {
        attr = attributes[l];
        var _attr = attr,
            name = _attr.name,
            namespaceURI = _attr.namespaceURI;

        value = stringTrim(attr.value);
        lcName = stringToLowerCase(name);

        /* Execute a hook if present */
        hookEvent.attrName = lcName;
        hookEvent.attrValue = value;
        hookEvent.keepAttr = true;
        hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
        _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
        value = hookEvent.attrValue;
        /* Did the hooks approve of the attribute? */
        if (hookEvent.forceKeepAttr) {
          continue;
        }

        /* Remove attribute */
        // Safari (iOS + Mac), last tested v8.0.5, crashes if you try to
        // remove a "name" attribute from an &lt;img&gt; tag that has an "id"
        // attribute at the time.
        if (lcName === 'name' &amp;&amp; currentNode.nodeName === 'IMG' &amp;&amp; attributes.id) {
          idAttr = attributes.id;
          attributes = arraySlice(attributes, []);
          _removeAttribute('id', currentNode);
          _removeAttribute(name, currentNode);
          if (arrayIndexOf(attributes, idAttr) &gt; l) {
            currentNode.setAttribute('id', idAttr.value);
          }
        } else if (
        // This works around a bug in Safari, where input[type=file]
        // cannot be dynamically set after type has been removed
        currentNode.nodeName === 'INPUT' &amp;&amp; lcName === 'type' &amp;&amp; value === 'file' &amp;&amp; hookEvent.keepAttr &amp;&amp; (ALLOWED_ATTR[lcName] || !FORBID_ATTR[lcName])) {
          continue;
        } else {
          // This avoids a crash in Safari v9.0 with double-ids.
          // The trick is to first set the id to be empty and then to
          // remove the attribute
          if (name === 'id') {
            currentNode.setAttribute(name, '');
          }

          _removeAttribute(name, currentNode);
        }

        /* Did the hooks approve of the attribute? */
        if (!hookEvent.keepAttr) {
          continue;
        }

        /* Work around a security issue in jQuery 3.0 */
        if (SAFE_FOR_JQUERY &amp;&amp; regExpTest(/\/&gt;/i, value)) {
          _removeAttribute(name, currentNode);
          continue;
        }

        /* Take care of an mXSS pattern using namespace switches */
        if (regExpTest(/svg|math/i, currentNode.namespaceURI) &amp;&amp; regExpTest(regExpCreate('&lt;/(' + arrayJoin(objectKeys(FORBID_CONTENTS), '|') + ')', 'i'), value)) {
          _removeAttribute(name, currentNode);
          continue;
        }

        /* Sanitize attribute content to be template-safe */
        if (SAFE_FOR_TEMPLATES) {
          value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');
          value = stringReplace(value, ERB_EXPR$$1, ' ');
        }

        /* Is `value` valid for this attribute? */
        var lcTag = currentNode.nodeName.toLowerCase();
        if (!_isValidAttribute(lcTag, lcName, value)) {
          continue;
        }

        /* Handle invalid data-* attribute set by try-catching it */
        try {
          if (namespaceURI) {
            currentNode.setAttributeNS(namespaceURI, name, value);
          } else {
            /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
            currentNode.setAttribute(name, value);
          }

          arrayPop(DOMPurify.removed);
        } catch (_) {}
      }

      /* Execute a hook if present */
      _executeHook('afterSanitizeAttributes', currentNode, null);
    };

    /**
     * _sanitizeShadowDOM
     *
     * @param  {DocumentFragment} fragment to iterate over recursively
     */
    var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
      var shadowNode = void 0;
      var shadowIterator = _createIterator(fragment);

      /* Execute a hook if present */
      _executeHook('beforeSanitizeShadowDOM', fragment, null);

      while (shadowNode = shadowIterator.nextNode()) {
        /* Execute a hook if present */
        _executeHook('uponSanitizeShadowNode', shadowNode, null);

        /* Sanitize tags and elements */
        if (_sanitizeElements(shadowNode)) {
          continue;
        }

        /* Deep shadow DOM detected */
        if (shadowNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(shadowNode.content);
        }

        /* Check attributes, sanitize if necessary */
        _sanitizeAttributes(shadowNode);
      }

      /* Execute a hook if present */
      _executeHook('afterSanitizeShadowDOM', fragment, null);
    };

    /**
     * Sanitize
     * Public method providing core sanitation functionality
     *
     * @param {String|Node} dirty string or DOM node
     * @param {Object} configuration object
     */
    // eslint-disable-next-line complexity
    DOMPurify.sanitize = function (dirty, cfg) {
      var body = void 0;
      var importedNode = void 0;
      var currentNode = void 0;
      var oldNode = void 0;
      var returnNode = void 0;
      /* Make sure we have a string to sanitize.
        DO NOT return early, as this will return the wrong type if
        the user has requested a DOM object rather than a string */
      if (!dirty) {
        dirty = '&lt;!--&gt;';
      }

      /* Stringify, in case dirty is an object */
      if (typeof dirty !== 'string' &amp;&amp; !_isNode(dirty)) {
        // eslint-disable-next-line no-negated-condition
        if (typeof dirty.toString !== 'function') {
          throw typeErrorCreate('toString is not a function');
        } else {
          dirty = dirty.toString();
          if (typeof dirty !== 'string') {
            throw typeErrorCreate('dirty is not a string, aborting');
          }
        }
      }

      /* Check we can run. Otherwise fall back or ignore */
      if (!DOMPurify.isSupported) {
        if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
          if (typeof dirty === 'string') {
            return window.toStaticHTML(dirty);
          }

          if (_isNode(dirty)) {
            return window.toStaticHTML(dirty.outerHTML);
          }
        }

        return dirty;
      }

      /* Assign config vars */
      if (!SET_CONFIG) {
        _parseConfig(cfg);
      }

      /* Clean up removed elements */
      DOMPurify.removed = [];

      /* Check if dirty is correctly typed for IN_PLACE */
      if (typeof dirty === 'string') {
        IN_PLACE = false;
      }

      if (IN_PLACE) ; else if (dirty instanceof Node) {
        /* If dirty is a DOM element, append to an empty document to avoid
           elements being stripped by the parser */
        body = _initDocument('&lt;!--&gt;');
        importedNode = body.ownerDocument.importNode(dirty, true);
        if (importedNode.nodeType === 1 &amp;&amp; importedNode.nodeName === 'BODY') {
          /* Node is already a body, use as is */
          body = importedNode;
        } else if (importedNode.nodeName === 'HTML') {
          body = importedNode;
        } else {
          // eslint-disable-next-line unicorn/prefer-node-append
          body.appendChild(importedNode);
        }
      } else {
        /* Exit directly if we have nothing to do */
        if (!RETURN_DOM &amp;&amp; !SAFE_FOR_TEMPLATES &amp;&amp; !WHOLE_DOCUMENT &amp;&amp;
        // eslint-disable-next-line unicorn/prefer-includes
        dirty.indexOf('&lt;') === -1) {
          return trustedTypesPolicy &amp;&amp; RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
        }

        /* Initialize the document to work on */
        body = _initDocument(dirty);

        /* Check we have a DOM node from the data */
        if (!body) {
          return RETURN_DOM ? null : emptyHTML;
        }
      }

      /* Remove first element node (ours) if FORCE_BODY is set */
      if (body &amp;&amp; FORCE_BODY) {
        _forceRemove(body.firstChild);
      }

      /* Get node iterator */
      var nodeIterator = _createIterator(IN_PLACE ? dirty : body);

      /* Now start iterating over the created document */
      while (currentNode = nodeIterator.nextNode()) {
        /* Fix IE's strange behavior with manipulated textNodes #89 */
        if (currentNode.nodeType === 3 &amp;&amp; currentNode === oldNode) {
          continue;
        }

        /* Sanitize tags and elements */
        if (_sanitizeElements(currentNode)) {
          continue;
        }

        /* Shadow DOM detected, sanitize it */
        if (currentNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(currentNode.content);
        }

        /* Check attributes, sanitize if necessary */
        _sanitizeAttributes(currentNode);

        oldNode = currentNode;
      }

      oldNode = null;

      /* If we sanitized `dirty` in-place, return it. */
      if (IN_PLACE) {
        return dirty;
      }

      /* Return sanitized string or DOM */
      if (RETURN_DOM) {
        if (RETURN_DOM_FRAGMENT) {
          returnNode = createDocumentFragment.call(body.ownerDocument);

          while (body.firstChild) {
            // eslint-disable-next-line unicorn/prefer-node-append
            returnNode.appendChild(body.firstChild);
          }
        } else {
          returnNode = body;
        }

        if (RETURN_DOM_IMPORT) {
          /*
            AdoptNode() is not used because internal state is not reset
            (e.g. the past names map of a HTMLFormElement), this is safe
            in theory but we would rather not risk another attack vector.
            The state that is cloned by importNode() is explicitly defined
            by the specs.
          */
          returnNode = importNode.call(originalDocument, returnNode, true);
        }

        return returnNode;
      }

      var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;

      /* Sanitize final string template-safe */
      if (SAFE_FOR_TEMPLATES) {
        serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');
        serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');
      }

      return trustedTypesPolicy &amp;&amp; RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
    };

    /**
     * Public method to set the configuration once
     * setConfig
     *
     * @param {Object} cfg configuration object
     */
    DOMPurify.setConfig = function (cfg) {
      _parseConfig(cfg);
      SET_CONFIG = true;
    };

    /**
     * Public method to remove the configuration
     * clearConfig
     *
     */
    DOMPurify.clearConfig = function () {
      CONFIG = null;
      SET_CONFIG = false;
    };

    /**
     * Public method to check if an attribute value is valid.
     * Uses last set config, if any. Otherwise, uses config defaults.
     * isValidAttribute
     *
     * @param  {string} tag Tag name of containing element.
     * @param  {string} attr Attribute name.
     * @param  {string} value Attribute value.
     * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
     */
    DOMPurify.isValidAttribute = function (tag, attr, value) {
      /* Initialize shared config vars if necessary. */
      if (!CONFIG) {
        _parseConfig({});
      }

      var lcTag = stringToLowerCase(tag);
      var lcName = stringToLowerCase(attr);
      return _isValidAttribute(lcTag, lcName, value);
    };

    /**
     * AddHook
     * Public method to add DOMPurify hooks
     *
     * @param {String} entryPoint entry point for the hook to add
     * @param {Function} hookFunction function to execute
     */
    DOMPurify.addHook = function (entryPoint, hookFunction) {
      if (typeof hookFunction !== 'function') {
        return;
      }

      hooks[entryPoint] = hooks[entryPoint] || [];
      arrayPush(hooks[entryPoint], hookFunction);
    };

    /**
     * RemoveHook
     * Public method to remove a DOMPurify hook at a given entryPoint
     * (pops it from the stack of hooks if more are present)
     *
     * @param {String} entryPoint entry point for the hook to remove
     */
    DOMPurify.removeHook = function (entryPoint) {
      if (hooks[entryPoint]) {
        arrayPop(hooks[entryPoint]);
      }
    };

    /**
     * RemoveHooks
     * Public method to remove all DOMPurify hooks at a given entryPoint
     *
     * @param  {String} entryPoint entry point for the hooks to remove
     */
    DOMPurify.removeHooks = function (entryPoint) {
      if (hooks[entryPoint]) {
        hooks[entryPoint] = [];
      }
    };

    /**
     * RemoveAllHooks
     * Public method to remove all DOMPurify hooks
     *
     */
    DOMPurify.removeAllHooks = function () {
      hooks = {};
    };

    return DOMPurify;
  }

  var purify = createDOMPurify();

  return purify;

}));
/*! Sortable 1.13.0 - MIT | git://github.com/SortableJS/Sortable.git */
!function(t,e){"object"==typeof exports&amp;&amp;"undefined"!=typeof module?module.exports=e():"function"==typeof define&amp;&amp;define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function o(t){return(o="function"==typeof Symbol&amp;&amp;"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&amp;&amp;"function"==typeof Symbol&amp;&amp;t.constructor===Symbol&amp;&amp;t!==Symbol.prototype?"symbol":typeof t})(t)}function a(){return(a=Object.assign||function(t){for(var e=1;e&lt;arguments.length;e++){var n=arguments[e];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&amp;&amp;(t[o]=n[o])}return t}).apply(this,arguments)}function I(i){for(var t=1;t&lt;arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},e=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&amp;&amp;(e=e.concat(Object.getOwnPropertySymbols(r).filter(function(t){return Object.getOwnPropertyDescriptor(r,t).enumerable}))),e.forEach(function(t){var e,n,o;e=i,o=r[n=t],n in e?Object.defineProperty(e,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[n]=o})}return i}function l(t,e){if(null==t)return{};var n,o,i=function(t,e){if(null==t)return{};var n,o,i={},r=Object.keys(t);for(o=0;o&lt;r.length;o++)n=r[o],0&lt;=e.indexOf(n)||(i[n]=t[n]);return i}(t,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(o=0;o&lt;r.length;o++)n=r[o],0&lt;=e.indexOf(n)||Object.prototype.propertyIsEnumerable.call(t,n)&amp;&amp;(i[n]=t[n])}return i}function e(t){return function(t){if(Array.isArray(t)){for(var e=0,n=new Array(t.length);e&lt;t.length;e++)n[e]=t[e];return n}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function t(t){if("undefined"!=typeof window&amp;&amp;window.navigator)return!!navigator.userAgent.match(t)}var w=t(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),E=t(/Edge/i),c=t(/firefox/i),u=t(/safari/i)&amp;&amp;!t(/chrome/i)&amp;&amp;!t(/android/i),n=t(/iP(ad|od|hone)/i),i=t(/chrome/i)&amp;&amp;t(/android/i),r={capture:!1,passive:!1};function d(t,e,n){t.addEventListener(e,n,!w&amp;&amp;r)}function s(t,e,n){t.removeEventListener(e,n,!w&amp;&amp;r)}function h(t,e){if(e){if("&gt;"===e[0]&amp;&amp;(e=e.substring(1)),t)try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return!1}return!1}}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&amp;&amp;("&gt;"===e[0]?t.parentNode===n&amp;&amp;h(t,e):h(t,e))||o&amp;&amp;t===n)return t;if(t===n)break}while(t=(i=t).host&amp;&amp;i!==document&amp;&amp;i.host.nodeType?i.host:i.parentNode)}var i;return null}var f,p=/\s+/g;function k(t,e,n){if(t&amp;&amp;e)if(t.classList)t.classList[n?"add":"remove"](e);else{var o=(" "+t.className+" ").replace(p," ").replace(" "+e+" "," ");t.className=(o+(n?" "+e:"")).replace(p," ")}}function R(t,e,n){var o=t&amp;&amp;t.style;if(o){if(void 0===n)return document.defaultView&amp;&amp;document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&amp;&amp;(n=t.currentStyle),void 0===e?n:n[e];e in o||-1!==e.indexOf("webkit")||(e="-webkit-"+e),o[e]=n+("string"==typeof n?"":"px")}}function v(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform");o&amp;&amp;"none"!==o&amp;&amp;(n=o+" "+n)}while(!e&amp;&amp;(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&amp;&amp;new i(n)}function g(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i&lt;r;i++)n(o[i],i);return o}return[]}function A(){var t=document.scrollingElement;return t||document.documentElement}function X(t,e,n,o,i){if(t.getBoundingClientRect||t===window){var r,a,l,s,c,u,d;if(d=t!==window&amp;&amp;t.parentNode&amp;&amp;t!==A()?(a=(r=t.getBoundingClientRect()).top,l=r.left,s=r.bottom,c=r.right,u=r.height,r.width):(l=a=0,s=window.innerHeight,c=window.innerWidth,u=window.innerHeight,window.innerWidth),(e||n)&amp;&amp;t!==window&amp;&amp;(i=i||t.parentNode,!w))do{if(i&amp;&amp;i.getBoundingClientRect&amp;&amp;("none"!==R(i,"transform")||n&amp;&amp;"static"!==R(i,"position"))){var h=i.getBoundingClientRect();a-=h.top+parseInt(R(i,"border-top-width")),l-=h.left+parseInt(R(i,"border-left-width")),s=a+r.height,c=l+r.width;break}}while(i=i.parentNode);if(o&amp;&amp;t!==window){var f=v(i||t),p=f&amp;&amp;f.a,g=f&amp;&amp;f.d;f&amp;&amp;(s=(a/=g)+(u/=g),c=(l/=p)+(d/=p))}return{top:a,left:l,bottom:s,right:c,width:d,height:u}}}function Y(t,e,n){for(var o=H(t,!0),i=X(t)[e];o;){var r=X(o)[n];if(!("top"===n||"left"===n?r&lt;=i:i&lt;=r))return o;if(o===A())break;o=H(o,!1)}return!1}function m(t,e,n){for(var o=0,i=0,r=t.children;i&lt;r.length;){if("none"!==r[i].style.display&amp;&amp;r[i]!==Rt.ghost&amp;&amp;r[i]!==Rt.dragged&amp;&amp;P(r[i],n.draggable,t,!1)){if(o===e)return r[i];o++}i++}return null}function B(t,e){for(var n=t.lastElementChild;n&amp;&amp;(n===Rt.ghost||"none"===R(n,"display")||e&amp;&amp;!h(n,e));)n=n.previousElementSibling;return n||null}function F(t,e){var n=0;if(!t||!t.parentNode)return-1;for(;t=t.previousElementSibling;)"TEMPLATE"===t.nodeName.toUpperCase()||t===Rt.clone||e&amp;&amp;!h(t,e)||n++;return n}function b(t){var e=0,n=0,o=A();if(t)do{var i=v(t),r=i.a,a=i.d;e+=t.scrollLeft*r,n+=t.scrollTop*a}while(t!==o&amp;&amp;(t=t.parentNode));return[e,n]}function H(t,e){if(!t||!t.getBoundingClientRect)return A();var n=t,o=!1;do{if(n.clientWidth&lt;n.scrollWidth||n.clientHeight&lt;n.scrollHeight){var i=R(n);if(n.clientWidth&lt;n.scrollWidth&amp;&amp;("auto"==i.overflowX||"scroll"==i.overflowX)||n.clientHeight&lt;n.scrollHeight&amp;&amp;("auto"==i.overflowY||"scroll"==i.overflowY)){if(!n.getBoundingClientRect||n===document.body)return A();if(o||e)return n;o=!0}}}while(n=n.parentNode);return A()}function y(t,e){return Math.round(t.top)===Math.round(e.top)&amp;&amp;Math.round(t.left)===Math.round(e.left)&amp;&amp;Math.round(t.height)===Math.round(e.height)&amp;&amp;Math.round(t.width)===Math.round(e.width)}function D(e,n){return function(){if(!f){var t=arguments;1===t.length?e.call(this,t[0]):e.apply(this,t),f=setTimeout(function(){f=void 0},n)}}}function L(t,e,n){t.scrollLeft+=e,t.scrollTop+=n}function S(t){var e=window.Polymer,n=window.jQuery||window.Zepto;return e&amp;&amp;e.dom?e.dom(t).cloneNode(!0):n?n(t).clone(!0)[0]:t.cloneNode(!0)}function _(t,e){R(t,"position","absolute"),R(t,"top",e.top),R(t,"left",e.left),R(t,"width",e.width),R(t,"height",e.height)}function C(t){R(t,"position",""),R(t,"top",""),R(t,"left",""),R(t,"width",""),R(t,"height","")}var j="Sortable"+(new Date).getTime();function T(){var e,o=[];return{captureAnimationState:function(){o=[],this.options.animation&amp;&amp;[].slice.call(this.el.children).forEach(function(t){if("none"!==R(t,"display")&amp;&amp;t!==Rt.ghost){o.push({target:t,rect:X(t)});var e=I({},o[o.length-1].rect);if(t.thisAnimationDuration){var n=v(t,!0);n&amp;&amp;(e.top-=n.f,e.left-=n.e)}t.fromRect=e}})},addAnimationState:function(t){o.push(t)},removeAnimationState:function(t){o.splice(function(t,e){for(var n in t)if(t.hasOwnProperty(n))for(var o in e)if(e.hasOwnProperty(o)&amp;&amp;e[o]===t[n][o])return Number(n);return-1}(o,{target:t}),1)},animateAll:function(t){var c=this;if(!this.options.animation)return clearTimeout(e),void("function"==typeof t&amp;&amp;t());var u=!1,d=0;o.forEach(function(t){var e=0,n=t.target,o=n.fromRect,i=X(n),r=n.prevFromRect,a=n.prevToRect,l=t.rect,s=v(n,!0);s&amp;&amp;(i.top-=s.f,i.left-=s.e),n.toRect=i,n.thisAnimationDuration&amp;&amp;y(r,i)&amp;&amp;!y(o,i)&amp;&amp;(l.top-i.top)/(l.left-i.left)==(o.top-i.top)/(o.left-i.left)&amp;&amp;(e=function(t,e,n,o){return Math.sqrt(Math.pow(e.top-t.top,2)+Math.pow(e.left-t.left,2))/Math.sqrt(Math.pow(e.top-n.top,2)+Math.pow(e.left-n.left,2))*o.animation}(l,r,a,c.options)),y(i,o)||(n.prevFromRect=o,n.prevToRect=i,e||(e=c.options.animation),c.animate(n,l,i,e)),e&amp;&amp;(u=!0,d=Math.max(d,e),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout(function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null},e),n.thisAnimationDuration=e)}),clearTimeout(e),u?e=setTimeout(function(){"function"==typeof t&amp;&amp;t()},d):"function"==typeof t&amp;&amp;t(),o=[]},animate:function(t,e,n,o){if(o){R(t,"transition",""),R(t,"transform","");var i=v(this.el),r=i&amp;&amp;i.a,a=i&amp;&amp;i.d,l=(e.left-n.left)/(r||1),s=(e.top-n.top)/(a||1);t.animatingX=!!l,t.animatingY=!!s,R(t,"transform","translate3d("+l+"px,"+s+"px,0)"),this.forRepaintDummy=function(t){return t.offsetWidth}(t),R(t,"transition","transform "+o+"ms"+(this.options.easing?" "+this.options.easing:"")),R(t,"transform","translate3d(0,0,0)"),"number"==typeof t.animated&amp;&amp;clearTimeout(t.animated),t.animated=setTimeout(function(){R(t,"transition",""),R(t,"transform",""),t.animated=!1,t.animatingX=!1,t.animatingY=!1},o)}}}}var x=[],M={initializeByDefault:!0},O={mount:function(e){for(var t in M)!M.hasOwnProperty(t)||t in e||(e[t]=M[t]);x.forEach(function(t){if(t.pluginName===e.pluginName)throw"Sortable: Cannot mount plugin ".concat(e.pluginName," more than once")}),x.push(e)},pluginEvent:function(e,n,o){var t=this;this.eventCanceled=!1,o.cancel=function(){t.eventCanceled=!0};var i=e+"Global";x.forEach(function(t){n[t.pluginName]&amp;&amp;(n[t.pluginName][i]&amp;&amp;n[t.pluginName][i](I({sortable:n},o)),n.options[t.pluginName]&amp;&amp;n[t.pluginName][e]&amp;&amp;n[t.pluginName][e](I({sortable:n},o)))})},initializePlugins:function(o,i,r,t){for(var e in x.forEach(function(t){var e=t.pluginName;if(o.options[e]||t.initializeByDefault){var n=new t(o,i,o.options);n.sortable=o,n.options=o.options,o[e]=n,a(r,n.defaults)}}),o.options)if(o.options.hasOwnProperty(e)){var n=this.modifyOption(o,e,o.options[e]);void 0!==n&amp;&amp;(o.options[e]=n)}},getEventProperties:function(e,n){var o={};return x.forEach(function(t){"function"==typeof t.eventProperties&amp;&amp;a(o,t.eventProperties.call(n[t.pluginName],e))}),o},modifyOption:function(e,n,o){var i;return x.forEach(function(t){e[t.pluginName]&amp;&amp;t.optionListeners&amp;&amp;"function"==typeof t.optionListeners[n]&amp;&amp;(i=t.optionListeners[n].call(e[t.pluginName],o))}),i}};function N(t){var e=t.sortable,n=t.rootEl,o=t.name,i=t.targetEl,r=t.cloneEl,a=t.toEl,l=t.fromEl,s=t.oldIndex,c=t.newIndex,u=t.oldDraggableIndex,d=t.newDraggableIndex,h=t.originalEvent,f=t.putSortable,p=t.extraEventProperties;if(e=e||n&amp;&amp;n[j]){var g,v=e.options,m="on"+o.charAt(0).toUpperCase()+o.substr(1);!window.CustomEvent||w||E?(g=document.createEvent("Event")).initEvent(o,!0,!0):g=new CustomEvent(o,{bubbles:!0,cancelable:!0}),g.to=a||n,g.from=l||n,g.item=i||n,g.clone=r,g.oldIndex=s,g.newIndex=c,g.oldDraggableIndex=u,g.newDraggableIndex=d,g.originalEvent=h,g.pullMode=f?f.lastPutMode:void 0;var b=I({},p,O.getEventProperties(o,e));for(var y in b)g[y]=b[y];n&amp;&amp;n.dispatchEvent(g),v[m]&amp;&amp;v[m].call(e,g)}}function K(t,e,n){var o=2&lt;arguments.length&amp;&amp;void 0!==n?n:{},i=o.evt,r=l(o,["evt"]);O.pluginEvent.bind(Rt)(t,e,I({dragEl:z,parentEl:G,ghostEl:U,rootEl:q,nextEl:V,lastDownEl:Z,cloneEl:Q,cloneHidden:$,dragStarted:dt,putSortable:it,activeSortable:Rt.active,originalEvent:i,oldIndex:J,oldDraggableIndex:et,newIndex:tt,newDraggableIndex:nt,hideGhostForTarget:At,unhideGhostForTarget:It,cloneNowHidden:function(){$=!0},cloneNowShown:function(){$=!1},dispatchSortableEvent:function(t){W({sortable:e,name:t,originalEvent:i})}},r))}function W(t){N(I({putSortable:it,cloneEl:Q,targetEl:z,rootEl:q,oldIndex:J,oldDraggableIndex:et,newIndex:tt,newDraggableIndex:nt},t))}var z,G,U,q,V,Z,Q,$,J,tt,et,nt,ot,it,rt,at,lt,st,ct,ut,dt,ht,ft,pt,gt,vt=!1,mt=!1,bt=[],yt=!1,wt=!1,Et=[],Dt=!1,St=[],_t="undefined"!=typeof document,Ct=n,Tt=E||w?"cssFloat":"float",xt=_t&amp;&amp;!i&amp;&amp;!n&amp;&amp;"draggable"in document.createElement("div"),Mt=function(){if(_t){if(w)return!1;var t=document.createElement("x");return t.style.cssText="pointer-events:auto","auto"===t.style.pointerEvents}}(),Ot=function(t,e){var n=R(t),o=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=m(t,0,e),r=m(t,1,e),a=i&amp;&amp;R(i),l=r&amp;&amp;R(r),s=a&amp;&amp;parseInt(a.marginLeft)+parseInt(a.marginRight)+X(i).width,c=l&amp;&amp;parseInt(l.marginLeft)+parseInt(l.marginRight)+X(r).width;if("flex"===n.display)return"column"===n.flexDirection||"column-reverse"===n.flexDirection?"vertical":"horizontal";if("grid"===n.display)return n.gridTemplateColumns.split(" ").length&lt;=1?"vertical":"horizontal";if(i&amp;&amp;a.float&amp;&amp;"none"!==a.float){var u="left"===a.float?"left":"right";return!r||"both"!==l.clear&amp;&amp;l.clear!==u?"horizontal":"vertical"}return i&amp;&amp;("block"===a.display||"flex"===a.display||"table"===a.display||"grid"===a.display||o&lt;=s&amp;&amp;"none"===n[Tt]||r&amp;&amp;"none"===n[Tt]&amp;&amp;o&lt;s+c)?"vertical":"horizontal"},Nt=function(t){function s(a,l){return function(t,e,n,o){var i=t.options.group.name&amp;&amp;e.options.group.name&amp;&amp;t.options.group.name===e.options.group.name;if(null==a&amp;&amp;(l||i))return!0;if(null==a||!1===a)return!1;if(l&amp;&amp;"clone"===a)return a;if("function"==typeof a)return s(a(t,e,n,o),l)(t,e,n,o);var r=(l?t:e).options.group.name;return!0===a||"string"==typeof a&amp;&amp;a===r||a.join&amp;&amp;-1&lt;a.indexOf(r)}}var e={},n=t.group;n&amp;&amp;"object"==o(n)||(n={name:n}),e.name=n.name,e.checkPull=s(n.pull,!0),e.checkPut=s(n.put),e.revertClone=n.revertClone,t.group=e},At=function(){!Mt&amp;&amp;U&amp;&amp;R(U,"display","none")},It=function(){!Mt&amp;&amp;U&amp;&amp;R(U,"display","")};_t&amp;&amp;document.addEventListener("click",function(t){if(mt)return t.preventDefault(),t.stopPropagation&amp;&amp;t.stopPropagation(),t.stopImmediatePropagation&amp;&amp;t.stopImmediatePropagation(),mt=!1},!0);function Pt(t){if(z){var e=function(r,a){var l;return bt.some(function(t){if(!B(t)){var e=X(t),n=t[j].options.emptyInsertThreshold,o=r&gt;=e.left-n&amp;&amp;r&lt;=e.right+n,i=a&gt;=e.top-n&amp;&amp;a&lt;=e.bottom+n;return n&amp;&amp;o&amp;&amp;i?l=t:void 0}}),l}((t=t.touches?t.touches[0]:t).clientX,t.clientY);if(e){var n={};for(var o in t)t.hasOwnProperty(o)&amp;&amp;(n[o]=t[o]);n.target=n.rootEl=e,n.preventDefault=void 0,n.stopPropagation=void 0,e[j]._onDragOver(n)}}}function kt(t){z&amp;&amp;z.parentNode[j]._isOutsideThisEl(t.target)}function Rt(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[j]=this;var n={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?"&gt;li":"&gt;*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Ot(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==Rt.supportPointer&amp;&amp;"PointerEvent"in window&amp;&amp;!u,emptyInsertThreshold:5};for(var o in O.initializePlugins(this,t,n),n)o in e||(e[o]=n[o]);for(var i in Nt(e),this)"_"===i.charAt(0)&amp;&amp;"function"==typeof this[i]&amp;&amp;(this[i]=this[i].bind(this));this.nativeDraggable=!e.forceFallback&amp;&amp;xt,this.nativeDraggable&amp;&amp;(this.options.touchStartThreshold=1),e.supportPointer?d(t,"pointerdown",this._onTapStart):(d(t,"mousedown",this._onTapStart),d(t,"touchstart",this._onTapStart)),this.nativeDraggable&amp;&amp;(d(t,"dragover",this),d(t,"dragenter",this)),bt.push(this.el),e.store&amp;&amp;e.store.get&amp;&amp;this.sort(e.store.get(this)||[]),a(this,T())}function Xt(t,e,n,o,i,r,a,l){var s,c,u=t[j],d=u.options.onMove;return!window.CustomEvent||w||E?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),d&amp;&amp;(c=d.call(u,s,a)),c}function Yt(t){t.draggable=!1}function Bt(){Dt=!1}function Ft(t){for(var e=t.tagName+t.className+t.src+t.href+t.textContent,n=e.length,o=0;n--;)o+=e.charCodeAt(n);return o.toString(36)}function Ht(t){return setTimeout(t,0)}function Lt(t){return clearTimeout(t)}Rt.prototype={constructor:Rt,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(ht=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,z):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&amp;&amp;e.touches[0]||e.pointerType&amp;&amp;"touch"===e.pointerType&amp;&amp;e,l=(a||e).target,s=e.target.shadowRoot&amp;&amp;(e.path&amp;&amp;e.path[0]||e.composedPath&amp;&amp;e.composedPath()[0])||l,c=t.filter;if(function(t){St.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&amp;&amp;St.push(o)}}(o),!z&amp;&amp;!(/mousedown|pointerdown/.test(r)&amp;&amp;0!==e.button||t.disabled)&amp;&amp;!s.isContentEditable&amp;&amp;(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&amp;&amp;!((l=P(l,t.draggable,o,!1))&amp;&amp;l.animated||Z===l)){if(J=F(l),et=F(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return W({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),K("filter",n,{evt:e}),void(i&amp;&amp;e.cancelable&amp;&amp;e.preventDefault())}else if(c&amp;&amp;(c=c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return W({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),K("filter",n,{evt:e}),!0})))return void(i&amp;&amp;e.cancelable&amp;&amp;e.preventDefault());t.handle&amp;&amp;!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;if(n&amp;&amp;!z&amp;&amp;n.parentNode===r){var s=X(n);if(q=r,G=(z=n).parentNode,V=z.nextSibling,Z=n,ot=a.group,rt={target:Rt.dragged=z,clientX:(e||t).clientX,clientY:(e||t).clientY},ct=rt.clientX-s.left,ut=rt.clientY-s.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,z.style["will-change"]="all",o=function(){K("delayEnded",i,{evt:t}),Rt.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!c&amp;&amp;i.nativeDraggable&amp;&amp;(z.draggable=!0),i._triggerDragStart(t,e),W({sortable:i,name:"choose",originalEvent:t}),k(z,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){g(z,t.trim(),Yt)}),d(l,"dragover",Pt),d(l,"mousemove",Pt),d(l,"touchmove",Pt),d(l,"mouseup",i._onDrop),d(l,"touchend",i._onDrop),d(l,"touchcancel",i._onDrop),c&amp;&amp;this.nativeDraggable&amp;&amp;(this.options.touchStartThreshold=4,z.draggable=!0),K("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&amp;&amp;!e||this.nativeDraggable&amp;&amp;(E||w))o();else{if(Rt.eventCanceled)return void this._onDrop();d(l,"mouseup",i._disableDelayedDrag),d(l,"touchend",i._disableDelayedDrag),d(l,"touchcancel",i._disableDelayedDrag),d(l,"mousemove",i._delayedDragTouchMoveHandler),d(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&amp;&amp;d(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)}}},_delayedDragTouchMoveHandler:function(t){var e=t.touches?t.touches[0]:t;Math.max(Math.abs(e.clientX-this._lastX),Math.abs(e.clientY-this._lastY))&gt;=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&amp;&amp;window.devicePixelRatio||1))&amp;&amp;this._disableDelayedDrag()},_disableDelayedDrag:function(){z&amp;&amp;Yt(z),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;s(t,"mouseup",this._disableDelayedDrag),s(t,"touchend",this._disableDelayedDrag),s(t,"touchcancel",this._disableDelayedDrag),s(t,"mousemove",this._delayedDragTouchMoveHandler),s(t,"touchmove",this._delayedDragTouchMoveHandler),s(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&amp;&amp;t,!this.nativeDraggable||e?this.options.supportPointer?d(document,"pointermove",this._onTouchMove):d(document,e?"touchmove":"mousemove",this._onTouchMove):(d(z,"dragend",this),d(q,"dragstart",this._onDragStart));try{document.selection?Ht(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){if(vt=!1,q&amp;&amp;z){K("dragStarted",this,{evt:e}),this.nativeDraggable&amp;&amp;d(document,"dragover",kt);var n=this.options;t||k(z,n.dragClass,!1),k(z,n.ghostClass,!0),Rt.active=this,t&amp;&amp;this._appendGhost(),W({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(at){this._lastX=at.clientX,this._lastY=at.clientY,At();for(var t=document.elementFromPoint(at.clientX,at.clientY),e=t;t&amp;&amp;t.shadowRoot&amp;&amp;(t=t.shadowRoot.elementFromPoint(at.clientX,at.clientY))!==e;)e=t;if(z.parentNode[j]._isOutsideThisEl(t),e)do{if(e[j]){if(e[j]._onDragOver({clientX:at.clientX,clientY:at.clientY,target:t,rootEl:e})&amp;&amp;!this.options.dragoverBubble)break}t=e}while(e=e.parentNode);It()}},_onTouchMove:function(t){if(rt){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=U&amp;&amp;v(U,!0),a=U&amp;&amp;r&amp;&amp;r.a,l=U&amp;&amp;r&amp;&amp;r.d,s=Ct&amp;&amp;gt&amp;&amp;b(gt),c=(i.clientX-rt.clientX+o.x)/(a||1)+(s?s[0]-Et[0]:0)/(a||1),u=(i.clientY-rt.clientY+o.y)/(l||1)+(s?s[1]-Et[1]:0)/(l||1);if(!Rt.active&amp;&amp;!vt){if(n&amp;&amp;Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))&lt;n)return;this._onDragStart(t,!0)}if(U){r?(r.e+=c-(lt||0),r.f+=u-(st||0)):r={a:1,b:0,c:0,d:1,e:c,f:u};var d="matrix(".concat(r.a,",").concat(r.b,",").concat(r.c,",").concat(r.d,",").concat(r.e,",").concat(r.f,")");R(U,"webkitTransform",d),R(U,"mozTransform",d),R(U,"msTransform",d),R(U,"transform",d),lt=c,st=u,at=i}t.cancelable&amp;&amp;t.preventDefault()}},_appendGhost:function(){if(!U){var t=this.options.fallbackOnBody?document.body:q,e=X(z,!0,Ct,!0,t),n=this.options;if(Ct){for(gt=t;"static"===R(gt,"position")&amp;&amp;"none"===R(gt,"transform")&amp;&amp;gt!==document;)gt=gt.parentNode;gt!==document.body&amp;&amp;gt!==document.documentElement?(gt===document&amp;&amp;(gt=A()),e.top+=gt.scrollTop,e.left+=gt.scrollLeft):gt=A(),Et=b(gt)}k(U=z.cloneNode(!0),n.ghostClass,!1),k(U,n.fallbackClass,!0),k(U,n.dragClass,!0),R(U,"transition",""),R(U,"transform",""),R(U,"box-sizing","border-box"),R(U,"margin",0),R(U,"top",e.top),R(U,"left",e.left),R(U,"width",e.width),R(U,"height",e.height),R(U,"opacity","0.8"),R(U,"position",Ct?"absolute":"fixed"),R(U,"zIndex","100000"),R(U,"pointerEvents","none"),Rt.ghost=U,t.appendChild(U),R(U,"transform-origin",ct/parseInt(U.style.width)*100+"% "+ut/parseInt(U.style.height)*100+"%")}},_onDragStart:function(t,e){var n=this,o=t.dataTransfer,i=n.options;K("dragStart",this,{evt:t}),Rt.eventCanceled?this._onDrop():(K("setupClone",this),Rt.eventCanceled||((Q=S(z)).draggable=!1,Q.style["will-change"]="",this._hideClone(),k(Q,this.options.chosenClass,!1),Rt.clone=Q),n.cloneId=Ht(function(){K("clone",n),Rt.eventCanceled||(n.options.removeCloneOnHide||q.insertBefore(Q,z),n._hideClone(),W({sortable:n,name:"clone"}))}),e||k(z,i.dragClass,!0),e?(mt=!0,n._loopId=setInterval(n._emulateDragOver,50)):(s(document,"mouseup",n._onDrop),s(document,"touchend",n._onDrop),s(document,"touchcancel",n._onDrop),o&amp;&amp;(o.effectAllowed="move",i.setData&amp;&amp;i.setData.call(n,o,z)),d(document,"drop",n),R(z,"transform","translateZ(0)")),vt=!0,n._dragStartId=Ht(n._dragStarted.bind(n,e,t)),d(document,"selectstart",n),dt=!0,u&amp;&amp;R(document.body,"user-select","none"))},_onDragOver:function(n){var o,i,r,a,l=this.el,s=n.target,e=this.options,t=e.group,c=Rt.active,u=ot===t,d=e.sort,h=it||c,f=this,p=!1;if(!Dt){if(void 0!==n.preventDefault&amp;&amp;n.cancelable&amp;&amp;n.preventDefault(),s=P(s,e.draggable,l,!0),M("dragOver"),Rt.eventCanceled)return p;if(z.contains(n.target)||s.animated&amp;&amp;s.animatingX&amp;&amp;s.animatingY||f._ignoreWhileAnimating===s)return N(!1);if(mt=!1,c&amp;&amp;!e.disabled&amp;&amp;(u?d||(r=!q.contains(z)):it===this||(this.lastPutMode=ot.checkPull(this,c,z,n))&amp;&amp;t.checkPut(this,c,z,n))){if(a="vertical"===this._getDirection(n,s),o=X(z),M("dragOverValid"),Rt.eventCanceled)return p;if(r)return G=q,O(),this._hideClone(),M("revert"),Rt.eventCanceled||(V?q.insertBefore(z,V):q.appendChild(z)),N(!0);var g=B(l,e.draggable);if(!g||function(t,e,n){var o=X(B(n.el,n.options.draggable));return e?t.clientX&gt;o.right+10||t.clientX&lt;=o.right&amp;&amp;t.clientY&gt;o.bottom&amp;&amp;t.clientX&gt;=o.left:t.clientX&gt;o.right&amp;&amp;t.clientY&gt;o.top||t.clientX&lt;=o.right&amp;&amp;t.clientY&gt;o.bottom+10}(n,a,this)&amp;&amp;!g.animated){if(g===z)return N(!1);if(g&amp;&amp;l===n.target&amp;&amp;(s=g),s&amp;&amp;(i=X(s)),!1!==Xt(q,l,z,o,s,i,n,!!s))return O(),l.appendChild(z),G=l,A(),N(!0)}else if(s.parentNode===l){i=X(s);var v,m,b,y=z.parentNode!==l,w=!function(t,e,n){var o=n?t.left:t.top,i=n?t.right:t.bottom,r=n?t.width:t.height,a=n?e.left:e.top,l=n?e.right:e.bottom,s=n?e.width:e.height;return o===a||i===l||o+r/2===a+s/2}(z.animated&amp;&amp;z.toRect||o,s.animated&amp;&amp;s.toRect||i,a),E=a?"top":"left",D=Y(s,"top","top")||Y(z,"top","top"),S=D?D.scrollTop:void 0;if(ht!==s&amp;&amp;(m=i[E],yt=!1,wt=!w&amp;&amp;e.invertSwap||y),0!==(v=function(t,e,n,o,i,r,a,l){var s=o?t.clientY:t.clientX,c=o?n.height:n.width,u=o?n.top:n.left,d=o?n.bottom:n.right,h=!1;if(!a)if(l&amp;&amp;pt&lt;c*i){if(!yt&amp;&amp;(1===ft?u+c*r/2&lt;s:s&lt;d-c*r/2)&amp;&amp;(yt=!0),yt)h=!0;else if(1===ft?s&lt;u+pt:d-pt&lt;s)return-ft}else if(u+c*(1-i)/2&lt;s&amp;&amp;s&lt;d-c*(1-i)/2)return function(t){return F(z)&lt;F(t)?1:-1}(e);if((h=h||a)&amp;&amp;(s&lt;u+c*r/2||d-c*r/2&lt;s))return u+c/2&lt;s?1:-1;return 0}(n,s,i,a,w?1:e.swapThreshold,null==e.invertedSwapThreshold?e.swapThreshold:e.invertedSwapThreshold,wt,ht===s)))for(var _=F(z);_-=v,(b=G.children[_])&amp;&amp;("none"===R(b,"display")||b===U););if(0===v||b===s)return N(!1);ft=v;var C=(ht=s).nextElementSibling,T=!1,x=Xt(q,l,z,o,s,i,n,T=1===v);if(!1!==x)return 1!==x&amp;&amp;-1!==x||(T=1===x),Dt=!0,setTimeout(Bt,30),O(),T&amp;&amp;!C?l.appendChild(z):s.parentNode.insertBefore(z,T?C:s),D&amp;&amp;L(D,0,S-D.scrollTop),G=z.parentNode,void 0===m||wt||(pt=Math.abs(m-X(s)[E])),A(),N(!0)}if(l.contains(z))return N(!1)}return!1}function M(t,e){K(t,f,I({evt:n,isOwner:u,axis:a?"vertical":"horizontal",revert:r,dragRect:o,targetRect:i,canSort:d,fromSortable:h,target:s,completed:N,onMove:function(t,e){return Xt(q,l,z,o,t,X(t),n,e)},changed:A},e))}function O(){M("dragOverAnimationCapture"),f.captureAnimationState(),f!==h&amp;&amp;h.captureAnimationState()}function N(t){return M("dragOverCompleted",{insertion:t}),t&amp;&amp;(u?c._hideClone():c._showClone(f),f!==h&amp;&amp;(k(z,it?it.options.ghostClass:c.options.ghostClass,!1),k(z,e.ghostClass,!0)),it!==f&amp;&amp;f!==Rt.active?it=f:f===Rt.active&amp;&amp;it&amp;&amp;(it=null),h===f&amp;&amp;(f._ignoreWhileAnimating=s),f.animateAll(function(){M("dragOverAnimationComplete"),f._ignoreWhileAnimating=null}),f!==h&amp;&amp;(h.animateAll(),h._ignoreWhileAnimating=null)),(s===z&amp;&amp;!z.animated||s===l&amp;&amp;!s.animated)&amp;&amp;(ht=null),e.dragoverBubble||n.rootEl||s===document||(z.parentNode[j]._isOutsideThisEl(n.target),t||Pt(n)),!e.dragoverBubble&amp;&amp;n.stopPropagation&amp;&amp;n.stopPropagation(),p=!0}function A(){tt=F(z),nt=F(z,e.draggable),W({sortable:f,name:"change",toEl:l,newIndex:tt,newDraggableIndex:nt,originalEvent:n})}},_ignoreWhileAnimating:null,_offMoveEvents:function(){s(document,"mousemove",this._onTouchMove),s(document,"touchmove",this._onTouchMove),s(document,"pointermove",this._onTouchMove),s(document,"dragover",Pt),s(document,"mousemove",Pt),s(document,"touchmove",Pt)},_offUpEvents:function(){var t=this.el.ownerDocument;s(t,"mouseup",this._onDrop),s(t,"touchend",this._onDrop),s(t,"pointerup",this._onDrop),s(t,"touchcancel",this._onDrop),s(document,"selectstart",this)},_onDrop:function(t){var e=this.el,n=this.options;tt=F(z),nt=F(z,n.draggable),K("drop",this,{evt:t}),G=z&amp;&amp;z.parentNode,tt=F(z),nt=F(z,n.draggable),Rt.eventCanceled||(yt=wt=vt=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),Lt(this.cloneId),Lt(this._dragStartId),this.nativeDraggable&amp;&amp;(s(document,"drop",this),s(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),u&amp;&amp;R(document.body,"user-select",""),R(z,"transform",""),t&amp;&amp;(dt&amp;&amp;(t.cancelable&amp;&amp;t.preventDefault(),n.dropBubble||t.stopPropagation()),U&amp;&amp;U.parentNode&amp;&amp;U.parentNode.removeChild(U),(q===G||it&amp;&amp;"clone"!==it.lastPutMode)&amp;&amp;Q&amp;&amp;Q.parentNode&amp;&amp;Q.parentNode.removeChild(Q),z&amp;&amp;(this.nativeDraggable&amp;&amp;s(z,"dragend",this),Yt(z),z.style["will-change"]="",dt&amp;&amp;!vt&amp;&amp;k(z,it?it.options.ghostClass:this.options.ghostClass,!1),k(z,this.options.chosenClass,!1),W({sortable:this,name:"unchoose",toEl:G,newIndex:null,newDraggableIndex:null,originalEvent:t}),q!==G?(0&lt;=tt&amp;&amp;(W({rootEl:G,name:"add",toEl:G,fromEl:q,originalEvent:t}),W({sortable:this,name:"remove",toEl:G,originalEvent:t}),W({rootEl:G,name:"sort",toEl:G,fromEl:q,originalEvent:t}),W({sortable:this,name:"sort",toEl:G,originalEvent:t})),it&amp;&amp;it.save()):tt!==J&amp;&amp;0&lt;=tt&amp;&amp;(W({sortable:this,name:"update",toEl:G,originalEvent:t}),W({sortable:this,name:"sort",toEl:G,originalEvent:t})),Rt.active&amp;&amp;(null!=tt&amp;&amp;-1!==tt||(tt=J,nt=et),W({sortable:this,name:"end",toEl:G,originalEvent:t}),this.save())))),this._nulling()},_nulling:function(){K("nulling",this),q=z=G=U=V=Q=Z=$=rt=at=dt=tt=nt=J=et=ht=ft=it=ot=Rt.dragged=Rt.ghost=Rt.clone=Rt.active=null,St.forEach(function(t){t.checked=!0}),St.length=lt=st=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":z&amp;&amp;(this._onDragOver(t),function(t){t.dataTransfer&amp;&amp;(t.dataTransfer.dropEffect="move");t.cancelable&amp;&amp;t.preventDefault()}(t));break;case"selectstart":t.preventDefault()}},toArray:function(){for(var t,e=[],n=this.el.children,o=0,i=n.length,r=this.options;o&lt;i;o++)P(t=n[o],r.draggable,this.el,!1)&amp;&amp;e.push(t.getAttribute(r.dataIdAttr)||Ft(t));return e},sort:function(t,e){var o={},i=this.el;this.toArray().forEach(function(t,e){var n=i.children[e];P(n,this.options.draggable,i,!1)&amp;&amp;(o[t]=n)},this),e&amp;&amp;this.captureAnimationState(),t.forEach(function(t){o[t]&amp;&amp;(i.removeChild(o[t]),i.appendChild(o[t]))}),e&amp;&amp;this.animateAll()},save:function(){var t=this.options.store;t&amp;&amp;t.set&amp;&amp;t.set(this)},closest:function(t,e){return P(t,e||this.options.draggable,this.el,!1)},option:function(t,e){var n=this.options;if(void 0===e)return n[t];var o=O.modifyOption(this,t,e);n[t]=void 0!==o?o:e,"group"===t&amp;&amp;Nt(n)},destroy:function(){K("destroy",this);var t=this.el;t[j]=null,s(t,"mousedown",this._onTapStart),s(t,"touchstart",this._onTapStart),s(t,"pointerdown",this._onTapStart),this.nativeDraggable&amp;&amp;(s(t,"dragover",this),s(t,"dragenter",this)),Array.prototype.forEach.call(t.querySelectorAll("[draggable]"),function(t){t.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),bt.splice(bt.indexOf(this.el),1),this.el=t=null},_hideClone:function(){if(!$){if(K("hideClone",this),Rt.eventCanceled)return;R(Q,"display","none"),this.options.removeCloneOnHide&amp;&amp;Q.parentNode&amp;&amp;Q.parentNode.removeChild(Q),$=!0}},_showClone:function(t){if("clone"===t.lastPutMode){if($){if(K("showClone",this),Rt.eventCanceled)return;z.parentNode!=q||this.options.group.revertClone?V?q.insertBefore(Q,V):q.appendChild(Q):q.insertBefore(Q,z),this.options.group.revertClone&amp;&amp;this.animate(z,Q),R(Q,"display",""),$=!1}}else this._hideClone()}},_t&amp;&amp;d(document,"touchmove",function(t){(Rt.active||vt)&amp;&amp;t.cancelable&amp;&amp;t.preventDefault()}),Rt.utils={on:d,off:s,css:R,find:g,is:function(t,e){return!!P(t,e,t,!1)},extend:function(t,e){if(t&amp;&amp;e)for(var n in e)e.hasOwnProperty(n)&amp;&amp;(t[n]=e[n]);return t},throttle:D,closest:P,toggleClass:k,clone:S,index:F,nextTick:Ht,cancelNextTick:Lt,detectDirection:Ot,getChild:m},Rt.get=function(t){return t[j]},Rt.mount=function(){for(var t=arguments.length,e=new Array(t),n=0;n&lt;t;n++)e[n]=arguments[n];e[0].constructor===Array&amp;&amp;(e=e[0]),e.forEach(function(t){if(!t.prototype||!t.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(t));t.utils&amp;&amp;(Rt.utils=I({},Rt.utils,t.utils)),O.mount(t)})},Rt.create=function(t,e){return new Rt(t,e)};var jt,Kt,Wt,zt,Gt,Ut,qt=[],Vt=!(Rt.version="1.13.0");function Zt(){qt.forEach(function(t){clearInterval(t.pid)}),qt=[]}function Qt(){clearInterval(Ut)}function $t(t){var e=t.originalEvent,n=t.putSortable,o=t.dragEl,i=t.activeSortable,r=t.dispatchSortableEvent,a=t.hideGhostForTarget,l=t.unhideGhostForTarget;if(e){var s=n||i;a();var c=e.changedTouches&amp;&amp;e.changedTouches.length?e.changedTouches[0]:e,u=document.elementFromPoint(c.clientX,c.clientY);l(),s&amp;&amp;!s.el.contains(u)&amp;&amp;(r("spill"),this.onSpill({dragEl:o,putSortable:n}))}}var Jt,te=D(function(n,t,e,o){if(t.scroll){var i,r=(n.touches?n.touches[0]:n).clientX,a=(n.touches?n.touches[0]:n).clientY,l=t.scrollSensitivity,s=t.scrollSpeed,c=A(),u=!1;Kt!==e&amp;&amp;(Kt=e,Zt(),jt=t.scroll,i=t.scrollFn,!0===jt&amp;&amp;(jt=H(e,!0)));var d=0,h=jt;do{var f=h,p=X(f),g=p.top,v=p.bottom,m=p.left,b=p.right,y=p.width,w=p.height,E=void 0,D=void 0,S=f.scrollWidth,_=f.scrollHeight,C=R(f),T=f.scrollLeft,x=f.scrollTop;D=f===c?(E=y&lt;S&amp;&amp;("auto"===C.overflowX||"scroll"===C.overflowX||"visible"===C.overflowX),w&lt;_&amp;&amp;("auto"===C.overflowY||"scroll"===C.overflowY||"visible"===C.overflowY)):(E=y&lt;S&amp;&amp;("auto"===C.overflowX||"scroll"===C.overflowX),w&lt;_&amp;&amp;("auto"===C.overflowY||"scroll"===C.overflowY));var M=E&amp;&amp;(Math.abs(b-r)&lt;=l&amp;&amp;T+y&lt;S)-(Math.abs(m-r)&lt;=l&amp;&amp;!!T),O=D&amp;&amp;(Math.abs(v-a)&lt;=l&amp;&amp;x+w&lt;_)-(Math.abs(g-a)&lt;=l&amp;&amp;!!x);if(!qt[d])for(var N=0;N&lt;=d;N++)qt[N]||(qt[N]={});qt[d].vx==M&amp;&amp;qt[d].vy==O&amp;&amp;qt[d].el===f||(qt[d].el=f,qt[d].vx=M,qt[d].vy=O,clearInterval(qt[d].pid),0==M&amp;&amp;0==O||(u=!0,qt[d].pid=setInterval(function(){o&amp;&amp;0===this.layer&amp;&amp;Rt.active._onTouchMove(Gt);var t=qt[this.layer].vy?qt[this.layer].vy*s:0,e=qt[this.layer].vx?qt[this.layer].vx*s:0;"function"==typeof i&amp;&amp;"continue"!==i.call(Rt.dragged.parentNode[j],e,t,n,Gt,qt[this.layer].el)||L(qt[this.layer].el,e,t)}.bind({layer:d}),24))),d++}while(t.bubbleScroll&amp;&amp;h!==c&amp;&amp;(h=H(h,!1)));Vt=u}},30);function ee(){}function ne(){}ee.prototype={startIndex:null,dragStart:function(t){var e=t.oldDraggableIndex;this.startIndex=e},onSpill:function(t){var e=t.dragEl,n=t.putSortable;this.sortable.captureAnimationState(),n&amp;&amp;n.captureAnimationState();var o=m(this.sortable.el,this.startIndex,this.options);o?this.sortable.el.insertBefore(e,o):this.sortable.el.appendChild(e),this.sortable.animateAll(),n&amp;&amp;n.animateAll()},drop:$t},a(ee,{pluginName:"revertOnSpill"}),ne.prototype={onSpill:function(t){var e=t.dragEl,n=t.putSortable||this.sortable;n.captureAnimationState(),e.parentNode&amp;&amp;e.parentNode.removeChild(e),n.animateAll()},drop:$t},a(ne,{pluginName:"removeOnSpill"});var oe,ie,re,ae,le,se=[],ce=[],ue=!1,de=!1,he=!1;function fe(o,i){ce.forEach(function(t,e){var n=i.children[t.sortableIndex+(o?Number(e):0)];n?i.insertBefore(t,n):i.appendChild(t)})}function pe(){se.forEach(function(t){t!==re&amp;&amp;t.parentNode&amp;&amp;t.parentNode.removeChild(t)})}return Rt.mount(new function(){function t(){for(var t in this.defaults={scroll:!0,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)"_"===t.charAt(0)&amp;&amp;"function"==typeof this[t]&amp;&amp;(this[t]=this[t].bind(this))}return t.prototype={dragStarted:function(t){var e=t.originalEvent;this.sortable.nativeDraggable?d(document,"dragover",this._handleAutoScroll):this.options.supportPointer?d(document,"pointermove",this._handleFallbackAutoScroll):e.touches?d(document,"touchmove",this._handleFallbackAutoScroll):d(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(t){var e=t.originalEvent;this.options.dragOverBubble||e.rootEl||this._handleAutoScroll(e)},drop:function(){this.sortable.nativeDraggable?s(document,"dragover",this._handleAutoScroll):(s(document,"pointermove",this._handleFallbackAutoScroll),s(document,"touchmove",this._handleFallbackAutoScroll),s(document,"mousemove",this._handleFallbackAutoScroll)),Qt(),Zt(),clearTimeout(f),f=void 0},nulling:function(){Gt=Kt=jt=Vt=Ut=Wt=zt=null,qt.length=0},_handleFallbackAutoScroll:function(t){this._handleAutoScroll(t,!0)},_handleAutoScroll:function(e,n){var o=this,i=(e.touches?e.touches[0]:e).clientX,r=(e.touches?e.touches[0]:e).clientY,t=document.elementFromPoint(i,r);if(Gt=e,n||E||w||u){te(e,this.options,t,n);var a=H(t,!0);!Vt||Ut&amp;&amp;i===Wt&amp;&amp;r===zt||(Ut&amp;&amp;Qt(),Ut=setInterval(function(){var t=H(document.elementFromPoint(i,r),!0);t!==a&amp;&amp;(a=t,Zt()),te(e,o.options,t,n)},10),Wt=i,zt=r)}else{if(!this.options.bubbleScroll||H(t,!0)===A())return void Zt();te(e,this.options,H(t,!1),!1)}}},a(t,{pluginName:"scroll",initializeByDefault:!0})}),Rt.mount(ne,ee),Rt.mount(new function(){function t(){this.defaults={swapClass:"sortable-swap-highlight"}}return t.prototype={dragStart:function(t){var e=t.dragEl;Jt=e},dragOverValid:function(t){var e=t.completed,n=t.target,o=t.onMove,i=t.activeSortable,r=t.changed,a=t.cancel;if(i.options.swap){var l=this.sortable.el,s=this.options;if(n&amp;&amp;n!==l){var c=Jt;Jt=!1!==o(n)?(k(n,s.swapClass,!0),n):null,c&amp;&amp;c!==Jt&amp;&amp;k(c,s.swapClass,!1)}r(),e(!0),a()}},drop:function(t){var e=t.activeSortable,n=t.putSortable,o=t.dragEl,i=n||this.sortable,r=this.options;Jt&amp;&amp;k(Jt,r.swapClass,!1),Jt&amp;&amp;(r.swap||n&amp;&amp;n.options.swap)&amp;&amp;o!==Jt&amp;&amp;(i.captureAnimationState(),i!==e&amp;&amp;e.captureAnimationState(),function(t,e){var n,o,i=t.parentNode,r=e.parentNode;if(!i||!r||i.isEqualNode(e)||r.isEqualNode(t))return;n=F(t),o=F(e),i.isEqualNode(r)&amp;&amp;n&lt;o&amp;&amp;o++;i.insertBefore(e,i.children[n]),r.insertBefore(t,r.children[o])}(o,Jt),i.animateAll(),i!==e&amp;&amp;e.animateAll())},nulling:function(){Jt=null}},a(t,{pluginName:"swap",eventProperties:function(){return{swapItem:Jt}}})}),Rt.mount(new function(){function t(o){for(var t in this)"_"===t.charAt(0)&amp;&amp;"function"==typeof this[t]&amp;&amp;(this[t]=this[t].bind(this));o.options.supportPointer?d(document,"pointerup",this._deselectMultiDrag):(d(document,"mouseup",this._deselectMultiDrag),d(document,"touchend",this._deselectMultiDrag)),d(document,"keydown",this._checkKeyDown),d(document,"keyup",this._checkKeyUp),this.defaults={selectedClass:"sortable-selected",multiDragKey:null,setData:function(t,e){var n="";se.length&amp;&amp;ie===o?se.forEach(function(t,e){n+=(e?", ":"")+t.textContent}):n=e.textContent,t.setData("Text",n)}}}return t.prototype={multiDragKeyDown:!1,isMultiDrag:!1,delayStartGlobal:function(t){var e=t.dragEl;re=e},delayEnded:function(){this.isMultiDrag=~se.indexOf(re)},setupClone:function(t){var e=t.sortable,n=t.cancel;if(this.isMultiDrag){for(var o=0;o&lt;se.length;o++)ce.push(S(se[o])),ce[o].sortableIndex=se[o].sortableIndex,ce[o].draggable=!1,ce[o].style["will-change"]="",k(ce[o],this.options.selectedClass,!1),se[o]===re&amp;&amp;k(ce[o],this.options.chosenClass,!1);e._hideClone(),n()}},clone:function(t){var e=t.sortable,n=t.rootEl,o=t.dispatchSortableEvent,i=t.cancel;this.isMultiDrag&amp;&amp;(this.options.removeCloneOnHide||se.length&amp;&amp;ie===e&amp;&amp;(fe(!0,n),o("clone"),i()))},showClone:function(t){var e=t.cloneNowShown,n=t.rootEl,o=t.cancel;this.isMultiDrag&amp;&amp;(fe(!1,n),ce.forEach(function(t){R(t,"display","")}),e(),le=!1,o())},hideClone:function(t){var e=this,n=(t.sortable,t.cloneNowHidden),o=t.cancel;this.isMultiDrag&amp;&amp;(ce.forEach(function(t){R(t,"display","none"),e.options.removeCloneOnHide&amp;&amp;t.parentNode&amp;&amp;t.parentNode.removeChild(t)}),n(),le=!0,o())},dragStartGlobal:function(t){t.sortable;!this.isMultiDrag&amp;&amp;ie&amp;&amp;ie.multiDrag._deselectMultiDrag(),se.forEach(function(t){t.sortableIndex=F(t)}),se=se.sort(function(t,e){return t.sortableIndex-e.sortableIndex}),he=!0},dragStarted:function(t){var e=this,n=t.sortable;if(this.isMultiDrag){if(this.options.sort&amp;&amp;(n.captureAnimationState(),this.options.animation)){se.forEach(function(t){t!==re&amp;&amp;R(t,"position","absolute")});var o=X(re,!1,!0,!0);se.forEach(function(t){t!==re&amp;&amp;_(t,o)}),ue=de=!0}n.animateAll(function(){ue=de=!1,e.options.animation&amp;&amp;se.forEach(function(t){C(t)}),e.options.sort&amp;&amp;pe()})}},dragOver:function(t){var e=t.target,n=t.completed,o=t.cancel;de&amp;&amp;~se.indexOf(e)&amp;&amp;(n(!1),o())},revert:function(t){var e=t.fromSortable,n=t.rootEl,o=t.sortable,i=t.dragRect;1&lt;se.length&amp;&amp;(se.forEach(function(t){o.addAnimationState({target:t,rect:de?X(t):i}),C(t),t.fromRect=i,e.removeAnimationState(t)}),de=!1,function(o,i){se.forEach(function(t,e){var n=i.children[t.sortableIndex+(o?Number(e):0)];n?i.insertBefore(t,n):i.appendChild(t)})}(!this.options.removeCloneOnHide,n))},dragOverCompleted:function(t){var e=t.sortable,n=t.isOwner,o=t.insertion,i=t.activeSortable,r=t.parentEl,a=t.putSortable,l=this.options;if(o){if(n&amp;&amp;i._hideClone(),ue=!1,l.animation&amp;&amp;1&lt;se.length&amp;&amp;(de||!n&amp;&amp;!i.options.sort&amp;&amp;!a)){var s=X(re,!1,!0,!0);se.forEach(function(t){t!==re&amp;&amp;(_(t,s),r.appendChild(t))}),de=!0}if(!n)if(de||pe(),1&lt;se.length){var c=le;i._showClone(e),i.options.animation&amp;&amp;!le&amp;&amp;c&amp;&amp;ce.forEach(function(t){i.addAnimationState({target:t,rect:ae}),t.fromRect=ae,t.thisAnimationDuration=null})}else i._showClone(e)}},dragOverAnimationCapture:function(t){var e=t.dragRect,n=t.isOwner,o=t.activeSortable;if(se.forEach(function(t){t.thisAnimationDuration=null}),o.options.animation&amp;&amp;!n&amp;&amp;o.multiDrag.isMultiDrag){ae=a({},e);var i=v(re,!0);ae.top-=i.f,ae.left-=i.e}},dragOverAnimationComplete:function(){de&amp;&amp;(de=!1,pe())},drop:function(t){var e=t.originalEvent,n=t.rootEl,o=t.parentEl,i=t.sortable,r=t.dispatchSortableEvent,a=t.oldIndex,l=t.putSortable,s=l||this.sortable;if(e){var c=this.options,u=o.children;if(!he)if(c.multiDragKey&amp;&amp;!this.multiDragKeyDown&amp;&amp;this._deselectMultiDrag(),k(re,c.selectedClass,!~se.indexOf(re)),~se.indexOf(re))se.splice(se.indexOf(re),1),oe=null,N({sortable:i,rootEl:n,name:"deselect",targetEl:re,originalEvt:e});else{if(se.push(re),N({sortable:i,rootEl:n,name:"select",targetEl:re,originalEvt:e}),e.shiftKey&amp;&amp;oe&amp;&amp;i.el.contains(oe)){var d,h,f=F(oe),p=F(re);if(~f&amp;&amp;~p&amp;&amp;f!==p)for(d=f&lt;p?(h=f,p):(h=p,f+1);h&lt;d;h++)~se.indexOf(u[h])||(k(u[h],c.selectedClass,!0),se.push(u[h]),N({sortable:i,rootEl:n,name:"select",targetEl:u[h],originalEvt:e}))}else oe=re;ie=s}if(he&amp;&amp;this.isMultiDrag){if((o[j].options.sort||o!==n)&amp;&amp;1&lt;se.length){var g=X(re),v=F(re,":not(."+this.options.selectedClass+")");if(!ue&amp;&amp;c.animation&amp;&amp;(re.thisAnimationDuration=null),s.captureAnimationState(),!ue&amp;&amp;(c.animation&amp;&amp;(re.fromRect=g,se.forEach(function(t){if(t.thisAnimationDuration=null,t!==re){var e=de?X(t):g;t.fromRect=e,s.addAnimationState({target:t,rect:e})}})),pe(),se.forEach(function(t){u[v]?o.insertBefore(t,u[v]):o.appendChild(t),v++}),a===F(re))){var m=!1;se.forEach(function(t){t.sortableIndex===F(t)||(m=!0)}),m&amp;&amp;r("update")}se.forEach(function(t){C(t)}),s.animateAll()}ie=s}(n===o||l&amp;&amp;"clone"!==l.lastPutMode)&amp;&amp;ce.forEach(function(t){t.parentNode&amp;&amp;t.parentNode.removeChild(t)})}},nullingGlobal:function(){this.isMultiDrag=he=!1,ce.length=0},destroyGlobal:function(){this._deselectMultiDrag(),s(document,"pointerup",this._deselectMultiDrag),s(document,"mouseup",this._deselectMultiDrag),s(document,"touchend",this._deselectMultiDrag),s(document,"keydown",this._checkKeyDown),s(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(t){if(!(void 0!==he&amp;&amp;he||ie!==this.sortable||t&amp;&amp;P(t.target,this.options.draggable,this.sortable.el,!1)||t&amp;&amp;0!==t.button))for(;se.length;){var e=se[0];k(e,this.options.selectedClass,!1),se.shift(),N({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:e,originalEvt:t})}},_checkKeyDown:function(t){t.key===this.options.multiDragKey&amp;&amp;(this.multiDragKeyDown=!0)},_checkKeyUp:function(t){t.key===this.options.multiDragKey&amp;&amp;(this.multiDragKeyDown=!1)}},a(t,{pluginName:"multiDrag",utils:{select:function(t){var e=t.parentNode[j];e&amp;&amp;e.options.multiDrag&amp;&amp;!~se.indexOf(t)&amp;&amp;(ie&amp;&amp;ie!==e&amp;&amp;(ie.multiDrag._deselectMultiDrag(),ie=e),k(t,e.options.selectedClass,!0),se.push(t))},deselect:function(t){var e=t.parentNode[j],n=se.indexOf(t);e&amp;&amp;e.options.multiDrag&amp;&amp;~n&amp;&amp;(k(t,e.options.selectedClass,!1),se.splice(n,1))}},eventProperties:function(){var n=this,o=[],i=[];return se.forEach(function(t){var e;o.push({multiDragElement:t,index:t.sortableIndex}),e=de&amp;&amp;t!==re?-1:de?F(t,":not(."+n.options.selectedClass+")"):F(t),i.push({multiDragElement:t,index:e})}),{items:e(se),clones:[].concat(ce),oldIndicies:o,newIndicies:i}},optionListeners:{multiDragKey:function(t){return"ctrl"===(t=t.toLowerCase())?t="Control":1&lt;t.length&amp;&amp;(t=t.charAt(0).toUpperCase()+t.substr(1)),t}}})}),Rt});
/**!

 @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt Expat
 handlebars v5.0.0-alpha.1

Copyright (C) 2011-2017 by Yehuda Katz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
!function(a,b){"object"==typeof exports&amp;&amp;"object"==typeof module?module.exports=b():"function"==typeof define&amp;&amp;define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}b.__esModule=!0;var f=c(1),g=d(f),h=c(19),i=d(h),j=c(20),k=c(25),l=c(26),m=d(l),n=c(23),o=d(n),p=c(18),q=d(p),r=g["default"].create,s=e();s.create=e,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a){if(a&amp;&amp;a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&amp;&amp;(b[c]=a[c]);return b["default"]=a,b}function f(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}b.__esModule=!0;var g=c(2),h=e(g),i=c(16),j=d(i),k=c(4),l=d(k),m=c(3),n=e(m),o=c(17),p=e(o),q=c(18),r=d(q),s=f();s.create=f,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}b.__esModule=!0,b.HandlebarsEnvironment=e;var f=c(3),g=c(4),h=d(g),i=c(5),j=c(13),k=c(15),l=d(k),m="4.0.10";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"&lt;= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:"&gt;= 2.0.0-beta.1",7:"&gt;= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";e.prototype={constructor:e,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return i[a]}function d(a){for(var b=1;b&lt;arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&amp;&amp;(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c&lt;d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&amp;&amp;a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return k.test(a)?a.replace(j,c):a}function g(a){return!a&amp;&amp;0!==a||!(!n(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h;var i={"&amp;":"&amp;amp;","&lt;":"&amp;lt;","&gt;":"&amp;gt;",'"':"&amp;quot;","'":"&amp;#x27;","`":"&amp;#x60;","=":"&amp;#x3D;"},j=/[&amp;&lt;&gt;"'`=]/g,k=/[&amp;&lt;&gt;"'`=]/,l=Object.prototype.toString;b.toString=l;var m=function(a){return"function"==typeof a};m(/x/)&amp;&amp;(b.isFunction=m=function(a){return"function"==typeof a&amp;&amp;"[object Function]"===l.call(a)}),b.isFunction=m;var n=Array.isArray||function(a){return!(!a||"object"!=typeof a)&amp;&amp;"[object Array]"===l.call(a)};b.isArray=n},function(a,b){"use strict";function c(a,b){var e=b&amp;&amp;b.loc,f=void 0,g=void 0;e&amp;&amp;(f=e.start.line,g=e.start.column,a+=" - "+f+":"+g);for(var h=Error.prototype.constructor.call(this,a),i=0;i&lt;d.length;i++)this[d[i]]=h[d[i]];Error.captureStackTrace&amp;&amp;Error.captureStackTrace(this,c);try{e&amp;&amp;(this.lineNumber=f,Object.defineProperty?Object.defineProperty(this,"column",{value:g,enumerable:!0}):this.column=g)}catch(j){}}b.__esModule=!0;var d=["description","fileName","lineNumber","message","name","number","stack"];c.prototype=new Error,b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}b.__esModule=!0,b.registerDefaultHelpers=e;var f=c(6),g=d(f),h=c(7),i=d(h),j=c(8),k=d(j),l=c(9),m=d(l),n=c(10),o=d(n),p=c(11),q=d(p),r=c(12),s=d(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(3);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;return b===!0?f(this):b===!1||null==b?e(this):d.isArray(b)?b.length&gt;0?a.helpers.each(b,c):e(this):f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}b.__esModule=!0;var e=c(3),f=c(4),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,e){j&amp;&amp;(j.key=b,j.index=c,j.first=0===c,j.last=!!e),i+=d(a[b],{data:j,blockParams:[a[b],b]})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0;if(e.isFunction(a)&amp;&amp;(a=a.call(this)),b.data&amp;&amp;(j=e.createFrame(b.data)),a&amp;&amp;"object"==typeof a)if(e.isArray(a))for(var k=a.length;h&lt;k;h++)h in a&amp;&amp;c(h,h,h===a.length-1);else{var l=void 0;for(var m in a)a.hasOwnProperty(m)&amp;&amp;(void 0!==l&amp;&amp;c(l,h-1),l=m,h++);void 0!==l&amp;&amp;c(l,h-1,!0)}return 0===h&amp;&amp;(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}b.__esModule=!0;var e=c(4),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(3);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&amp;&amp;(a=a.call(this)),!b.hash.includeZero&amp;&amp;!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d&lt;arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&amp;&amp;null!=c.data.level&amp;&amp;(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&amp;&amp;a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(3);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&amp;&amp;(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return c(a,{data:e,blockParams:[a]})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a){g["default"](a)}b.__esModule=!0,b.registerDefaultDecorators=e;var f=c(14),g=d(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(3);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(3),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b&gt;=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&amp;&amp;e.lookupLevel(e.level)&lt;=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c&gt;1?c-1:0),f=1;f&lt;c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a){if(a&amp;&amp;a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&amp;&amp;(b[c]=a[c]);return b["default"]=a,b}function f(a){var b=a&amp;&amp;a[0]||1,c=r.COMPILER_REVISION;if(b!==c){if(b&lt;c){var d=r.REVISION_CHANGES[c],e=r.REVISION_CHANGES[b];throw new q["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new q["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function g(a,b){function c(c,d,e){e.hash&amp;&amp;(d=o.extend({},d,e.hash)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&amp;&amp;b.compile&amp;&amp;(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h&lt;i&amp;&amp;(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new q["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(f,b,f.helpers,f.partials,g,i,h)}var d=arguments.length&lt;=1||void 0===arguments[1]?{}:arguments[1],g=d.data;e(d),!d.partial&amp;&amp;a.useData&amp;&amp;(g=l(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&amp;&amp;(h=d.depths?b!=d.depths[0]?[b].concat(d.depths):d.depths:[b]),(c=m(a.main,c,f,d.depths||[],g,i))(b,d)}function e(c){c.partial?(f.helpers=c.helpers,f.partials=c.partials,f.decorators=c.decorators):(f.helpers=f.merge(c.helpers,b.helpers),a.usePartial&amp;&amp;(f.partials=f.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&amp;&amp;(f.decorators=f.merge(c.decorators,b.decorators)))}if(!b)throw new q["default"]("No environment passed to template");if(!a||!a.main)throw new q["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var f={strict:function(a,b){if(!(b in a))throw new q["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d&lt;c;d++)if(a[d]&amp;&amp;null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:o.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var f=this.programs[a],g=this.fn(a);return b||e||d||c?f=h(this,a,g,b,c,d,e):f||(f=this.programs[a]=h(this,a,g)),f},data:function(a,b){for(;a&amp;&amp;b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&amp;&amp;b&amp;&amp;a!==b&amp;&amp;(c=o.extend({},b,a)),c},nullContext:Object.seal({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d}function h(a,b,c,d,e,f,g){function h(b){var e=arguments.length&lt;=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&amp;&amp;null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&amp;&amp;[e.blockParams].concat(f),h)}return h=m(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function i(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function j(a,b,c){var d=c.data&amp;&amp;c.data["partial-block"];c.partial=!0;var e=void 0;if(c.fn&amp;&amp;c.fn!==k&amp;&amp;!function(){c.data=r.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length&lt;=1||void 0===arguments[1]?{}:arguments[1];return c.data=r.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&amp;&amp;(c.partials=o.extend({},c.partials,a.partials))}(),void 0===a&amp;&amp;e&amp;&amp;(a=e),void 0===a)throw new q["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function k(){return""}function l(a,b){return b&amp;&amp;"root"in b||(b=b?r.createFrame(b):{},b.root=a),b}function m(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&amp;&amp;d[0],e,f,d),o.extend(b,g)}return b}b.__esModule=!0,b.checkRevision=f,b.template=g,b.wrapProgram=h,b.resolvePartial=i,b.invokePartial=j,b.noop=k;var n=c(3),o=e(n),p=c(4),q=d(p),r=c(2)},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&amp;&amp;(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&amp;&amp;!!(a.params&amp;&amp;a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&amp;&amp;!c.helpers.scopedId(a)&amp;&amp;!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){if(a&amp;&amp;a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&amp;&amp;(b[c]=a[c]);return b["default"]=a,b}function e(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function f(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&amp;&amp;b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}b.__esModule=!0,b.parse=f;var g=c(21),h=e(g),i=c(22),j=e(i),k=c(24),l=d(k),m=c(3);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b=function(a,b,c,d){for(c=c||{},d=a.length;d--;c[a[d]]=b);return c},c=[2,46],d=[1,20],e=[5,14,15,19,29,34,39,44,47,48,51,55,60],f=[1,35],g=[1,28],h=[1,29],i=[1,30],j=[1,31],k=[1,32],l=[1,34],m=[14,15,19,29,34,39,44,47,48,51,55,60],n=[14,15,19,29,34,44,47,48,51,55,60],o=[1,44],p=[14,15,19,29,34,47,48,51,55,60],q=[33,65,72,80,81,82,83,84,85],r=[23,33,54,65,68,72,75,80,81,82,83,84,85],s=[1,51],t=[23,33,54,65,68,72,75,80,81,82,83,84,85,87],u=[2,45],v=[54,65,72,80,81,82,83,84,85],w=[1,58],x=[1,59],y=[15,18],z=[1,67],A=[33,65,72,75,80,81,82,83,84,85],B=[23,65,72,80,81,82,83,84,85],C=[1,79],D=[65,68,72,80,81,82,83,84,85],E=[33,75],F=[23,33,54,68,72,75],G=[1,109],H=[1,121],I=[72,77],J={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:case 4:case 5:case 6:case 7:case 8:case 20:case 27:case 28:case 33:case 34:case 40:case 41:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:case 50:case 58:case 64:case 70:case 78:case 82:case 86:case 90:case 94:this.$=[];break;case 47:case 49:case 51:case 59:case 65:case 71:case 79:case 83:case 87:case 91:case 95:case 99:case 101:f[h-1].push(f[h]);break;case 48:case 98:case 100:this.$=[f[h]]}},table:[b([5,14,15,19,29,34,48,51,55,60],c,{3:1,4:2,6:3}),{1:[3]},{5:[1,4]},b([5,39,44,47],[2,2],{7:5,8:6,9:7,10:8,11:9,12:10,13:11,24:15,27:16,16:17,59:19,14:[1,12],15:d,19:[1,23],29:[1,21],34:[1,22],48:[1,13],51:[1,14],55:[1,18],60:[1,24]}),{1:[2,1]},b(e,[2,47]),b(e,[2,3]),b(e,[2,4]),b(e,[2,5]),b(e,[2,6]),b(e,[2,7]),b(e,[2,8]),b(e,[2,9]),{20:25,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{20:36,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(m,c,{6:3,4:37}),b(n,c,{6:3,4:38}),{13:40,15:d,17:39},{20:42,56:41,64:43,65:o,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(p,c,{6:3,4:45}),b([5,14,15,18,19,29,34,39,44,47,48,51,55,60],[2,10]),{20:46,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{20:47,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{20:48,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{20:42,56:49,64:43,65:o,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(q,[2,78],{49:50}),b(r,[2,33]),b(r,[2,34]),b(r,[2,35]),b(r,[2,36]),b(r,[2,37]),b(r,[2,38]),b(r,[2,39]),b(r,[2,43],{87:s}),{72:f,86:52},b(t,u),b(v,[2,82],{52:53}),{25:54,38:56,39:w,43:57,44:x,45:55,47:[2,54]},{28:60,43:61,44:x,47:[2,56]},{13:63,15:d,18:[1,62]},b(y,[2,48]),b(q,[2,86],{57:64}),b(q,[2,40]),b(q,[2,41]),{20:65,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{26:66,47:z},b(A,[2,58],{30:68}),b(A,[2,64],{35:69}),b(B,[2,50],{21:70}),b(q,[2,90],{61:71}),{20:75,33:[2,80],50:72,63:73,64:76,65:o,69:74,70:77,71:78,72:C,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{72:[1,80]},b(r,[2,42],{87:s}),{20:75,53:81,54:[2,84],63:82,64:76,65:o,69:83,70:77,71:78,72:C,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{26:84,47:z},{47:[2,55]},b(m,c,{6:3,4:85}),{47:[2,20]},{20:86,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(p,c,{6:3,4:87}),{26:88,47:z},{47:[2,57]},b(e,[2,11]),b(y,[2,49]),{20:75,33:[2,88],58:89,63:90,64:76,65:o,69:91,70:77,71:78,72:C,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(D,[2,94],{66:92}),b(e,[2,25]),{20:93,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(E,[2,60],{78:26,79:27,86:33,20:75,64:76,70:77,71:78,31:94,63:95,69:96,65:o,72:C,80:g,81:h,82:i,83:j,84:k,85:l}),b(E,[2,66],{78:26,79:27,86:33,20:75,64:76,70:77,71:78,36:97,63:98,69:99,65:o,72:C,80:g,81:h,82:i,83:j,84:k,85:l}),{20:75,22:100,23:[2,52],63:101,64:76,65:o,69:102,70:77,71:78,72:C,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:o,69:105,70:77,71:78,72:C,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{33:[1,106]},b(q,[2,79]),{33:[2,81]},b(r,[2,27]),b(r,[2,28]),b([23,33,54,68,75],[2,30],{71:107,72:[1,108]}),b(F,[2,98]),b(t,u,{73:G}),b(t,[2,44]),{54:[1,110]},b(v,[2,83]),{54:[2,85]},b(e,[2,13]),{38:56,39:w,43:57,44:x,45:112,46:111,47:[2,76]},b(A,[2,70],{40:113}),{47:[2,18]},b(e,[2,14]),{33:[1,114]},b(q,[2,87]),{33:[2,89]},{20:75,63:116,64:76,65:o,67:115,68:[2,96],69:117,70:77,71:78,72:C,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:H},b(A,[2,59]),b(E,[2,61]),{33:[2,68],37:122,74:123,75:H},b(A,[2,65]),b(E,[2,67]),{23:[1,124]},b(B,[2,51]),{23:[2,53]},{33:[1,125]},b(q,[2,91]),{33:[2,93]},b(e,[2,22]),b(F,[2,99]),{73:G},{20:75,63:126,64:76,65:o,72:f,78:26,79:27,80:g,81:h,82:i,83:j,84:k,85:l,86:33},b(e,[2,23]),{47:[2,19]},{47:[2,77]},b(E,[2,72],{78:26,79:27,86:33,20:75,64:76,70:77,71:78,41:127,63:128,69:129,65:o,72:C,80:g,81:h,82:i,83:j,84:k,85:l}),b(e,[2,24]),{68:[1,130]},b(D,[2,95]),{68:[2,97]},b(e,[2,21]),{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},b(p,[2,26]),b(F,[2,31]),{33:[2,74],42:135,74:136,75:H},b(A,[2,71]),b(E,[2,73]),b(r,[2,29]),b(m,[2,15]),{72:[1,138],77:[1,137]},b(I,[2,100]),b(n,[2,16]),{33:[1,139]},{33:[2,75]},{33:[2,32]},b(I,[2,101]),b(m,[2,17])],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){if(!b.recoverable){var c=function(a,b){this.message=a,this.hash=b};throw c.prototype=new Error,new c(a,b)}this.trace(a)},parse:function(a){var b=this,c=[0],d=[null],e=[],f=this.table,g="",h=0,i=0,j=0,k=2,l=1,m=e.slice.call(arguments,1),n=Object.create(this.lexer),o={yy:{}};for(var p in this.yy)Object.prototype.hasOwnProperty.call(this.yy,p)&amp;&amp;(o.yy[p]=this.yy[p]);n.setInput(a,o.yy),o.yy.lexer=n,o.yy.parser=this,"undefined"==typeof n.yylloc&amp;&amp;(n.yylloc={});var q=n.yylloc;e.push(q);var r=n.options&amp;&amp;n.options.ranges;"function"==typeof o.yy.parseError?this.parseError=o.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var s,t,u,v,w,x,y,z,A,B=function(){var a;return a=n.lex()||l,"number"!=typeof a&amp;&amp;(a=b.symbols_[a]||a),a},C={};;){if(u=c[c.length-1],this.defaultActions[u]?v=this.defaultActions[u]:(null!==s&amp;&amp;"undefined"!=typeof s||(s=B()),v=f[u]&amp;&amp;f[u][s]),"undefined"==typeof v||!v.length||!v[0]){var D="";A=[];for(x in f[u])this.terminals_[x]&amp;&amp;x&gt;k&amp;&amp;A.push("'"+this.terminals_[x]+"'");D=n.showPosition?"Parse error on line "+(h+1)+":\n"+n.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[s]||s)+"'":"Parse error on line "+(h+1)+": Unexpected "+(s==l?"end of input":"'"+(this.terminals_[s]||s)+"'"),this.parseError(D,{text:n.match,token:this.terminals_[s]||s,line:n.yylineno,loc:q,expected:A})}if(v[0]instanceof Array&amp;&amp;v.length&gt;1)throw new Error("Parse Error: multiple actions possible at state: "+u+", token: "+s);switch(v[0]){case 1:c.push(s),d.push(n.yytext),e.push(n.yylloc),c.push(v[1]),s=null,t?(s=t,t=null):(i=n.yyleng,g=n.yytext,h=n.yylineno,q=n.yylloc,j&gt;0&amp;&amp;j--);break;case 2:if(y=this.productions_[v[1]][1],C.$=d[d.length-y],C._$={first_line:e[e.length-(y||1)].first_line,last_line:e[e.length-1].last_line,first_column:e[e.length-(y||1)].first_column,last_column:e[e.length-1].last_column},r&amp;&amp;(C._$.range=[e[e.length-(y||1)].range[0],e[e.length-1].range[1]]),w=this.performAction.apply(C,[g,i,h,o.yy,v[1],d,e].concat(m)),"undefined"!=typeof w)return w;y&amp;&amp;(c=c.slice(0,-1*y*2),d=d.slice(0,-1*y),e=e.slice(0,-1*y)),c.push(this.productions_[v[1]][0]),d.push(C.$),e.push(C._$),z=f[c[c.length-2]][c[c.length-1]],c.push(z);break;case 3:return!0}}return!0}},K=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a,b){return this.yy=b||this.yy||{},this._input=a,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&amp;&amp;(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&amp;&amp;this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&amp;&amp;(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&amp;&amp;(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length&gt;20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length&lt;20&amp;&amp;(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length&gt;20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},test_match:function(a,b){var c,d,e;if(this.options.backtrack_lexer&amp;&amp;(e={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&amp;&amp;(e.yylloc.range=this.yylloc.range.slice(0))),d=a[0].match(/(?:\r\n?|\n).*/g),d&amp;&amp;(this.yylineno+=d.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:d?d[d.length-1].length-d[d.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+a[0].length},this.yytext+=a[0],this.match+=a[0],this.matches=a,this.yyleng=this.yytext.length,this.options.ranges&amp;&amp;(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(a[0].length),this.matched+=a[0],c=this.performAction.call(this,this.yy,this,b,this.conditionStack[this.conditionStack.length-1]),this.done&amp;&amp;this._input&amp;&amp;(this.done=!1),c)return c;if(this._backtrack){for(var f in e)this[f]=e[f];return!1}return!1},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d;this._more||(this.yytext="",this.match="");for(var e=this._currentRules(),f=0;f&lt;e.length;f++)if(c=this._input.match(this.rules[e[f]]),c&amp;&amp;(!b||c[0].length&gt;b[0].length)){if(b=c,d=f,this.options.backtrack_lexer){if(a=this.test_match(c,e[f]),a!==!1)return a;if(this._backtrack){b=!1;continue}return!1}if(!this.options.flex)break}return b?(a=this.test_match(b,e[d]),a!==!1&amp;&amp;a):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){var a=this.conditionStack.length-1;return a&gt;0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&amp;&amp;this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(a){return a=this.conditionStack.length-1-Math.abs(a||0),a&gt;=0?this.conditionStack[a]:"INITIAL"},pushState:function(a){this.begin(a)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;
break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),18);case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},rules:[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;-&gt;@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?&gt;)/,/^(?:\{\{(~)?#&gt;)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&amp;)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;-&gt;@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],conditions:{mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}}};return a}();return J.lexer=K,a.prototype=J,J.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(){var a=arguments.length&lt;=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function f(a,b,c){void 0===b&amp;&amp;(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function g(a,b,c){void 0===b&amp;&amp;(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function h(a,b,c){var d=a[null==b?0:b+1];if(d&amp;&amp;"ContentStatement"===d.type&amp;&amp;(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function i(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&amp;&amp;"ContentStatement"===d.type&amp;&amp;(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}b.__esModule=!0;var j=c(23),k=d(j);e.prototype=new k["default"],e.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,e=0,j=d.length;e&lt;j;e++){var k=d[e],l=this.accept(k);if(l){var m=f(d,e,c),n=g(d,e,c),o=l.openStandalone&amp;&amp;m,p=l.closeStandalone&amp;&amp;n,q=l.inlineStandalone&amp;&amp;m&amp;&amp;n;l.close&amp;&amp;h(d,e,!0),l.open&amp;&amp;i(d,e,!0),b&amp;&amp;q&amp;&amp;(h(d,e),i(d,e)&amp;&amp;"PartialStatement"===k.type&amp;&amp;(k.indent=/([ \t]+$)/.exec(d[e-1].original)[1])),b&amp;&amp;o&amp;&amp;(h((k.program||k.inverse).body),i(d,e)),b&amp;&amp;p&amp;&amp;(h(d,e),i((k.inverse||k.program).body))}}return a},e.prototype.BlockStatement=e.prototype.DecoratorBlock=e.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&amp;&amp;a.inverse,d=c,e=c;if(c&amp;&amp;c.chained)for(d=c.body[0].program;e.chained;)e=e.body[e.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:g(b.body),closeStandalone:f((d||b).body)};if(a.openStrip.close&amp;&amp;h(b.body,null,!0),c){var k=a.inverseStrip;k.open&amp;&amp;i(b.body,null,!0),k.close&amp;&amp;h(d.body,null,!0),a.closeStrip.open&amp;&amp;i(e.body,null,!0),!this.options.ignoreStandalone&amp;&amp;f(b.body)&amp;&amp;g(d.body)&amp;&amp;(i(b.body),h(d.body))}else a.closeStrip.open&amp;&amp;i(b.body,null,!0);return j},e.prototype.Decorator=e.prototype.MustacheStatement=function(a){return a.strip},e.prototype.PartialStatement=e.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(){this.parents=[]}function f(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function g(a){f.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function h(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}b.__esModule=!0;var i=c(4),j=d(i);e.prototype={constructor:e,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&amp;&amp;!e.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b&lt;c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&amp;&amp;this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:f,Decorator:f,BlockStatement:g,DecoratorBlock:g,PartialStatement:h,PartialBlockStatement:function(a){h.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:f,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function f(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function g(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function h(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function i(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function j(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g=0,h=b.length;g&lt;h;g++){var i=b[g].part,j=b[g].original!==i;if(d+=(b[g].separator||"")+i,j||".."!==i&amp;&amp;"."!==i&amp;&amp;"this"!==i)e.push(i);else{if(e.length&gt;0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===i&amp;&amp;f++}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function k(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&amp;&amp;"&amp;"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function l(a,b,c,d){e(a,c),d=this.locInfo(d);var f={type:"Program",body:b,strip:{},loc:d};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:d}}function m(a,b,c,d,f,g){d&amp;&amp;d.path&amp;&amp;e(a,d);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&amp;&amp;(c.program.body[0].closeStrip=d.strip),j=c.strip,i=c.program}return f&amp;&amp;(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:d&amp;&amp;d.strip,loc:this.locInfo(g)}}function n(a,b){if(!b&amp;&amp;a.length){var c=a[0].loc,d=a[a.length-1].loc;c&amp;&amp;d&amp;&amp;(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function o(a,b,c,d){return e(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&amp;&amp;c.strip,loc:this.locInfo(d)}}b.__esModule=!0,b.SourceLocation=f,b.id=g,b.stripFlags=h,b.stripComment=i,b.preparePath=j,b.prepareMustache=k,b.prepareRawBlock=l,b.prepareBlock=m,b.prepareProgram=n,b.preparePartialBlock=o;var p=c(4),q=d(p)},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(){}function f(a,b,c){void 0===b&amp;&amp;(b={}),h(a,b);var d=i(a,b,c);return(new c.JavaScriptCompiler).compile(d,b)}function g(a,b,c){function d(){var d=i(a,b,c),e=(new c.JavaScriptCompiler).compile(d,b,void 0,!0);return c.template(e)}void 0===b&amp;&amp;(b={}),b=n.extend({},b),h(a,b);var e=void 0;return function(a,b){return e||(e=d()),e.call(this,a,b)}}function h(a,b){if(null==a||"string"!=typeof a&amp;&amp;"Program"!==a.type)throw new m["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);if(b.trackIds||b.stringParams)throw new m["default"]("TrackIds and stringParams are no longer supported. See Github #1145");"data"in b||(b.data=!0),b.compat&amp;&amp;(b.useDepths=!0)}function i(a,b,c){var d=c.parse(a,b);return(new c.Compiler).compile(d,b)}function j(a,b){if(a===b)return!0;if(n.isArray(a)&amp;&amp;n.isArray(b)&amp;&amp;a.length===b.length){for(var c=0;c&lt;a.length;c++)if(!j(a[c],b[c]))return!1;return!0}}function k(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}b.__esModule=!0,b.Compiler=e,b.precompile=f,b.compile=g;var l=c(4),m=d(l),n=c(3),o=c(19),p=d(o),q=[].slice;e.prototype={compiler:e,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c&lt;b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!j(d.args,e.args))return!1}b=this.children.length;for(var c=0;c&lt;b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&amp;&amp;(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new m["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d&lt;c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){k(a);var b=a.program,c=a.inverse;b=b&amp;&amp;this.compileProgram(b),c=c&amp;&amp;this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&amp;&amp;this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&amp;&amp;(b=this.compileProgram(a.program));var c=a.params;if(c.length&gt;1)throw new m["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&amp;&amp;this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&amp;&amp;f&amp;&amp;(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&amp;&amp;!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&amp;&amp;this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){k(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new m["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,p["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=p["default"].helpers.scopedId(a),d=!a.depth&amp;&amp;!c&amp;&amp;this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c&lt;d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:q.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&amp;&amp;(this.useDepths=!0)},classifySexpr:function(a){var b=p["default"].helpers.simpleId(a.path),c=b&amp;&amp;!!this.blockParamIndex(a.path.parts[0]),d=!c&amp;&amp;p["default"].helpers.helperExpression(a),e=!c&amp;&amp;(d||b);if(e&amp;&amp;!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&amp;&amp;(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b&lt;c;b++)this.pushParam(a[b])},pushParam:function(a){this.accept(a)},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b&lt;c;b++){var d=this.options.blockParams[b],e=d&amp;&amp;n.indexOf(d,a);if(d&amp;&amp;e&gt;=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){return a&amp;&amp;a.__esModule?a:{"default":a}}function e(a){this.value=a}function f(){}function g(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&amp;&amp;g--;f&lt;g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}b.__esModule=!0;var h=c(2),i=c(4),j=d(i),k=c(3),l=c(27),m=d(l);f.prototype={nameLookup:function(a,b){return f.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h&lt;i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&amp;&amp;(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h&lt;i;h++)n[h]&amp;&amp;(l[h]=n[h],o[h]&amp;&amp;(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&amp;&amp;(l.usePartial=!0),this.options.data&amp;&amp;(l.useData=!0),this.useDepths&amp;&amp;(l.useDepths=!0),this.useBlockParams&amp;&amp;(l.useBlockParams=!0),this.options.compat&amp;&amp;(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&amp;&amp;l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length&gt;0&amp;&amp;(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&amp;&amp;f.children&amp;&amp;f.referenceCount&gt;1&amp;&amp;(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&amp;&amp;g.push("blockParams"),this.useDepths&amp;&amp;g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n  ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend("  + "):f=a,g=a):(f&amp;&amp;(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&amp;&amp;this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&amp;&amp;this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var f=this;if(this.options.strict||this.options.assumeObjects)return void this.push(g(this.options.strict&amp;&amp;e,this,b,a));for(var h=b.length;c&lt;h;c++)this.replaceStack(function(e){var g=f.nameLookup(e,b[c],a);return d?[" &amp;&amp; ",g]:[" != null ? ",g," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},emptyHash:function(a){this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&amp;&amp;this.hashes.push(this.hash),this.hash={values:{}}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&amp;&amp;(b=this.popStack(),delete e.name),c&amp;&amp;(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&amp;&amp;(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){this.hash.values[a]=this.popStack()},compiler:f,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f&lt;g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b&lt;c;b++){var d=this.context.environments[b];if(d&amp;&amp;d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&amp;&amp;c.push("blockParams"),this.useDepths&amp;&amp;c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof e||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new e(a))},pushSource:function(a){this.pendingContent&amp;&amp;(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&amp;&amp;this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,d=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof e)c=[g.value],b=["(",c],f=!0;else{d=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),d&amp;&amp;this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot&gt;this.stackVars.length&amp;&amp;this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b&lt;c;b++){var d=a[b];if(d instanceof e)this.compileStack.push(d);else{var f=this.incrStack();this.pushSource([f," = ",d,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&amp;&amp;c instanceof e)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof e?b.value:b},contextName:function(a){return this.useDepths&amp;&amp;a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=!c,f=void 0;e&amp;&amp;(c=[]),d.name=this.quotedString(a),d.hash=this.popStack();var g=this.popStack(),h=this.popStack();(h||g)&amp;&amp;(d.fn=h||"container.noop",d.inverse=g||"container.noop");for(var i=b;i--;)f=this.popStack(),c[i]=f;return e&amp;&amp;(d.args=this.source.generateArray(c)),this.options.data&amp;&amp;(d.data="data"),this.useBlockParams&amp;&amp;(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=f.RESERVED_WORDS={},c=0,d=a.length;c&lt;d;c++)b[a[c]]=!0}(),f.isValidJavaScriptVariableName=function(a){return!f.RESERVED_WORDS[a]&amp;&amp;/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=f,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e&lt;g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(3),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&amp;&amp;this.add(d)},g.prototype={add:function(a){f.isArray(a)&amp;&amp;(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&amp;&amp;(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add(["  ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b&lt;c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length&lt;=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&amp;&amp;b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c&lt;e;c++)c&amp;&amp;b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
// @license-end;
( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} ( function( $ ) {

$.ui = $.ui || {};

return $.ui.version = "1.12.1";

} ) );


/*!
 * jQuery UI Keycode 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//&gt;&gt;label: Keycode
//&gt;&gt;group: Core
//&gt;&gt;description: Provide keycodes as keynames
//&gt;&gt;docs: http://api.jqueryui.com/jQuery.ui.keyCode/

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} ( function( $ ) {
return $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};

} ) );


/*!
 * jQuery UI Position 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

//&gt;&gt;label: Position
//&gt;&gt;group: Core
//&gt;&gt;description: Positions elements relative to other elements.
//&gt;&gt;docs: http://api.jqueryui.com/position/
//&gt;&gt;demos: http://jqueryui.com/position/

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}( function( $ ) {
( function() {
var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[ 0 ];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "&lt;div " +
				"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'&gt;" +
				"&lt;div style='height:100px;width:auto;'&gt;&lt;/div&gt;&lt;/div&gt;" ),
			innerDiv = div.children()[ 0 ];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[ 0 ].clientWidth;
		}

		div.remove();

		return ( cachedScrollbarWidth = w1 - w2 );
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" &amp;&amp; within.width &lt; within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" &amp;&amp; within.height &lt; within.element[ 0 ].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[ 0 ] ),
			isDocument = !!withinElement[ 0 ] &amp;&amp; withinElement[ 0 ].nodeType === 9,
			hasOffset = !isWindow &amp;&amp; !isDocument;
		return {
			element: withinElement,
			isWindow: isWindow,
			isDocument: isDocument,
			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: withinElement.outerWidth(),
			height: withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// Make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// Force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1 ) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// Calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// Reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	} );

	// Normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each( function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
				scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
				scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				} );
			}
		} );

		if ( options.using ) {

			// Adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right &lt; 0 ? "left" : left &gt; 0 ? "right" : "center",
						vertical: bottom &lt; 0 ? "top" : top &gt; 0 ? "bottom" : "middle"
					};
				if ( targetWidth &lt; elemWidth &amp;&amp; abs( left + right ) &lt; targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight &lt; elemHeight &amp;&amp; abs( top + bottom ) &lt; targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) &gt; max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	} );
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// Element is wider than within
			if ( data.collisionWidth &gt; outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft &gt; 0 &amp;&amp; overRight &lt;= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight &gt; 0 &amp;&amp; overLeft &lt;= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft &gt; overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -&gt; align with left edge
			} else if ( overLeft &gt; 0 ) {
				position.left += overLeft;

			// Too far right -&gt; align with right edge
			} else if ( overRight &gt; 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight &gt; outerHeight ) {

				// Element is initially over the top of within
				if ( overTop &gt; 0 &amp;&amp; overBottom &lt;= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom &gt; 0 &amp;&amp; overTop &lt;= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop &gt; overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -&gt; align with top
			} else if ( overTop &gt; 0 ) {
				position.top += overTop;

			// Too far down -&gt; align with bottom edge
			} else if ( overBottom &gt; 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft &lt; 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight &lt; 0 || newOverRight &lt; abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight &gt; 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft &gt; 0 || abs( newOverLeft ) &lt; overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop &lt; 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom &lt; 0 || newOverBottom &lt; abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom &gt; 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop &gt; 0 || abs( newOverTop ) &lt; overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

} )();

return $.ui.position;

} ) );

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} ( function( $ ) {
return $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an &lt;iframe&gt;
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an &lt;iframe&gt;
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};

} ) );


/*!
 * jQuery UI Unique ID 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//&gt;&gt;label: uniqueId
//&gt;&gt;group: Core
//&gt;&gt;description: Functions to generate and remove uniqueId's
//&gt;&gt;docs: http://api.jqueryui.com/uniqueId/

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
} ( function( $ ) {

return $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

		return function() {
			return this.each( function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			} );
		};
	} )(),

	removeUniqueId: function() {
		return this.each( function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		} );
	}
} );

} ) );


/*!
 * jQuery UI Widget 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//&gt;&gt;label: Widget
//&gt;&gt;group: Core
//&gt;&gt;description: Provides a factory for creating stateful widgets with a common API.
//&gt;&gt;docs: http://api.jqueryui.com/jQuery.widget/
//&gt;&gt;demos: http://jqueryui.com/widget/

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [ "jquery", "./version" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}( function( $ ) {

var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events &amp;&amp; events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// Http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( $.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex &lt; inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) &amp;&amp; value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length &amp;&amp; options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance &amp;&amp; methodValue !== undefined ) {
						returnValue = methodValue &amp;&amp; methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "&lt;div&gt;",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" =&gt; { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i &lt; parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i &lt; classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					current = $( $.unique( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption &amp;&amp; options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		this._on( options.element, {
			"remove": "_untrackClassesElement"
		} );

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &amp;&amp;
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName ).off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &amp;&amp;
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions &amp;&amp; $.effects &amp;&amp; $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method &amp;&amp; element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

return $.widget;

} ) );







/*!
 * jQuery UI Menu 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//&gt;&gt;label: Menu
//&gt;&gt;group: Widgets
//&gt;&gt;description: Creates nestable menus.
//&gt;&gt;docs: http://api.jqueryui.com/menu/
//&gt;&gt;demos: http://jqueryui.com/menu/
//&gt;&gt;css.structure: ../../themes/base/core.css
//&gt;&gt;css.structure: ../../themes/base/menu.css
//&gt;&gt;css.theme: ../../themes/base/theme.css

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"../keycode",
			"../position",
			"../safe-active-element",
			"../unique-id",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}( function( $ ) {

return $.widget( "ui.menu", {
	version: "1.12.1",
	defaultElement: "&lt;ul&gt;",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-caret-1-e"
		},
		items: "&gt; *",
		menus: "ul",
		position: {
			my: "left top",
			at: "right top"
		},
		role: "menu",

		// Callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.attr( {
				role: this.options.role,
				tabIndex: 0
			} );

		this._addClass( "ui-menu", "ui-widget ui-widget-content" );
		this._on( {

			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				var active = $( $.ui.safeActiveElement( this.document[ 0 ] ) );
				if ( !this.mouseHandled &amp;&amp; target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) &amp;&amp;
							active.closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active &amp;&amp; this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {

				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}

				var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
					target = $( event.currentTarget );

				// Ignore bubbled events on parent items, see #11641
				if ( actualTarget[ 0 ] !== target[ 0 ] ) {
					return;
				}

				// Remove ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				this._removeClass( target.siblings().children( ".ui-state-active" ),
					null, "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {

				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay( function() {
					var notContained = !$.contains(
						this.element[ 0 ],
						$.ui.safeActiveElement( this.document[ 0 ] )
					);
					if ( notContained ) {
						this.collapseAll( event );
					}
				} );
			},
			keydown: "_keydown"
		} );

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		} );
	},

	_destroy: function() {
		var items = this.element.find( ".ui-menu-item" )
				.removeAttr( "role aria-disabled" ),
			submenus = items.children( ".ui-menu-item-wrapper" )
				.removeUniqueId()
				.removeAttr( "tabIndex role aria-haspopup" );

		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
					"tabIndex" )
				.removeUniqueId()
				.show();

		submenus.children().each( function() {
			var elem = $( this );
			if ( elem.data( "ui-menu-submenu-caret" ) ) {
				elem.remove();
			}
		} );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active &amp;&amp; !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			skip = false;

			// Support number pad values
			character = event.keyCode &gt;= 96 &amp;&amp; event.keyCode &lt;= 105 ?
				( event.keyCode - 96 ).toString() : String.fromCharCode( event.keyCode );

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip &amp;&amp; match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay( function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( this.active &amp;&amp; !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.children( "[aria-haspopup='true']" ).length ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items, newSubmenus, newItems, newWrappers,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this._toggleClass( "ui-menu-icons", null, !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		newSubmenus = submenus.filter( ":not(.ui-menu)" )
			.hide()
			.attr( {
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			} )
			.each( function() {
				var menu = $( this ),
					item = menu.prev(),
					submenuCaret = $( "&lt;span&gt;" ).data( "ui-menu-submenu-caret", true );

				that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCaret );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			} );

		this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each( function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				that._addClass( item, "ui-menu-divider", "ui-widget-content" );
			}
		} );

		// Don't refresh list items that are already adapted
		newItems = items.not( ".ui-menu-item, .ui-menu-divider" );
		newWrappers = newItems.children()
			.not( ".ui-menu" )
				.uniqueId()
				.attr( {
					tabIndex: -1,
					role: this._itemRole()
				} );
		this._addClass( newItems, "ui-menu-item" )
			._addClass( newWrappers, "ui-menu-item-wrapper" );

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active &amp;&amp; !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icons = this.element.find( ".ui-menu-icon" );
			this._removeClass( icons, null, this.options.icons.submenu )
				._addClass( icons, null, value.submenu );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", String( value ) );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	focus: function( event, item ) {
		var nested, focused, activeParent;
		this.blur( event, event &amp;&amp; event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();

		focused = this.active.children( ".ui-menu-item-wrapper" );
		this._addClass( focused, null, "ui-state-active" );

		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		activeParent = this.active
			.parent()
				.closest( ".ui-menu-item" )
					.children( ".ui-menu-item-wrapper" );
		this._addClass( activeParent, null, "ui-state-active" );

		if ( event &amp;&amp; event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay( function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length &amp;&amp; event &amp;&amp; ( /^mouse/.test( event.type ) ) ) {
			this._startOpening( nested );
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[ 0 ], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[ 0 ], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset &lt; 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight &gt; elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
			null, "ui-state-active" );

		this._trigger( "blur", event, { item: this.active } );
		this.active = null;
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the caret icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay( function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend( {
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay( function() {

			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event &amp;&amp; event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all
			// sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );

			// Work around active item staying active after menu is blurred
			this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );

			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu.find( ".ui-menu" )
			.hide()
			.attr( "aria-hidden", "true" )
			.attr( "aria-expanded", "false" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &amp;&amp;
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem &amp;&amp; newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &amp;&amp;
			this.active
				.children( ".ui-menu " )
					.find( this.options.items )
						.first();

		if ( newItem &amp;&amp; newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay( function() {
				this.focus( event, newItem );
			} );
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active &amp;&amp; !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active &amp;&amp; !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.find( this.options.items )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base - height &lt; 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".ui-menu-item" ).each( function() {
				item = $( this );
				return item.offset().top - base + height &gt; 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() &lt; this.element.prop( "scrollHeight" );
	},

	select: function( event ) {

		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function( character ) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&amp;" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

				// Only match on items, not dividers or other content (#10571)
				.filter( ".ui-menu-item" )
					.filter( function() {
						return regex.test(
							$.trim( $( this ).children( ".ui-menu-item-wrapper" ).text() ) );
					} );
	}
} );

} ) );







/*!
 * jQuery UI Autocomplete 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//&gt;&gt;label: Autocomplete
//&gt;&gt;group: Widgets
//&gt;&gt;description: Lists suggested words as the user is typing.
//&gt;&gt;docs: http://api.jqueryui.com/autocomplete/
//&gt;&gt;demos: http://jqueryui.com/autocomplete/
//&gt;&gt;css.structure: ../../themes/base/core.css
//&gt;&gt;css.structure: ../../themes/base/autocomplete.css
//&gt;&gt;css.theme: ../../themes/base/theme.css

( function( factory ) {
	if ( typeof define === "function" &amp;&amp; define.amd ) {

		// AMD. Register as an anonymous module.
		define( [
			"jquery",
			"./menu",
			"../keycode",
			"../position",
			"../safe-active-element",
			"../version",
			"../widget"
		], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}( function( $ ) {

$.widget( "ui.autocomplete", {
	version: "1.12.1",
	defaultElement: "&lt;input&gt;",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {

		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for &amp; in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		// Textareas are always multi-line
		// Inputs are always single-line, even if inside a contentEditable element
		// IE also treats inputs as contentEditable
		// All other element types are determined by whether or not they're contentEditable
		this.isMultiLine = isTextarea || !isInput &amp;&amp; this._isContentEditable( this.element );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this._addClass( "ui-autocomplete-input" );
		this.element.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:

					// when menu is open and has focus
					if ( this.menu.active ) {

						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );

						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;

					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// Replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		} );

		this._initSource();
		this.menu = $( "&lt;ul&gt;" )
			.appendTo( this._appendTo() )
			.menu( {

				// disable ARIA support, the live region takes care of that
				role: null
			} )
			.hide()
			.menu( "instance" );

		this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
		this._on( this.menu.element, {
			mousedown: function( event ) {

				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay( function() {
					delete this.cancelBlur;

					// Support: IE 8 only
					// Right clicking a menu item or selecting text from the menu items will
					// result in focus moving out of the input. However, we've already received
					// and ignored the blur event because of the cancelBlur flag set above. So
					// we restore focus to ensure that the menu closes properly based on the user's
					// next actions.
					if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
						this.element.trigger( "focus" );
					}
				} );
			},
			menufocus: function( event, ui ) {
				var label, item;

				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent &amp;&amp; /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						} );

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {

					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent &amp;&amp; /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label &amp;&amp; $.trim( label ).length ) {
					this.liveRegion.children().hide();
					$( "&lt;div&gt;" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// Only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
					this.element.trigger( "focus" );
					this.previous = previous;

					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay( function() {
						this.previous = previous;
						this.selectedItem = item;
					} );
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}

				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		} );

		this.liveRegion = $( "&lt;div&gt;", {
			role: "status",
			"aria-live": "assertive",
			"aria-relevant": "additions"
		} )
			.appendTo( this.document[ 0 ].body );

		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		// Turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		} );
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" &amp;&amp; value &amp;&amp; this.xhr ) {
			this.xhr.abort();
		}
	},

	_isEventTargetInWidget: function( event ) {
		var menuElement = this.menu.element[ 0 ];

		return event.target === this.element[ 0 ] ||
			event.target === menuElement ||
			$.contains( menuElement, event.target );
	},

	_closeOnClickOutside: function( event ) {
		if ( !this._isEventTargetInWidget( event ) ) {
			this.close();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front, dialog" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax( {
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				} );
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay( function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues &amp;&amp; !menuVisible &amp;&amp; !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// Always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length &lt; this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this._addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return $.proxy( function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this._removeClass( "ui-autocomplete-loading" );
			}
		}, this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled &amp;&amp; content &amp;&amp; content.length &amp;&amp; !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {

			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {

		// Remove the handler that closes the menu on outside clicks
		this._off( this.document, "mousedown" );

		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {

		// assume all items have the right format when the first item is complete
		if ( items.length &amp;&amp; items[ 0 ].label &amp;&amp; items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			} );
		} );
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// Size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend( {
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}

		// Listen for interactions outside of the widget (#6642)
		this._on( this.document, {
			mousedown: "_closeOnClickOutside"
		} );
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(

			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "&lt;li&gt;" )
			.append( $( "&lt;div&gt;" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() &amp;&amp; /^previous/.test( direction ) ||
				this.menu.isLastItem() &amp;&amp; /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// Prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	},

	// Support: Chrome &lt;=50
	// We should be able to just use this.element.prop( "isContentEditable" )
	// but hidden elements always report false in Chrome.
	// https://code.google.com/p/chromium/issues/detail?id=313082
	_isContentEditable: function( element ) {
		if ( !element.length ) {
			return false;
		}

		var editable = element.prop( "contentEditable" );

		if ( editable === "inherit" ) {
		  return this._isContentEditable( element.parent() );
		}

		return editable === "true";
	}
} );

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&amp;" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		} );
	}
} );

// Live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount &gt; 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content &amp;&amp; content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		this.liveRegion.children().hide();
		$( "&lt;div&gt;" ).text( message ).appendTo( this.liveRegion );
	}
} );

return $.ui.autocomplete;

} ) );
/*!
 * Select2 4.0.13
 * https://select2.github.io
 *
 * Released under the MIT license
 * https://github.com/select2/select2/blob/master/LICENSE.md
 */
;(function (factory) {
  if (typeof define === 'function' &amp;&amp; define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' &amp;&amp; module.exports) {
    // Node/CommonJS
    module.exports = function (root, jQuery) {
      if (jQuery === undefined) {
        // require('jQuery') returns a factory that requires window to
        // build a jQuery instance, we normalize how we use modules
        // that require this pattern but the window provided is a noop
        // if it's defined (how jquery works)
        if (typeof window !== 'undefined') {
          jQuery = require('jquery');
        }
        else {
          jQuery = require('jquery')(root);
        }
      }
      factory(jQuery);
      return jQuery;
    };
  } else {
    // Browser globals
    factory(jQuery);
  }
} (function (jQuery) {
  // This is needed so we can catch the AMD loader configuration and use it
  // The inner file should be wrapped (by `banner.start.js`) in a function that
  // returns the AMD loader references.
  var S2 =(function () {
  // Restore the Select2 AMD loader so it can be used
  // Needed mostly in the language files, where the loader is not inserted
  if (jQuery &amp;&amp; jQuery.fn &amp;&amp; jQuery.fn.select2 &amp;&amp; jQuery.fn.select2.amd) {
    var S2 = jQuery.fn.select2.amd;
  }
var S2;(function () { if (!S2 || !S2.requirejs) {
if (!S2) { S2 = {}; } else { require = S2; }
/**
 * @license almond 0.3.3 Copyright jQuery Foundation and other contributors.
 * Released under MIT license, http://github.com/requirejs/almond/LICENSE
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice,
        jsSuffixRegExp = /\.js$/;

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap, lastIndex,
            foundI, foundStarMap, starI, i, j, part, normalizedBaseParts,
            baseParts = baseName &amp;&amp; baseName.split("/"),
            map = config.map,
            starMap = (map &amp;&amp; map['*']) || {};

        //Adjust any relative paths.
        if (name) {
            name = name.split('/');
            lastIndex = name.length - 1;

            // If wanting node ID compatibility, strip .js from end
            // of IDs. Have to do this here, and not in nameToUrl
            // because node allows either .js or non .js to map
            // to same file.
            if (config.nodeIdCompat &amp;&amp; jsSuffixRegExp.test(name[lastIndex])) {
                name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
            }

            // Starts with a '.' so need the baseName
            if (name[0].charAt(0) === '.' &amp;&amp; baseParts) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that 'directory' and not name of the baseName's
                //module. For instance, baseName of 'one/two/three', maps to
                //'one/two/three.js', but we want the directory, 'one/two' for
                //this normalization.
                normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
                name = normalizedBaseParts.concat(name);
            }

            //start trimDots
            for (i = 0; i &lt; name.length; i++) {
                part = name[i];
                if (part === '.') {
                    name.splice(i, 1);
                    i -= 1;
                } else if (part === '..') {
                    // If at the start, or previous value is still ..,
                    // keep them so that when converted to a path it may
                    // still work when converted to a path, even though
                    // as an ID it is less than ideal. In larger point
                    // releases, may be better to just kick out an error.
                    if (i === 0 || (i === 1 &amp;&amp; name[2] === '..') || name[i - 1] === '..') {
                        continue;
                    } else if (i &gt; 0) {
                        name.splice(i - 1, 2);
                        i -= 2;
                    }
                }
            }
            //end trimDots

            name = name.join('/');
        }

        //Apply map config if available.
        if ((baseParts || starMap) &amp;&amp; map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i &gt; 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j &gt; 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap &amp;&amp; starMap &amp;&amp; starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap &amp;&amp; foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            var args = aps.call(arguments, 0);

            //If first arg is not require('string'), and there is only
            //one arg, it is the array form without a callback. Insert
            //a null so that the following concat is correct.
            if (typeof args[0] !== 'string' &amp;&amp; args.length === 1) {
                args.push(null);
            }
            return req.apply(undef, args.concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) &amp;&amp; !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index &gt; -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    //Creates a parts array for a relName where first part is plugin ID,
    //second part is resource ID. Assumes relName has already been normalized.
    function makeRelParts(relName) {
        return relName ? splitPrefix(relName) : [];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relParts) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0],
            relResourceName = relParts[1];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relResourceName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin &amp;&amp; plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relResourceName));
            } else {
                name = normalize(name, relResourceName);
            }
        } else {
            name = normalize(name, relResourceName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config &amp;&amp; config.config &amp;&amp; config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i, relParts,
            args = [],
            callbackType = typeof callback,
            usingExports;

        //Use name if no relName
        relName = relName || name;
        relParts = makeRelParts(relName);

        //Call the callback to define the module, if necessary.
        if (callbackType === 'undefined' || callbackType === 'function') {
            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length &amp;&amp; callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i &lt; deps.length; i += 1) {
                map = makeMap(deps[i], relParts);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback ? callback.apply(defined[name], args) : undefined;

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule &amp;&amp; cjsModule.exports !== undef &amp;&amp;
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, makeRelParts(callback)).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (config.deps) {
                req(config.deps, config.callback);
            }
            if (!callback) {
                return;
            }

            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        return req(cfg);
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {
        if (typeof name !== 'string') {
            throw new Error('See almond README: incorrect module build, no module name');
        }

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) &amp;&amp; !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());

S2.requirejs = requirejs;S2.require = require;S2.define = define;
}
}());
S2.define("almond", function(){});

/* global jQuery:false, $:false */
S2.define('jquery',[],function () {
  var _$ = jQuery || $;

  if (_$ == null &amp;&amp; console &amp;&amp; console.error) {
    console.error(
      'Select2: An instance of jQuery or a jQuery-compatible library was not ' +
      'found. Make sure that you are including jQuery before Select2 on your ' +
      'web page.'
    );
  }

  return _$;
});

S2.define('select2/utils',[
  'jquery'
], function ($) {
  var Utils = {};

  Utils.Extend = function (ChildClass, SuperClass) {
    var __hasProp = {}.hasOwnProperty;

    function BaseConstructor () {
      this.constructor = ChildClass;
    }

    for (var key in SuperClass) {
      if (__hasProp.call(SuperClass, key)) {
        ChildClass[key] = SuperClass[key];
      }
    }

    BaseConstructor.prototype = SuperClass.prototype;
    ChildClass.prototype = new BaseConstructor();
    ChildClass.__super__ = SuperClass.prototype;

    return ChildClass;
  };

  function getMethods (theClass) {
    var proto = theClass.prototype;

    var methods = [];

    for (var methodName in proto) {
      var m = proto[methodName];

      if (typeof m !== 'function') {
        continue;
      }

      if (methodName === 'constructor') {
        continue;
      }

      methods.push(methodName);
    }

    return methods;
  }

  Utils.Decorate = function (SuperClass, DecoratorClass) {
    var decoratedMethods = getMethods(DecoratorClass);
    var superMethods = getMethods(SuperClass);

    function DecoratedClass () {
      var unshift = Array.prototype.unshift;

      var argCount = DecoratorClass.prototype.constructor.length;

      var calledConstructor = SuperClass.prototype.constructor;

      if (argCount &gt; 0) {
        unshift.call(arguments, SuperClass.prototype.constructor);

        calledConstructor = DecoratorClass.prototype.constructor;
      }

      calledConstructor.apply(this, arguments);
    }

    DecoratorClass.displayName = SuperClass.displayName;

    function ctr () {
      this.constructor = DecoratedClass;
    }

    DecoratedClass.prototype = new ctr();

    for (var m = 0; m &lt; superMethods.length; m++) {
      var superMethod = superMethods[m];

      DecoratedClass.prototype[superMethod] =
        SuperClass.prototype[superMethod];
    }

    var calledMethod = function (methodName) {
      // Stub out the original method if it's not decorating an actual method
      var originalMethod = function () {};

      if (methodName in DecoratedClass.prototype) {
        originalMethod = DecoratedClass.prototype[methodName];
      }

      var decoratedMethod = DecoratorClass.prototype[methodName];

      return function () {
        var unshift = Array.prototype.unshift;

        unshift.call(arguments, originalMethod);

        return decoratedMethod.apply(this, arguments);
      };
    };

    for (var d = 0; d &lt; decoratedMethods.length; d++) {
      var decoratedMethod = decoratedMethods[d];

      DecoratedClass.prototype[decoratedMethod] = calledMethod(decoratedMethod);
    }

    return DecoratedClass;
  };

  var Observable = function () {
    this.listeners = {};
  };

  Observable.prototype.on = function (event, callback) {
    this.listeners = this.listeners || {};

    if (event in this.listeners) {
      this.listeners[event].push(callback);
    } else {
      this.listeners[event] = [callback];
    }
  };

  Observable.prototype.trigger = function (event) {
    var slice = Array.prototype.slice;
    var params = slice.call(arguments, 1);

    this.listeners = this.listeners || {};

    // Params should always come in as an array
    if (params == null) {
      params = [];
    }

    // If there are no arguments to the event, use a temporary object
    if (params.length === 0) {
      params.push({});
    }

    // Set the `_type` of the first object to the event
    params[0]._type = event;

    if (event in this.listeners) {
      this.invoke(this.listeners[event], slice.call(arguments, 1));
    }

    if ('*' in this.listeners) {
      this.invoke(this.listeners['*'], arguments);
    }
  };

  Observable.prototype.invoke = function (listeners, params) {
    for (var i = 0, len = listeners.length; i &lt; len; i++) {
      listeners[i].apply(this, params);
    }
  };

  Utils.Observable = Observable;

  Utils.generateChars = function (length) {
    var chars = '';

    for (var i = 0; i &lt; length; i++) {
      var randomChar = Math.floor(Math.random() * 36);
      chars += randomChar.toString(36);
    }

    return chars;
  };

  Utils.bind = function (func, context) {
    return function () {
      func.apply(context, arguments);
    };
  };

  Utils._convertData = function (data) {
    for (var originalKey in data) {
      var keys = originalKey.split('-');

      var dataLevel = data;

      if (keys.length === 1) {
        continue;
      }

      for (var k = 0; k &lt; keys.length; k++) {
        var key = keys[k];

        // Lowercase the first letter
        // By default, dash-separated becomes camelCase
        key = key.substring(0, 1).toLowerCase() + key.substring(1);

        if (!(key in dataLevel)) {
          dataLevel[key] = {};
        }

        if (k == keys.length - 1) {
          dataLevel[key] = data[originalKey];
        }

        dataLevel = dataLevel[key];
      }

      delete data[originalKey];
    }

    return data;
  };

  Utils.hasScroll = function (index, el) {
    // Adapted from the function created by @ShadowScripter
    // and adapted by @BillBarry on the Stack Exchange Code Review website.
    // The original code can be found at
    // http://codereview.stackexchange.com/q/13338
    // and was designed to be used with the Sizzle selector engine.

    var $el = $(el);
    var overflowX = el.style.overflowX;
    var overflowY = el.style.overflowY;

    //Check both x and y declarations
    if (overflowX === overflowY &amp;&amp;
        (overflowY === 'hidden' || overflowY === 'visible')) {
      return false;
    }

    if (overflowX === 'scroll' || overflowY === 'scroll') {
      return true;
    }

    return ($el.innerHeight() &lt; el.scrollHeight ||
      $el.innerWidth() &lt; el.scrollWidth);
  };

  Utils.escapeMarkup = function (markup) {
    var replaceMap = {
      '\\': '&amp;#92;',
      '&amp;': '&amp;amp;',
      '&lt;': '&amp;lt;',
      '&gt;': '&amp;gt;',
      '"': '&amp;quot;',
      '\'': '&amp;#39;',
      '/': '&amp;#47;'
    };

    // Do not try to escape the markup if it's not a string
    if (typeof markup !== 'string') {
      return markup;
    }

    return String(markup).replace(/[&amp;&lt;&gt;"'\/\\]/g, function (match) {
      return replaceMap[match];
    });
  };

  // Append an array of jQuery nodes to a given element.
  Utils.appendMany = function ($element, $nodes) {
    // jQuery 1.7.x does not support $.fn.append() with an array
    // Fall back to a jQuery object collection using $.fn.add()
    if ($.fn.jquery.substr(0, 3) === '1.7') {
      var $jqNodes = $();

      $.map($nodes, function (node) {
        $jqNodes = $jqNodes.add(node);
      });

      $nodes = $jqNodes;
    }

    $element.append($nodes);
  };

  // Cache objects in Utils.__cache instead of $.data (see #4346)
  Utils.__cache = {};

  var id = 0;
  Utils.GetUniqueElementId = function (element) {
    // Get a unique element Id. If element has no id,
    // creates a new unique number, stores it in the id
    // attribute and returns the new id.
    // If an id already exists, it simply returns it.

    var select2Id = element.getAttribute('data-select2-id');
    if (select2Id == null) {
      // If element has id, use it.
      if (element.id) {
        select2Id = element.id;
        element.setAttribute('data-select2-id', select2Id);
      } else {
        element.setAttribute('data-select2-id', ++id);
        select2Id = id.toString();
      }
    }
    return select2Id;
  };

  Utils.StoreData = function (element, name, value) {
    // Stores an item in the cache for a specified element.
    // name is the cache key.
    var id = Utils.GetUniqueElementId(element);
    if (!Utils.__cache[id]) {
      Utils.__cache[id] = {};
    }

    Utils.__cache[id][name] = value;
  };

  Utils.GetData = function (element, name) {
    // Retrieves a value from the cache by its key (name)
    // name is optional. If no name specified, return
    // all cache items for the specified element.
    // and for a specified element.
    var id = Utils.GetUniqueElementId(element);
    if (name) {
      if (Utils.__cache[id]) {
        if (Utils.__cache[id][name] != null) {
          return Utils.__cache[id][name];
        }
        return $(element).data(name); // Fallback to HTML5 data attribs.
      }
      return $(element).data(name); // Fallback to HTML5 data attribs.
    } else {
      return Utils.__cache[id];
    }
  };

  Utils.RemoveData = function (element) {
    // Removes all cached items for a specified element.
    var id = Utils.GetUniqueElementId(element);
    if (Utils.__cache[id] != null) {
      delete Utils.__cache[id];
    }

    element.removeAttribute('data-select2-id');
  };

  return Utils;
});

S2.define('select2/results',[
  'jquery',
  './utils'
], function ($, Utils) {
  function Results ($element, options, dataAdapter) {
    this.$element = $element;
    this.data = dataAdapter;
    this.options = options;

    Results.__super__.constructor.call(this);
  }

  Utils.Extend(Results, Utils.Observable);

  Results.prototype.render = function () {
    var $results = $(
      '&lt;ul class="select2-results__options" role="listbox"&gt;&lt;/ul&gt;'
    );

    if (this.options.get('multiple')) {
      $results.attr('aria-multiselectable', 'true');
    }

    this.$results = $results;

    return $results;
  };

  Results.prototype.clear = function () {
    this.$results.empty();
  };

  Results.prototype.displayMessage = function (params) {
    var escapeMarkup = this.options.get('escapeMarkup');

    this.clear();
    this.hideLoading();

    var $message = $(
      '&lt;li role="alert" aria-live="assertive"' +
      ' class="select2-results__option"&gt;&lt;/li&gt;'
    );

    var message = this.options.get('translations').get(params.message);

    $message.append(
      escapeMarkup(
        message(params.args)
      )
    );

    $message[0].className += ' select2-results__message';

    this.$results.append($message);
  };

  Results.prototype.hideMessages = function () {
    this.$results.find('.select2-results__message').remove();
  };

  Results.prototype.append = function (data) {
    this.hideLoading();

    var $options = [];

    if (data.results == null || data.results.length === 0) {
      if (this.$results.children().length === 0) {
        this.trigger('results:message', {
          message: 'noResults'
        });
      }

      return;
    }

    data.results = this.sort(data.results);

    for (var d = 0; d &lt; data.results.length; d++) {
      var item = data.results[d];

      var $option = this.option(item);

      $options.push($option);
    }

    this.$results.append($options);
  };

  Results.prototype.position = function ($results, $dropdown) {
    var $resultsContainer = $dropdown.find('.select2-results');
    $resultsContainer.append($results);
  };

  Results.prototype.sort = function (data) {
    var sorter = this.options.get('sorter');

    return sorter(data);
  };

  Results.prototype.highlightFirstItem = function () {
    var $options = this.$results
      .find('.select2-results__option[aria-selected]');

    var $selected = $options.filter('[aria-selected=true]');

    // Check if there are any selected options
    if ($selected.length &gt; 0) {
      // If there are selected options, highlight the first
      $selected.first().trigger('mouseenter');
    } else {
      // If there are no selected options, highlight the first option
      // in the dropdown
      $options.first().trigger('mouseenter');
    }

    this.ensureHighlightVisible();
  };

  Results.prototype.setClasses = function () {
    var self = this;

    this.data.current(function (selected) {
      var selectedIds = $.map(selected, function (s) {
        return s.id.toString();
      });

      var $options = self.$results
        .find('.select2-results__option[aria-selected]');

      $options.each(function () {
        var $option = $(this);

        var item = Utils.GetData(this, 'data');

        // id needs to be converted to a string when comparing
        var id = '' + item.id;

        if ((item.element != null &amp;&amp; item.element.selected) ||
            (item.element == null &amp;&amp; $.inArray(id, selectedIds) &gt; -1)) {
          $option.attr('aria-selected', 'true');
        } else {
          $option.attr('aria-selected', 'false');
        }
      });

    });
  };

  Results.prototype.showLoading = function (params) {
    this.hideLoading();

    var loadingMore = this.options.get('translations').get('searching');

    var loading = {
      disabled: true,
      loading: true,
      text: loadingMore(params)
    };
    var $loading = this.option(loading);
    $loading.className += ' loading-results';

    this.$results.prepend($loading);
  };

  Results.prototype.hideLoading = function () {
    this.$results.find('.loading-results').remove();
  };

  Results.prototype.option = function (data) {
    var option = document.createElement('li');
    option.className = 'select2-results__option';

    var attrs = {
      'role': 'option',
      'aria-selected': 'false'
    };

    var matches = window.Element.prototype.matches ||
      window.Element.prototype.msMatchesSelector ||
      window.Element.prototype.webkitMatchesSelector;

    if ((data.element != null &amp;&amp; matches.call(data.element, ':disabled')) ||
        (data.element == null &amp;&amp; data.disabled)) {
      delete attrs['aria-selected'];
      attrs['aria-disabled'] = 'true';
    }

    if (data.id == null) {
      delete attrs['aria-selected'];
    }

    if (data._resultId != null) {
      option.id = data._resultId;
    }

    if (data.title) {
      option.title = data.title;
    }

    if (data.children) {
      attrs.role = 'group';
      attrs['aria-label'] = data.text;
      delete attrs['aria-selected'];
    }

    for (var attr in attrs) {
      var val = attrs[attr];

      option.setAttribute(attr, val);
    }

    if (data.children) {
      var $option = $(option);

      var label = document.createElement('strong');
      label.className = 'select2-results__group';

      var $label = $(label);
      this.template(data, label);

      var $children = [];

      for (var c = 0; c &lt; data.children.length; c++) {
        var child = data.children[c];

        var $child = this.option(child);

        $children.push($child);
      }

      var $childrenContainer = $('&lt;ul&gt;&lt;/ul&gt;', {
        'class': 'select2-results__options select2-results__options--nested'
      });

      $childrenContainer.append($children);

      $option.append(label);
      $option.append($childrenContainer);
    } else {
      this.template(data, option);
    }

    Utils.StoreData(option, 'data', data);

    return option;
  };

  Results.prototype.bind = function (container, $container) {
    var self = this;

    var id = container.id + '-results';

    this.$results.attr('id', id);

    container.on('results:all', function (params) {
      self.clear();
      self.append(params.data);

      if (container.isOpen()) {
        self.setClasses();
        self.highlightFirstItem();
      }
    });

    container.on('results:append', function (params) {
      self.append(params.data);

      if (container.isOpen()) {
        self.setClasses();
      }
    });

    container.on('query', function (params) {
      self.hideMessages();
      self.showLoading(params);
    });

    container.on('select', function () {
      if (!container.isOpen()) {
        return;
      }

      self.setClasses();

      if (self.options.get('scrollAfterSelect')) {
        self.highlightFirstItem();
      }
    });

    container.on('unselect', function () {
      if (!container.isOpen()) {
        return;
      }

      self.setClasses();

      if (self.options.get('scrollAfterSelect')) {
        self.highlightFirstItem();
      }
    });

    container.on('open', function () {
      // When the dropdown is open, aria-expended="true"
      self.$results.attr('aria-expanded', 'true');
      self.$results.attr('aria-hidden', 'false');

      self.setClasses();
      self.ensureHighlightVisible();
    });

    container.on('close', function () {
      // When the dropdown is closed, aria-expended="false"
      self.$results.attr('aria-expanded', 'false');
      self.$results.attr('aria-hidden', 'true');
      self.$results.removeAttr('aria-activedescendant');
    });

    container.on('results:toggle', function () {
      var $highlighted = self.getHighlightedResults();

      if ($highlighted.length === 0) {
        return;
      }

      $highlighted.trigger('mouseup');
    });

    container.on('results:select', function () {
      var $highlighted = self.getHighlightedResults();

      if ($highlighted.length === 0) {
        return;
      }

      var data = Utils.GetData($highlighted[0], 'data');

      if ($highlighted.attr('aria-selected') == 'true') {
        self.trigger('close', {});
      } else {
        self.trigger('select', {
          data: data
        });
      }
    });

    container.on('results:previous', function () {
      var $highlighted = self.getHighlightedResults();

      var $options = self.$results.find('[aria-selected]');

      var currentIndex = $options.index($highlighted);

      // If we are already at the top, don't move further
      // If no options, currentIndex will be -1
      if (currentIndex &lt;= 0) {
        return;
      }

      var nextIndex = currentIndex - 1;

      // If none are highlighted, highlight the first
      if ($highlighted.length === 0) {
        nextIndex = 0;
      }

      var $next = $options.eq(nextIndex);

      $next.trigger('mouseenter');

      var currentOffset = self.$results.offset().top;
      var nextTop = $next.offset().top;
      var nextOffset = self.$results.scrollTop() + (nextTop - currentOffset);

      if (nextIndex === 0) {
        self.$results.scrollTop(0);
      } else if (nextTop - currentOffset &lt; 0) {
        self.$results.scrollTop(nextOffset);
      }
    });

    container.on('results:next', function () {
      var $highlighted = self.getHighlightedResults();

      var $options = self.$results.find('[aria-selected]');

      var currentIndex = $options.index($highlighted);

      var nextIndex = currentIndex + 1;

      // If we are at the last option, stay there
      if (nextIndex &gt;= $options.length) {
        return;
      }

      var $next = $options.eq(nextIndex);

      $next.trigger('mouseenter');

      var currentOffset = self.$results.offset().top +
        self.$results.outerHeight(false);
      var nextBottom = $next.offset().top + $next.outerHeight(false);
      var nextOffset = self.$results.scrollTop() + nextBottom - currentOffset;

      if (nextIndex === 0) {
        self.$results.scrollTop(0);
      } else if (nextBottom &gt; currentOffset) {
        self.$results.scrollTop(nextOffset);
      }
    });

    container.on('results:focus', function (params) {
      params.element.addClass('select2-results__option--highlighted');
    });

    container.on('results:message', function (params) {
      self.displayMessage(params);
    });

    if ($.fn.mousewheel) {
      this.$results.on('mousewheel', function (e) {
        var top = self.$results.scrollTop();

        var bottom = self.$results.get(0).scrollHeight - top + e.deltaY;

        var isAtTop = e.deltaY &gt; 0 &amp;&amp; top - e.deltaY &lt;= 0;
        var isAtBottom = e.deltaY &lt; 0 &amp;&amp; bottom &lt;= self.$results.height();

        if (isAtTop) {
          self.$results.scrollTop(0);

          e.preventDefault();
          e.stopPropagation();
        } else if (isAtBottom) {
          self.$results.scrollTop(
            self.$results.get(0).scrollHeight - self.$results.height()
          );

          e.preventDefault();
          e.stopPropagation();
        }
      });
    }

    this.$results.on('mouseup', '.select2-results__option[aria-selected]',
      function (evt) {
      var $this = $(this);

      var data = Utils.GetData(this, 'data');

      if ($this.attr('aria-selected') === 'true') {
        if (self.options.get('multiple')) {
          self.trigger('unselect', {
            originalEvent: evt,
            data: data
          });
        } else {
          self.trigger('close', {});
        }

        return;
      }

      self.trigger('select', {
        originalEvent: evt,
        data: data
      });
    });

    this.$results.on('mouseenter', '.select2-results__option[aria-selected]',
      function (evt) {
      var data = Utils.GetData(this, 'data');

      self.getHighlightedResults()
          .removeClass('select2-results__option--highlighted');

      self.trigger('results:focus', {
        data: data,
        element: $(this)
      });
    });
  };

  Results.prototype.getHighlightedResults = function () {
    var $highlighted = this.$results
    .find('.select2-results__option--highlighted');

    return $highlighted;
  };

  Results.prototype.destroy = function () {
    this.$results.remove();
  };

  Results.prototype.ensureHighlightVisible = function () {
    var $highlighted = this.getHighlightedResults();

    if ($highlighted.length === 0) {
      return;
    }

    var $options = this.$results.find('[aria-selected]');

    var currentIndex = $options.index($highlighted);

    var currentOffset = this.$results.offset().top;
    var nextTop = $highlighted.offset().top;
    var nextOffset = this.$results.scrollTop() + (nextTop - currentOffset);

    var offsetDelta = nextTop - currentOffset;
    nextOffset -= $highlighted.outerHeight(false) * 2;

    if (currentIndex &lt;= 2) {
      this.$results.scrollTop(0);
    } else if (offsetDelta &gt; this.$results.outerHeight() || offsetDelta &lt; 0) {
      this.$results.scrollTop(nextOffset);
    }
  };

  Results.prototype.template = function (result, container) {
    var template = this.options.get('templateResult');
    var escapeMarkup = this.options.get('escapeMarkup');

    var content = template(result, container);

    if (content == null) {
      container.style.display = 'none';
    } else if (typeof content === 'string') {
      container.innerHTML = escapeMarkup(content);
    } else {
      $(container).append(content);
    }
  };

  return Results;
});

S2.define('select2/keys',[

], function () {
  var KEYS = {
    BACKSPACE: 8,
    TAB: 9,
    ENTER: 13,
    SHIFT: 16,
    CTRL: 17,
    ALT: 18,
    ESC: 27,
    SPACE: 32,
    PAGE_UP: 33,
    PAGE_DOWN: 34,
    END: 35,
    HOME: 36,
    LEFT: 37,
    UP: 38,
    RIGHT: 39,
    DOWN: 40,
    DELETE: 46
  };

  return KEYS;
});

S2.define('select2/selection/base',[
  'jquery',
  '../utils',
  '../keys'
], function ($, Utils, KEYS) {
  function BaseSelection ($element, options) {
    this.$element = $element;
    this.options = options;

    BaseSelection.__super__.constructor.call(this);
  }

  Utils.Extend(BaseSelection, Utils.Observable);

  BaseSelection.prototype.render = function () {
    var $selection = $(
      '&lt;span class="select2-selection" role="combobox" ' +
      ' aria-haspopup="true" aria-expanded="false"&gt;' +
      '&lt;/span&gt;'
    );

    this._tabindex = 0;

    if (Utils.GetData(this.$element[0], 'old-tabindex') != null) {
      this._tabindex = Utils.GetData(this.$element[0], 'old-tabindex');
    } else if (this.$element.attr('tabindex') != null) {
      this._tabindex = this.$element.attr('tabindex');
    }

    $selection.attr('title', this.$element.attr('title'));
    $selection.attr('tabindex', this._tabindex);
    $selection.attr('aria-disabled', 'false');

    this.$selection = $selection;

    return $selection;
  };

  BaseSelection.prototype.bind = function (container, $container) {
    var self = this;

    var resultsId = container.id + '-results';

    this.container = container;

    this.$selection.on('focus', function (evt) {
      self.trigger('focus', evt);
    });

    this.$selection.on('blur', function (evt) {
      self._handleBlur(evt);
    });

    this.$selection.on('keydown', function (evt) {
      self.trigger('keypress', evt);

      if (evt.which === KEYS.SPACE) {
        evt.preventDefault();
      }
    });

    container.on('results:focus', function (params) {
      self.$selection.attr('aria-activedescendant', params.data._resultId);
    });

    container.on('selection:update', function (params) {
      self.update(params.data);
    });

    container.on('open', function () {
      // When the dropdown is open, aria-expanded="true"
      self.$selection.attr('aria-expanded', 'true');
      self.$selection.attr('aria-owns', resultsId);

      self._attachCloseHandler(container);
    });

    container.on('close', function () {
      // When the dropdown is closed, aria-expanded="false"
      self.$selection.attr('aria-expanded', 'false');
      self.$selection.removeAttr('aria-activedescendant');
      self.$selection.removeAttr('aria-owns');

      self.$selection.trigger('focus');

      self._detachCloseHandler(container);
    });

    container.on('enable', function () {
      self.$selection.attr('tabindex', self._tabindex);
      self.$selection.attr('aria-disabled', 'false');
    });

    container.on('disable', function () {
      self.$selection.attr('tabindex', '-1');
      self.$selection.attr('aria-disabled', 'true');
    });
  };

  BaseSelection.prototype._handleBlur = function (evt) {
    var self = this;

    // This needs to be delayed as the active element is the body when the tab
    // key is pressed, possibly along with others.
    window.setTimeout(function () {
      // Don't trigger `blur` if the focus is still in the selection
      if (
        (document.activeElement == self.$selection[0]) ||
        ($.contains(self.$selection[0], document.activeElement))
      ) {
        return;
      }

      self.trigger('blur', evt);
    }, 1);
  };

  BaseSelection.prototype._attachCloseHandler = function (container) {

    $(document.body).on('mousedown.select2.' + container.id, function (e) {
      var $target = $(e.target);

      var $select = $target.closest('.select2');

      var $all = $('.select2.select2-container--open');

      $all.each(function () {
        if (this == $select[0]) {
          return;
        }

        var $element = Utils.GetData(this, 'element');

        $element.select2('close');
      });
    });
  };

  BaseSelection.prototype._detachCloseHandler = function (container) {
    $(document.body).off('mousedown.select2.' + container.id);
  };

  BaseSelection.prototype.position = function ($selection, $container) {
    var $selectionContainer = $container.find('.selection');
    $selectionContainer.append($selection);
  };

  BaseSelection.prototype.destroy = function () {
    this._detachCloseHandler(this.container);
  };

  BaseSelection.prototype.update = function (data) {
    throw new Error('The `update` method must be defined in child classes.');
  };

  /**
   * Helper method to abstract the "enabled" (not "disabled") state of this
   * object.
   *
   * @return {true} if the instance is not disabled.
   * @return {false} if the instance is disabled.
   */
  BaseSelection.prototype.isEnabled = function () {
    return !this.isDisabled();
  };

  /**
   * Helper method to abstract the "disabled" state of this object.
   *
   * @return {true} if the disabled option is true.
   * @return {false} if the disabled option is false.
   */
  BaseSelection.prototype.isDisabled = function () {
    return this.options.get('disabled');
  };

  return BaseSelection;
});

S2.define('select2/selection/single',[
  'jquery',
  './base',
  '../utils',
  '../keys'
], function ($, BaseSelection, Utils, KEYS) {
  function SingleSelection () {
    SingleSelection.__super__.constructor.apply(this, arguments);
  }

  Utils.Extend(SingleSelection, BaseSelection);

  SingleSelection.prototype.render = function () {
    var $selection = SingleSelection.__super__.render.call(this);

    $selection.addClass('select2-selection--single');

    $selection.html(
      '&lt;span class="select2-selection__rendered"&gt;&lt;/span&gt;' +
      '&lt;span class="select2-selection__arrow" role="presentation"&gt;' +
        '&lt;b role="presentation"&gt;&lt;/b&gt;' +
      '&lt;/span&gt;'
    );

    return $selection;
  };

  SingleSelection.prototype.bind = function (container, $container) {
    var self = this;

    SingleSelection.__super__.bind.apply(this, arguments);

    var id = container.id + '-container';

    this.$selection.find('.select2-selection__rendered')
      .attr('id', id)
      .attr('role', 'textbox')
      .attr('aria-readonly', 'true');
    this.$selection.attr('aria-labelledby', id);

    this.$selection.on('mousedown', function (evt) {
      // Only respond to left clicks
      if (evt.which !== 1) {
        return;
      }

      self.trigger('toggle', {
        originalEvent: evt
      });
    });

    this.$selection.on('focus', function (evt) {
      // User focuses on the container
    });

    this.$selection.on('blur', function (evt) {
      // User exits the container
    });

    container.on('focus', function (evt) {
      if (!container.isOpen()) {
        self.$selection.trigger('focus');
      }
    });
  };

  SingleSelection.prototype.clear = function () {
    var $rendered = this.$selection.find('.select2-selection__rendered');
    $rendered.empty();
    $rendered.removeAttr('title'); // clear tooltip on empty
  };

  SingleSelection.prototype.display = function (data, container) {
    var template = this.options.get('templateSelection');
    var escapeMarkup = this.options.get('escapeMarkup');

    return escapeMarkup(template(data, container));
  };

  SingleSelection.prototype.selectionContainer = function () {
    return $('&lt;span&gt;&lt;/span&gt;');
  };

  SingleSelection.prototype.update = function (data) {
    if (data.length === 0) {
      this.clear();
      return;
    }

    var selection = data[0];

    var $rendered = this.$selection.find('.select2-selection__rendered');
    var formatted = this.display(selection, $rendered);

    $rendered.empty().append(formatted);

    var title = selection.title || selection.text;

    if (title) {
      $rendered.attr('title', title);
    } else {
      $rendered.removeAttr('title');
    }
  };

  return SingleSelection;
});

S2.define('select2/selection/multiple',[
  'jquery',
  './base',
  '../utils'
], function ($, BaseSelection, Utils) {
  function MultipleSelection ($element, options) {
    MultipleSelection.__super__.constructor.apply(this, arguments);
  }

  Utils.Extend(MultipleSelection, BaseSelection);

  MultipleSelection.prototype.render = function () {
    var $selection = MultipleSelection.__super__.render.call(this);

    $selection.addClass('select2-selection--multiple');

    $selection.html(
      '&lt;ul class="select2-selection__rendered"&gt;&lt;/ul&gt;'
    );

    return $selection;
  };

  MultipleSelection.prototype.bind = function (container, $container) {
    var self = this;

    MultipleSelection.__super__.bind.apply(this, arguments);

    this.$selection.on('click', function (evt) {
      self.trigger('toggle', {
        originalEvent: evt
      });
    });

    this.$selection.on(
      'click',
      '.select2-selection__choice__remove',
      function (evt) {
        // Ignore the event if it is disabled
        if (self.isDisabled()) {
          return;
        }

        var $remove = $(this);
        var $selection = $remove.parent();

        var data = Utils.GetData($selection[0], 'data');

        self.trigger('unselect', {
          originalEvent: evt,
          data: data
        });
      }
    );
  };

  MultipleSelection.prototype.clear = function () {
    var $rendered = this.$selection.find('.select2-selection__rendered');
    $rendered.empty();
    $rendered.removeAttr('title');
  };

  MultipleSelection.prototype.display = function (data, container) {
    var template = this.options.get('templateSelection');
    var escapeMarkup = this.options.get('escapeMarkup');

    return escapeMarkup(template(data, container));
  };

  MultipleSelection.prototype.selectionContainer = function () {
    var $container = $(
      '&lt;li class="select2-selection__choice"&gt;' +
        '&lt;span class="select2-selection__choice__remove" role="presentation"&gt;' +
          '&amp;times;' +
        '&lt;/span&gt;' +
      '&lt;/li&gt;'
    );

    return $container;
  };

  MultipleSelection.prototype.update = function (data) {
    this.clear();

    if (data.length === 0) {
      return;
    }

    var $selections = [];

    for (var d = 0; d &lt; data.length; d++) {
      var selection = data[d];

      var $selection = this.selectionContainer();
      var formatted = this.display(selection, $selection);

      $selection.append(formatted);

      var title = selection.title || selection.text;

      if (title) {
        $selection.attr('title', title);
      }

      Utils.StoreData($selection[0], 'data', selection);

      $selections.push($selection);
    }

    var $rendered = this.$selection.find('.select2-selection__rendered');

    Utils.appendMany($rendered, $selections);
  };

  return MultipleSelection;
});

S2.define('select2/selection/placeholder',[
  '../utils'
], function (Utils) {
  function Placeholder (decorated, $element, options) {
    this.placeholder = this.normalizePlaceholder(options.get('placeholder'));

    decorated.call(this, $element, options);
  }

  Placeholder.prototype.normalizePlaceholder = function (_, placeholder) {
    if (typeof placeholder === 'string') {
      placeholder = {
        id: '',
        text: placeholder
      };
    }

    return placeholder;
  };

  Placeholder.prototype.createPlaceholder = function (decorated, placeholder) {
    var $placeholder = this.selectionContainer();

    $placeholder.html(this.display(placeholder));
    $placeholder.addClass('select2-selection__placeholder')
                .removeClass('select2-selection__choice');

    return $placeholder;
  };

  Placeholder.prototype.update = function (decorated, data) {
    var singlePlaceholder = (
      data.length == 1 &amp;&amp; data[0].id != this.placeholder.id
    );
    var multipleSelections = data.length &gt; 1;

    if (multipleSelections || singlePlaceholder) {
      return decorated.call(this, data);
    }

    this.clear();

    var $placeholder = this.createPlaceholder(this.placeholder);

    this.$selection.find('.select2-selection__rendered').append($placeholder);
  };

  return Placeholder;
});

S2.define('select2/selection/allowClear',[
  'jquery',
  '../keys',
  '../utils'
], function ($, KEYS, Utils) {
  function AllowClear () { }

  AllowClear.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    if (this.placeholder == null) {
      if (this.options.get('debug') &amp;&amp; window.console &amp;&amp; console.error) {
        console.error(
          'Select2: The `allowClear` option should be used in combination ' +
          'with the `placeholder` option.'
        );
      }
    }

    this.$selection.on('mousedown', '.select2-selection__clear',
      function (evt) {
        self._handleClear(evt);
    });

    container.on('keypress', function (evt) {
      self._handleKeyboardClear(evt, container);
    });
  };

  AllowClear.prototype._handleClear = function (_, evt) {
    // Ignore the event if it is disabled
    if (this.isDisabled()) {
      return;
    }

    var $clear = this.$selection.find('.select2-selection__clear');

    // Ignore the event if nothing has been selected
    if ($clear.length === 0) {
      return;
    }

    evt.stopPropagation();

    var data = Utils.GetData($clear[0], 'data');

    var previousVal = this.$element.val();
    this.$element.val(this.placeholder.id);

    var unselectData = {
      data: data
    };
    this.trigger('clear', unselectData);
    if (unselectData.prevented) {
      this.$element.val(previousVal);
      return;
    }

    for (var d = 0; d &lt; data.length; d++) {
      unselectData = {
        data: data[d]
      };

      // Trigger the `unselect` event, so people can prevent it from being
      // cleared.
      this.trigger('unselect', unselectData);

      // If the event was prevented, don't clear it out.
      if (unselectData.prevented) {
        this.$element.val(previousVal);
        return;
      }
    }

    this.$element.trigger('input').trigger('change');

    this.trigger('toggle', {});
  };

  AllowClear.prototype._handleKeyboardClear = function (_, evt, container) {
    if (container.isOpen()) {
      return;
    }

    if (evt.which == KEYS.DELETE || evt.which == KEYS.BACKSPACE) {
      this._handleClear(evt);
    }
  };

  AllowClear.prototype.update = function (decorated, data) {
    decorated.call(this, data);

    if (this.$selection.find('.select2-selection__placeholder').length &gt; 0 ||
        data.length === 0) {
      return;
    }

    var removeAll = this.options.get('translations').get('removeAllItems');

    var $remove = $(
      '&lt;span class="select2-selection__clear" title="' + removeAll() +'"&gt;' +
        '&amp;times;' +
      '&lt;/span&gt;'
    );
    Utils.StoreData($remove[0], 'data', data);

    this.$selection.find('.select2-selection__rendered').prepend($remove);
  };

  return AllowClear;
});

S2.define('select2/selection/search',[
  'jquery',
  '../utils',
  '../keys'
], function ($, Utils, KEYS) {
  function Search (decorated, $element, options) {
    decorated.call(this, $element, options);
  }

  Search.prototype.render = function (decorated) {
    var $search = $(
      '&lt;li class="select2-search select2-search--inline"&gt;' +
        '&lt;input class="select2-search__field" type="search" tabindex="-1"' +
        ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
        ' spellcheck="false" role="searchbox" aria-autocomplete="list" /&gt;' +
      '&lt;/li&gt;'
    );

    this.$searchContainer = $search;
    this.$search = $search.find('input');

    var $rendered = decorated.call(this);

    this._transferTabIndex();

    return $rendered;
  };

  Search.prototype.bind = function (decorated, container, $container) {
    var self = this;

    var resultsId = container.id + '-results';

    decorated.call(this, container, $container);

    container.on('open', function () {
      self.$search.attr('aria-controls', resultsId);
      self.$search.trigger('focus');
    });

    container.on('close', function () {
      self.$search.val('');
      self.$search.removeAttr('aria-controls');
      self.$search.removeAttr('aria-activedescendant');
      self.$search.trigger('focus');
    });

    container.on('enable', function () {
      self.$search.prop('disabled', false);

      self._transferTabIndex();
    });

    container.on('disable', function () {
      self.$search.prop('disabled', true);
    });

    container.on('focus', function (evt) {
      self.$search.trigger('focus');
    });

    container.on('results:focus', function (params) {
      if (params.data._resultId) {
        self.$search.attr('aria-activedescendant', params.data._resultId);
      } else {
        self.$search.removeAttr('aria-activedescendant');
      }
    });

    this.$selection.on('focusin', '.select2-search--inline', function (evt) {
      self.trigger('focus', evt);
    });

    this.$selection.on('focusout', '.select2-search--inline', function (evt) {
      self._handleBlur(evt);
    });

    this.$selection.on('keydown', '.select2-search--inline', function (evt) {
      evt.stopPropagation();

      self.trigger('keypress', evt);

      self._keyUpPrevented = evt.isDefaultPrevented();

      var key = evt.which;

      if (key === KEYS.BACKSPACE &amp;&amp; self.$search.val() === '') {
        var $previousChoice = self.$searchContainer
          .prev('.select2-selection__choice');

        if ($previousChoice.length &gt; 0) {
          var item = Utils.GetData($previousChoice[0], 'data');

          self.searchRemoveChoice(item);

          evt.preventDefault();
        }
      }
    });

    this.$selection.on('click', '.select2-search--inline', function (evt) {
      if (self.$search.val()) {
        evt.stopPropagation();
      }
    });

    // Try to detect the IE version should the `documentMode` property that
    // is stored on the document. This is only implemented in IE and is
    // slightly cleaner than doing a user agent check.
    // This property is not available in Edge, but Edge also doesn't have
    // this bug.
    var msie = document.documentMode;
    var disableInputEvents = msie &amp;&amp; msie &lt;= 11;

    // Workaround for browsers which do not support the `input` event
    // This will prevent double-triggering of events for browsers which support
    // both the `keyup` and `input` events.
    this.$selection.on(
      'input.searchcheck',
      '.select2-search--inline',
      function (evt) {
        // IE will trigger the `input` event when a placeholder is used on a
        // search box. To get around this issue, we are forced to ignore all
        // `input` events in IE and keep using `keyup`.
        if (disableInputEvents) {
          self.$selection.off('input.search input.searchcheck');
          return;
        }

        // Unbind the duplicated `keyup` event
        self.$selection.off('keyup.search');
      }
    );

    this.$selection.on(
      'keyup.search input.search',
      '.select2-search--inline',
      function (evt) {
        // IE will trigger the `input` event when a placeholder is used on a
        // search box. To get around this issue, we are forced to ignore all
        // `input` events in IE and keep using `keyup`.
        if (disableInputEvents &amp;&amp; evt.type === 'input') {
          self.$selection.off('input.search input.searchcheck');
          return;
        }

        var key = evt.which;

        // We can freely ignore events from modifier keys
        if (key == KEYS.SHIFT || key == KEYS.CTRL || key == KEYS.ALT) {
          return;
        }

        // Tabbing will be handled during the `keydown` phase
        if (key == KEYS.TAB) {
          return;
        }

        self.handleSearch(evt);
      }
    );
  };

  /**
   * This method will transfer the tabindex attribute from the rendered
   * selection to the search box. This allows for the search box to be used as
   * the primary focus instead of the selection container.
   *
   * @private
   */
  Search.prototype._transferTabIndex = function (decorated) {
    this.$search.attr('tabindex', this.$selection.attr('tabindex'));
    this.$selection.attr('tabindex', '-1');
  };

  Search.prototype.createPlaceholder = function (decorated, placeholder) {
    this.$search.attr('placeholder', placeholder.text);
  };

  Search.prototype.update = function (decorated, data) {
    var searchHadFocus = this.$search[0] == document.activeElement;

    this.$search.attr('placeholder', '');

    decorated.call(this, data);

    this.$selection.find('.select2-selection__rendered')
                   .append(this.$searchContainer);

    this.resizeSearch();
    if (searchHadFocus) {
      this.$search.trigger('focus');
    }
  };

  Search.prototype.handleSearch = function () {
    this.resizeSearch();

    if (!this._keyUpPrevented) {
      var input = this.$search.val();

      this.trigger('query', {
        term: input
      });
    }

    this._keyUpPrevented = false;
  };

  Search.prototype.searchRemoveChoice = function (decorated, item) {
    this.trigger('unselect', {
      data: item
    });

    this.$search.val(item.text);
    this.handleSearch();
  };

  Search.prototype.resizeSearch = function () {
    this.$search.css('width', '25px');

    var width = '';

    if (this.$search.attr('placeholder') !== '') {
      width = this.$selection.find('.select2-selection__rendered').width();
    } else {
      var minimumWidth = this.$search.val().length + 1;

      width = (minimumWidth * 0.75) + 'em';
    }

    this.$search.css('width', width);
  };

  return Search;
});

S2.define('select2/selection/eventRelay',[
  'jquery'
], function ($) {
  function EventRelay () { }

  EventRelay.prototype.bind = function (decorated, container, $container) {
    var self = this;
    var relayEvents = [
      'open', 'opening',
      'close', 'closing',
      'select', 'selecting',
      'unselect', 'unselecting',
      'clear', 'clearing'
    ];

    var preventableEvents = [
      'opening', 'closing', 'selecting', 'unselecting', 'clearing'
    ];

    decorated.call(this, container, $container);

    container.on('*', function (name, params) {
      // Ignore events that should not be relayed
      if ($.inArray(name, relayEvents) === -1) {
        return;
      }

      // The parameters should always be an object
      params = params || {};

      // Generate the jQuery event for the Select2 event
      var evt = $.Event('select2:' + name, {
        params: params
      });

      self.$element.trigger(evt);

      // Only handle preventable events if it was one
      if ($.inArray(name, preventableEvents) === -1) {
        return;
      }

      params.prevented = evt.isDefaultPrevented();
    });
  };

  return EventRelay;
});

S2.define('select2/translation',[
  'jquery',
  'require'
], function ($, require) {
  function Translation (dict) {
    this.dict = dict || {};
  }

  Translation.prototype.all = function () {
    return this.dict;
  };

  Translation.prototype.get = function (key) {
    return this.dict[key];
  };

  Translation.prototype.extend = function (translation) {
    this.dict = $.extend({}, translation.all(), this.dict);
  };

  // Static functions

  Translation._cache = {};

  Translation.loadPath = function (path) {
    if (!(path in Translation._cache)) {
      var translations = require(path);

      Translation._cache[path] = translations;
    }

    return new Translation(Translation._cache[path]);
  };

  return Translation;
});

S2.define('select2/diacritics',[

], function () {
  var diacritics = {
    '\u24B6': 'A',
    '\uFF21': 'A',
    '\u00C0': 'A',
    '\u00C1': 'A',
    '\u00C2': 'A',
    '\u1EA6': 'A',
    '\u1EA4': 'A',
    '\u1EAA': 'A',
    '\u1EA8': 'A',
    '\u00C3': 'A',
    '\u0100': 'A',
    '\u0102': 'A',
    '\u1EB0': 'A',
    '\u1EAE': 'A',
    '\u1EB4': 'A',
    '\u1EB2': 'A',
    '\u0226': 'A',
    '\u01E0': 'A',
    '\u00C4': 'A',
    '\u01DE': 'A',
    '\u1EA2': 'A',
    '\u00C5': 'A',
    '\u01FA': 'A',
    '\u01CD': 'A',
    '\u0200': 'A',
    '\u0202': 'A',
    '\u1EA0': 'A',
    '\u1EAC': 'A',
    '\u1EB6': 'A',
    '\u1E00': 'A',
    '\u0104': 'A',
    '\u023A': 'A',
    '\u2C6F': 'A',
    '\uA732': 'AA',
    '\u00C6': 'AE',
    '\u01FC': 'AE',
    '\u01E2': 'AE',
    '\uA734': 'AO',
    '\uA736': 'AU',
    '\uA738': 'AV',
    '\uA73A': 'AV',
    '\uA73C': 'AY',
    '\u24B7': 'B',
    '\uFF22': 'B',
    '\u1E02': 'B',
    '\u1E04': 'B',
    '\u1E06': 'B',
    '\u0243': 'B',
    '\u0182': 'B',
    '\u0181': 'B',
    '\u24B8': 'C',
    '\uFF23': 'C',
    '\u0106': 'C',
    '\u0108': 'C',
    '\u010A': 'C',
    '\u010C': 'C',
    '\u00C7': 'C',
    '\u1E08': 'C',
    '\u0187': 'C',
    '\u023B': 'C',
    '\uA73E': 'C',
    '\u24B9': 'D',
    '\uFF24': 'D',
    '\u1E0A': 'D',
    '\u010E': 'D',
    '\u1E0C': 'D',
    '\u1E10': 'D',
    '\u1E12': 'D',
    '\u1E0E': 'D',
    '\u0110': 'D',
    '\u018B': 'D',
    '\u018A': 'D',
    '\u0189': 'D',
    '\uA779': 'D',
    '\u01F1': 'DZ',
    '\u01C4': 'DZ',
    '\u01F2': 'Dz',
    '\u01C5': 'Dz',
    '\u24BA': 'E',
    '\uFF25': 'E',
    '\u00C8': 'E',
    '\u00C9': 'E',
    '\u00CA': 'E',
    '\u1EC0': 'E',
    '\u1EBE': 'E',
    '\u1EC4': 'E',
    '\u1EC2': 'E',
    '\u1EBC': 'E',
    '\u0112': 'E',
    '\u1E14': 'E',
    '\u1E16': 'E',
    '\u0114': 'E',
    '\u0116': 'E',
    '\u00CB': 'E',
    '\u1EBA': 'E',
    '\u011A': 'E',
    '\u0204': 'E',
    '\u0206': 'E',
    '\u1EB8': 'E',
    '\u1EC6': 'E',
    '\u0228': 'E',
    '\u1E1C': 'E',
    '\u0118': 'E',
    '\u1E18': 'E',
    '\u1E1A': 'E',
    '\u0190': 'E',
    '\u018E': 'E',
    '\u24BB': 'F',
    '\uFF26': 'F',
    '\u1E1E': 'F',
    '\u0191': 'F',
    '\uA77B': 'F',
    '\u24BC': 'G',
    '\uFF27': 'G',
    '\u01F4': 'G',
    '\u011C': 'G',
    '\u1E20': 'G',
    '\u011E': 'G',
    '\u0120': 'G',
    '\u01E6': 'G',
    '\u0122': 'G',
    '\u01E4': 'G',
    '\u0193': 'G',
    '\uA7A0': 'G',
    '\uA77D': 'G',
    '\uA77E': 'G',
    '\u24BD': 'H',
    '\uFF28': 'H',
    '\u0124': 'H',
    '\u1E22': 'H',
    '\u1E26': 'H',
    '\u021E': 'H',
    '\u1E24': 'H',
    '\u1E28': 'H',
    '\u1E2A': 'H',
    '\u0126': 'H',
    '\u2C67': 'H',
    '\u2C75': 'H',
    '\uA78D': 'H',
    '\u24BE': 'I',
    '\uFF29': 'I',
    '\u00CC': 'I',
    '\u00CD': 'I',
    '\u00CE': 'I',
    '\u0128': 'I',
    '\u012A': 'I',
    '\u012C': 'I',
    '\u0130': 'I',
    '\u00CF': 'I',
    '\u1E2E': 'I',
    '\u1EC8': 'I',
    '\u01CF': 'I',
    '\u0208': 'I',
    '\u020A': 'I',
    '\u1ECA': 'I',
    '\u012E': 'I',
    '\u1E2C': 'I',
    '\u0197': 'I',
    '\u24BF': 'J',
    '\uFF2A': 'J',
    '\u0134': 'J',
    '\u0248': 'J',
    '\u24C0': 'K',
    '\uFF2B': 'K',
    '\u1E30': 'K',
    '\u01E8': 'K',
    '\u1E32': 'K',
    '\u0136': 'K',
    '\u1E34': 'K',
    '\u0198': 'K',
    '\u2C69': 'K',
    '\uA740': 'K',
    '\uA742': 'K',
    '\uA744': 'K',
    '\uA7A2': 'K',
    '\u24C1': 'L',
    '\uFF2C': 'L',
    '\u013F': 'L',
    '\u0139': 'L',
    '\u013D': 'L',
    '\u1E36': 'L',
    '\u1E38': 'L',
    '\u013B': 'L',
    '\u1E3C': 'L',
    '\u1E3A': 'L',
    '\u0141': 'L',
    '\u023D': 'L',
    '\u2C62': 'L',
    '\u2C60': 'L',
    '\uA748': 'L',
    '\uA746': 'L',
    '\uA780': 'L',
    '\u01C7': 'LJ',
    '\u01C8': 'Lj',
    '\u24C2': 'M',
    '\uFF2D': 'M',
    '\u1E3E': 'M',
    '\u1E40': 'M',
    '\u1E42': 'M',
    '\u2C6E': 'M',
    '\u019C': 'M',
    '\u24C3': 'N',
    '\uFF2E': 'N',
    '\u01F8': 'N',
    '\u0143': 'N',
    '\u00D1': 'N',
    '\u1E44': 'N',
    '\u0147': 'N',
    '\u1E46': 'N',
    '\u0145': 'N',
    '\u1E4A': 'N',
    '\u1E48': 'N',
    '\u0220': 'N',
    '\u019D': 'N',
    '\uA790': 'N',
    '\uA7A4': 'N',
    '\u01CA': 'NJ',
    '\u01CB': 'Nj',
    '\u24C4': 'O',
    '\uFF2F': 'O',
    '\u00D2': 'O',
    '\u00D3': 'O',
    '\u00D4': 'O',
    '\u1ED2': 'O',
    '\u1ED0': 'O',
    '\u1ED6': 'O',
    '\u1ED4': 'O',
    '\u00D5': 'O',
    '\u1E4C': 'O',
    '\u022C': 'O',
    '\u1E4E': 'O',
    '\u014C': 'O',
    '\u1E50': 'O',
    '\u1E52': 'O',
    '\u014E': 'O',
    '\u022E': 'O',
    '\u0230': 'O',
    '\u00D6': 'O',
    '\u022A': 'O',
    '\u1ECE': 'O',
    '\u0150': 'O',
    '\u01D1': 'O',
    '\u020C': 'O',
    '\u020E': 'O',
    '\u01A0': 'O',
    '\u1EDC': 'O',
    '\u1EDA': 'O',
    '\u1EE0': 'O',
    '\u1EDE': 'O',
    '\u1EE2': 'O',
    '\u1ECC': 'O',
    '\u1ED8': 'O',
    '\u01EA': 'O',
    '\u01EC': 'O',
    '\u00D8': 'O',
    '\u01FE': 'O',
    '\u0186': 'O',
    '\u019F': 'O',
    '\uA74A': 'O',
    '\uA74C': 'O',
    '\u0152': 'OE',
    '\u01A2': 'OI',
    '\uA74E': 'OO',
    '\u0222': 'OU',
    '\u24C5': 'P',
    '\uFF30': 'P',
    '\u1E54': 'P',
    '\u1E56': 'P',
    '\u01A4': 'P',
    '\u2C63': 'P',
    '\uA750': 'P',
    '\uA752': 'P',
    '\uA754': 'P',
    '\u24C6': 'Q',
    '\uFF31': 'Q',
    '\uA756': 'Q',
    '\uA758': 'Q',
    '\u024A': 'Q',
    '\u24C7': 'R',
    '\uFF32': 'R',
    '\u0154': 'R',
    '\u1E58': 'R',
    '\u0158': 'R',
    '\u0210': 'R',
    '\u0212': 'R',
    '\u1E5A': 'R',
    '\u1E5C': 'R',
    '\u0156': 'R',
    '\u1E5E': 'R',
    '\u024C': 'R',
    '\u2C64': 'R',
    '\uA75A': 'R',
    '\uA7A6': 'R',
    '\uA782': 'R',
    '\u24C8': 'S',
    '\uFF33': 'S',
    '\u1E9E': 'S',
    '\u015A': 'S',
    '\u1E64': 'S',
    '\u015C': 'S',
    '\u1E60': 'S',
    '\u0160': 'S',
    '\u1E66': 'S',
    '\u1E62': 'S',
    '\u1E68': 'S',
    '\u0218': 'S',
    '\u015E': 'S',
    '\u2C7E': 'S',
    '\uA7A8': 'S',
    '\uA784': 'S',
    '\u24C9': 'T',
    '\uFF34': 'T',
    '\u1E6A': 'T',
    '\u0164': 'T',
    '\u1E6C': 'T',
    '\u021A': 'T',
    '\u0162': 'T',
    '\u1E70': 'T',
    '\u1E6E': 'T',
    '\u0166': 'T',
    '\u01AC': 'T',
    '\u01AE': 'T',
    '\u023E': 'T',
    '\uA786': 'T',
    '\uA728': 'TZ',
    '\u24CA': 'U',
    '\uFF35': 'U',
    '\u00D9': 'U',
    '\u00DA': 'U',
    '\u00DB': 'U',
    '\u0168': 'U',
    '\u1E78': 'U',
    '\u016A': 'U',
    '\u1E7A': 'U',
    '\u016C': 'U',
    '\u00DC': 'U',
    '\u01DB': 'U',
    '\u01D7': 'U',
    '\u01D5': 'U',
    '\u01D9': 'U',
    '\u1EE6': 'U',
    '\u016E': 'U',
    '\u0170': 'U',
    '\u01D3': 'U',
    '\u0214': 'U',
    '\u0216': 'U',
    '\u01AF': 'U',
    '\u1EEA': 'U',
    '\u1EE8': 'U',
    '\u1EEE': 'U',
    '\u1EEC': 'U',
    '\u1EF0': 'U',
    '\u1EE4': 'U',
    '\u1E72': 'U',
    '\u0172': 'U',
    '\u1E76': 'U',
    '\u1E74': 'U',
    '\u0244': 'U',
    '\u24CB': 'V',
    '\uFF36': 'V',
    '\u1E7C': 'V',
    '\u1E7E': 'V',
    '\u01B2': 'V',
    '\uA75E': 'V',
    '\u0245': 'V',
    '\uA760': 'VY',
    '\u24CC': 'W',
    '\uFF37': 'W',
    '\u1E80': 'W',
    '\u1E82': 'W',
    '\u0174': 'W',
    '\u1E86': 'W',
    '\u1E84': 'W',
    '\u1E88': 'W',
    '\u2C72': 'W',
    '\u24CD': 'X',
    '\uFF38': 'X',
    '\u1E8A': 'X',
    '\u1E8C': 'X',
    '\u24CE': 'Y',
    '\uFF39': 'Y',
    '\u1EF2': 'Y',
    '\u00DD': 'Y',
    '\u0176': 'Y',
    '\u1EF8': 'Y',
    '\u0232': 'Y',
    '\u1E8E': 'Y',
    '\u0178': 'Y',
    '\u1EF6': 'Y',
    '\u1EF4': 'Y',
    '\u01B3': 'Y',
    '\u024E': 'Y',
    '\u1EFE': 'Y',
    '\u24CF': 'Z',
    '\uFF3A': 'Z',
    '\u0179': 'Z',
    '\u1E90': 'Z',
    '\u017B': 'Z',
    '\u017D': 'Z',
    '\u1E92': 'Z',
    '\u1E94': 'Z',
    '\u01B5': 'Z',
    '\u0224': 'Z',
    '\u2C7F': 'Z',
    '\u2C6B': 'Z',
    '\uA762': 'Z',
    '\u24D0': 'a',
    '\uFF41': 'a',
    '\u1E9A': 'a',
    '\u00E0': 'a',
    '\u00E1': 'a',
    '\u00E2': 'a',
    '\u1EA7': 'a',
    '\u1EA5': 'a',
    '\u1EAB': 'a',
    '\u1EA9': 'a',
    '\u00E3': 'a',
    '\u0101': 'a',
    '\u0103': 'a',
    '\u1EB1': 'a',
    '\u1EAF': 'a',
    '\u1EB5': 'a',
    '\u1EB3': 'a',
    '\u0227': 'a',
    '\u01E1': 'a',
    '\u00E4': 'a',
    '\u01DF': 'a',
    '\u1EA3': 'a',
    '\u00E5': 'a',
    '\u01FB': 'a',
    '\u01CE': 'a',
    '\u0201': 'a',
    '\u0203': 'a',
    '\u1EA1': 'a',
    '\u1EAD': 'a',
    '\u1EB7': 'a',
    '\u1E01': 'a',
    '\u0105': 'a',
    '\u2C65': 'a',
    '\u0250': 'a',
    '\uA733': 'aa',
    '\u00E6': 'ae',
    '\u01FD': 'ae',
    '\u01E3': 'ae',
    '\uA735': 'ao',
    '\uA737': 'au',
    '\uA739': 'av',
    '\uA73B': 'av',
    '\uA73D': 'ay',
    '\u24D1': 'b',
    '\uFF42': 'b',
    '\u1E03': 'b',
    '\u1E05': 'b',
    '\u1E07': 'b',
    '\u0180': 'b',
    '\u0183': 'b',
    '\u0253': 'b',
    '\u24D2': 'c',
    '\uFF43': 'c',
    '\u0107': 'c',
    '\u0109': 'c',
    '\u010B': 'c',
    '\u010D': 'c',
    '\u00E7': 'c',
    '\u1E09': 'c',
    '\u0188': 'c',
    '\u023C': 'c',
    '\uA73F': 'c',
    '\u2184': 'c',
    '\u24D3': 'd',
    '\uFF44': 'd',
    '\u1E0B': 'd',
    '\u010F': 'd',
    '\u1E0D': 'd',
    '\u1E11': 'd',
    '\u1E13': 'd',
    '\u1E0F': 'd',
    '\u0111': 'd',
    '\u018C': 'd',
    '\u0256': 'd',
    '\u0257': 'd',
    '\uA77A': 'd',
    '\u01F3': 'dz',
    '\u01C6': 'dz',
    '\u24D4': 'e',
    '\uFF45': 'e',
    '\u00E8': 'e',
    '\u00E9': 'e',
    '\u00EA': 'e',
    '\u1EC1': 'e',
    '\u1EBF': 'e',
    '\u1EC5': 'e',
    '\u1EC3': 'e',
    '\u1EBD': 'e',
    '\u0113': 'e',
    '\u1E15': 'e',
    '\u1E17': 'e',
    '\u0115': 'e',
    '\u0117': 'e',
    '\u00EB': 'e',
    '\u1EBB': 'e',
    '\u011B': 'e',
    '\u0205': 'e',
    '\u0207': 'e',
    '\u1EB9': 'e',
    '\u1EC7': 'e',
    '\u0229': 'e',
    '\u1E1D': 'e',
    '\u0119': 'e',
    '\u1E19': 'e',
    '\u1E1B': 'e',
    '\u0247': 'e',
    '\u025B': 'e',
    '\u01DD': 'e',
    '\u24D5': 'f',
    '\uFF46': 'f',
    '\u1E1F': 'f',
    '\u0192': 'f',
    '\uA77C': 'f',
    '\u24D6': 'g',
    '\uFF47': 'g',
    '\u01F5': 'g',
    '\u011D': 'g',
    '\u1E21': 'g',
    '\u011F': 'g',
    '\u0121': 'g',
    '\u01E7': 'g',
    '\u0123': 'g',
    '\u01E5': 'g',
    '\u0260': 'g',
    '\uA7A1': 'g',
    '\u1D79': 'g',
    '\uA77F': 'g',
    '\u24D7': 'h',
    '\uFF48': 'h',
    '\u0125': 'h',
    '\u1E23': 'h',
    '\u1E27': 'h',
    '\u021F': 'h',
    '\u1E25': 'h',
    '\u1E29': 'h',
    '\u1E2B': 'h',
    '\u1E96': 'h',
    '\u0127': 'h',
    '\u2C68': 'h',
    '\u2C76': 'h',
    '\u0265': 'h',
    '\u0195': 'hv',
    '\u24D8': 'i',
    '\uFF49': 'i',
    '\u00EC': 'i',
    '\u00ED': 'i',
    '\u00EE': 'i',
    '\u0129': 'i',
    '\u012B': 'i',
    '\u012D': 'i',
    '\u00EF': 'i',
    '\u1E2F': 'i',
    '\u1EC9': 'i',
    '\u01D0': 'i',
    '\u0209': 'i',
    '\u020B': 'i',
    '\u1ECB': 'i',
    '\u012F': 'i',
    '\u1E2D': 'i',
    '\u0268': 'i',
    '\u0131': 'i',
    '\u24D9': 'j',
    '\uFF4A': 'j',
    '\u0135': 'j',
    '\u01F0': 'j',
    '\u0249': 'j',
    '\u24DA': 'k',
    '\uFF4B': 'k',
    '\u1E31': 'k',
    '\u01E9': 'k',
    '\u1E33': 'k',
    '\u0137': 'k',
    '\u1E35': 'k',
    '\u0199': 'k',
    '\u2C6A': 'k',
    '\uA741': 'k',
    '\uA743': 'k',
    '\uA745': 'k',
    '\uA7A3': 'k',
    '\u24DB': 'l',
    '\uFF4C': 'l',
    '\u0140': 'l',
    '\u013A': 'l',
    '\u013E': 'l',
    '\u1E37': 'l',
    '\u1E39': 'l',
    '\u013C': 'l',
    '\u1E3D': 'l',
    '\u1E3B': 'l',
    '\u017F': 'l',
    '\u0142': 'l',
    '\u019A': 'l',
    '\u026B': 'l',
    '\u2C61': 'l',
    '\uA749': 'l',
    '\uA781': 'l',
    '\uA747': 'l',
    '\u01C9': 'lj',
    '\u24DC': 'm',
    '\uFF4D': 'm',
    '\u1E3F': 'm',
    '\u1E41': 'm',
    '\u1E43': 'm',
    '\u0271': 'm',
    '\u026F': 'm',
    '\u24DD': 'n',
    '\uFF4E': 'n',
    '\u01F9': 'n',
    '\u0144': 'n',
    '\u00F1': 'n',
    '\u1E45': 'n',
    '\u0148': 'n',
    '\u1E47': 'n',
    '\u0146': 'n',
    '\u1E4B': 'n',
    '\u1E49': 'n',
    '\u019E': 'n',
    '\u0272': 'n',
    '\u0149': 'n',
    '\uA791': 'n',
    '\uA7A5': 'n',
    '\u01CC': 'nj',
    '\u24DE': 'o',
    '\uFF4F': 'o',
    '\u00F2': 'o',
    '\u00F3': 'o',
    '\u00F4': 'o',
    '\u1ED3': 'o',
    '\u1ED1': 'o',
    '\u1ED7': 'o',
    '\u1ED5': 'o',
    '\u00F5': 'o',
    '\u1E4D': 'o',
    '\u022D': 'o',
    '\u1E4F': 'o',
    '\u014D': 'o',
    '\u1E51': 'o',
    '\u1E53': 'o',
    '\u014F': 'o',
    '\u022F': 'o',
    '\u0231': 'o',
    '\u00F6': 'o',
    '\u022B': 'o',
    '\u1ECF': 'o',
    '\u0151': 'o',
    '\u01D2': 'o',
    '\u020D': 'o',
    '\u020F': 'o',
    '\u01A1': 'o',
    '\u1EDD': 'o',
    '\u1EDB': 'o',
    '\u1EE1': 'o',
    '\u1EDF': 'o',
    '\u1EE3': 'o',
    '\u1ECD': 'o',
    '\u1ED9': 'o',
    '\u01EB': 'o',
    '\u01ED': 'o',
    '\u00F8': 'o',
    '\u01FF': 'o',
    '\u0254': 'o',
    '\uA74B': 'o',
    '\uA74D': 'o',
    '\u0275': 'o',
    '\u0153': 'oe',
    '\u01A3': 'oi',
    '\u0223': 'ou',
    '\uA74F': 'oo',
    '\u24DF': 'p',
    '\uFF50': 'p',
    '\u1E55': 'p',
    '\u1E57': 'p',
    '\u01A5': 'p',
    '\u1D7D': 'p',
    '\uA751': 'p',
    '\uA753': 'p',
    '\uA755': 'p',
    '\u24E0': 'q',
    '\uFF51': 'q',
    '\u024B': 'q',
    '\uA757': 'q',
    '\uA759': 'q',
    '\u24E1': 'r',
    '\uFF52': 'r',
    '\u0155': 'r',
    '\u1E59': 'r',
    '\u0159': 'r',
    '\u0211': 'r',
    '\u0213': 'r',
    '\u1E5B': 'r',
    '\u1E5D': 'r',
    '\u0157': 'r',
    '\u1E5F': 'r',
    '\u024D': 'r',
    '\u027D': 'r',
    '\uA75B': 'r',
    '\uA7A7': 'r',
    '\uA783': 'r',
    '\u24E2': 's',
    '\uFF53': 's',
    '\u00DF': 's',
    '\u015B': 's',
    '\u1E65': 's',
    '\u015D': 's',
    '\u1E61': 's',
    '\u0161': 's',
    '\u1E67': 's',
    '\u1E63': 's',
    '\u1E69': 's',
    '\u0219': 's',
    '\u015F': 's',
    '\u023F': 's',
    '\uA7A9': 's',
    '\uA785': 's',
    '\u1E9B': 's',
    '\u24E3': 't',
    '\uFF54': 't',
    '\u1E6B': 't',
    '\u1E97': 't',
    '\u0165': 't',
    '\u1E6D': 't',
    '\u021B': 't',
    '\u0163': 't',
    '\u1E71': 't',
    '\u1E6F': 't',
    '\u0167': 't',
    '\u01AD': 't',
    '\u0288': 't',
    '\u2C66': 't',
    '\uA787': 't',
    '\uA729': 'tz',
    '\u24E4': 'u',
    '\uFF55': 'u',
    '\u00F9': 'u',
    '\u00FA': 'u',
    '\u00FB': 'u',
    '\u0169': 'u',
    '\u1E79': 'u',
    '\u016B': 'u',
    '\u1E7B': 'u',
    '\u016D': 'u',
    '\u00FC': 'u',
    '\u01DC': 'u',
    '\u01D8': 'u',
    '\u01D6': 'u',
    '\u01DA': 'u',
    '\u1EE7': 'u',
    '\u016F': 'u',
    '\u0171': 'u',
    '\u01D4': 'u',
    '\u0215': 'u',
    '\u0217': 'u',
    '\u01B0': 'u',
    '\u1EEB': 'u',
    '\u1EE9': 'u',
    '\u1EEF': 'u',
    '\u1EED': 'u',
    '\u1EF1': 'u',
    '\u1EE5': 'u',
    '\u1E73': 'u',
    '\u0173': 'u',
    '\u1E77': 'u',
    '\u1E75': 'u',
    '\u0289': 'u',
    '\u24E5': 'v',
    '\uFF56': 'v',
    '\u1E7D': 'v',
    '\u1E7F': 'v',
    '\u028B': 'v',
    '\uA75F': 'v',
    '\u028C': 'v',
    '\uA761': 'vy',
    '\u24E6': 'w',
    '\uFF57': 'w',
    '\u1E81': 'w',
    '\u1E83': 'w',
    '\u0175': 'w',
    '\u1E87': 'w',
    '\u1E85': 'w',
    '\u1E98': 'w',
    '\u1E89': 'w',
    '\u2C73': 'w',
    '\u24E7': 'x',
    '\uFF58': 'x',
    '\u1E8B': 'x',
    '\u1E8D': 'x',
    '\u24E8': 'y',
    '\uFF59': 'y',
    '\u1EF3': 'y',
    '\u00FD': 'y',
    '\u0177': 'y',
    '\u1EF9': 'y',
    '\u0233': 'y',
    '\u1E8F': 'y',
    '\u00FF': 'y',
    '\u1EF7': 'y',
    '\u1E99': 'y',
    '\u1EF5': 'y',
    '\u01B4': 'y',
    '\u024F': 'y',
    '\u1EFF': 'y',
    '\u24E9': 'z',
    '\uFF5A': 'z',
    '\u017A': 'z',
    '\u1E91': 'z',
    '\u017C': 'z',
    '\u017E': 'z',
    '\u1E93': 'z',
    '\u1E95': 'z',
    '\u01B6': 'z',
    '\u0225': 'z',
    '\u0240': 'z',
    '\u2C6C': 'z',
    '\uA763': 'z',
    '\u0386': '\u0391',
    '\u0388': '\u0395',
    '\u0389': '\u0397',
    '\u038A': '\u0399',
    '\u03AA': '\u0399',
    '\u038C': '\u039F',
    '\u038E': '\u03A5',
    '\u03AB': '\u03A5',
    '\u038F': '\u03A9',
    '\u03AC': '\u03B1',
    '\u03AD': '\u03B5',
    '\u03AE': '\u03B7',
    '\u03AF': '\u03B9',
    '\u03CA': '\u03B9',
    '\u0390': '\u03B9',
    '\u03CC': '\u03BF',
    '\u03CD': '\u03C5',
    '\u03CB': '\u03C5',
    '\u03B0': '\u03C5',
    '\u03CE': '\u03C9',
    '\u03C2': '\u03C3',
    '\u2019': '\''
  };

  return diacritics;
});

S2.define('select2/data/base',[
  '../utils'
], function (Utils) {
  function BaseAdapter ($element, options) {
    BaseAdapter.__super__.constructor.call(this);
  }

  Utils.Extend(BaseAdapter, Utils.Observable);

  BaseAdapter.prototype.current = function (callback) {
    throw new Error('The `current` method must be defined in child classes.');
  };

  BaseAdapter.prototype.query = function (params, callback) {
    throw new Error('The `query` method must be defined in child classes.');
  };

  BaseAdapter.prototype.bind = function (container, $container) {
    // Can be implemented in subclasses
  };

  BaseAdapter.prototype.destroy = function () {
    // Can be implemented in subclasses
  };

  BaseAdapter.prototype.generateResultId = function (container, data) {
    var id = container.id + '-result-';

    id += Utils.generateChars(4);

    if (data.id != null) {
      id += '-' + data.id.toString();
    } else {
      id += '-' + Utils.generateChars(4);
    }
    return id;
  };

  return BaseAdapter;
});

S2.define('select2/data/select',[
  './base',
  '../utils',
  'jquery'
], function (BaseAdapter, Utils, $) {
  function SelectAdapter ($element, options) {
    this.$element = $element;
    this.options = options;

    SelectAdapter.__super__.constructor.call(this);
  }

  Utils.Extend(SelectAdapter, BaseAdapter);

  SelectAdapter.prototype.current = function (callback) {
    var data = [];
    var self = this;

    this.$element.find(':selected').each(function () {
      var $option = $(this);

      var option = self.item($option);

      data.push(option);
    });

    callback(data);
  };

  SelectAdapter.prototype.select = function (data) {
    var self = this;

    data.selected = true;

    // If data.element is a DOM node, use it instead
    if ($(data.element).is('option')) {
      data.element.selected = true;

      this.$element.trigger('input').trigger('change');

      return;
    }

    if (this.$element.prop('multiple')) {
      this.current(function (currentData) {
        var val = [];

        data = [data];
        data.push.apply(data, currentData);

        for (var d = 0; d &lt; data.length; d++) {
          var id = data[d].id;

          if ($.inArray(id, val) === -1) {
            val.push(id);
          }
        }

        self.$element.val(val);
        self.$element.trigger('input').trigger('change');
      });
    } else {
      var val = data.id;

      this.$element.val(val);
      this.$element.trigger('input').trigger('change');
    }
  };

  SelectAdapter.prototype.unselect = function (data) {
    var self = this;

    if (!this.$element.prop('multiple')) {
      return;
    }

    data.selected = false;

    if ($(data.element).is('option')) {
      data.element.selected = false;

      this.$element.trigger('input').trigger('change');

      return;
    }

    this.current(function (currentData) {
      var val = [];

      for (var d = 0; d &lt; currentData.length; d++) {
        var id = currentData[d].id;

        if (id !== data.id &amp;&amp; $.inArray(id, val) === -1) {
          val.push(id);
        }
      }

      self.$element.val(val);

      self.$element.trigger('input').trigger('change');
    });
  };

  SelectAdapter.prototype.bind = function (container, $container) {
    var self = this;

    this.container = container;

    container.on('select', function (params) {
      self.select(params.data);
    });

    container.on('unselect', function (params) {
      self.unselect(params.data);
    });
  };

  SelectAdapter.prototype.destroy = function () {
    // Remove anything added to child elements
    this.$element.find('*').each(function () {
      // Remove any custom data set by Select2
      Utils.RemoveData(this);
    });
  };

  SelectAdapter.prototype.query = function (params, callback) {
    var data = [];
    var self = this;

    var $options = this.$element.children();

    $options.each(function () {
      var $option = $(this);

      if (!$option.is('option') &amp;&amp; !$option.is('optgroup')) {
        return;
      }

      var option = self.item($option);

      var matches = self.matches(params, option);

      if (matches !== null) {
        data.push(matches);
      }
    });

    callback({
      results: data
    });
  };

  SelectAdapter.prototype.addOptions = function ($options) {
    Utils.appendMany(this.$element, $options);
  };

  SelectAdapter.prototype.option = function (data) {
    var option;

    if (data.children) {
      option = document.createElement('optgroup');
      option.label = data.text;
    } else {
      option = document.createElement('option');

      if (option.textContent !== undefined) {
        option.textContent = data.text;
      } else {
        option.innerText = data.text;
      }
    }

    if (data.id !== undefined) {
      option.value = data.id;
    }

    if (data.disabled) {
      option.disabled = true;
    }

    if (data.selected) {
      option.selected = true;
    }

    if (data.title) {
      option.title = data.title;
    }

    var $option = $(option);

    var normalizedData = this._normalizeItem(data);
    normalizedData.element = option;

    // Override the option's data with the combined data
    Utils.StoreData(option, 'data', normalizedData);

    return $option;
  };

  SelectAdapter.prototype.item = function ($option) {
    var data = {};

    data = Utils.GetData($option[0], 'data');

    if (data != null) {
      return data;
    }

    if ($option.is('option')) {
      data = {
        id: $option.val(),
        text: $option.text(),
        disabled: $option.prop('disabled'),
        selected: $option.prop('selected'),
        title: $option.prop('title')
      };
    } else if ($option.is('optgroup')) {
      data = {
        text: $option.prop('label'),
        children: [],
        title: $option.prop('title')
      };

      var $children = $option.children('option');
      var children = [];

      for (var c = 0; c &lt; $children.length; c++) {
        var $child = $($children[c]);

        var child = this.item($child);

        children.push(child);
      }

      data.children = children;
    }

    data = this._normalizeItem(data);
    data.element = $option[0];

    Utils.StoreData($option[0], 'data', data);

    return data;
  };

  SelectAdapter.prototype._normalizeItem = function (item) {
    if (item !== Object(item)) {
      item = {
        id: item,
        text: item
      };
    }

    item = $.extend({}, {
      text: ''
    }, item);

    var defaults = {
      selected: false,
      disabled: false
    };

    if (item.id != null) {
      item.id = item.id.toString();
    }

    if (item.text != null) {
      item.text = item.text.toString();
    }

    if (item._resultId == null &amp;&amp; item.id &amp;&amp; this.container != null) {
      item._resultId = this.generateResultId(this.container, item);
    }

    return $.extend({}, defaults, item);
  };

  SelectAdapter.prototype.matches = function (params, data) {
    var matcher = this.options.get('matcher');

    return matcher(params, data);
  };

  return SelectAdapter;
});

S2.define('select2/data/array',[
  './select',
  '../utils',
  'jquery'
], function (SelectAdapter, Utils, $) {
  function ArrayAdapter ($element, options) {
    this._dataToConvert = options.get('data') || [];

    ArrayAdapter.__super__.constructor.call(this, $element, options);
  }

  Utils.Extend(ArrayAdapter, SelectAdapter);

  ArrayAdapter.prototype.bind = function (container, $container) {
    ArrayAdapter.__super__.bind.call(this, container, $container);

    this.addOptions(this.convertToOptions(this._dataToConvert));
  };

  ArrayAdapter.prototype.select = function (data) {
    var $option = this.$element.find('option').filter(function (i, elm) {
      return elm.value == data.id.toString();
    });

    if ($option.length === 0) {
      $option = this.option(data);

      this.addOptions($option);
    }

    ArrayAdapter.__super__.select.call(this, data);
  };

  ArrayAdapter.prototype.convertToOptions = function (data) {
    var self = this;

    var $existing = this.$element.find('option');
    var existingIds = $existing.map(function () {
      return self.item($(this)).id;
    }).get();

    var $options = [];

    // Filter out all items except for the one passed in the argument
    function onlyItem (item) {
      return function () {
        return $(this).val() == item.id;
      };
    }

    for (var d = 0; d &lt; data.length; d++) {
      var item = this._normalizeItem(data[d]);

      // Skip items which were pre-loaded, only merge the data
      if ($.inArray(item.id, existingIds) &gt;= 0) {
        var $existingOption = $existing.filter(onlyItem(item));

        var existingData = this.item($existingOption);
        var newData = $.extend(true, {}, item, existingData);

        var $newOption = this.option(newData);

        $existingOption.replaceWith($newOption);

        continue;
      }

      var $option = this.option(item);

      if (item.children) {
        var $children = this.convertToOptions(item.children);

        Utils.appendMany($option, $children);
      }

      $options.push($option);
    }

    return $options;
  };

  return ArrayAdapter;
});

S2.define('select2/data/ajax',[
  './array',
  '../utils',
  'jquery'
], function (ArrayAdapter, Utils, $) {
  function AjaxAdapter ($element, options) {
    this.ajaxOptions = this._applyDefaults(options.get('ajax'));

    if (this.ajaxOptions.processResults != null) {
      this.processResults = this.ajaxOptions.processResults;
    }

    AjaxAdapter.__super__.constructor.call(this, $element, options);
  }

  Utils.Extend(AjaxAdapter, ArrayAdapter);

  AjaxAdapter.prototype._applyDefaults = function (options) {
    var defaults = {
      data: function (params) {
        return $.extend({}, params, {
          q: params.term
        });
      },
      transport: function (params, success, failure) {
        var $request = $.ajax(params);

        $request.then(success);
        $request.fail(failure);

        return $request;
      }
    };

    return $.extend({}, defaults, options, true);
  };

  AjaxAdapter.prototype.processResults = function (results) {
    return results;
  };

  AjaxAdapter.prototype.query = function (params, callback) {
    var matches = [];
    var self = this;

    if (this._request != null) {
      // JSONP requests cannot always be aborted
      if ($.isFunction(this._request.abort)) {
        this._request.abort();
      }

      this._request = null;
    }

    var options = $.extend({
      type: 'GET'
    }, this.ajaxOptions);

    if (typeof options.url === 'function') {
      options.url = options.url.call(this.$element, params);
    }

    if (typeof options.data === 'function') {
      options.data = options.data.call(this.$element, params);
    }

    function request () {
      var $request = options.transport(options, function (data) {
        var results = self.processResults(data, params);

        if (self.options.get('debug') &amp;&amp; window.console &amp;&amp; console.error) {
          // Check to make sure that the response included a `results` key.
          if (!results || !results.results || !$.isArray(results.results)) {
            console.error(
              'Select2: The AJAX results did not return an array in the ' +
              '`results` key of the response.'
            );
          }
        }

        callback(results);
      }, function () {
        // Attempt to detect if a request was aborted
        // Only works if the transport exposes a status property
        if ('status' in $request &amp;&amp;
            ($request.status === 0 || $request.status === '0')) {
          return;
        }

        self.trigger('results:message', {
          message: 'errorLoading'
        });
      });

      self._request = $request;
    }

    if (this.ajaxOptions.delay &amp;&amp; params.term != null) {
      if (this._queryTimeout) {
        window.clearTimeout(this._queryTimeout);
      }

      this._queryTimeout = window.setTimeout(request, this.ajaxOptions.delay);
    } else {
      request();
    }
  };

  return AjaxAdapter;
});

S2.define('select2/data/tags',[
  'jquery'
], function ($) {
  function Tags (decorated, $element, options) {
    var tags = options.get('tags');

    var createTag = options.get('createTag');

    if (createTag !== undefined) {
      this.createTag = createTag;
    }

    var insertTag = options.get('insertTag');

    if (insertTag !== undefined) {
        this.insertTag = insertTag;
    }

    decorated.call(this, $element, options);

    if ($.isArray(tags)) {
      for (var t = 0; t &lt; tags.length; t++) {
        var tag = tags[t];
        var item = this._normalizeItem(tag);

        var $option = this.option(item);

        this.$element.append($option);
      }
    }
  }

  Tags.prototype.query = function (decorated, params, callback) {
    var self = this;

    this._removeOldTags();

    if (params.term == null || params.page != null) {
      decorated.call(this, params, callback);
      return;
    }

    function wrapper (obj, child) {
      var data = obj.results;

      for (var i = 0; i &lt; data.length; i++) {
        var option = data[i];

        var checkChildren = (
          option.children != null &amp;&amp;
          !wrapper({
            results: option.children
          }, true)
        );

        var optionText = (option.text || '').toUpperCase();
        var paramsTerm = (params.term || '').toUpperCase();

        var checkText = optionText === paramsTerm;

        if (checkText || checkChildren) {
          if (child) {
            return false;
          }

          obj.data = data;
          callback(obj);

          return;
        }
      }

      if (child) {
        return true;
      }

      var tag = self.createTag(params);

      if (tag != null) {
        var $option = self.option(tag);
        $option.attr('data-select2-tag', true);

        self.addOptions([$option]);

        self.insertTag(data, tag);
      }

      obj.results = data;

      callback(obj);
    }

    decorated.call(this, params, wrapper);
  };

  Tags.prototype.createTag = function (decorated, params) {
    var term = $.trim(params.term);

    if (term === '') {
      return null;
    }

    return {
      id: term,
      text: term
    };
  };

  Tags.prototype.insertTag = function (_, data, tag) {
    data.unshift(tag);
  };

  Tags.prototype._removeOldTags = function (_) {
    var $options = this.$element.find('option[data-select2-tag]');

    $options.each(function () {
      if (this.selected) {
        return;
      }

      $(this).remove();
    });
  };

  return Tags;
});

S2.define('select2/data/tokenizer',[
  'jquery'
], function ($) {
  function Tokenizer (decorated, $element, options) {
    var tokenizer = options.get('tokenizer');

    if (tokenizer !== undefined) {
      this.tokenizer = tokenizer;
    }

    decorated.call(this, $element, options);
  }

  Tokenizer.prototype.bind = function (decorated, container, $container) {
    decorated.call(this, container, $container);

    this.$search =  container.dropdown.$search || container.selection.$search ||
      $container.find('.select2-search__field');
  };

  Tokenizer.prototype.query = function (decorated, params, callback) {
    var self = this;

    function createAndSelect (data) {
      // Normalize the data object so we can use it for checks
      var item = self._normalizeItem(data);

      // Check if the data object already exists as a tag
      // Select it if it doesn't
      var $existingOptions = self.$element.find('option').filter(function () {
        return $(this).val() === item.id;
      });

      // If an existing option wasn't found for it, create the option
      if (!$existingOptions.length) {
        var $option = self.option(item);
        $option.attr('data-select2-tag', true);

        self._removeOldTags();
        self.addOptions([$option]);
      }

      // Select the item, now that we know there is an option for it
      select(item);
    }

    function select (data) {
      self.trigger('select', {
        data: data
      });
    }

    params.term = params.term || '';

    var tokenData = this.tokenizer(params, this.options, createAndSelect);

    if (tokenData.term !== params.term) {
      // Replace the search term if we have the search box
      if (this.$search.length) {
        this.$search.val(tokenData.term);
        this.$search.trigger('focus');
      }

      params.term = tokenData.term;
    }

    decorated.call(this, params, callback);
  };

  Tokenizer.prototype.tokenizer = function (_, params, options, callback) {
    var separators = options.get('tokenSeparators') || [];
    var term = params.term;
    var i = 0;

    var createTag = this.createTag || function (params) {
      return {
        id: params.term,
        text: params.term
      };
    };

    while (i &lt; term.length) {
      var termChar = term[i];

      if ($.inArray(termChar, separators) === -1) {
        i++;

        continue;
      }

      var part = term.substr(0, i);
      var partParams = $.extend({}, params, {
        term: part
      });

      var data = createTag(partParams);

      if (data == null) {
        i++;
        continue;
      }

      callback(data);

      // Reset the term to not include the tokenized portion
      term = term.substr(i + 1) || '';
      i = 0;
    }

    return {
      term: term
    };
  };

  return Tokenizer;
});

S2.define('select2/data/minimumInputLength',[

], function () {
  function MinimumInputLength (decorated, $e, options) {
    this.minimumInputLength = options.get('minimumInputLength');

    decorated.call(this, $e, options);
  }

  MinimumInputLength.prototype.query = function (decorated, params, callback) {
    params.term = params.term || '';

    if (params.term.length &lt; this.minimumInputLength) {
      this.trigger('results:message', {
        message: 'inputTooShort',
        args: {
          minimum: this.minimumInputLength,
          input: params.term,
          params: params
        }
      });

      return;
    }

    decorated.call(this, params, callback);
  };

  return MinimumInputLength;
});

S2.define('select2/data/maximumInputLength',[

], function () {
  function MaximumInputLength (decorated, $e, options) {
    this.maximumInputLength = options.get('maximumInputLength');

    decorated.call(this, $e, options);
  }

  MaximumInputLength.prototype.query = function (decorated, params, callback) {
    params.term = params.term || '';

    if (this.maximumInputLength &gt; 0 &amp;&amp;
        params.term.length &gt; this.maximumInputLength) {
      this.trigger('results:message', {
        message: 'inputTooLong',
        args: {
          maximum: this.maximumInputLength,
          input: params.term,
          params: params
        }
      });

      return;
    }

    decorated.call(this, params, callback);
  };

  return MaximumInputLength;
});

S2.define('select2/data/maximumSelectionLength',[

], function (){
  function MaximumSelectionLength (decorated, $e, options) {
    this.maximumSelectionLength = options.get('maximumSelectionLength');

    decorated.call(this, $e, options);
  }

  MaximumSelectionLength.prototype.bind =
    function (decorated, container, $container) {
      var self = this;

      decorated.call(this, container, $container);

      container.on('select', function () {
        self._checkIfMaximumSelected();
      });
  };

  MaximumSelectionLength.prototype.query =
    function (decorated, params, callback) {
      var self = this;

      this._checkIfMaximumSelected(function () {
        decorated.call(self, params, callback);
      });
  };

  MaximumSelectionLength.prototype._checkIfMaximumSelected =
    function (_, successCallback) {
      var self = this;

      this.current(function (currentData) {
        var count = currentData != null ? currentData.length : 0;
        if (self.maximumSelectionLength &gt; 0 &amp;&amp;
          count &gt;= self.maximumSelectionLength) {
          self.trigger('results:message', {
            message: 'maximumSelected',
            args: {
              maximum: self.maximumSelectionLength
            }
          });
          return;
        }

        if (successCallback) {
          successCallback();
        }
      });
  };

  return MaximumSelectionLength;
});

S2.define('select2/dropdown',[
  'jquery',
  './utils'
], function ($, Utils) {
  function Dropdown ($element, options) {
    this.$element = $element;
    this.options = options;

    Dropdown.__super__.constructor.call(this);
  }

  Utils.Extend(Dropdown, Utils.Observable);

  Dropdown.prototype.render = function () {
    var $dropdown = $(
      '&lt;span class="select2-dropdown"&gt;' +
        '&lt;span class="select2-results"&gt;&lt;/span&gt;' +
      '&lt;/span&gt;'
    );

    $dropdown.attr('dir', this.options.get('dir'));

    this.$dropdown = $dropdown;

    return $dropdown;
  };

  Dropdown.prototype.bind = function () {
    // Should be implemented in subclasses
  };

  Dropdown.prototype.position = function ($dropdown, $container) {
    // Should be implemented in subclasses
  };

  Dropdown.prototype.destroy = function () {
    // Remove the dropdown from the DOM
    this.$dropdown.remove();
  };

  return Dropdown;
});

S2.define('select2/dropdown/search',[
  'jquery',
  '../utils'
], function ($, Utils) {
  function Search () { }

  Search.prototype.render = function (decorated) {
    var $rendered = decorated.call(this);

    var $search = $(
      '&lt;span class="select2-search select2-search--dropdown"&gt;' +
        '&lt;input class="select2-search__field" type="search" tabindex="-1"' +
        ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
        ' spellcheck="false" role="searchbox" aria-autocomplete="list" /&gt;' +
      '&lt;/span&gt;'
    );

    this.$searchContainer = $search;
    this.$search = $search.find('input');

    $rendered.prepend($search);

    return $rendered;
  };

  Search.prototype.bind = function (decorated, container, $container) {
    var self = this;

    var resultsId = container.id + '-results';

    decorated.call(this, container, $container);

    this.$search.on('keydown', function (evt) {
      self.trigger('keypress', evt);

      self._keyUpPrevented = evt.isDefaultPrevented();
    });

    // Workaround for browsers which do not support the `input` event
    // This will prevent double-triggering of events for browsers which support
    // both the `keyup` and `input` events.
    this.$search.on('input', function (evt) {
      // Unbind the duplicated `keyup` event
      $(this).off('keyup');
    });

    this.$search.on('keyup input', function (evt) {
      self.handleSearch(evt);
    });

    container.on('open', function () {
      self.$search.attr('tabindex', 0);
      self.$search.attr('aria-controls', resultsId);

      self.$search.trigger('focus');

      window.setTimeout(function () {
        self.$search.trigger('focus');
      }, 0);
    });

    container.on('close', function () {
      self.$search.attr('tabindex', -1);
      self.$search.removeAttr('aria-controls');
      self.$search.removeAttr('aria-activedescendant');

      self.$search.val('');
      self.$search.trigger('blur');
    });

    container.on('focus', function () {
      if (!container.isOpen()) {
        self.$search.trigger('focus');
      }
    });

    container.on('results:all', function (params) {
      if (params.query.term == null || params.query.term === '') {
        var showSearch = self.showSearch(params);

        if (showSearch) {
          self.$searchContainer.removeClass('select2-search--hide');
        } else {
          self.$searchContainer.addClass('select2-search--hide');
        }
      }
    });

    container.on('results:focus', function (params) {
      if (params.data._resultId) {
        self.$search.attr('aria-activedescendant', params.data._resultId);
      } else {
        self.$search.removeAttr('aria-activedescendant');
      }
    });
  };

  Search.prototype.handleSearch = function (evt) {
    if (!this._keyUpPrevented) {
      var input = this.$search.val();

      this.trigger('query', {
        term: input
      });
    }

    this._keyUpPrevented = false;
  };

  Search.prototype.showSearch = function (_, params) {
    return true;
  };

  return Search;
});

S2.define('select2/dropdown/hidePlaceholder',[

], function () {
  function HidePlaceholder (decorated, $element, options, dataAdapter) {
    this.placeholder = this.normalizePlaceholder(options.get('placeholder'));

    decorated.call(this, $element, options, dataAdapter);
  }

  HidePlaceholder.prototype.append = function (decorated, data) {
    data.results = this.removePlaceholder(data.results);

    decorated.call(this, data);
  };

  HidePlaceholder.prototype.normalizePlaceholder = function (_, placeholder) {
    if (typeof placeholder === 'string') {
      placeholder = {
        id: '',
        text: placeholder
      };
    }

    return placeholder;
  };

  HidePlaceholder.prototype.removePlaceholder = function (_, data) {
    var modifiedData = data.slice(0);

    for (var d = data.length - 1; d &gt;= 0; d--) {
      var item = data[d];

      if (this.placeholder.id === item.id) {
        modifiedData.splice(d, 1);
      }
    }

    return modifiedData;
  };

  return HidePlaceholder;
});

S2.define('select2/dropdown/infiniteScroll',[
  'jquery'
], function ($) {
  function InfiniteScroll (decorated, $element, options, dataAdapter) {
    this.lastParams = {};

    decorated.call(this, $element, options, dataAdapter);

    this.$loadingMore = this.createLoadingMore();
    this.loading = false;
  }

  InfiniteScroll.prototype.append = function (decorated, data) {
    this.$loadingMore.remove();
    this.loading = false;

    decorated.call(this, data);

    if (this.showLoadingMore(data)) {
      this.$results.append(this.$loadingMore);
      this.loadMoreIfNeeded();
    }
  };

  InfiniteScroll.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('query', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    container.on('query:append', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    this.$results.on('scroll', this.loadMoreIfNeeded.bind(this));
  };

  InfiniteScroll.prototype.loadMoreIfNeeded = function () {
    var isLoadMoreVisible = $.contains(
      document.documentElement,
      this.$loadingMore[0]
    );

    if (this.loading || !isLoadMoreVisible) {
      return;
    }

    var currentOffset = this.$results.offset().top +
      this.$results.outerHeight(false);
    var loadingMoreOffset = this.$loadingMore.offset().top +
      this.$loadingMore.outerHeight(false);

    if (currentOffset + 50 &gt;= loadingMoreOffset) {
      this.loadMore();
    }
  };

  InfiniteScroll.prototype.loadMore = function () {
    this.loading = true;

    var params = $.extend({}, {page: 1}, this.lastParams);

    params.page++;

    this.trigger('query:append', params);
  };

  InfiniteScroll.prototype.showLoadingMore = function (_, data) {
    return data.pagination &amp;&amp; data.pagination.more;
  };

  InfiniteScroll.prototype.createLoadingMore = function () {
    var $option = $(
      '&lt;li ' +
      'class="select2-results__option select2-results__option--load-more"' +
      'role="option" aria-disabled="true"&gt;&lt;/li&gt;'
    );

    var message = this.options.get('translations').get('loadingMore');

    $option.html(message(this.lastParams));

    return $option;
  };

  return InfiniteScroll;
});

S2.define('select2/dropdown/attachBody',[
  'jquery',
  '../utils'
], function ($, Utils) {
  function AttachBody (decorated, $element, options) {
    this.$dropdownParent = $(options.get('dropdownParent') || document.body);

    decorated.call(this, $element, options);
  }

  AttachBody.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('open', function () {
      self._showDropdown();
      self._attachPositioningHandler(container);

      // Must bind after the results handlers to ensure correct sizing
      self._bindContainerResultHandlers(container);
    });

    container.on('close', function () {
      self._hideDropdown();
      self._detachPositioningHandler(container);
    });

    this.$dropdownContainer.on('mousedown', function (evt) {
      evt.stopPropagation();
    });
  };

  AttachBody.prototype.destroy = function (decorated) {
    decorated.call(this);

    this.$dropdownContainer.remove();
  };

  AttachBody.prototype.position = function (decorated, $dropdown, $container) {
    // Clone all of the container classes
    $dropdown.attr('class', $container.attr('class'));

    $dropdown.removeClass('select2');
    $dropdown.addClass('select2-container--open');

    $dropdown.css({
      position: 'absolute',
      top: -999999
    });

    this.$container = $container;
  };

  AttachBody.prototype.render = function (decorated) {
    var $container = $('&lt;span&gt;&lt;/span&gt;');

    var $dropdown = decorated.call(this);
    $container.append($dropdown);

    this.$dropdownContainer = $container;

    return $container;
  };

  AttachBody.prototype._hideDropdown = function (decorated) {
    this.$dropdownContainer.detach();
  };

  AttachBody.prototype._bindContainerResultHandlers =
      function (decorated, container) {

    // These should only be bound once
    if (this._containerResultsHandlersBound) {
      return;
    }

    var self = this;

    container.on('results:all', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('results:append', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('results:message', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('select', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('unselect', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    this._containerResultsHandlersBound = true;
  };

  AttachBody.prototype._attachPositioningHandler =
      function (decorated, container) {
    var self = this;

    var scrollEvent = 'scroll.select2.' + container.id;
    var resizeEvent = 'resize.select2.' + container.id;
    var orientationEvent = 'orientationchange.select2.' + container.id;

    var $watchers = this.$container.parents().filter(Utils.hasScroll);
    $watchers.each(function () {
      Utils.StoreData(this, 'select2-scroll-position', {
        x: $(this).scrollLeft(),
        y: $(this).scrollTop()
      });
    });

    $watchers.on(scrollEvent, function (ev) {
      var position = Utils.GetData(this, 'select2-scroll-position');
      $(this).scrollTop(position.y);
    });

    $(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent,
      function (e) {
      self._positionDropdown();
      self._resizeDropdown();
    });
  };

  AttachBody.prototype._detachPositioningHandler =
      function (decorated, container) {
    var scrollEvent = 'scroll.select2.' + container.id;
    var resizeEvent = 'resize.select2.' + container.id;
    var orientationEvent = 'orientationchange.select2.' + container.id;

    var $watchers = this.$container.parents().filter(Utils.hasScroll);
    $watchers.off(scrollEvent);

    $(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent);
  };

  AttachBody.prototype._positionDropdown = function () {
    var $window = $(window);

    var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
    var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');

    var newDirection = null;

    var offset = this.$container.offset();

    offset.bottom = offset.top + this.$container.outerHeight(false);

    var container = {
      height: this.$container.outerHeight(false)
    };

    container.top = offset.top;
    container.bottom = offset.top + container.height;

    var dropdown = {
      height: this.$dropdown.outerHeight(false)
    };

    var viewport = {
      top: $window.scrollTop(),
      bottom: $window.scrollTop() + $window.height()
    };

    var enoughRoomAbove = viewport.top &lt; (offset.top - dropdown.height);
    var enoughRoomBelow = viewport.bottom &gt; (offset.bottom + dropdown.height);

    var css = {
      left: offset.left,
      top: container.bottom
    };

    // Determine what the parent element is to use for calculating the offset
    var $offsetParent = this.$dropdownParent;

    // For statically positioned elements, we need to get the element
    // that is determining the offset
    if ($offsetParent.css('position') === 'static') {
      $offsetParent = $offsetParent.offsetParent();
    }

    var parentOffset = {
      top: 0,
      left: 0
    };

    if (
      $.contains(document.body, $offsetParent[0]) ||
      $offsetParent[0].isConnected
      ) {
      parentOffset = $offsetParent.offset();
    }

    css.top -= parentOffset.top;
    css.left -= parentOffset.left;

    if (!isCurrentlyAbove &amp;&amp; !isCurrentlyBelow) {
      newDirection = 'below';
    }

    if (!enoughRoomBelow &amp;&amp; enoughRoomAbove &amp;&amp; !isCurrentlyAbove) {
      newDirection = 'above';
    } else if (!enoughRoomAbove &amp;&amp; enoughRoomBelow &amp;&amp; isCurrentlyAbove) {
      newDirection = 'below';
    }

    if (newDirection == 'above' ||
      (isCurrentlyAbove &amp;&amp; newDirection !== 'below')) {
      css.top = container.top - parentOffset.top - dropdown.height;
    }

    if (newDirection != null) {
      this.$dropdown
        .removeClass('select2-dropdown--below select2-dropdown--above')
        .addClass('select2-dropdown--' + newDirection);
      this.$container
        .removeClass('select2-container--below select2-container--above')
        .addClass('select2-container--' + newDirection);
    }

    this.$dropdownContainer.css(css);
  };

  AttachBody.prototype._resizeDropdown = function () {
    var css = {
      width: this.$container.outerWidth(false) + 'px'
    };

    if (this.options.get('dropdownAutoWidth')) {
      css.minWidth = css.width;
      css.position = 'relative';
      css.width = 'auto';
    }

    this.$dropdown.css(css);
  };

  AttachBody.prototype._showDropdown = function (decorated) {
    this.$dropdownContainer.appendTo(this.$dropdownParent);

    this._positionDropdown();
    this._resizeDropdown();
  };

  return AttachBody;
});

S2.define('select2/dropdown/minimumResultsForSearch',[

], function () {
  function countResults (data) {
    var count = 0;

    for (var d = 0; d &lt; data.length; d++) {
      var item = data[d];

      if (item.children) {
        count += countResults(item.children);
      } else {
        count++;
      }
    }

    return count;
  }

  function MinimumResultsForSearch (decorated, $element, options, dataAdapter) {
    this.minimumResultsForSearch = options.get('minimumResultsForSearch');

    if (this.minimumResultsForSearch &lt; 0) {
      this.minimumResultsForSearch = Infinity;
    }

    decorated.call(this, $element, options, dataAdapter);
  }

  MinimumResultsForSearch.prototype.showSearch = function (decorated, params) {
    if (countResults(params.data.results) &lt; this.minimumResultsForSearch) {
      return false;
    }

    return decorated.call(this, params);
  };

  return MinimumResultsForSearch;
});

S2.define('select2/dropdown/selectOnClose',[
  '../utils'
], function (Utils) {
  function SelectOnClose () { }

  SelectOnClose.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('close', function (params) {
      self._handleSelectOnClose(params);
    });
  };

  SelectOnClose.prototype._handleSelectOnClose = function (_, params) {
    if (params &amp;&amp; params.originalSelect2Event != null) {
      var event = params.originalSelect2Event;

      // Don't select an item if the close event was triggered from a select or
      // unselect event
      if (event._type === 'select' || event._type === 'unselect') {
        return;
      }
    }

    var $highlightedResults = this.getHighlightedResults();

    // Only select highlighted results
    if ($highlightedResults.length &lt; 1) {
      return;
    }

    var data = Utils.GetData($highlightedResults[0], 'data');

    // Don't re-select already selected resulte
    if (
      (data.element != null &amp;&amp; data.element.selected) ||
      (data.element == null &amp;&amp; data.selected)
    ) {
      return;
    }

    this.trigger('select', {
        data: data
    });
  };

  return SelectOnClose;
});

S2.define('select2/dropdown/closeOnSelect',[

], function () {
  function CloseOnSelect () { }

  CloseOnSelect.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('select', function (evt) {
      self._selectTriggered(evt);
    });

    container.on('unselect', function (evt) {
      self._selectTriggered(evt);
    });
  };

  CloseOnSelect.prototype._selectTriggered = function (_, evt) {
    var originalEvent = evt.originalEvent;

    // Don't close if the control key is being held
    if (originalEvent &amp;&amp; (originalEvent.ctrlKey || originalEvent.metaKey)) {
      return;
    }

    this.trigger('close', {
      originalEvent: originalEvent,
      originalSelect2Event: evt
    });
  };

  return CloseOnSelect;
});

S2.define('select2/i18n/en',[],function () {
  // English
  return {
    errorLoading: function () {
      return 'The results could not be loaded.';
    },
    inputTooLong: function (args) {
      var overChars = args.input.length - args.maximum;

      var message = 'Please delete ' + overChars + ' character';

      if (overChars != 1) {
        message += 's';
      }

      return message;
    },
    inputTooShort: function (args) {
      var remainingChars = args.minimum - args.input.length;

      var message = 'Please enter ' + remainingChars + ' or more characters';

      return message;
    },
    loadingMore: function () {
      return 'Loading more resultsâ€¦';
    },
    maximumSelected: function (args) {
      var message = 'You can only select ' + args.maximum + ' item';

      if (args.maximum != 1) {
        message += 's';
      }

      return message;
    },
    noResults: function () {
      return 'No results found';
    },
    searching: function () {
      return 'Searchingâ€¦';
    },
    removeAllItems: function () {
      return 'Remove all items';
    }
  };
});

S2.define('select2/defaults',[
  'jquery',
  'require',

  './results',

  './selection/single',
  './selection/multiple',
  './selection/placeholder',
  './selection/allowClear',
  './selection/search',
  './selection/eventRelay',

  './utils',
  './translation',
  './diacritics',

  './data/select',
  './data/array',
  './data/ajax',
  './data/tags',
  './data/tokenizer',
  './data/minimumInputLength',
  './data/maximumInputLength',
  './data/maximumSelectionLength',

  './dropdown',
  './dropdown/search',
  './dropdown/hidePlaceholder',
  './dropdown/infiniteScroll',
  './dropdown/attachBody',
  './dropdown/minimumResultsForSearch',
  './dropdown/selectOnClose',
  './dropdown/closeOnSelect',

  './i18n/en'
], function ($, require,

             ResultsList,

             SingleSelection, MultipleSelection, Placeholder, AllowClear,
             SelectionSearch, EventRelay,

             Utils, Translation, DIACRITICS,

             SelectData, ArrayData, AjaxData, Tags, Tokenizer,
             MinimumInputLength, MaximumInputLength, MaximumSelectionLength,

             Dropdown, DropdownSearch, HidePlaceholder, InfiniteScroll,
             AttachBody, MinimumResultsForSearch, SelectOnClose, CloseOnSelect,

             EnglishTranslation) {
  function Defaults () {
    this.reset();
  }

  Defaults.prototype.apply = function (options) {
    options = $.extend(true, {}, this.defaults, options);

    if (options.dataAdapter == null) {
      if (options.ajax != null) {
        options.dataAdapter = AjaxData;
      } else if (options.data != null) {
        options.dataAdapter = ArrayData;
      } else {
        options.dataAdapter = SelectData;
      }

      if (options.minimumInputLength &gt; 0) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          MinimumInputLength
        );
      }

      if (options.maximumInputLength &gt; 0) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          MaximumInputLength
        );
      }

      if (options.maximumSelectionLength &gt; 0) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          MaximumSelectionLength
        );
      }

      if (options.tags) {
        options.dataAdapter = Utils.Decorate(options.dataAdapter, Tags);
      }

      if (options.tokenSeparators != null || options.tokenizer != null) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          Tokenizer
        );
      }

      if (options.query != null) {
        var Query = require(options.amdBase + 'compat/query');

        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          Query
        );
      }

      if (options.initSelection != null) {
        var InitSelection = require(options.amdBase + 'compat/initSelection');

        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          InitSelection
        );
      }
    }

    if (options.resultsAdapter == null) {
      options.resultsAdapter = ResultsList;

      if (options.ajax != null) {
        options.resultsAdapter = Utils.Decorate(
          options.resultsAdapter,
          InfiniteScroll
        );
      }

      if (options.placeholder != null) {
        options.resultsAdapter = Utils.Decorate(
          options.resultsAdapter,
          HidePlaceholder
        );
      }

      if (options.selectOnClose) {
        options.resultsAdapter = Utils.Decorate(
          options.resultsAdapter,
          SelectOnClose
        );
      }
    }

    if (options.dropdownAdapter == null) {
      if (options.multiple) {
        options.dropdownAdapter = Dropdown;
      } else {
        var SearchableDropdown = Utils.Decorate(Dropdown, DropdownSearch);

        options.dropdownAdapter = SearchableDropdown;
      }

      if (options.minimumResultsForSearch !== 0) {
        options.dropdownAdapter = Utils.Decorate(
          options.dropdownAdapter,
          MinimumResultsForSearch
        );
      }

      if (options.closeOnSelect) {
        options.dropdownAdapter = Utils.Decorate(
          options.dropdownAdapter,
          CloseOnSelect
        );
      }

      if (
        options.dropdownCssClass != null ||
        options.dropdownCss != null ||
        options.adaptDropdownCssClass != null
      ) {
        var DropdownCSS = require(options.amdBase + 'compat/dropdownCss');

        options.dropdownAdapter = Utils.Decorate(
          options.dropdownAdapter,
          DropdownCSS
        );
      }

      options.dropdownAdapter = Utils.Decorate(
        options.dropdownAdapter,
        AttachBody
      );
    }

    if (options.selectionAdapter == null) {
      if (options.multiple) {
        options.selectionAdapter = MultipleSelection;
      } else {
        options.selectionAdapter = SingleSelection;
      }

      // Add the placeholder mixin if a placeholder was specified
      if (options.placeholder != null) {
        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          Placeholder
        );
      }

      if (options.allowClear) {
        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          AllowClear
        );
      }

      if (options.multiple) {
        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          SelectionSearch
        );
      }

      if (
        options.containerCssClass != null ||
        options.containerCss != null ||
        options.adaptContainerCssClass != null
      ) {
        var ContainerCSS = require(options.amdBase + 'compat/containerCss');

        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          ContainerCSS
        );
      }

      options.selectionAdapter = Utils.Decorate(
        options.selectionAdapter,
        EventRelay
      );
    }

    // If the defaults were not previously applied from an element, it is
    // possible for the language option to have not been resolved
    options.language = this._resolveLanguage(options.language);

    // Always fall back to English since it will always be complete
    options.language.push('en');

    var uniqueLanguages = [];

    for (var l = 0; l &lt; options.language.length; l++) {
      var language = options.language[l];

      if (uniqueLanguages.indexOf(language) === -1) {
        uniqueLanguages.push(language);
      }
    }

    options.language = uniqueLanguages;

    options.translations = this._processTranslations(
      options.language,
      options.debug
    );

    return options;
  };

  Defaults.prototype.reset = function () {
    function stripDiacritics (text) {
      // Used 'uni range + named function' from http://jsperf.com/diacritics/18
      function match(a) {
        return DIACRITICS[a] || a;
      }

      return text.replace(/[^\u0000-\u007E]/g, match);
    }

    function matcher (params, data) {
      // Always return the object if there is nothing to compare
      if ($.trim(params.term) === '') {
        return data;
      }

      // Do a recursive check for options with children
      if (data.children &amp;&amp; data.children.length &gt; 0) {
        // Clone the data object if there are children
        // This is required as we modify the object to remove any non-matches
        var match = $.extend(true, {}, data);

        // Check each child of the option
        for (var c = data.children.length - 1; c &gt;= 0; c--) {
          var child = data.children[c];

          var matches = matcher(params, child);

          // If there wasn't a match, remove the object in the array
          if (matches == null) {
            match.children.splice(c, 1);
          }
        }

        // If any children matched, return the new object
        if (match.children.length &gt; 0) {
          return match;
        }

        // If there were no matching children, check just the plain object
        return matcher(params, match);
      }

      var original = stripDiacritics(data.text).toUpperCase();
      var term = stripDiacritics(params.term).toUpperCase();

      // Check if the text contains the term
      if (original.indexOf(term) &gt; -1) {
        return data;
      }

      // If it doesn't contain the term, don't return anything
      return null;
    }

    this.defaults = {
      amdBase: './',
      amdLanguageBase: './i18n/',
      closeOnSelect: true,
      debug: false,
      dropdownAutoWidth: false,
      escapeMarkup: Utils.escapeMarkup,
      language: {},
      matcher: matcher,
      minimumInputLength: 0,
      maximumInputLength: 0,
      maximumSelectionLength: 0,
      minimumResultsForSearch: 0,
      selectOnClose: false,
      scrollAfterSelect: false,
      sorter: function (data) {
        return data;
      },
      templateResult: function (result) {
        return result.text;
      },
      templateSelection: function (selection) {
        return selection.text;
      },
      theme: 'default',
      width: 'resolve'
    };
  };

  Defaults.prototype.applyFromElement = function (options, $element) {
    var optionLanguage = options.language;
    var defaultLanguage = this.defaults.language;
    var elementLanguage = $element.prop('lang');
    var parentLanguage = $element.closest('[lang]').prop('lang');

    var languages = Array.prototype.concat.call(
      this._resolveLanguage(elementLanguage),
      this._resolveLanguage(optionLanguage),
      this._resolveLanguage(defaultLanguage),
      this._resolveLanguage(parentLanguage)
    );

    options.language = languages;

    return options;
  };

  Defaults.prototype._resolveLanguage = function (language) {
    if (!language) {
      return [];
    }

    if ($.isEmptyObject(language)) {
      return [];
    }

    if ($.isPlainObject(language)) {
      return [language];
    }

    var languages;

    if (!$.isArray(language)) {
      languages = [language];
    } else {
      languages = language;
    }

    var resolvedLanguages = [];

    for (var l = 0; l &lt; languages.length; l++) {
      resolvedLanguages.push(languages[l]);

      if (typeof languages[l] === 'string' &amp;&amp; languages[l].indexOf('-') &gt; 0) {
        // Extract the region information if it is included
        var languageParts = languages[l].split('-');
        var baseLanguage = languageParts[0];

        resolvedLanguages.push(baseLanguage);
      }
    }

    return resolvedLanguages;
  };

  Defaults.prototype._processTranslations = function (languages, debug) {
    var translations = new Translation();

    for (var l = 0; l &lt; languages.length; l++) {
      var languageData = new Translation();

      var language = languages[l];

      if (typeof language === 'string') {
        try {
          // Try to load it with the original name
          languageData = Translation.loadPath(language);
        } catch (e) {
          try {
            // If we couldn't load it, check if it wasn't the full path
            language = this.defaults.amdLanguageBase + language;
            languageData = Translation.loadPath(language);
          } catch (ex) {
            // The translation could not be loaded at all. Sometimes this is
            // because of a configuration problem, other times this can be
            // because of how Select2 helps load all possible translation files
            if (debug &amp;&amp; window.console &amp;&amp; console.warn) {
              console.warn(
                'Select2: The language file for "' + language + '" could ' +
                'not be automatically loaded. A fallback will be used instead.'
              );
            }
          }
        }
      } else if ($.isPlainObject(language)) {
        languageData = new Translation(language);
      } else {
        languageData = language;
      }

      translations.extend(languageData);
    }

    return translations;
  };

  Defaults.prototype.set = function (key, value) {
    var camelKey = $.camelCase(key);

    var data = {};
    data[camelKey] = value;

    var convertedData = Utils._convertData(data);

    $.extend(true, this.defaults, convertedData);
  };

  var defaults = new Defaults();

  return defaults;
});

S2.define('select2/options',[
  'require',
  'jquery',
  './defaults',
  './utils'
], function (require, $, Defaults, Utils) {
  function Options (options, $element) {
    this.options = options;

    if ($element != null) {
      this.fromElement($element);
    }

    if ($element != null) {
      this.options = Defaults.applyFromElement(this.options, $element);
    }

    this.options = Defaults.apply(this.options);

    if ($element &amp;&amp; $element.is('input')) {
      var InputCompat = require(this.get('amdBase') + 'compat/inputData');

      this.options.dataAdapter = Utils.Decorate(
        this.options.dataAdapter,
        InputCompat
      );
    }
  }

  Options.prototype.fromElement = function ($e) {
    var excludedData = ['select2'];

    if (this.options.multiple == null) {
      this.options.multiple = $e.prop('multiple');
    }

    if (this.options.disabled == null) {
      this.options.disabled = $e.prop('disabled');
    }

    if (this.options.dir == null) {
      if ($e.prop('dir')) {
        this.options.dir = $e.prop('dir');
      } else if ($e.closest('[dir]').prop('dir')) {
        this.options.dir = $e.closest('[dir]').prop('dir');
      } else {
        this.options.dir = 'ltr';
      }
    }

    $e.prop('disabled', this.options.disabled);
    $e.prop('multiple', this.options.multiple);

    if (Utils.GetData($e[0], 'select2Tags')) {
      if (this.options.debug &amp;&amp; window.console &amp;&amp; console.warn) {
        console.warn(
          'Select2: The `data-select2-tags` attribute has been changed to ' +
          'use the `data-data` and `data-tags="true"` attributes and will be ' +
          'removed in future versions of Select2.'
        );
      }

      Utils.StoreData($e[0], 'data', Utils.GetData($e[0], 'select2Tags'));
      Utils.StoreData($e[0], 'tags', true);
    }

    if (Utils.GetData($e[0], 'ajaxUrl')) {
      if (this.options.debug &amp;&amp; window.console &amp;&amp; console.warn) {
        console.warn(
          'Select2: The `data-ajax-url` attribute has been changed to ' +
          '`data-ajax--url` and support for the old attribute will be removed' +
          ' in future versions of Select2.'
        );
      }

      $e.attr('ajax--url', Utils.GetData($e[0], 'ajaxUrl'));
      Utils.StoreData($e[0], 'ajax-Url', Utils.GetData($e[0], 'ajaxUrl'));
    }

    var dataset = {};

    function upperCaseLetter(_, letter) {
      return letter.toUpperCase();
    }

    // Pre-load all of the attributes which are prefixed with `data-`
    for (var attr = 0; attr &lt; $e[0].attributes.length; attr++) {
      var attributeName = $e[0].attributes[attr].name;
      var prefix = 'data-';

      if (attributeName.substr(0, prefix.length) == prefix) {
        // Get the contents of the attribute after `data-`
        var dataName = attributeName.substring(prefix.length);

        // Get the data contents from the consistent source
        // This is more than likely the jQuery data helper
        var dataValue = Utils.GetData($e[0], dataName);

        // camelCase the attribute name to match the spec
        var camelDataName = dataName.replace(/-([a-z])/g, upperCaseLetter);

        // Store the data attribute contents into the dataset since
        dataset[camelDataName] = dataValue;
      }
    }

    // Prefer the element's `dataset` attribute if it exists
    // jQuery 1.x does not correctly handle data attributes with multiple dashes
    if ($.fn.jquery &amp;&amp; $.fn.jquery.substr(0, 2) == '1.' &amp;&amp; $e[0].dataset) {
      dataset = $.extend(true, {}, $e[0].dataset, dataset);
    }

    // Prefer our internal data cache if it exists
    var data = $.extend(true, {}, Utils.GetData($e[0]), dataset);

    data = Utils._convertData(data);

    for (var key in data) {
      if ($.inArray(key, excludedData) &gt; -1) {
        continue;
      }

      if ($.isPlainObject(this.options[key])) {
        $.extend(this.options[key], data[key]);
      } else {
        this.options[key] = data[key];
      }
    }

    return this;
  };

  Options.prototype.get = function (key) {
    return this.options[key];
  };

  Options.prototype.set = function (key, val) {
    this.options[key] = val;
  };

  return Options;
});

S2.define('select2/core',[
  'jquery',
  './options',
  './utils',
  './keys'
], function ($, Options, Utils, KEYS) {
  var Select2 = function ($element, options) {
    if (Utils.GetData($element[0], 'select2') != null) {
      Utils.GetData($element[0], 'select2').destroy();
    }

    this.$element = $element;

    this.id = this._generateId($element);

    options = options || {};

    this.options = new Options(options, $element);

    Select2.__super__.constructor.call(this);

    // Set up the tabindex

    var tabindex = $element.attr('tabindex') || 0;
    Utils.StoreData($element[0], 'old-tabindex', tabindex);
    $element.attr('tabindex', '-1');

    // Set up containers and adapters

    var DataAdapter = this.options.get('dataAdapter');
    this.dataAdapter = new DataAdapter($element, this.options);

    var $container = this.render();

    this._placeContainer($container);

    var SelectionAdapter = this.options.get('selectionAdapter');
    this.selection = new SelectionAdapter($element, this.options);
    this.$selection = this.selection.render();

    this.selection.position(this.$selection, $container);

    var DropdownAdapter = this.options.get('dropdownAdapter');
    this.dropdown = new DropdownAdapter($element, this.options);
    this.$dropdown = this.dropdown.render();

    this.dropdown.position(this.$dropdown, $container);

    var ResultsAdapter = this.options.get('resultsAdapter');
    this.results = new ResultsAdapter($element, this.options, this.dataAdapter);
    this.$results = this.results.render();

    this.results.position(this.$results, this.$dropdown);

    // Bind events

    var self = this;

    // Bind the container to all of the adapters
    this._bindAdapters();

    // Register any DOM event handlers
    this._registerDomEvents();

    // Register any internal event handlers
    this._registerDataEvents();
    this._registerSelectionEvents();
    this._registerDropdownEvents();
    this._registerResultsEvents();
    this._registerEvents();

    // Set the initial state
    this.dataAdapter.current(function (initialData) {
      self.trigger('selection:update', {
        data: initialData
      });
    });

    // Hide the original select
    $element.addClass('select2-hidden-accessible');
    $element.attr('aria-hidden', 'true');

    // Synchronize any monitored attributes
    this._syncAttributes();

    Utils.StoreData($element[0], 'select2', this);

    // Ensure backwards compatibility with $element.data('select2').
    $element.data('select2', this);
  };

  Utils.Extend(Select2, Utils.Observable);

  Select2.prototype._generateId = function ($element) {
    var id = '';

    if ($element.attr('id') != null) {
      id = $element.attr('id');
    } else if ($element.attr('name') != null) {
      id = $element.attr('name') + '-' + Utils.generateChars(2);
    } else {
      id = Utils.generateChars(4);
    }

    id = id.replace(/(:|\.|\[|\]|,)/g, '');
    id = 'select2-' + id;

    return id;
  };

  Select2.prototype._placeContainer = function ($container) {
    $container.insertAfter(this.$element);

    var width = this._resolveWidth(this.$element, this.options.get('width'));

    if (width != null) {
      $container.css('width', width);
    }
  };

  Select2.prototype._resolveWidth = function ($element, method) {
    var WIDTH = /^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;

    if (method == 'resolve') {
      var styleWidth = this._resolveWidth($element, 'style');

      if (styleWidth != null) {
        return styleWidth;
      }

      return this._resolveWidth($element, 'element');
    }

    if (method == 'element') {
      var elementWidth = $element.outerWidth(false);

      if (elementWidth &lt;= 0) {
        return 'auto';
      }

      return elementWidth + 'px';
    }

    if (method == 'style') {
      var style = $element.attr('style');

      if (typeof(style) !== 'string') {
        return null;
      }

      var attrs = style.split(';');

      for (var i = 0, l = attrs.length; i &lt; l; i = i + 1) {
        var attr = attrs[i].replace(/\s/g, '');
        var matches = attr.match(WIDTH);

        if (matches !== null &amp;&amp; matches.length &gt;= 1) {
          return matches[1];
        }
      }

      return null;
    }

    if (method == 'computedstyle') {
      var computedStyle = window.getComputedStyle($element[0]);

      return computedStyle.width;
    }

    return method;
  };

  Select2.prototype._bindAdapters = function () {
    this.dataAdapter.bind(this, this.$container);
    this.selection.bind(this, this.$container);

    this.dropdown.bind(this, this.$container);
    this.results.bind(this, this.$container);
  };

  Select2.prototype._registerDomEvents = function () {
    var self = this;

    this.$element.on('change.select2', function () {
      self.dataAdapter.current(function (data) {
        self.trigger('selection:update', {
          data: data
        });
      });
    });

    this.$element.on('focus.select2', function (evt) {
      self.trigger('focus', evt);
    });

    this._syncA = Utils.bind(this._syncAttributes, this);
    this._syncS = Utils.bind(this._syncSubtree, this);

    if (this.$element[0].attachEvent) {
      this.$element[0].attachEvent('onpropertychange', this._syncA);
    }

    var observer = window.MutationObserver ||
      window.WebKitMutationObserver ||
      window.MozMutationObserver
    ;

    if (observer != null) {
      this._observer = new observer(function (mutations) {
        self._syncA();
        self._syncS(null, mutations);
      });
      this._observer.observe(this.$element[0], {
        attributes: true,
        childList: true,
        subtree: false
      });
    } else if (this.$element[0].addEventListener) {
      this.$element[0].addEventListener(
        'DOMAttrModified',
        self._syncA,
        false
      );
      this.$element[0].addEventListener(
        'DOMNodeInserted',
        self._syncS,
        false
      );
      this.$element[0].addEventListener(
        'DOMNodeRemoved',
        self._syncS,
        false
      );
    }
  };

  Select2.prototype._registerDataEvents = function () {
    var self = this;

    this.dataAdapter.on('*', function (name, params) {
      self.trigger(name, params);
    });
  };

  Select2.prototype._registerSelectionEvents = function () {
    var self = this;
    var nonRelayEvents = ['toggle', 'focus'];

    this.selection.on('toggle', function () {
      self.toggleDropdown();
    });

    this.selection.on('focus', function (params) {
      self.focus(params);
    });

    this.selection.on('*', function (name, params) {
      if ($.inArray(name, nonRelayEvents) !== -1) {
        return;
      }

      self.trigger(name, params);
    });
  };

  Select2.prototype._registerDropdownEvents = function () {
    var self = this;

    this.dropdown.on('*', function (name, params) {
      self.trigger(name, params);
    });
  };

  Select2.prototype._registerResultsEvents = function () {
    var self = this;

    this.results.on('*', function (name, params) {
      self.trigger(name, params);
    });
  };

  Select2.prototype._registerEvents = function () {
    var self = this;

    this.on('open', function () {
      self.$container.addClass('select2-container--open');
    });

    this.on('close', function () {
      self.$container.removeClass('select2-container--open');
    });

    this.on('enable', function () {
      self.$container.removeClass('select2-container--disabled');
    });

    this.on('disable', function () {
      self.$container.addClass('select2-container--disabled');
    });

    this.on('blur', function () {
      self.$container.removeClass('select2-container--focus');
    });

    this.on('query', function (params) {
      if (!self.isOpen()) {
        self.trigger('open', {});
      }

      this.dataAdapter.query(params, function (data) {
        self.trigger('results:all', {
          data: data,
          query: params
        });
      });
    });

    this.on('query:append', function (params) {
      this.dataAdapter.query(params, function (data) {
        self.trigger('results:append', {
          data: data,
          query: params
        });
      });
    });

    this.on('keypress', function (evt) {
      var key = evt.which;

      if (self.isOpen()) {
        if (key === KEYS.ESC || key === KEYS.TAB ||
            (key === KEYS.UP &amp;&amp; evt.altKey)) {
          self.close(evt);

          evt.preventDefault();
        } else if (key === KEYS.ENTER) {
          self.trigger('results:select', {});

          evt.preventDefault();
        } else if ((key === KEYS.SPACE &amp;&amp; evt.ctrlKey)) {
          self.trigger('results:toggle', {});

          evt.preventDefault();
        } else if (key === KEYS.UP) {
          self.trigger('results:previous', {});

          evt.preventDefault();
        } else if (key === KEYS.DOWN) {
          self.trigger('results:next', {});

          evt.preventDefault();
        }
      } else {
        if (key === KEYS.ENTER || key === KEYS.SPACE ||
            (key === KEYS.DOWN &amp;&amp; evt.altKey)) {
          self.open();

          evt.preventDefault();
        }
      }
    });
  };

  Select2.prototype._syncAttributes = function () {
    this.options.set('disabled', this.$element.prop('disabled'));

    if (this.isDisabled()) {
      if (this.isOpen()) {
        this.close();
      }

      this.trigger('disable', {});
    } else {
      this.trigger('enable', {});
    }
  };

  Select2.prototype._isChangeMutation = function (evt, mutations) {
    var changed = false;
    var self = this;

    // Ignore any mutation events raised for elements that aren't options or
    // optgroups. This handles the case when the select element is destroyed
    if (
      evt &amp;&amp; evt.target &amp;&amp; (
        evt.target.nodeName !== 'OPTION' &amp;&amp; evt.target.nodeName !== 'OPTGROUP'
      )
    ) {
      return;
    }

    if (!mutations) {
      // If mutation events aren't supported, then we can only assume that the
      // change affected the selections
      changed = true;
    } else if (mutations.addedNodes &amp;&amp; mutations.addedNodes.length &gt; 0) {
      for (var n = 0; n &lt; mutations.addedNodes.length; n++) {
        var node = mutations.addedNodes[n];

        if (node.selected) {
          changed = true;
        }
      }
    } else if (mutations.removedNodes &amp;&amp; mutations.removedNodes.length &gt; 0) {
      changed = true;
    } else if ($.isArray(mutations)) {
      $.each(mutations, function(evt, mutation) {
        if (self._isChangeMutation(evt, mutation)) {
          // We've found a change mutation.
          // Let's escape from the loop and continue
          changed = true;
          return false;
        }
      });
    }
    return changed;
  };

  Select2.prototype._syncSubtree = function (evt, mutations) {
    var changed = this._isChangeMutation(evt, mutations);
    var self = this;

    // Only re-pull the data if we think there is a change
    if (changed) {
      this.dataAdapter.current(function (currentData) {
        self.trigger('selection:update', {
          data: currentData
        });
      });
    }
  };

  /**
   * Override the trigger method to automatically trigger pre-events when
   * there are events that can be prevented.
   */
  Select2.prototype.trigger = function (name, args) {
    var actualTrigger = Select2.__super__.trigger;
    var preTriggerMap = {
      'open': 'opening',
      'close': 'closing',
      'select': 'selecting',
      'unselect': 'unselecting',
      'clear': 'clearing'
    };

    if (args === undefined) {
      args = {};
    }

    if (name in preTriggerMap) {
      var preTriggerName = preTriggerMap[name];
      var preTriggerArgs = {
        prevented: false,
        name: name,
        args: args
      };

      actualTrigger.call(this, preTriggerName, preTriggerArgs);

      if (preTriggerArgs.prevented) {
        args.prevented = true;

        return;
      }
    }

    actualTrigger.call(this, name, args);
  };

  Select2.prototype.toggleDropdown = function () {
    if (this.isDisabled()) {
      return;
    }

    if (this.isOpen()) {
      this.close();
    } else {
      this.open();
    }
  };

  Select2.prototype.open = function () {
    if (this.isOpen()) {
      return;
    }

    if (this.isDisabled()) {
      return;
    }

    this.trigger('query', {});
  };

  Select2.prototype.close = function (evt) {
    if (!this.isOpen()) {
      return;
    }

    this.trigger('close', { originalEvent : evt });
  };

  /**
   * Helper method to abstract the "enabled" (not "disabled") state of this
   * object.
   *
   * @return {true} if the instance is not disabled.
   * @return {false} if the instance is disabled.
   */
  Select2.prototype.isEnabled = function () {
    return !this.isDisabled();
  };

  /**
   * Helper method to abstract the "disabled" state of this object.
   *
   * @return {true} if the disabled option is true.
   * @return {false} if the disabled option is false.
   */
  Select2.prototype.isDisabled = function () {
    return this.options.get('disabled');
  };

  Select2.prototype.isOpen = function () {
    return this.$container.hasClass('select2-container--open');
  };

  Select2.prototype.hasFocus = function () {
    return this.$container.hasClass('select2-container--focus');
  };

  Select2.prototype.focus = function (data) {
    // No need to re-trigger focus events if we are already focused
    if (this.hasFocus()) {
      return;
    }

    this.$container.addClass('select2-container--focus');
    this.trigger('focus', {});
  };

  Select2.prototype.enable = function (args) {
    if (this.options.get('debug') &amp;&amp; window.console &amp;&amp; console.warn) {
      console.warn(
        'Select2: The `select2("enable")` method has been deprecated and will' +
        ' be removed in later Select2 versions. Use $element.prop("disabled")' +
        ' instead.'
      );
    }

    if (args == null || args.length === 0) {
      args = [true];
    }

    var disabled = !args[0];

    this.$element.prop('disabled', disabled);
  };

  Select2.prototype.data = function () {
    if (this.options.get('debug') &amp;&amp;
        arguments.length &gt; 0 &amp;&amp; window.console &amp;&amp; console.warn) {
      console.warn(
        'Select2: Data can no longer be set using `select2("data")`. You ' +
        'should consider setting the value instead using `$element.val()`.'
      );
    }

    var data = [];

    this.dataAdapter.current(function (currentData) {
      data = currentData;
    });

    return data;
  };

  Select2.prototype.val = function (args) {
    if (this.options.get('debug') &amp;&amp; window.console &amp;&amp; console.warn) {
      console.warn(
        'Select2: The `select2("val")` method has been deprecated and will be' +
        ' removed in later Select2 versions. Use $element.val() instead.'
      );
    }

    if (args == null || args.length === 0) {
      return this.$element.val();
    }

    var newVal = args[0];

    if ($.isArray(newVal)) {
      newVal = $.map(newVal, function (obj) {
        return obj.toString();
      });
    }

    this.$element.val(newVal).trigger('input').trigger('change');
  };

  Select2.prototype.destroy = function () {
    this.$container.remove();

    if (this.$element[0].detachEvent) {
      this.$element[0].detachEvent('onpropertychange', this._syncA);
    }

    if (this._observer != null) {
      this._observer.disconnect();
      this._observer = null;
    } else if (this.$element[0].removeEventListener) {
      this.$element[0]
        .removeEventListener('DOMAttrModified', this._syncA, false);
      this.$element[0]
        .removeEventListener('DOMNodeInserted', this._syncS, false);
      this.$element[0]
        .removeEventListener('DOMNodeRemoved', this._syncS, false);
    }

    this._syncA = null;
    this._syncS = null;

    this.$element.off('.select2');
    this.$element.attr('tabindex',
    Utils.GetData(this.$element[0], 'old-tabindex'));

    this.$element.removeClass('select2-hidden-accessible');
    this.$element.attr('aria-hidden', 'false');
    Utils.RemoveData(this.$element[0]);
    this.$element.removeData('select2');

    this.dataAdapter.destroy();
    this.selection.destroy();
    this.dropdown.destroy();
    this.results.destroy();

    this.dataAdapter = null;
    this.selection = null;
    this.dropdown = null;
    this.results = null;
  };

  Select2.prototype.render = function () {
    var $container = $(
      '&lt;span class="select2 select2-container"&gt;' +
        '&lt;span class="selection"&gt;&lt;/span&gt;' +
        '&lt;span class="dropdown-wrapper" aria-hidden="true"&gt;&lt;/span&gt;' +
      '&lt;/span&gt;'
    );

    $container.attr('dir', this.options.get('dir'));

    this.$container = $container;

    this.$container.addClass('select2-container--' + this.options.get('theme'));

    Utils.StoreData($container[0], 'element', this.$element);

    return $container;
  };

  return Select2;
});

S2.define('select2/compat/utils',[
  'jquery'
], function ($) {
  function syncCssClasses ($dest, $src, adapter) {
    var classes, replacements = [], adapted;

    classes = $.trim($dest.attr('class'));

    if (classes) {
      classes = '' + classes; // for IE which returns object

      $(classes.split(/\s+/)).each(function () {
        // Save all Select2 classes
        if (this.indexOf('select2-') === 0) {
          replacements.push(this);
        }
      });
    }

    classes = $.trim($src.attr('class'));

    if (classes) {
      classes = '' + classes; // for IE which returns object

      $(classes.split(/\s+/)).each(function () {
        // Only adapt non-Select2 classes
        if (this.indexOf('select2-') !== 0) {
          adapted = adapter(this);

          if (adapted != null) {
            replacements.push(adapted);
          }
        }
      });
    }

    $dest.attr('class', replacements.join(' '));
  }

  return {
    syncCssClasses: syncCssClasses
  };
});

S2.define('select2/compat/containerCss',[
  'jquery',
  './utils'
], function ($, CompatUtils) {
  // No-op CSS adapter that discards all classes by default
  function _containerAdapter (clazz) {
    return null;
  }

  function ContainerCSS () { }

  ContainerCSS.prototype.render = function (decorated) {
    var $container = decorated.call(this);

    var containerCssClass = this.options.get('containerCssClass') || '';

    if ($.isFunction(containerCssClass)) {
      containerCssClass = containerCssClass(this.$element);
    }

    var containerCssAdapter = this.options.get('adaptContainerCssClass');
    containerCssAdapter = containerCssAdapter || _containerAdapter;

    if (containerCssClass.indexOf(':all:') !== -1) {
      containerCssClass = containerCssClass.replace(':all:', '');

      var _cssAdapter = containerCssAdapter;

      containerCssAdapter = function (clazz) {
        var adapted = _cssAdapter(clazz);

        if (adapted != null) {
          // Append the old one along with the adapted one
          return adapted + ' ' + clazz;
        }

        return clazz;
      };
    }

    var containerCss = this.options.get('containerCss') || {};

    if ($.isFunction(containerCss)) {
      containerCss = containerCss(this.$element);
    }

    CompatUtils.syncCssClasses($container, this.$element, containerCssAdapter);

    $container.css(containerCss);
    $container.addClass(containerCssClass);

    return $container;
  };

  return ContainerCSS;
});

S2.define('select2/compat/dropdownCss',[
  'jquery',
  './utils'
], function ($, CompatUtils) {
  // No-op CSS adapter that discards all classes by default
  function _dropdownAdapter (clazz) {
    return null;
  }

  function DropdownCSS () { }

  DropdownCSS.prototype.render = function (decorated) {
    var $dropdown = decorated.call(this);

    var dropdownCssClass = this.options.get('dropdownCssClass') || '';

    if ($.isFunction(dropdownCssClass)) {
      dropdownCssClass = dropdownCssClass(this.$element);
    }

    var dropdownCssAdapter = this.options.get('adaptDropdownCssClass');
    dropdownCssAdapter = dropdownCssAdapter || _dropdownAdapter;

    if (dropdownCssClass.indexOf(':all:') !== -1) {
      dropdownCssClass = dropdownCssClass.replace(':all:', '');

      var _cssAdapter = dropdownCssAdapter;

      dropdownCssAdapter = function (clazz) {
        var adapted = _cssAdapter(clazz);

        if (adapted != null) {
          // Append the old one along with the adapted one
          return adapted + ' ' + clazz;
        }

        return clazz;
      };
    }

    var dropdownCss = this.options.get('dropdownCss') || {};

    if ($.isFunction(dropdownCss)) {
      dropdownCss = dropdownCss(this.$element);
    }

    CompatUtils.syncCssClasses($dropdown, this.$element, dropdownCssAdapter);

    $dropdown.css(dropdownCss);
    $dropdown.addClass(dropdownCssClass);

    return $dropdown;
  };

  return DropdownCSS;
});

S2.define('select2/compat/initSelection',[
  'jquery'
], function ($) {
  function InitSelection (decorated, $element, options) {
    if (options.get('debug') &amp;&amp; window.console &amp;&amp; console.warn) {
      console.warn(
        'Select2: The `initSelection` option has been deprecated in favor' +
        ' of a custom data adapter that overrides the `current` method. ' +
        'This method is now called multiple times instead of a single ' +
        'time when the instance is initialized. Support will be removed ' +
        'for the `initSelection` option in future versions of Select2'
      );
    }

    this.initSelection = options.get('initSelection');
    this._isInitialized = false;

    decorated.call(this, $element, options);
  }

  InitSelection.prototype.current = function (decorated, callback) {
    var self = this;

    if (this._isInitialized) {
      decorated.call(this, callback);

      return;
    }

    this.initSelection.call(null, this.$element, function (data) {
      self._isInitialized = true;

      if (!$.isArray(data)) {
        data = [data];
      }

      callback(data);
    });
  };

  return InitSelection;
});

S2.define('select2/compat/inputData',[
  'jquery',
  '../utils'
], function ($, Utils) {
  function InputData (decorated, $element, options) {
    this._currentData = [];
    this._valueSeparator = options.get('valueSeparator') || ',';

    if ($element.prop('type') === 'hidden') {
      if (options.get('debug') &amp;&amp; console &amp;&amp; console.warn) {
        console.warn(
          'Select2: Using a hidden input with Select2 is no longer ' +
          'supported and may stop working in the future. It is recommended ' +
          'to use a `&lt;select&gt;` element instead.'
        );
      }
    }

    decorated.call(this, $element, options);
  }

  InputData.prototype.current = function (_, callback) {
    function getSelected (data, selectedIds) {
      var selected = [];

      if (data.selected || $.inArray(data.id, selectedIds) !== -1) {
        data.selected = true;
        selected.push(data);
      } else {
        data.selected = false;
      }

      if (data.children) {
        selected.push.apply(selected, getSelected(data.children, selectedIds));
      }

      return selected;
    }

    var selected = [];

    for (var d = 0; d &lt; this._currentData.length; d++) {
      var data = this._currentData[d];

      selected.push.apply(
        selected,
        getSelected(
          data,
          this.$element.val().split(
            this._valueSeparator
          )
        )
      );
    }

    callback(selected);
  };

  InputData.prototype.select = function (_, data) {
    if (!this.options.get('multiple')) {
      this.current(function (allData) {
        $.map(allData, function (data) {
          data.selected = false;
        });
      });

      this.$element.val(data.id);
      this.$element.trigger('input').trigger('change');
    } else {
      var value = this.$element.val();
      value += this._valueSeparator + data.id;

      this.$element.val(value);
      this.$element.trigger('input').trigger('change');
    }
  };

  InputData.prototype.unselect = function (_, data) {
    var self = this;

    data.selected = false;

    this.current(function (allData) {
      var values = [];

      for (var d = 0; d &lt; allData.length; d++) {
        var item = allData[d];

        if (data.id == item.id) {
          continue;
        }

        values.push(item.id);
      }

      self.$element.val(values.join(self._valueSeparator));
      self.$element.trigger('input').trigger('change');
    });
  };

  InputData.prototype.query = function (_, params, callback) {
    var results = [];

    for (var d = 0; d &lt; this._currentData.length; d++) {
      var data = this._currentData[d];

      var matches = this.matches(params, data);

      if (matches !== null) {
        results.push(matches);
      }
    }

    callback({
      results: results
    });
  };

  InputData.prototype.addOptions = function (_, $options) {
    var options = $.map($options, function ($option) {
      return Utils.GetData($option[0], 'data');
    });

    this._currentData.push.apply(this._currentData, options);
  };

  return InputData;
});

S2.define('select2/compat/matcher',[
  'jquery'
], function ($) {
  function oldMatcher (matcher) {
    function wrappedMatcher (params, data) {
      var match = $.extend(true, {}, data);

      if (params.term == null || $.trim(params.term) === '') {
        return match;
      }

      if (data.children) {
        for (var c = data.children.length - 1; c &gt;= 0; c--) {
          var child = data.children[c];

          // Check if the child object matches
          // The old matcher returned a boolean true or false
          var doesMatch = matcher(params.term, child.text, child);

          // If the child didn't match, pop it off
          if (!doesMatch) {
            match.children.splice(c, 1);
          }
        }

        if (match.children.length &gt; 0) {
          return match;
        }
      }

      if (matcher(params.term, data.text, data)) {
        return match;
      }

      return null;
    }

    return wrappedMatcher;
  }

  return oldMatcher;
});

S2.define('select2/compat/query',[

], function () {
  function Query (decorated, $element, options) {
    if (options.get('debug') &amp;&amp; window.console &amp;&amp; console.warn) {
      console.warn(
        'Select2: The `query` option has been deprecated in favor of a ' +
        'custom data adapter that overrides the `query` method. Support ' +
        'will be removed for the `query` option in future versions of ' +
        'Select2.'
      );
    }

    decorated.call(this, $element, options);
  }

  Query.prototype.query = function (_, params, callback) {
    params.callback = callback;

    var query = this.options.get('query');

    query.call(null, params);
  };

  return Query;
});

S2.define('select2/dropdown/attachContainer',[

], function () {
  function AttachContainer (decorated, $element, options) {
    decorated.call(this, $element, options);
  }

  AttachContainer.prototype.position =
    function (decorated, $dropdown, $container) {
    var $dropdownContainer = $container.find('.dropdown-wrapper');
    $dropdownContainer.append($dropdown);

    $dropdown.addClass('select2-dropdown--below');
    $container.addClass('select2-container--below');
  };

  return AttachContainer;
});

S2.define('select2/dropdown/stopPropagation',[

], function () {
  function StopPropagation () { }

  StopPropagation.prototype.bind = function (decorated, container, $container) {
    decorated.call(this, container, $container);

    var stoppedEvents = [
    'blur',
    'change',
    'click',
    'dblclick',
    'focus',
    'focusin',
    'focusout',
    'input',
    'keydown',
    'keyup',
    'keypress',
    'mousedown',
    'mouseenter',
    'mouseleave',
    'mousemove',
    'mouseover',
    'mouseup',
    'search',
    'touchend',
    'touchstart'
    ];

    this.$dropdown.on(stoppedEvents.join(' '), function (evt) {
      evt.stopPropagation();
    });
  };

  return StopPropagation;
});

S2.define('select2/selection/stopPropagation',[

], function () {
  function StopPropagation () { }

  StopPropagation.prototype.bind = function (decorated, container, $container) {
    decorated.call(this, container, $container);

    var stoppedEvents = [
      'blur',
      'change',
      'click',
      'dblclick',
      'focus',
      'focusin',
      'focusout',
      'input',
      'keydown',
      'keyup',
      'keypress',
      'mousedown',
      'mouseenter',
      'mouseleave',
      'mousemove',
      'mouseover',
      'mouseup',
      'search',
      'touchend',
      'touchstart'
    ];

    this.$selection.on(stoppedEvents.join(' '), function (evt) {
      evt.stopPropagation();
    });
  };

  return StopPropagation;
});

/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */

(function (factory) {
    if ( typeof S2.define === 'function' &amp;&amp; S2.define.amd ) {
        // AMD. Register as an anonymous module.
        S2.define('jquery-mousewheel',['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode &gt;= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: '3.1.12',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
            // Clean up the data we added to the element
            $.removeData(this, 'mousewheel-line-height');
            $.removeData(this, 'mousewheel-page-height');
        },

        getLineHeight: function(elem) {
            var $elem = $(elem),
                $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
            if (!$parent.length) {
                $parent = $('body');
            }
            return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
        },

        getPageHeight: function(elem) {
            return $(elem).height();
        },

        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0,
            offsetX    = 0,
            offsetY    = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox &lt; 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent &amp;&amp; orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 &amp;&amp; deltaX === 0 ) { return; }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );

        if ( !lowestDelta || absDelta &lt; lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  &gt;= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX &gt;= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY &gt;= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset &amp;&amp; this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            offsetX = event.clientX - boundingRect.left;
            offsetY = event.clientY - boundingRect.top;
        }

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        event.offsetX = offsetX;
        event.offsetY = offsetY;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas &amp;&amp; orgEvent.type === 'mousewheel' &amp;&amp; absDelta % 120 === 0;
    }

}));

S2.define('jquery.select2',[
  'jquery',
  'jquery-mousewheel',

  './select2/core',
  './select2/defaults',
  './select2/utils'
], function ($, _, Select2, Defaults, Utils) {
  if ($.fn.select2 == null) {
    // All methods that should return the element
    var thisMethods = ['open', 'close', 'destroy'];

    $.fn.select2 = function (options) {
      options = options || {};

      if (typeof options === 'object') {
        this.each(function () {
          var instanceOptions = $.extend(true, {}, options);

          var instance = new Select2($(this), instanceOptions);
        });

        return this;
      } else if (typeof options === 'string') {
        var ret;
        var args = Array.prototype.slice.call(arguments, 1);

        this.each(function () {
          var instance = Utils.GetData(this, 'select2');

          if (instance == null &amp;&amp; window.console &amp;&amp; console.error) {
            console.error(
              'The select2(\'' + options + '\') method was called on an ' +
              'element that is not using Select2.'
            );
          }

          ret = instance[options].apply(instance, args);
        });

        // Check if we should be returning `this`
        if ($.inArray(options, thisMethods) &gt; -1) {
          return this;
        }

        return ret;
      } else {
        throw new Error('Invalid arguments for Select2: ' + options);
      }
    };
  }

  if ($.fn.select2.defaults == null) {
    $.fn.select2.defaults = Defaults;
  }

  return Select2;
});

  // Return the AMD loader configuration so it can be used outside of this file
  return {
    define: S2.define,
    require: S2.require
  };
}());

  // Autoload the jQuery bindings
  // We know that all of the modules exist above this, so we're safe
  var select2 = S2.require('jquery.select2');

  // Hold the AMD module references on the jQuery function that was just loaded
  // This allows Select2 to use the internal loader outside of this file, such
  // as in the language files.
  jQuery.fn.select2.amd = S2;

  // Return the Select2 instance for anyone who is importing it.
  return select2;
}));
!function(t,e){"object"==typeof exports&amp;&amp;"undefined"!=typeof module?module.exports=e():"function"==typeof define&amp;&amp;define.amd?define(e):(t=t||self).Sweetalert2=e()}(this,function(){"use strict";function r(t){return(r="function"==typeof Symbol&amp;&amp;"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&amp;&amp;"function"==typeof Symbol&amp;&amp;t.constructor===Symbol&amp;&amp;t!==Symbol.prototype?"symbol":typeof t})(t)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n&lt;e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&amp;&amp;(o.writable=!0),Object.defineProperty(t,o.key,o)}}function s(t,e,n){return e&amp;&amp;o(t.prototype,e),n&amp;&amp;o(t,n),t}function u(){return(u=Object.assign||function(t){for(var e=1;e&lt;arguments.length;e++){var n,o=arguments[e];for(n in o)Object.prototype.hasOwnProperty.call(o,n)&amp;&amp;(t[n]=o[n])}return t}).apply(this,arguments)}function c(t){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function l(t,e){return(l=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function d(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}function i(t,e,n){return(i=d()?Reflect.construct:function(t,e,n){var o=[null];o.push.apply(o,e);o=new(Function.bind.apply(t,o));return n&amp;&amp;l(o,n.prototype),o}).apply(null,arguments)}function p(t,e){return!e||"object"!=typeof e&amp;&amp;"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function f(t,e,n){return(f="undefined"!=typeof Reflect&amp;&amp;Reflect.get?Reflect.get:function(t,e,n){t=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&amp;&amp;null!==(t=c(t)););return t}(t,e);if(t){e=Object.getOwnPropertyDescriptor(t,e);return e.get?e.get.call(n):e.value}})(t,e,n||t)}function m(t){return t.charAt(0).toUpperCase()+t.slice(1)}function h(e){return Object.keys(e).map(function(t){return e[t]})}function g(t){return Array.prototype.slice.call(t)}function v(t,e){e='"'.concat(t,'" is deprecated and will be removed in the next major release. Please use "').concat(e,'" instead.'),-1===Y.indexOf(e)&amp;&amp;(Y.push(e),W(e))}function b(t){return t&amp;&amp;"function"==typeof t.toPromise}function y(t){return b(t)?t.toPromise():Promise.resolve(t)}function w(t){return t&amp;&amp;Promise.resolve(t)===t}function C(t){return t instanceof Element||"object"===r(t=t)&amp;&amp;t.jquery}function k(){return document.body.querySelector(".".concat($.container))}function e(t){var e=k();return e?e.querySelector(t):null}function t(t){return e(".".concat(t))}function A(){return t($.popup)}function x(){return t($.icon)}function B(){return t($.title)}function P(){return t($.content)}function O(){return t($["html-container"])}function E(){return t($.image)}function n(){return t($["progress-steps"])}function S(){return t($["validation-message"])}function T(){return e(".".concat($.actions," .").concat($.confirm))}function L(){return e(".".concat($.actions," .").concat($.deny))}function D(){return e(".".concat($.loader))}function q(){return e(".".concat($.actions," .").concat($.cancel))}function j(){return t($.actions)}function M(){return t($.header)}function I(){return t($.footer)}function H(){return t($["timer-progress-bar"])}function V(){return t($.close)}function R(){var t=g(A().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')).sort(function(t,e){return t=parseInt(t.getAttribute("tabindex")),(e=parseInt(e.getAttribute("tabindex")))&lt;t?1:t&lt;e?-1:0}),e=g(A().querySelectorAll('\n  a[href],\n  area[href],\n  input:not([disabled]),\n  select:not([disabled]),\n  textarea:not([disabled]),\n  button:not([disabled]),\n  iframe,\n  object,\n  embed,\n  [tabindex="0"],\n  [contenteditable],\n  audio[controls],\n  video[controls],\n  summary\n')).filter(function(t){return"-1"!==t.getAttribute("tabindex")});return function(t){for(var e=[],n=0;n&lt;t.length;n++)-1===e.indexOf(t[n])&amp;&amp;e.push(t[n]);return e}(t.concat(e)).filter(function(t){return wt(t)})}function N(){return!G()&amp;&amp;!document.body.classList.contains($["no-backdrop"])}function U(e,t){e.textContent="",t&amp;&amp;(t=(new DOMParser).parseFromString(t,"text/html"),g(t.querySelector("head").childNodes).forEach(function(t){e.appendChild(t)}),g(t.querySelector("body").childNodes).forEach(function(t){e.appendChild(t)}))}function _(t,e){if(e){for(var n=e.split(/\s+/),o=0;o&lt;n.length;o++)if(!t.classList.contains(n[o]))return;return 1}}function F(t,e,n){var o,i;if(i=e,g((o=t).classList).forEach(function(t){-1===h($).indexOf(t)&amp;&amp;-1===h(X).indexOf(t)&amp;&amp;-1===h(i.showClass).indexOf(t)&amp;&amp;o.classList.remove(t)}),e.customClass&amp;&amp;e.customClass[n]){if("string"!=typeof e.customClass[n]&amp;&amp;!e.customClass[n].forEach)return W("Invalid type of customClass.".concat(n,'! Expected string or iterable object, got "').concat(r(e.customClass[n]),'"'));vt(t,e.customClass[n])}}var z="SweetAlert2:",W=function(t){console.warn("".concat(z," ").concat("object"===r(t)?t.join(" "):t))},K=function(t){console.error("".concat(z," ").concat(t))},Y=[],Z=function(t){return"function"==typeof t?t():t},Q=Object.freeze({cancel:"cancel",backdrop:"backdrop",close:"close",esc:"esc",timer:"timer"}),J=function(t){var e,n={};for(e in t)n[t[e]]="swal2-"+t[e];return n},$=J(["container","shown","height-auto","iosfix","popup","modal","no-backdrop","no-transition","toast","toast-shown","toast-column","show","hide","close","title","header","content","html-container","actions","confirm","deny","cancel","footer","icon","icon-content","image","input","file","range","select","radio","checkbox","label","textarea","inputerror","input-label","validation-message","progress-steps","active-progress-step","progress-step","progress-step-line","loader","loading","styled","top","top-start","top-end","top-left","top-right","center","center-start","center-end","center-left","center-right","bottom","bottom-start","bottom-end","bottom-left","bottom-right","grow-row","grow-column","grow-fullscreen","rtl","timer-progress-bar","timer-progress-bar-container","scrollbar-measure","icon-success","icon-warning","icon-info","icon-question","icon-error"]),X=J(["success","warning","info","question","error"]),G=function(){return document.body.classList.contains($["toast-shown"])},tt={previousBodyPadding:null};function et(t,e){if(!e)return null;switch(e){case"select":case"textarea":case"file":return yt(t,$[e]);case"checkbox":return t.querySelector(".".concat($.checkbox," input"));case"radio":return t.querySelector(".".concat($.radio," input:checked"))||t.querySelector(".".concat($.radio," input:first-child"));case"range":return t.querySelector(".".concat($.range," input"));default:return yt(t,$.input)}}function nt(t){var e;t.focus(),"file"!==t.type&amp;&amp;(e=t.value,t.value="",t.value=e)}function ot(t,e,n){t&amp;&amp;e&amp;&amp;(e="string"==typeof e?e.split(/\s+/).filter(Boolean):e).forEach(function(e){t.forEach?t.forEach(function(t){n?t.classList.add(e):t.classList.remove(e)}):n?t.classList.add(e):t.classList.remove(e)})}function it(t,e,n){(n=n==="".concat(parseInt(n))?parseInt(n):n)||0===parseInt(n)?t.style[e]="number"==typeof n?"".concat(n,"px"):n:t.style.removeProperty(e)}function rt(t){var e=1&lt;arguments.length&amp;&amp;void 0!==arguments[1]?arguments[1]:"flex";t.style.display=e}function at(t){t.style.display="none"}function st(t,e,n,o){(e=t.querySelector(e))&amp;&amp;(e.style[n]=o)}function ut(t,e,n){e?rt(t,n):at(t)}function ct(t){return!!(t.scrollHeight&gt;t.clientHeight)}function lt(t){var e=window.getComputedStyle(t),t=parseFloat(e.getPropertyValue("animation-duration")||"0"),e=parseFloat(e.getPropertyValue("transition-duration")||"0");return 0&lt;t||0&lt;e}function dt(t){var e=1&lt;arguments.length&amp;&amp;void 0!==arguments[1]&amp;&amp;arguments[1],n=H();wt(n)&amp;&amp;(e&amp;&amp;(n.style.transition="none",n.style.width="100%"),setTimeout(function(){n.style.transition="width ".concat(t/1e3,"s linear"),n.style.width="0%"},10))}function pt(){return"undefined"==typeof window||"undefined"==typeof document}function ft(t){Mn.isVisible()&amp;&amp;gt!==t.target.value&amp;&amp;Mn.resetValidationMessage(),gt=t.target.value}function mt(t,e){t instanceof HTMLElement?e.appendChild(t):"object"===r(t)?At(t,e):t&amp;&amp;U(e,t)}function ht(t,e){var n=j(),o=D(),i=T(),r=L(),a=q();e.showConfirmButton||e.showDenyButton||e.showCancelButton||at(n),F(n,e,"actions"),Pt(i,"confirm",e),Pt(r,"deny",e),Pt(a,"cancel",e),function(t,e,n,o){if(!o.buttonsStyling)return bt([t,e,n],$.styled);vt([t,e,n],$.styled),o.confirmButtonColor&amp;&amp;(t.style.backgroundColor=o.confirmButtonColor);o.denyButtonColor&amp;&amp;(e.style.backgroundColor=o.denyButtonColor);o.cancelButtonColor&amp;&amp;(n.style.backgroundColor=o.cancelButtonColor)}(i,r,a,e),e.reverseButtons&amp;&amp;(n.insertBefore(a,o),n.insertBefore(r,o),n.insertBefore(i,o)),U(o,e.loaderHtml),F(o,e,"loader")}var gt,vt=function(t,e){ot(t,e,!0)},bt=function(t,e){ot(t,e,!1)},yt=function(t,e){for(var n=0;n&lt;t.childNodes.length;n++)if(_(t.childNodes[n],e))return t.childNodes[n]},wt=function(t){return!(!t||!(t.offsetWidth||t.offsetHeight||t.getClientRects().length))},Ct='\n &lt;div aria-labelledby="'.concat($.title,'" aria-describedby="').concat($.content,'" class="').concat($.popup,'" tabindex="-1"&gt;\n   &lt;div class="').concat($.header,'"&gt;\n     &lt;ul class="').concat($["progress-steps"],'"&gt;&lt;/ul&gt;\n     &lt;div class="').concat($.icon,'"&gt;&lt;/div&gt;\n     &lt;img class="').concat($.image,'" /&gt;\n     &lt;h2 class="').concat($.title,'" id="').concat($.title,'"&gt;&lt;/h2&gt;\n     &lt;button type="button" class="').concat($.close,'"&gt;&lt;/button&gt;\n   &lt;/div&gt;\n   &lt;div class="').concat($.content,'"&gt;\n     &lt;div id="').concat($.content,'" class="').concat($["html-container"],'"&gt;&lt;/div&gt;\n     &lt;input class="').concat($.input,'" /&gt;\n     &lt;input type="file" class="').concat($.file,'" /&gt;\n     &lt;div class="').concat($.range,'"&gt;\n       &lt;input type="range" /&gt;\n       &lt;output&gt;&lt;/output&gt;\n     &lt;/div&gt;\n     &lt;select class="').concat($.select,'"&gt;&lt;/select&gt;\n     &lt;div class="').concat($.radio,'"&gt;&lt;/div&gt;\n     &lt;label for="').concat($.checkbox,'" class="').concat($.checkbox,'"&gt;\n       &lt;input type="checkbox" /&gt;\n       &lt;span class="').concat($.label,'"&gt;&lt;/span&gt;\n     &lt;/label&gt;\n     &lt;textarea class="').concat($.textarea,'"&gt;&lt;/textarea&gt;\n     &lt;div class="').concat($["validation-message"],'" id="').concat($["validation-message"],'"&gt;&lt;/div&gt;\n   &lt;/div&gt;\n   &lt;div class="').concat($.actions,'"&gt;\n     &lt;div class="').concat($.loader,'"&gt;&lt;/div&gt;\n     &lt;button type="button" class="').concat($.confirm,'"&gt;&lt;/button&gt;\n     &lt;button type="button" class="').concat($.deny,'"&gt;&lt;/button&gt;\n     &lt;button type="button" class="').concat($.cancel,'"&gt;&lt;/button&gt;\n   &lt;/div&gt;\n   &lt;div class="').concat($.footer,'"&gt;&lt;/div&gt;\n   &lt;div class="').concat($["timer-progress-bar-container"],'"&gt;\n     &lt;div class="').concat($["timer-progress-bar"],'"&gt;&lt;/div&gt;\n   &lt;/div&gt;\n &lt;/div&gt;\n').replace(/(^|\n)\s*/g,""),kt=function(t){var e,n,o,i,r,a=!!(i=k())&amp;&amp;(i.parentNode.removeChild(i),bt([document.documentElement,document.body],[$["no-backdrop"],$["toast-shown"],$["has-column"]]),!0);pt()?K("SweetAlert2 requires document to initialize"):((r=document.createElement("div")).className=$.container,a&amp;&amp;vt(r,$["no-transition"]),U(r,Ct),(i="string"==typeof(e=t.target)?document.querySelector(e):e).appendChild(r),a=t,(e=A()).setAttribute("role",a.toast?"alert":"dialog"),e.setAttribute("aria-live",a.toast?"polite":"assertive"),a.toast||e.setAttribute("aria-modal","true"),r=i,"rtl"===window.getComputedStyle(r).direction&amp;&amp;vt(k(),$.rtl),t=P(),a=yt(t,$.input),e=yt(t,$.file),n=t.querySelector(".".concat($.range," input")),o=t.querySelector(".".concat($.range," output")),i=yt(t,$.select),r=t.querySelector(".".concat($.checkbox," input")),t=yt(t,$.textarea),a.oninput=ft,e.onchange=ft,i.onchange=ft,r.onchange=ft,t.oninput=ft,n.oninput=function(t){ft(t),o.value=n.value},n.onchange=function(t){ft(t),n.nextSibling.value=n.value})},At=function(t,e){t.jquery?xt(e,t):U(e,t.toString())},xt=function(t,e){if(t.textContent="",0 in e)for(var n=0;n in e;n++)t.appendChild(e[n].cloneNode(!0));else t.appendChild(e.cloneNode(!0))},Bt=function(){if(pt())return!1;var t,e=document.createElement("div"),n={WebkitAnimation:"webkitAnimationEnd",OAnimation:"oAnimationEnd oanimationend",animation:"animationend"};for(t in n)if(Object.prototype.hasOwnProperty.call(n,t)&amp;&amp;void 0!==e.style[t])return n[t];return!1}();function Pt(t,e,n){ut(t,n["show".concat(m(e),"Button")],"inline-block"),U(t,n["".concat(e,"ButtonText")]),t.setAttribute("aria-label",n["".concat(e,"ButtonAriaLabel")]),t.className=$[e],F(t,n,"".concat(e,"Button")),vt(t,n["".concat(e,"ButtonClass")])}function Ot(t,e){var n,o,i=k();i&amp;&amp;(o=i,"string"==typeof(n=e.backdrop)?o.style.background=n:n||vt([document.documentElement,document.body],$["no-backdrop"]),!e.backdrop&amp;&amp;e.allowOutsideClick&amp;&amp;W('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`'),o=i,(n=e.position)in $?vt(o,$[n]):(W('The "position" parameter is not valid, defaulting to "center"'),vt(o,$.center)),n=i,!(o=e.grow)||"string"!=typeof o||(o="grow-".concat(o))in $&amp;&amp;vt(n,$[o]),F(i,e,"container"),(e=document.body.getAttribute("data-swal2-queue-step"))&amp;&amp;(i.setAttribute("data-queue-step",e),document.body.removeAttribute("data-swal2-queue-step")))}function Et(t,e){t.placeholder&amp;&amp;!e.inputPlaceholder||(t.placeholder=e.inputPlaceholder)}function St(t,e,n){var o,i;n.inputLabel&amp;&amp;(t.id=$.input,o=document.createElement("label"),i=$["input-label"],o.setAttribute("for",t.id),o.className=i,vt(o,n.customClass.inputLabel),o.innerText=n.inputLabel,e.insertAdjacentElement("beforebegin",o))}var Tt={promise:new WeakMap,innerParams:new WeakMap,domCache:new WeakMap},Lt=["input","file","range","select","radio","checkbox","textarea"],Dt=function(t){if(!It[t.input])return K('Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "'.concat(t.input,'"'));var e=Mt(t.input),n=It[t.input](e,t);rt(n),setTimeout(function(){nt(n)})},qt=function(t,e){var n=et(P(),t);if(n)for(var o in!function(t){for(var e=0;e&lt;t.attributes.length;e++){var n=t.attributes[e].name;-1===["type","value","style"].indexOf(n)&amp;&amp;t.removeAttribute(n)}}(n),e)"range"===t&amp;&amp;"placeholder"===o||n.setAttribute(o,e[o])},jt=function(t){var e=Mt(t.input);t.customClass&amp;&amp;vt(e,t.customClass.input)},Mt=function(t){t=$[t]||$.input;return yt(P(),t)},It={};It.text=It.email=It.password=It.number=It.tel=It.url=function(t,e){return"string"==typeof e.inputValue||"number"==typeof e.inputValue?t.value=e.inputValue:w(e.inputValue)||W('Unexpected type of inputValue! Expected "string", "number" or "Promise", got "'.concat(r(e.inputValue),'"')),St(t,t,e),Et(t,e),t.type=e.input,t},It.file=function(t,e){return St(t,t,e),Et(t,e),t},It.range=function(t,e){var n=t.querySelector("input"),o=t.querySelector("output");return n.value=e.inputValue,n.type=e.input,o.value=e.inputValue,St(n,t,e),t},It.select=function(t,e){var n;return t.textContent="",e.inputPlaceholder&amp;&amp;(n=document.createElement("option"),U(n,e.inputPlaceholder),n.value="",n.disabled=!0,n.selected=!0,t.appendChild(n)),St(t,t,e),t},It.radio=function(t){return t.textContent="",t},It.checkbox=function(t,e){var n=et(P(),"checkbox");n.value=1,n.id=$.checkbox,n.checked=Boolean(e.inputValue);n=t.querySelector("span");return U(n,e.inputPlaceholder),t},It.textarea=function(e,t){e.value=t.inputValue,Et(e,t),St(e,e,t);function n(t){return parseInt(window.getComputedStyle(t).paddingLeft)+parseInt(window.getComputedStyle(t).paddingRight)}var o;return"MutationObserver"in window&amp;&amp;(o=parseInt(window.getComputedStyle(A()).width),new MutationObserver(function(){var t=e.offsetWidth+n(A())+n(P());A().style.width=o&lt;t?"".concat(t,"px"):null}).observe(e,{attributes:!0,attributeFilter:["style"]})),e};function Ht(t,e){var o,i,r,n=O();F(n,e,"htmlContainer"),e.html?(mt(e.html,n),rt(n,"block")):e.text?(n.textContent=e.text,rt(n,"block")):at(n),t=t,o=e,i=P(),t=Tt.innerParams.get(t),r=!t||o.input!==t.input,Lt.forEach(function(t){var e=$[t],n=yt(i,e);qt(t,o.inputAttributes),n.className=e,r&amp;&amp;at(n)}),o.input&amp;&amp;(r&amp;&amp;Dt(o),jt(o)),F(P(),e,"content")}function Vt(){return k()&amp;&amp;k().getAttribute("data-queue-step")}function Rt(t,o){var i=n();if(!o.progressSteps||0===o.progressSteps.length)return at(i),0;rt(i),i.textContent="";var r=parseInt(void 0===o.currentProgressStep?Vt():o.currentProgressStep);r&gt;=o.progressSteps.length&amp;&amp;W("Invalid currentProgressStep parameter, it should be less than progressSteps.length (currentProgressStep like JS arrays starts from 0)"),o.progressSteps.forEach(function(t,e){var n,t=(n=t,t=document.createElement("li"),vt(t,$["progress-step"]),U(t,n),t);i.appendChild(t),e===r&amp;&amp;vt(t,$["active-progress-step"]),e!==o.progressSteps.length-1&amp;&amp;(t=o,e=document.createElement("li"),vt(e,$["progress-step-line"]),t.progressStepsDistance&amp;&amp;(e.style.width=t.progressStepsDistance),e=e,i.appendChild(e))})}function Nt(t,e){var n,o=M();F(o,e,"header"),Rt(0,e),n=t,o=e,t=Tt.innerParams.get(n),n=x(),t&amp;&amp;o.icon===t.icon?(Wt(n,o),Ft(n,o)):o.icon||o.iconHtml?o.icon&amp;&amp;-1===Object.keys(X).indexOf(o.icon)?(K('Unknown icon! Expected "success", "error", "warning", "info" or "question", got "'.concat(o.icon,'"')),at(n)):(rt(n),Wt(n,o),Ft(n,o),vt(n,o.showClass.icon)):at(n),function(t){var e=E();if(!t.imageUrl)return at(e);rt(e,""),e.setAttribute("src",t.imageUrl),e.setAttribute("alt",t.imageAlt),it(e,"width",t.imageWidth),it(e,"height",t.imageHeight),e.className=$.image,F(e,t,"image")}(e),o=e,n=B(),ut(n,o.title||o.titleText),o.title&amp;&amp;mt(o.title,n),o.titleText&amp;&amp;(n.innerText=o.titleText),F(n,o,"title"),o=e,e=V(),U(e,o.closeButtonHtml),F(e,o,"closeButton"),ut(e,o.showCloseButton),e.setAttribute("aria-label",o.closeButtonAriaLabel)}function Ut(t,e){var n,o,i;i=e,n=k(),o=A(),i.toast?(it(n,"width",i.width),o.style.width="100%"):it(o,"width",i.width),it(o,"padding",i.padding),i.background&amp;&amp;(o.style.background=i.background),at(S()),Qt(o,i),Ot(0,e),Nt(t,e),Ht(t,e),ht(0,e),i=e,t=I(),ut(t,i.footer),i.footer&amp;&amp;mt(i.footer,t),F(t,i,"footer"),"function"==typeof e.didRender?e.didRender(A()):"function"==typeof e.onRender&amp;&amp;e.onRender(A())}function _t(){return T()&amp;&amp;T().click()}var Ft=function(t,e){for(var n in X)e.icon!==n&amp;&amp;bt(t,X[n]);vt(t,X[e.icon]),Kt(t,e),zt(),F(t,e,"icon")},zt=function(){for(var t=A(),e=window.getComputedStyle(t).getPropertyValue("background-color"),n=t.querySelectorAll("[class^=swal2-success-circular-line], .swal2-success-fix"),o=0;o&lt;n.length;o++)n[o].style.backgroundColor=e},Wt=function(t,e){t.textContent="",e.iconHtml?U(t,Yt(e.iconHtml)):"success"===e.icon?U(t,'\n      &lt;div class="swal2-success-circular-line-left"&gt;&lt;/div&gt;\n      &lt;span class="swal2-success-line-tip"&gt;&lt;/span&gt; &lt;span class="swal2-success-line-long"&gt;&lt;/span&gt;\n      &lt;div class="swal2-success-ring"&gt;&lt;/div&gt; &lt;div class="swal2-success-fix"&gt;&lt;/div&gt;\n      &lt;div class="swal2-success-circular-line-right"&gt;&lt;/div&gt;\n    '):"error"===e.icon?U(t,'\n      &lt;span class="swal2-x-mark"&gt;\n        &lt;span class="swal2-x-mark-line-left"&gt;&lt;/span&gt;\n        &lt;span class="swal2-x-mark-line-right"&gt;&lt;/span&gt;\n      &lt;/span&gt;\n    '):U(t,Yt({question:"?",warning:"!",info:"i"}[e.icon]))},Kt=function(t,e){if(e.iconColor){t.style.color=e.iconColor,t.style.borderColor=e.iconColor;for(var n=0,o=[".swal2-success-line-tip",".swal2-success-line-long",".swal2-x-mark-line-left",".swal2-x-mark-line-right"];n&lt;o.length;n++)st(t,o[n],"backgroundColor",e.iconColor);st(t,".swal2-success-ring","borderColor",e.iconColor)}},Yt=function(t){return'&lt;div class="'.concat($["icon-content"],'"&gt;').concat(t,"&lt;/div&gt;")},Zt=[],Qt=function(t,e){t.className="".concat($.popup," ").concat(wt(t)?e.showClass.popup:""),e.toast?(vt([document.documentElement,document.body],$["toast-shown"]),vt(t,$.toast)):vt(t,$.modal),F(t,e,"popup"),"string"==typeof e.customClass&amp;&amp;vt(t,e.customClass),e.icon&amp;&amp;vt(t,$["icon-".concat(e.icon)])};function Jt(t){(e=A())||Mn.fire();var e=A(),n=j(),o=D();!t&amp;&amp;wt(T())&amp;&amp;(t=T()),rt(n),t&amp;&amp;(at(t),o.setAttribute("data-button-to-replace",t.className)),o.parentNode.insertBefore(o,t),vt([e,n],$.loading),rt(o),e.setAttribute("data-loading",!0),e.setAttribute("aria-busy",!0),e.focus()}function $t(){return new Promise(function(t){var e=window.scrollX,n=window.scrollY;te.restoreFocusTimeout=setTimeout(function(){te.previousActiveElement&amp;&amp;te.previousActiveElement.focus?(te.previousActiveElement.focus(),te.previousActiveElement=null):document.body&amp;&amp;document.body.focus(),t()},100),void 0!==e&amp;&amp;void 0!==n&amp;&amp;window.scrollTo(e,n)})}function Xt(){if(te.timeout)return function(){var t=H(),e=parseInt(window.getComputedStyle(t).width);t.style.removeProperty("transition"),t.style.width="100%";var n=parseInt(window.getComputedStyle(t).width),n=parseInt(e/n*100);t.style.removeProperty("transition"),t.style.width="".concat(n,"%")}(),te.timeout.stop()}function Gt(){if(te.timeout){var t=te.timeout.start();return dt(t),t}}var te={},ee=!1,ne={};function oe(t){for(var e=t.target;e&amp;&amp;e!==document;e=e.parentNode)for(var n in ne){var o=e.getAttribute(n);if(o)return void ne[n].fire({template:o})}}function ie(t){return Object.prototype.hasOwnProperty.call(se,t)}function re(t){return ce[t]}function ae(t){for(var e in t)ie(n=e)||W('Unknown parameter "'.concat(n,'"')),t.toast&amp;&amp;(n=e,-1!==le.indexOf(n)&amp;&amp;W('The parameter "'.concat(n,'" is incompatible with toasts'))),re(e=e)&amp;&amp;v(e,re(e));var n}var se={title:"",titleText:"",text:"",html:"",footer:"",icon:void 0,iconColor:void 0,iconHtml:void 0,template:void 0,toast:!1,animation:!0,showClass:{popup:"swal2-show",backdrop:"swal2-backdrop-show",icon:"swal2-icon-show"},hideClass:{popup:"swal2-hide",backdrop:"swal2-backdrop-hide",icon:"swal2-icon-hide"},customClass:{},target:"body",backdrop:!0,heightAuto:!0,allowOutsideClick:!0,allowEscapeKey:!0,allowEnterKey:!0,stopKeydownPropagation:!0,keydownListenerCapture:!1,showConfirmButton:!0,showDenyButton:!1,showCancelButton:!1,preConfirm:void 0,preDeny:void 0,confirmButtonText:"OK",confirmButtonAriaLabel:"",confirmButtonColor:void 0,denyButtonText:"No",denyButtonAriaLabel:"",denyButtonColor:void 0,cancelButtonText:"Cancel",cancelButtonAriaLabel:"",cancelButtonColor:void 0,buttonsStyling:!0,reverseButtons:!1,focusConfirm:!0,focusDeny:!1,focusCancel:!1,showCloseButton:!1,closeButtonHtml:"&amp;times;",closeButtonAriaLabel:"Close this dialog",loaderHtml:"",showLoaderOnConfirm:!1,showLoaderOnDeny:!1,imageUrl:void 0,imageWidth:void 0,imageHeight:void 0,imageAlt:"",timer:void 0,timerProgressBar:!1,width:void 0,padding:void 0,background:void 0,input:void 0,inputPlaceholder:"",inputLabel:"",inputValue:"",inputOptions:{},inputAutoTrim:!0,inputAttributes:{},inputValidator:void 0,returnInputValueOnDeny:!1,validationMessage:void 0,grow:!1,position:"center",progressSteps:[],currentProgressStep:void 0,progressStepsDistance:void 0,onBeforeOpen:void 0,onOpen:void 0,willOpen:void 0,didOpen:void 0,onRender:void 0,didRender:void 0,onClose:void 0,onAfterClose:void 0,willClose:void 0,didClose:void 0,onDestroy:void 0,didDestroy:void 0,scrollbarPadding:!0},ue=["allowEscapeKey","allowOutsideClick","background","buttonsStyling","cancelButtonAriaLabel","cancelButtonColor","cancelButtonText","closeButtonAriaLabel","closeButtonHtml","confirmButtonAriaLabel","confirmButtonColor","confirmButtonText","currentProgressStep","customClass","denyButtonAriaLabel","denyButtonColor","denyButtonText","didClose","didDestroy","footer","hideClass","html","icon","iconColor","iconHtml","imageAlt","imageHeight","imageUrl","imageWidth","onAfterClose","onClose","onDestroy","progressSteps","reverseButtons","showCancelButton","showCloseButton","showConfirmButton","showDenyButton","text","title","titleText","willClose"],ce={animation:'showClass" and "hideClass',onBeforeOpen:"willOpen",onOpen:"didOpen",onRender:"didRender",onClose:"willClose",onAfterClose:"didClose",onDestroy:"didDestroy"},le=["allowOutsideClick","allowEnterKey","backdrop","focusConfirm","focusDeny","focusCancel","heightAuto","keydownListenerCapture"],de=Object.freeze({isValidParameter:ie,isUpdatableParameter:function(t){return-1!==ue.indexOf(t)},isDeprecatedParameter:re,argsToParams:function(n){var o={};return"object"!==r(n[0])||C(n[0])?["title","html","icon"].forEach(function(t,e){e=n[e];"string"==typeof e||C(e)?o[t]=e:void 0!==e&amp;&amp;K("Unexpected type of ".concat(t,'! Expected "string" or "Element", got ').concat(r(e)))}):u(o,n[0]),o},isVisible:function(){return wt(A())},clickConfirm:_t,clickDeny:function(){return L()&amp;&amp;L().click()},clickCancel:function(){return q()&amp;&amp;q().click()},getContainer:k,getPopup:A,getTitle:B,getContent:P,getHtmlContainer:O,getImage:E,getIcon:x,getInputLabel:function(){return t($["input-label"])},getCloseButton:V,getActions:j,getConfirmButton:T,getDenyButton:L,getCancelButton:q,getLoader:D,getHeader:M,getFooter:I,getTimerProgressBar:H,getFocusableElements:R,getValidationMessage:S,isLoading:function(){return A().hasAttribute("data-loading")},fire:function(){for(var t=arguments.length,e=new Array(t),n=0;n&lt;t;n++)e[n]=arguments[n];return i(this,e)},mixin:function(r){return function(t){!function(t,e){if("function"!=typeof e&amp;&amp;null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&amp;&amp;e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&amp;&amp;l(t,e)}(i,t);var n,o,e=(n=i,o=d(),function(){var t,e=c(n);return p(this,o?(t=c(this).constructor,Reflect.construct(e,arguments,t)):e.apply(this,arguments))});function i(){return a(this,i),e.apply(this,arguments)}return s(i,[{key:"_main",value:function(t,e){return f(c(i.prototype),"_main",this).call(this,t,u({},r,e))}}]),i}(this)},queue:function(t){var r=this;Zt=t;function a(t,e){Zt=[],t(e)}var s=[];return new Promise(function(i){!function e(n,o){n&lt;Zt.length?(document.body.setAttribute("data-swal2-queue-step",n),r.fire(Zt[n]).then(function(t){void 0!==t.value?(s.push(t.value),e(n+1,o)):a(i,{dismiss:t.dismiss})})):a(i,{value:s})}(0)})},getQueueStep:Vt,insertQueueStep:function(t,e){return e&amp;&amp;e&lt;Zt.length?Zt.splice(e,0,t):Zt.push(t)},deleteQueueStep:function(t){void 0!==Zt[t]&amp;&amp;Zt.splice(t,1)},showLoading:Jt,enableLoading:Jt,getTimerLeft:function(){return te.timeout&amp;&amp;te.timeout.getTimerLeft()},stopTimer:Xt,resumeTimer:Gt,toggleTimer:function(){var t=te.timeout;return t&amp;&amp;(t.running?Xt:Gt)()},increaseTimer:function(t){if(te.timeout){t=te.timeout.increase(t);return dt(t,!0),t}},isTimerRunning:function(){return te.timeout&amp;&amp;te.timeout.isRunning()},bindClickHandler:function(){ne[0&lt;arguments.length&amp;&amp;void 0!==arguments[0]?arguments[0]:"data-swal-template"]=this,ee||(document.body.addEventListener("click",oe),ee=!0)}});function pe(){var t,e;Tt.innerParams.get(this)&amp;&amp;(t=Tt.domCache.get(this),at(t.loader),(e=t.popup.getElementsByClassName(t.loader.getAttribute("data-button-to-replace"))).length?rt(e[0],"inline-block"):wt(T())||wt(L())||wt(q())||at(t.actions),bt([t.popup,t.actions],$.loading),t.popup.removeAttribute("aria-busy"),t.popup.removeAttribute("data-loading"),t.confirmButton.disabled=!1,t.denyButton.disabled=!1,t.cancelButton.disabled=!1)}function fe(){null===tt.previousBodyPadding&amp;&amp;document.body.scrollHeight&gt;window.innerHeight&amp;&amp;(tt.previousBodyPadding=parseInt(window.getComputedStyle(document.body).getPropertyValue("padding-right")),document.body.style.paddingRight="".concat(tt.previousBodyPadding+function(){var t=document.createElement("div");t.className=$["scrollbar-measure"],document.body.appendChild(t);var e=t.getBoundingClientRect().width-t.clientWidth;return document.body.removeChild(t),e}(),"px"))}function me(){return!!window.MSInputMethodContext&amp;&amp;!!document.documentMode}function he(){var t=k(),e=A();t.style.removeProperty("align-items"),e.offsetTop&lt;0&amp;&amp;(t.style.alignItems="flex-start")}var ge=function(){navigator.userAgent.match(/(CriOS|FxiOS|EdgiOS|YaBrowser|UCBrowser)/i)||A().scrollHeight&gt;window.innerHeight-44&amp;&amp;(k().style.paddingBottom="".concat(44,"px"))},ve=function(){var e,t=k();t.ontouchstart=function(t){e=be(t)},t.ontouchmove=function(t){e&amp;&amp;(t.preventDefault(),t.stopPropagation())}},be=function(t){var e=t.target,n=k();return!ye(t)&amp;&amp;!we(t)&amp;&amp;(e===n||!(ct(n)||"INPUT"===e.tagName||ct(P())&amp;&amp;P().contains(e)))},ye=function(t){return t.touches&amp;&amp;t.touches.length&amp;&amp;"stylus"===t.touches[0].touchType},we=function(t){return t.touches&amp;&amp;1&lt;t.touches.length},Ce={swalPromiseResolve:new WeakMap};function ke(t,e,n,o){n?Ee(t,o):($t().then(function(){return Ee(t,o)}),te.keydownTarget.removeEventListener("keydown",te.keydownHandler,{capture:te.keydownListenerCapture}),te.keydownHandlerAdded=!1),e.parentNode&amp;&amp;!document.body.getAttribute("data-swal2-queue-step")&amp;&amp;e.parentNode.removeChild(e),N()&amp;&amp;(null!==tt.previousBodyPadding&amp;&amp;(document.body.style.paddingRight="".concat(tt.previousBodyPadding,"px"),tt.previousBodyPadding=null),_(document.body,$.iosfix)&amp;&amp;(e=parseInt(document.body.style.top,10),bt(document.body,$.iosfix),document.body.style.top="",document.body.scrollTop=-1*e),"undefined"!=typeof window&amp;&amp;me()&amp;&amp;window.removeEventListener("resize",he),g(document.body.children).forEach(function(t){t.hasAttribute("data-previous-aria-hidden")?(t.setAttribute("aria-hidden",t.getAttribute("data-previous-aria-hidden")),t.removeAttribute("data-previous-aria-hidden")):t.removeAttribute("aria-hidden")})),bt([document.documentElement,document.body],[$.shown,$["height-auto"],$["no-backdrop"],$["toast-shown"],$["toast-column"]])}function Ae(t){var e,n,o,i=A();i&amp;&amp;(t=xe(t),(e=Tt.innerParams.get(this))&amp;&amp;!_(i,e.hideClass.popup)&amp;&amp;(n=Ce.swalPromiseResolve.get(this),bt(i,e.showClass.popup),vt(i,e.hideClass.popup),o=k(),bt(o,e.showClass.backdrop),vt(o,e.hideClass.backdrop),Be(this,i,e),n(t)))}function xe(t){return void 0===t?{isConfirmed:!1,isDenied:!1,isDismissed:!0}:u({isConfirmed:!1,isDenied:!1,isDismissed:!1},t)}function Be(t,e,n){var o=k(),i=Bt&amp;&amp;lt(e),r=n.onClose,a=n.onAfterClose,s=n.willClose,n=n.didClose;Pe(e,s,r),i?Oe(t,e,o,n||a):ke(t,o,G(),n||a)}var Pe=function(t,e,n){null!==e&amp;&amp;"function"==typeof e?e(t):null!==n&amp;&amp;"function"==typeof n&amp;&amp;n(t)},Oe=function(t,e,n,o){te.swalCloseEventFinishedCallback=ke.bind(null,t,n,G(),o),e.addEventListener(Bt,function(t){t.target===e&amp;&amp;(te.swalCloseEventFinishedCallback(),delete te.swalCloseEventFinishedCallback)})},Ee=function(t,e){setTimeout(function(){"function"==typeof e&amp;&amp;e(),t._destroy()})};function Se(t,e,n){var o=Tt.domCache.get(t);e.forEach(function(t){o[t].disabled=n})}function Te(t,e){if(!t)return!1;if("radio"===t.type)for(var n=t.parentNode.parentNode.querySelectorAll("input"),o=0;o&lt;n.length;o++)n[o].disabled=e;else t.disabled=e}var Le=function(){function n(t,e){a(this,n),this.callback=t,this.remaining=e,this.running=!1,this.start()}return s(n,[{key:"start",value:function(){return this.running||(this.running=!0,this.started=new Date,this.id=setTimeout(this.callback,this.remaining)),this.remaining}},{key:"stop",value:function(){return this.running&amp;&amp;(this.running=!1,clearTimeout(this.id),this.remaining-=new Date-this.started),this.remaining}},{key:"increase",value:function(t){var e=this.running;return e&amp;&amp;this.stop(),this.remaining+=t,e&amp;&amp;this.start(),this.remaining}},{key:"getTimerLeft",value:function(){return this.running&amp;&amp;(this.stop(),this.start()),this.remaining}},{key:"isRunning",value:function(){return this.running}}]),n}(),De={email:function(t,e){return/^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(t)?Promise.resolve():Promise.resolve(e||"Invalid email address")},url:function(t,e){return/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&amp;/=]*)$/.test(t)?Promise.resolve():Promise.resolve(e||"Invalid URL")}};function qe(t){var e,n;(e=t).inputValidator||Object.keys(De).forEach(function(t){e.input===t&amp;&amp;(e.inputValidator=De[t])}),t.showLoaderOnConfirm&amp;&amp;!t.preConfirm&amp;&amp;W("showLoaderOnConfirm is set to true, but preConfirm is not defined.\nshowLoaderOnConfirm should be used together with preConfirm, see usage example:\nhttps://sweetalert2.github.io/#ajax-request"),t.animation=Z(t.animation),(n=t).target&amp;&amp;("string"!=typeof n.target||document.querySelector(n.target))&amp;&amp;("string"==typeof n.target||n.target.appendChild)||(W('Target parameter is not valid, defaulting to "body"'),n.target="body"),"string"==typeof t.title&amp;&amp;(t.title=t.title.split("\n").join("&lt;br /&gt;")),kt(t)}function je(t){var e=k(),n=A();"function"==typeof t.willOpen?t.willOpen(n):"function"==typeof t.onBeforeOpen&amp;&amp;t.onBeforeOpen(n);var o=window.getComputedStyle(document.body).overflowY;Je(e,n,t),setTimeout(function(){Ze(e,n)},10),N()&amp;&amp;(Qe(e,t.scrollbarPadding,o),g(document.body.children).forEach(function(t){t===k()||function(t,e){if("function"==typeof t.contains)return t.contains(e)}(t,k())||(t.hasAttribute("aria-hidden")&amp;&amp;t.setAttribute("data-previous-aria-hidden",t.getAttribute("aria-hidden")),t.setAttribute("aria-hidden","true"))})),G()||te.previousActiveElement||(te.previousActiveElement=document.activeElement),Ye(n,t),bt(e,$["no-transition"])}function Me(t){var e=A();t.target===e&amp;&amp;(t=k(),e.removeEventListener(Bt,Me),t.style.overflowY="auto")}function Ie(t,e){t.closePopup({isConfirmed:!0,value:e})}function He(t,e,n){var o=R();if(o.length)return(e+=n)===o.length?e=0:-1===e&amp;&amp;(e=o.length-1),o[e].focus();A().focus()}var Ve=["swal-title","swal-html","swal-footer"],Re=function(t){var n={};return g(t.querySelectorAll("swal-param")).forEach(function(t){Ke(t,["name","value"]);var e=t.getAttribute("name"),t=t.getAttribute("value");"boolean"==typeof se[e]&amp;&amp;"false"===t&amp;&amp;(t=!1),"object"===r(se[e])&amp;&amp;(t=JSON.parse(t)),n[e]=t}),n},Ne=function(t){var n={};return g(t.querySelectorAll("swal-button")).forEach(function(t){Ke(t,["type","color","aria-label"]);var e=t.getAttribute("type");n["".concat(e,"ButtonText")]=t.innerHTML,n["show".concat(m(e),"Button")]=!0,t.hasAttribute("color")&amp;&amp;(n["".concat(e,"ButtonColor")]=t.getAttribute("color")),t.hasAttribute("aria-label")&amp;&amp;(n["".concat(e,"ButtonAriaLabel")]=t.getAttribute("aria-label"))}),n},Ue=function(t){var e={},t=t.querySelector("swal-image");return t&amp;&amp;(Ke(t,["src","width","height","alt"]),t.hasAttribute("src")&amp;&amp;(e.imageUrl=t.getAttribute("src")),t.hasAttribute("width")&amp;&amp;(e.imageWidth=t.getAttribute("width")),t.hasAttribute("height")&amp;&amp;(e.imageHeight=t.getAttribute("height")),t.hasAttribute("alt")&amp;&amp;(e.imageAlt=t.getAttribute("alt"))),e},_e=function(t){var e={},t=t.querySelector("swal-icon");return t&amp;&amp;(Ke(t,["type","color"]),t.hasAttribute("type")&amp;&amp;(e.icon=t.getAttribute("type")),t.hasAttribute("color")&amp;&amp;(e.iconColor=t.getAttribute("color")),e.iconHtml=t.innerHTML),e},Fe=function(t){var n={},e=t.querySelector("swal-input");e&amp;&amp;(Ke(e,["type","label","placeholder","value"]),n.input=e.getAttribute("type")||"text",e.hasAttribute("label")&amp;&amp;(n.inputLabel=e.getAttribute("label")),e.hasAttribute("placeholder")&amp;&amp;(n.inputPlaceholder=e.getAttribute("placeholder")),e.hasAttribute("value")&amp;&amp;(n.inputValue=e.getAttribute("value")));t=t.querySelectorAll("swal-input-option");return t.length&amp;&amp;(n.inputOptions={},g(t).forEach(function(t){Ke(t,["value"]);var e=t.getAttribute("value"),t=t.innerHTML;n.inputOptions[e]=t})),n},ze=function(t,e){var n,o={};for(n in e){var i=e[n],r=t.querySelector(i);r&amp;&amp;(Ke(r,[]),o[i.replace(/^swal-/,"")]=r.innerHTML)}return o},We=function(e){var n=Ve.concat(["swal-param","swal-button","swal-image","swal-icon","swal-input","swal-input-option"]);g(e.querySelectorAll("*")).forEach(function(t){t.parentNode===e&amp;&amp;(t=t.tagName.toLowerCase(),-1===n.indexOf(t)&amp;&amp;W("Unrecognized element &lt;".concat(t,"&gt;")))})},Ke=function(e,n){g(e.attributes).forEach(function(t){-1===n.indexOf(t.name)&amp;&amp;W(['Unrecognized attribute "'.concat(t.name,'" on &lt;').concat(e.tagName.toLowerCase(),"&gt;."),"".concat(n.length?"Allowed attributes are: ".concat(n.join(", ")):"To set the value, use HTML within the element.")])})},Ye=function(t,e){"function"==typeof e.didOpen?setTimeout(function(){return e.didOpen(t)}):"function"==typeof e.onOpen&amp;&amp;setTimeout(function(){return e.onOpen(t)})},Ze=function(t,e){Bt&amp;&amp;lt(e)?(t.style.overflowY="hidden",e.addEventListener(Bt,Me)):t.style.overflowY="auto"},Qe=function(t,e,n){var o;(/iPad|iPhone|iPod/.test(navigator.userAgent)&amp;&amp;!window.MSStream||"MacIntel"===navigator.platform&amp;&amp;1&lt;navigator.maxTouchPoints)&amp;&amp;!_(document.body,$.iosfix)&amp;&amp;(o=document.body.scrollTop,document.body.style.top="".concat(-1*o,"px"),vt(document.body,$.iosfix),ve(),ge()),"undefined"!=typeof window&amp;&amp;me()&amp;&amp;(he(),window.addEventListener("resize",he)),e&amp;&amp;"hidden"!==n&amp;&amp;fe(),setTimeout(function(){t.scrollTop=0})},Je=function(t,e,n){vt(t,n.showClass.backdrop),e.style.setProperty("opacity","0","important"),rt(e),setTimeout(function(){vt(e,n.showClass.popup),e.style.removeProperty("opacity")},10),vt([document.documentElement,document.body],$.shown),n.heightAuto&amp;&amp;n.backdrop&amp;&amp;!n.toast&amp;&amp;vt([document.documentElement,document.body],$["height-auto"])},$e=function(t){return t.checked?1:0},Xe=function(t){return t.checked?t.value:null},Ge=function(t){return t.files.length?null!==t.getAttribute("multiple")?t.files:t.files[0]:null},tn=function(e,n){function o(t){return nn[n.input](i,on(t),n)}var i=P();b(n.inputOptions)||w(n.inputOptions)?(Jt(T()),y(n.inputOptions).then(function(t){e.hideLoading(),o(t)})):"object"===r(n.inputOptions)?o(n.inputOptions):K("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(r(n.inputOptions)))},en=function(e,n){var o=e.getInput();at(o),y(n.inputValue).then(function(t){o.value="number"===n.input?parseFloat(t)||0:"".concat(t),rt(o),o.focus(),e.hideLoading()}).catch(function(t){K("Error in inputValue promise: ".concat(t)),o.value="",rt(o),o.focus(),e.hideLoading()})},nn={select:function(t,e,i){function o(t,e,n){var o=document.createElement("option");o.value=n,U(o,e),o.selected=rn(n,i.inputValue),t.appendChild(o)}var r=yt(t,$.select);e.forEach(function(t){var e,n=t[0],t=t[1];Array.isArray(t)?((e=document.createElement("optgroup")).label=n,e.disabled=!1,r.appendChild(e),t.forEach(function(t){return o(e,t[1],t[0])})):o(r,t,n)}),r.focus()},radio:function(t,e,i){var r=yt(t,$.radio);e.forEach(function(t){var e=t[0],n=t[1],o=document.createElement("input"),t=document.createElement("label");o.type="radio",o.name=$.radio,o.value=e,rn(e,i.inputValue)&amp;&amp;(o.checked=!0);e=document.createElement("span");U(e,n),e.className=$.label,t.appendChild(o),t.appendChild(e),r.appendChild(t)});e=r.querySelectorAll("input");e.length&amp;&amp;e[0].focus()}},on=function n(o){var i=[];return"undefined"!=typeof Map&amp;&amp;o instanceof Map?o.forEach(function(t,e){"object"===r(t)&amp;&amp;(t=n(t)),i.push([e,t])}):Object.keys(o).forEach(function(t){var e=o[t];"object"===r(e)&amp;&amp;(e=n(e)),i.push([t,e])}),i},rn=function(t,e){return e&amp;&amp;e.toString()===t.toString()},an=function(t,e,n){var o=function(t,e){var n=t.getInput();if(!n)return null;switch(e.input){case"checkbox":return $e(n);case"radio":return Xe(n);case"file":return Ge(n);default:return e.inputAutoTrim?n.value.trim():n.value}}(t,e);e.inputValidator?sn(t,e,o):t.getInput().checkValidity()?("deny"===n?un:cn)(t,e,o):(t.enableButtons(),t.showValidationMessage(e.validationMessage))},sn=function(e,n,o){e.disableInput(),Promise.resolve().then(function(){return y(n.inputValidator(o,n.validationMessage))}).then(function(t){e.enableButtons(),e.enableInput(),t?e.showValidationMessage(t):cn(e,n,o)})},un=function(e,t,n){t.showLoaderOnDeny&amp;&amp;Jt(L()),t.preDeny?Promise.resolve().then(function(){return y(t.preDeny(n,t.validationMessage))}).then(function(t){!1===t?e.hideLoading():e.closePopup({isDenied:!0,value:void 0===t?n:t})}):e.closePopup({isDenied:!0,value:n})},cn=function(e,t,n){t.showLoaderOnConfirm&amp;&amp;Jt(),t.preConfirm?(e.resetValidationMessage(),Promise.resolve().then(function(){return y(t.preConfirm(n,t.validationMessage))}).then(function(t){wt(S())||!1===t?e.hideLoading():Ie(e,void 0===t?n:t)})):Ie(e,n)},ln=["ArrowRight","ArrowDown","Right","Down"],dn=["ArrowLeft","ArrowUp","Left","Up"],pn=["Escape","Esc"],fn=function(t,e,n){var o=Tt.innerParams.get(t);o&amp;&amp;(o.stopKeydownPropagation&amp;&amp;e.stopPropagation(),"Enter"===e.key?mn(t,e,o):"Tab"===e.key?hn(e,o):-1!==[].concat(ln,dn).indexOf(e.key)?gn(e.key):-1!==pn.indexOf(e.key)&amp;&amp;vn(e,o,n))},mn=function(t,e,n){e.isComposing||e.target&amp;&amp;t.getInput()&amp;&amp;e.target.outerHTML===t.getInput().outerHTML&amp;&amp;-1===["textarea","file"].indexOf(n.input)&amp;&amp;(_t(),e.preventDefault())},hn=function(t,e){for(var n=t.target,o=R(),i=-1,r=0;r&lt;o.length;r++)if(n===o[r]){i=r;break}t.shiftKey?He(0,i,-1):He(0,i,1),t.stopPropagation(),t.preventDefault()},gn=function(t){-1!==[T(),L(),q()].indexOf(document.activeElement)&amp;&amp;(t=-1!==ln.indexOf(t)?"nextElementSibling":"previousElementSibling",(t=document.activeElement[t])&amp;&amp;t.focus())},vn=function(t,e,n){Z(e.allowEscapeKey)&amp;&amp;(t.preventDefault(),n(Q.esc))},bn=function(e,t,n){t.popup.onclick=function(){var t=Tt.innerParams.get(e);t.showConfirmButton||t.showDenyButton||t.showCancelButton||t.showCloseButton||t.timer||t.input||n(Q.close)}},yn=!1,wn=function(e){e.popup.onmousedown=function(){e.container.onmouseup=function(t){e.container.onmouseup=void 0,t.target===e.container&amp;&amp;(yn=!0)}}},Cn=function(e){e.container.onmousedown=function(){e.popup.onmouseup=function(t){e.popup.onmouseup=void 0,t.target!==e.popup&amp;&amp;!e.popup.contains(t.target)||(yn=!0)}}},kn=function(n,o,i){o.container.onclick=function(t){var e=Tt.innerParams.get(n);yn?yn=!1:t.target===o.container&amp;&amp;Z(e.allowOutsideClick)&amp;&amp;i(Q.backdrop)}};function An(t,e){var n=function(t){t="string"==typeof t.template?document.querySelector(t.template):t.template;if(!t)return{};t=t.content||t;return We(t),u(Re(t),Ne(t),Ue(t),_e(t),Fe(t),ze(t,Ve))}(t),o=u({},se.showClass,e.showClass,n.showClass,t.showClass),i=u({},se.hideClass,e.hideClass,n.hideClass,t.hideClass);return(n=u({},se,e,n,t)).showClass=o,n.hideClass=i,!1===t.animation&amp;&amp;(n.showClass={popup:"swal2-noanimation",backdrop:"swal2-noanimation"},n.hideClass={}),n}function xn(a,s,u){return new Promise(function(t){function e(t){a.closePopup({isDismissed:!0,dismiss:t})}var n,o,i,r;Ce.swalPromiseResolve.set(a,t),s.confirmButton.onclick=function(){return e=u,(t=a).disableButtons(),void(e.input?an(t,e,"confirm"):cn(t,e,!0));var t,e},s.denyButton.onclick=function(){return e=u,(t=a).disableButtons(),void(e.returnInputValueOnDeny?an(t,e,"deny"):un(t,e,!1));var t,e},s.cancelButton.onclick=function(){return t=e,a.disableButtons(),void t(Q.cancel);var t},s.closeButton.onclick=function(){return e(Q.close)},n=a,r=s,t=e,Tt.innerParams.get(n).toast?bn(n,r,t):(wn(r),Cn(r),kn(n,r,t)),o=a,r=u,i=e,(t=te).keydownTarget&amp;&amp;t.keydownHandlerAdded&amp;&amp;(t.keydownTarget.removeEventListener("keydown",t.keydownHandler,{capture:t.keydownListenerCapture}),t.keydownHandlerAdded=!1),r.toast||(t.keydownHandler=function(t){return fn(o,t,i)},t.keydownTarget=r.keydownListenerCapture?window:A(),t.keydownListenerCapture=r.keydownListenerCapture,t.keydownTarget.addEventListener("keydown",t.keydownHandler,{capture:t.keydownListenerCapture}),t.keydownHandlerAdded=!0),(u.toast&amp;&amp;(u.input||u.footer||u.showCloseButton)?vt:bt)(document.body,$["toast-column"]),r=a,"select"===(t=u).input||"radio"===t.input?tn(r,t):-1!==["text","email","number","tel","textarea"].indexOf(t.input)&amp;&amp;(b(t.inputValue)||w(t.inputValue))&amp;&amp;en(r,t),je(u),Pn(te,u,e),On(s,u),setTimeout(function(){s.container.scrollTop=0})})}function Bn(t){var e={popup:A(),container:k(),content:P(),actions:j(),confirmButton:T(),denyButton:L(),cancelButton:q(),loader:D(),closeButton:V(),validationMessage:S(),progressSteps:n()};return Tt.domCache.set(t,e),e}var Pn=function(t,e,n){var o=H();at(o),e.timer&amp;&amp;(t.timeout=new Le(function(){n("timer"),delete t.timeout},e.timer),e.timerProgressBar&amp;&amp;(rt(o),setTimeout(function(){t.timeout&amp;&amp;t.timeout.running&amp;&amp;dt(e.timer)})))},On=function(t,e){if(!e.toast)return Z(e.allowEnterKey)?void(En(t,e)||He(0,-1,1)):Sn()},En=function(t,e){return e.focusDeny&amp;&amp;wt(t.denyButton)?(t.denyButton.focus(),!0):e.focusCancel&amp;&amp;wt(t.cancelButton)?(t.cancelButton.focus(),!0):!(!e.focusConfirm||!wt(t.confirmButton))&amp;&amp;(t.confirmButton.focus(),!0)},Sn=function(){document.activeElement&amp;&amp;"function"==typeof document.activeElement.blur&amp;&amp;document.activeElement.blur()};function Tn(t){"function"==typeof t.didDestroy?t.didDestroy():"function"==typeof t.onDestroy&amp;&amp;t.onDestroy()}function Ln(t){delete t.params,delete te.keydownHandler,delete te.keydownTarget,qn(Tt),qn(Ce)}var Dn,qn=function(t){for(var e in t)t[e]=new WeakMap},J=Object.freeze({hideLoading:pe,disableLoading:pe,getInput:function(t){var e=Tt.innerParams.get(t||this);return(t=Tt.domCache.get(t||this))?et(t.content,e.input):null},close:Ae,closePopup:Ae,closeModal:Ae,closeToast:Ae,enableButtons:function(){Se(this,["confirmButton","denyButton","cancelButton"],!1)},disableButtons:function(){Se(this,["confirmButton","denyButton","cancelButton"],!0)},enableInput:function(){return Te(this.getInput(),!1)},disableInput:function(){return Te(this.getInput(),!0)},showValidationMessage:function(t){var e=Tt.domCache.get(this),n=Tt.innerParams.get(this);U(e.validationMessage,t),e.validationMessage.className=$["validation-message"],n.customClass&amp;&amp;n.customClass.validationMessage&amp;&amp;vt(e.validationMessage,n.customClass.validationMessage),rt(e.validationMessage),(e=this.getInput())&amp;&amp;(e.setAttribute("aria-invalid",!0),e.setAttribute("aria-describedBy",$["validation-message"]),nt(e),vt(e,$.inputerror))},resetValidationMessage:function(){var t=Tt.domCache.get(this);t.validationMessage&amp;&amp;at(t.validationMessage),(t=this.getInput())&amp;&amp;(t.removeAttribute("aria-invalid"),t.removeAttribute("aria-describedBy"),bt(t,$.inputerror))},getProgressSteps:function(){return Tt.domCache.get(this).progressSteps},_main:function(t){var e=1&lt;arguments.length&amp;&amp;void 0!==arguments[1]?arguments[1]:{};return ae(u({},e,t)),te.currentInstance&amp;&amp;te.currentInstance._destroy(),te.currentInstance=this,qe(t=An(t,e)),Object.freeze(t),te.timeout&amp;&amp;(te.timeout.stop(),delete te.timeout),clearTimeout(te.restoreFocusTimeout),e=Bn(this),Ut(this,t),Tt.innerParams.set(this,t),xn(this,e,t)},update:function(e){var t=A(),n=Tt.innerParams.get(this);if(!t||_(t,n.hideClass.popup))return W("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");var o={};Object.keys(e).forEach(function(t){Mn.isUpdatableParameter(t)?o[t]=e[t]:W('Invalid parameter to update: "'.concat(t,'". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md'))}),n=u({},n,o),Ut(this,n),Tt.innerParams.set(this,n),Object.defineProperties(this,{params:{value:u({},this.params,e),writable:!1,enumerable:!0}})},_destroy:function(){var t=Tt.domCache.get(this),e=Tt.innerParams.get(this);e&amp;&amp;(t.popup&amp;&amp;te.swalCloseEventFinishedCallback&amp;&amp;(te.swalCloseEventFinishedCallback(),delete te.swalCloseEventFinishedCallback),te.deferDisposalTimer&amp;&amp;(clearTimeout(te.deferDisposalTimer),delete te.deferDisposalTimer),Tn(e),Ln(this))}}),jn=function(){function i(){if(a(this,i),"undefined"!=typeof window){"undefined"==typeof Promise&amp;&amp;K("This package requires a Promise library, please include a shim to enable it in this browser (See: https://github.com/sweetalert2/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2#1-ie-support)"),Dn=this;for(var t=arguments.length,e=new Array(t),n=0;n&lt;t;n++)e[n]=arguments[n];var o=Object.freeze(this.constructor.argsToParams(e));Object.defineProperties(this,{params:{value:o,writable:!1,enumerable:!0,configurable:!0}});o=this._main(this.params);Tt.promise.set(this,o)}}return s(i,[{key:"then",value:function(t){return Tt.promise.get(this).then(t)}},{key:"finally",value:function(t){return Tt.promise.get(this).finally(t)}}]),i}();u(jn.prototype,J),u(jn,de),Object.keys(J).forEach(function(t){jn[t]=function(){if(Dn)return Dn[t].apply(Dn,arguments)}}),jn.DismissReason=Q,jn.version="10.15.7";var Mn=jn;return Mn.default=Mn}),void 0!==this&amp;&amp;this.Sweetalert2&amp;&amp;(this.swal=this.sweetAlert=this.Swal=this.SweetAlert=this.Sweetalert2);
"undefined"!=typeof document&amp;&amp;function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,".swal2-popup.swal2-toast{flex-direction:row;align-items:center;width:auto;padding:.625em;overflow-y:hidden;background:#fff;box-shadow:0 0 .625em #d9d9d9}.swal2-popup.swal2-toast .swal2-header{flex-direction:row;padding:0}.swal2-popup.swal2-toast .swal2-title{flex-grow:1;justify-content:flex-start;margin:0 .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{position:static;width:.8em;height:.8em;line-height:.8}.swal2-popup.swal2-toast .swal2-content{justify-content:flex-start;padding:0;font-size:1em}.swal2-popup.swal2-toast .swal2-icon{width:2em;min-width:2em;height:2em;margin:0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:700}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{font-size:.25em}}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{flex-basis:auto!important;width:auto;height:auto;margin:0 .3125em;padding:0}.swal2-popup.swal2-toast .swal2-styled{margin:.125em .3125em;padding:.3125em .625em;font-size:1em}.swal2-popup.swal2-toast .swal2-styled:focus{box-shadow:0 0 0 1px #fff,0 0 0 3px rgba(100,150,200,.5)}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-container{display:flex;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;flex-direction:row;align-items:center;justify-content:center;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:0 0!important}.swal2-container.swal2-top{align-items:flex-start}.swal2-container.swal2-top-left,.swal2-container.swal2-top-start{align-items:flex-start;justify-content:flex-start}.swal2-container.swal2-top-end,.swal2-container.swal2-top-right{align-items:flex-start;justify-content:flex-end}.swal2-container.swal2-center{align-items:center}.swal2-container.swal2-center-left,.swal2-container.swal2-center-start{align-items:center;justify-content:flex-start}.swal2-container.swal2-center-end,.swal2-container.swal2-center-right{align-items:center;justify-content:flex-end}.swal2-container.swal2-bottom{align-items:flex-end}.swal2-container.swal2-bottom-left,.swal2-container.swal2-bottom-start{align-items:flex-end;justify-content:flex-start}.swal2-container.swal2-bottom-end,.swal2-container.swal2-bottom-right{align-items:flex-end;justify-content:flex-end}.swal2-container.swal2-bottom-end&gt;:first-child,.swal2-container.swal2-bottom-left&gt;:first-child,.swal2-container.swal2-bottom-right&gt;:first-child,.swal2-container.swal2-bottom-start&gt;:first-child,.swal2-container.swal2-bottom&gt;:first-child{margin-top:auto}.swal2-container.swal2-grow-fullscreen&gt;.swal2-modal{display:flex!important;flex:1;align-self:stretch;justify-content:center}.swal2-container.swal2-grow-row&gt;.swal2-modal{display:flex!important;flex:1;align-content:center;justify-content:center}.swal2-container.swal2-grow-column{flex:1;flex-direction:column}.swal2-container.swal2-grow-column.swal2-bottom,.swal2-container.swal2-grow-column.swal2-center,.swal2-container.swal2-grow-column.swal2-top{align-items:center}.swal2-container.swal2-grow-column.swal2-bottom-left,.swal2-container.swal2-grow-column.swal2-bottom-start,.swal2-container.swal2-grow-column.swal2-center-left,.swal2-container.swal2-grow-column.swal2-center-start,.swal2-container.swal2-grow-column.swal2-top-left,.swal2-container.swal2-grow-column.swal2-top-start{align-items:flex-start}.swal2-container.swal2-grow-column.swal2-bottom-end,.swal2-container.swal2-grow-column.swal2-bottom-right,.swal2-container.swal2-grow-column.swal2-center-end,.swal2-container.swal2-grow-column.swal2-center-right,.swal2-container.swal2-grow-column.swal2-top-end,.swal2-container.swal2-grow-column.swal2-top-right{align-items:flex-end}.swal2-container.swal2-grow-column&gt;.swal2-modal{display:flex!important;flex:1;align-content:center;justify-content:center}.swal2-container.swal2-no-transition{transition:none!important}.swal2-container:not(.swal2-top):not(.swal2-top-start):not(.swal2-top-end):not(.swal2-top-left):not(.swal2-top-right):not(.swal2-center-start):not(.swal2-center-end):not(.swal2-center-left):not(.swal2-center-right):not(.swal2-bottom):not(.swal2-bottom-start):not(.swal2-bottom-end):not(.swal2-bottom-left):not(.swal2-bottom-right):not(.swal2-grow-fullscreen)&gt;.swal2-modal{margin:auto}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-container .swal2-modal{margin:0!important}}.swal2-popup{display:none;position:relative;box-sizing:border-box;flex-direction:column;justify-content:center;width:32em;max-width:100%;padding:1.25em;border:none;border-radius:5px;background:#fff;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-header{display:flex;flex-direction:column;align-items:center;padding:0 1.8em}.swal2-title{position:relative;max-width:100%;margin:0 0 .4em;padding:0;color:#595959;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:100%;margin:1.25em auto 0;padding:0 1.6em}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 transparent #2778c4 transparent}.swal2-styled{margin:.3125em;padding:.625em 1.1em;box-shadow:none;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#2778c4;color:#fff;font-size:1.0625em}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#d14529;color:#fff;font-size:1.0625em}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#757575;color:#fff;font-size:1.0625em}.swal2-styled:focus{outline:0;box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1.25em 0 0;padding:1em 0 0;border-top:1px solid #eee;color:#545454;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;height:.25em;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:1.25em auto}.swal2-close{position:absolute;z-index:2;top:0;right:0;align-items:center;justify-content:center;width:1.2em;height:1.2em;padding:0;overflow:hidden;transition:color .1s ease-out;border:none;border-radius:5px;background:0 0;color:#ccc;font-family:serif;font-size:2.5em;line-height:1.2;cursor:pointer}.swal2-close:hover{transform:none;background:0 0;color:#f27474}.swal2-close:focus{outline:0;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-content{z-index:1;justify-content:center;margin:0;padding:0 1.6em;color:#545454;font-size:1.125em;font-weight:400;line-height:normal;text-align:center;word-wrap:break-word}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em auto}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:100%;transition:border-color .3s,box-shadow .3s;border:1px solid #d9d9d9;border-radius:.1875em;background:inherit;box-shadow:inset 0 1px 1px rgba(0,0,0,.06);color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em auto;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-input[type=number]{max-width:10em}.swal2-file{background:inherit;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:inherit;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto}.swal2-validation-message{align-items:center;justify-content:center;margin:0 -2.7em;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:1.25em auto 1.875em;border:.25em solid transparent;border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:0 0 1.25em;padding:0;background:inherit;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{right:auto;left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@supports (-ms-accelerator:true){.swal2-range input{width:100%!important}.swal2-range output{display:none}}@media all and (-ms-high-contrast:none),(-ms-high-contrast:active){.swal2-range input{width:100%!important}.swal2-range output{display:none}}@-webkit-keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@-webkit-keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@-webkit-keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-container{top:auto;right:auto;bottom:auto;left:auto;max-width:calc(100% - .625em * 2);background-color:transparent!important}body.swal2-no-backdrop .swal2-container&gt;.swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}body.swal2-no-backdrop .swal2-container.swal2-top{top:0;left:50%;transform:translateX(-50%)}body.swal2-no-backdrop .swal2-container.swal2-top-left,body.swal2-no-backdrop .swal2-container.swal2-top-start{top:0;left:0}body.swal2-no-backdrop .swal2-container.swal2-top-end,body.swal2-no-backdrop .swal2-container.swal2-top-right{top:0;right:0}body.swal2-no-backdrop .swal2-container.swal2-center{top:50%;left:50%;transform:translate(-50%,-50%)}body.swal2-no-backdrop .swal2-container.swal2-center-left,body.swal2-no-backdrop .swal2-container.swal2-center-start{top:50%;left:0;transform:translateY(-50%)}body.swal2-no-backdrop .swal2-container.swal2-center-end,body.swal2-no-backdrop .swal2-container.swal2-center-right{top:50%;right:0;transform:translateY(-50%)}body.swal2-no-backdrop .swal2-container.swal2-bottom{bottom:0;left:50%;transform:translateX(-50%)}body.swal2-no-backdrop .swal2-container.swal2-bottom-left,body.swal2-no-backdrop .swal2-container.swal2-bottom-start{bottom:0;left:0}body.swal2-no-backdrop .swal2-container.swal2-bottom-end,body.swal2-no-backdrop .swal2-container.swal2-bottom-right{right:0;bottom:0}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)&gt;[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}body.swal2-toast-shown .swal2-container{background-color:transparent}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}body.swal2-toast-column .swal2-toast{flex-direction:column;align-items:stretch}body.swal2-toast-column .swal2-toast .swal2-actions{flex:1;align-self:stretch;height:2.2em;margin-top:.3125em}body.swal2-toast-column .swal2-toast .swal2-loading{justify-content:center}body.swal2-toast-column .swal2-toast .swal2-input{height:2em;margin:.3125em auto;font-size:1em}body.swal2-toast-column .swal2-toast .swal2-validation-message{font-size:1em}");
/**
 * Copyright (c) Tiny Technologies, Inc. All rights reserved.
 * Licensed under the LGPL or a commercial license.
 * For LGPL see License.txt in the project root for license information.
 * For commercial licenses see https://www.tiny.cloud/
 *
 * Version: 5.8.2 (2021-06-23)
 */
(function () {
    'use strict';

    var typeOf = function (x) {
      if (x === null) {
        return 'null';
      }
      if (x === undefined) {
        return 'undefined';
      }
      var t = typeof x;
      if (t === 'object' &amp;&amp; (Array.prototype.isPrototypeOf(x) || x.constructor &amp;&amp; x.constructor.name === 'Array')) {
        return 'array';
      }
      if (t === 'object' &amp;&amp; (String.prototype.isPrototypeOf(x) || x.constructor &amp;&amp; x.constructor.name === 'String')) {
        return 'string';
      }
      return t;
    };
    var isEquatableType = function (x) {
      return [
        'undefined',
        'boolean',
        'number',
        'string',
        'function',
        'xml',
        'null'
      ].indexOf(x) !== -1;
    };

    var sort = function (xs, compareFn) {
      var clone = Array.prototype.slice.call(xs);
      return clone.sort(compareFn);
    };

    var contramap = function (eqa, f) {
      return eq(function (x, y) {
        return eqa.eq(f(x), f(y));
      });
    };
    var eq = function (f) {
      return { eq: f };
    };
    var tripleEq = eq(function (x, y) {
      return x === y;
    });
    var eqString = tripleEq;
    var eqArray = function (eqa) {
      return eq(function (x, y) {
        if (x.length !== y.length) {
          return false;
        }
        var len = x.length;
        for (var i = 0; i &lt; len; i++) {
          if (!eqa.eq(x[i], y[i])) {
            return false;
          }
        }
        return true;
      });
    };
    var eqSortedArray = function (eqa, compareFn) {
      return contramap(eqArray(eqa), function (xs) {
        return sort(xs, compareFn);
      });
    };
    var eqRecord = function (eqa) {
      return eq(function (x, y) {
        var kx = Object.keys(x);
        var ky = Object.keys(y);
        if (!eqSortedArray(eqString).eq(kx, ky)) {
          return false;
        }
        var len = kx.length;
        for (var i = 0; i &lt; len; i++) {
          var q = kx[i];
          if (!eqa.eq(x[q], y[q])) {
            return false;
          }
        }
        return true;
      });
    };
    var eqAny = eq(function (x, y) {
      if (x === y) {
        return true;
      }
      var tx = typeOf(x);
      var ty = typeOf(y);
      if (tx !== ty) {
        return false;
      }
      if (isEquatableType(tx)) {
        return x === y;
      } else if (tx === 'array') {
        return eqArray(eqAny).eq(x, y);
      } else if (tx === 'object') {
        return eqRecord(eqAny).eq(x, y);
      }
      return false;
    });

    var typeOf$1 = function (x) {
      var t = typeof x;
      if (x === null) {
        return 'null';
      } else if (t === 'object' &amp;&amp; (Array.prototype.isPrototypeOf(x) || x.constructor &amp;&amp; x.constructor.name === 'Array')) {
        return 'array';
      } else if (t === 'object' &amp;&amp; (String.prototype.isPrototypeOf(x) || x.constructor &amp;&amp; x.constructor.name === 'String')) {
        return 'string';
      } else {
        return t;
      }
    };
    var isType = function (type) {
      return function (value) {
        return typeOf$1(value) === type;
      };
    };
    var isSimpleType = function (type) {
      return function (value) {
        return typeof value === type;
      };
    };
    var eq$1 = function (t) {
      return function (a) {
        return t === a;
      };
    };
    var isString = isType('string');
    var isObject = isType('object');
    var isArray = isType('array');
    var isNull = eq$1(null);
    var isBoolean = isSimpleType('boolean');
    var isUndefined = eq$1(undefined);
    var isNullable = function (a) {
      return a === null || a === undefined;
    };
    var isNonNullable = function (a) {
      return !isNullable(a);
    };
    var isFunction = isSimpleType('function');
    var isNumber = isSimpleType('number');

    var noop = function () {
    };
    var compose = function (fa, fb) {
      return function () {
        var args = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return fa(fb.apply(null, args));
      };
    };
    var compose1 = function (fbc, fab) {
      return function (a) {
        return fbc(fab(a));
      };
    };
    var constant = function (value) {
      return function () {
        return value;
      };
    };
    var identity = function (x) {
      return x;
    };
    function curry(fn) {
      var initialArgs = [];
      for (var _i = 1; _i &lt; arguments.length; _i++) {
        initialArgs[_i - 1] = arguments[_i];
      }
      return function () {
        var restArgs = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          restArgs[_i] = arguments[_i];
        }
        var all = initialArgs.concat(restArgs);
        return fn.apply(null, all);
      };
    }
    var not = function (f) {
      return function (t) {
        return !f(t);
      };
    };
    var die = function (msg) {
      return function () {
        throw new Error(msg);
      };
    };
    var apply = function (f) {
      return f();
    };
    var call = function (f) {
      f();
    };
    var never = constant(false);
    var always = constant(true);

    var none = function () {
      return NONE;
    };
    var NONE = function () {
      var eq = function (o) {
        return o.isNone();
      };
      var call = function (thunk) {
        return thunk();
      };
      var id = function (n) {
        return n;
      };
      var me = {
        fold: function (n, _s) {
          return n();
        },
        is: never,
        isSome: never,
        isNone: always,
        getOr: id,
        getOrThunk: call,
        getOrDie: function (msg) {
          throw new Error(msg || 'error: getOrDie called on none.');
        },
        getOrNull: constant(null),
        getOrUndefined: constant(undefined),
        or: id,
        orThunk: call,
        map: none,
        each: noop,
        bind: none,
        exists: never,
        forall: always,
        filter: none,
        equals: eq,
        equals_: eq,
        toArray: function () {
          return [];
        },
        toString: constant('none()')
      };
      return me;
    }();
    var some = function (a) {
      var constant_a = constant(a);
      var self = function () {
        return me;
      };
      var bind = function (f) {
        return f(a);
      };
      var me = {
        fold: function (n, s) {
          return s(a);
        },
        is: function (v) {
          return a === v;
        },
        isSome: always,
        isNone: never,
        getOr: constant_a,
        getOrThunk: constant_a,
        getOrDie: constant_a,
        getOrNull: constant_a,
        getOrUndefined: constant_a,
        or: self,
        orThunk: self,
        map: function (f) {
          return some(f(a));
        },
        each: function (f) {
          f(a);
        },
        bind: bind,
        exists: bind,
        forall: bind,
        filter: function (f) {
          return f(a) ? me : NONE;
        },
        toArray: function () {
          return [a];
        },
        toString: function () {
          return 'some(' + a + ')';
        },
        equals: function (o) {
          return o.is(a);
        },
        equals_: function (o, elementEq) {
          return o.fold(never, function (b) {
            return elementEq(a, b);
          });
        }
      };
      return me;
    };
    var from = function (value) {
      return value === null || value === undefined ? NONE : some(value);
    };
    var Optional = {
      some: some,
      none: none,
      from: from
    };

    var nativeSlice = Array.prototype.slice;
    var nativeIndexOf = Array.prototype.indexOf;
    var nativePush = Array.prototype.push;
    var rawIndexOf = function (ts, t) {
      return nativeIndexOf.call(ts, t);
    };
    var indexOf = function (xs, x) {
      var r = rawIndexOf(xs, x);
      return r === -1 ? Optional.none() : Optional.some(r);
    };
    var contains = function (xs, x) {
      return rawIndexOf(xs, x) &gt; -1;
    };
    var exists = function (xs, pred) {
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        if (pred(x, i)) {
          return true;
        }
      }
      return false;
    };
    var map = function (xs, f) {
      var len = xs.length;
      var r = new Array(len);
      for (var i = 0; i &lt; len; i++) {
        var x = xs[i];
        r[i] = f(x, i);
      }
      return r;
    };
    var each = function (xs, f) {
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        f(x, i);
      }
    };
    var eachr = function (xs, f) {
      for (var i = xs.length - 1; i &gt;= 0; i--) {
        var x = xs[i];
        f(x, i);
      }
    };
    var partition = function (xs, pred) {
      var pass = [];
      var fail = [];
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        var arr = pred(x, i) ? pass : fail;
        arr.push(x);
      }
      return {
        pass: pass,
        fail: fail
      };
    };
    var filter = function (xs, pred) {
      var r = [];
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        if (pred(x, i)) {
          r.push(x);
        }
      }
      return r;
    };
    var foldr = function (xs, f, acc) {
      eachr(xs, function (x) {
        acc = f(acc, x);
      });
      return acc;
    };
    var foldl = function (xs, f, acc) {
      each(xs, function (x) {
        acc = f(acc, x);
      });
      return acc;
    };
    var findUntil = function (xs, pred, until) {
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        if (pred(x, i)) {
          return Optional.some(x);
        } else if (until(x, i)) {
          break;
        }
      }
      return Optional.none();
    };
    var find = function (xs, pred) {
      return findUntil(xs, pred, never);
    };
    var findIndex = function (xs, pred) {
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        if (pred(x, i)) {
          return Optional.some(i);
        }
      }
      return Optional.none();
    };
    var flatten = function (xs) {
      var r = [];
      for (var i = 0, len = xs.length; i &lt; len; ++i) {
        if (!isArray(xs[i])) {
          throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
        }
        nativePush.apply(r, xs[i]);
      }
      return r;
    };
    var bind = function (xs, f) {
      return flatten(map(xs, f));
    };
    var forall = function (xs, pred) {
      for (var i = 0, len = xs.length; i &lt; len; ++i) {
        var x = xs[i];
        if (pred(x, i) !== true) {
          return false;
        }
      }
      return true;
    };
    var reverse = function (xs) {
      var r = nativeSlice.call(xs, 0);
      r.reverse();
      return r;
    };
    var difference = function (a1, a2) {
      return filter(a1, function (x) {
        return !contains(a2, x);
      });
    };
    var mapToObject = function (xs, f) {
      var r = {};
      for (var i = 0, len = xs.length; i &lt; len; i++) {
        var x = xs[i];
        r[String(x)] = f(x, i);
      }
      return r;
    };
    var sort$1 = function (xs, comparator) {
      var copy = nativeSlice.call(xs, 0);
      copy.sort(comparator);
      return copy;
    };
    var get = function (xs, i) {
      return i &gt;= 0 &amp;&amp; i &lt; xs.length ? Optional.some(xs[i]) : Optional.none();
    };
    var head = function (xs) {
      return get(xs, 0);
    };
    var last = function (xs) {
      return get(xs, xs.length - 1);
    };
    var from$1 = isFunction(Array.from) ? Array.from : function (x) {
      return nativeSlice.call(x);
    };
    var findMap = function (arr, f) {
      for (var i = 0; i &lt; arr.length; i++) {
        var r = f(arr[i], i);
        if (r.isSome()) {
          return r;
        }
      }
      return Optional.none();
    };

    var keys = Object.keys;
    var hasOwnProperty = Object.hasOwnProperty;
    var each$1 = function (obj, f) {
      var props = keys(obj);
      for (var k = 0, len = props.length; k &lt; len; k++) {
        var i = props[k];
        var x = obj[i];
        f(x, i);
      }
    };
    var map$1 = function (obj, f) {
      return tupleMap(obj, function (x, i) {
        return {
          k: i,
          v: f(x, i)
        };
      });
    };
    var tupleMap = function (obj, f) {
      var r = {};
      each$1(obj, function (x, i) {
        var tuple = f(x, i);
        r[tuple.k] = tuple.v;
      });
      return r;
    };
    var objAcc = function (r) {
      return function (x, i) {
        r[i] = x;
      };
    };
    var internalFilter = function (obj, pred, onTrue, onFalse) {
      var r = {};
      each$1(obj, function (x, i) {
        (pred(x, i) ? onTrue : onFalse)(x, i);
      });
      return r;
    };
    var bifilter = function (obj, pred) {
      var t = {};
      var f = {};
      internalFilter(obj, pred, objAcc(t), objAcc(f));
      return {
        t: t,
        f: f
      };
    };
    var filter$1 = function (obj, pred) {
      var t = {};
      internalFilter(obj, pred, objAcc(t), noop);
      return t;
    };
    var mapToArray = function (obj, f) {
      var r = [];
      each$1(obj, function (value, name) {
        r.push(f(value, name));
      });
      return r;
    };
    var values = function (obj) {
      return mapToArray(obj, function (v) {
        return v;
      });
    };
    var get$1 = function (obj, key) {
      return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
    };
    var has = function (obj, key) {
      return hasOwnProperty.call(obj, key);
    };
    var hasNonNullableKey = function (obj, key) {
      return has(obj, key) &amp;&amp; obj[key] !== undefined &amp;&amp; obj[key] !== null;
    };
    var equal = function (a1, a2, eq) {
      if (eq === void 0) {
        eq = eqAny;
      }
      return eqRecord(eq).eq(a1, a2);
    };

    var isArray$1 = Array.isArray;
    var toArray = function (obj) {
      if (!isArray$1(obj)) {
        var array = [];
        for (var i = 0, l = obj.length; i &lt; l; i++) {
          array[i] = obj[i];
        }
        return array;
      } else {
        return obj;
      }
    };
    var each$2 = function (o, cb, s) {
      var n, l;
      if (!o) {
        return false;
      }
      s = s || o;
      if (o.length !== undefined) {
        for (n = 0, l = o.length; n &lt; l; n++) {
          if (cb.call(s, o[n], n, o) === false) {
            return false;
          }
        }
      } else {
        for (n in o) {
          if (o.hasOwnProperty(n)) {
            if (cb.call(s, o[n], n, o) === false) {
              return false;
            }
          }
        }
      }
      return true;
    };
    var map$2 = function (array, callback) {
      var out = [];
      each$2(array, function (item, index) {
        out.push(callback(item, index, array));
      });
      return out;
    };
    var filter$2 = function (a, f) {
      var o = [];
      each$2(a, function (v, index) {
        if (!f || f(v, index, a)) {
          o.push(v);
        }
      });
      return o;
    };
    var indexOf$1 = function (a, v) {
      if (a) {
        for (var i = 0, l = a.length; i &lt; l; i++) {
          if (a[i] === v) {
            return i;
          }
        }
      }
      return -1;
    };
    var reduce = function (collection, iteratee, accumulator, thisArg) {
      var acc = isUndefined(accumulator) ? collection[0] : accumulator;
      for (var i = 0; i &lt; collection.length; i++) {
        acc = iteratee.call(thisArg, acc, collection[i], i);
      }
      return acc;
    };
    var findIndex$1 = function (array, predicate, thisArg) {
      var i, l;
      for (i = 0, l = array.length; i &lt; l; i++) {
        if (predicate.call(thisArg, array[i], i, array)) {
          return i;
        }
      }
      return -1;
    };
    var last$1 = function (collection) {
      return collection[collection.length - 1];
    };

    var __assign = function () {
      __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i &lt; n; i++) {
          s = arguments[i];
          for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p))
              t[p] = s[p];
        }
        return t;
      };
      return __assign.apply(this, arguments);
    };
    function __rest(s, e) {
      var t = {};
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p) &amp;&amp; e.indexOf(p) &lt; 0)
          t[p] = s[p];
      if (s != null &amp;&amp; typeof Object.getOwnPropertySymbols === 'function')
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i &lt; p.length; i++) {
          if (e.indexOf(p[i]) &lt; 0 &amp;&amp; Object.prototype.propertyIsEnumerable.call(s, p[i]))
            t[p[i]] = s[p[i]];
        }
      return t;
    }
    function __spreadArrays() {
      for (var s = 0, i = 0, il = arguments.length; i &lt; il; i++)
        s += arguments[i].length;
      for (var r = Array(s), k = 0, i = 0; i &lt; il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j &lt; jl; j++, k++)
          r[k] = a[j];
      return r;
    }

    var cached = function (f) {
      var called = false;
      var r;
      return function () {
        var args = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        if (!called) {
          called = true;
          r = f.apply(null, args);
        }
        return r;
      };
    };

    var DeviceType = function (os, browser, userAgent, mediaMatch) {
      var isiPad = os.isiOS() &amp;&amp; /ipad/i.test(userAgent) === true;
      var isiPhone = os.isiOS() &amp;&amp; !isiPad;
      var isMobile = os.isiOS() || os.isAndroid();
      var isTouch = isMobile || mediaMatch('(pointer:coarse)');
      var isTablet = isiPad || !isiPhone &amp;&amp; isMobile &amp;&amp; mediaMatch('(min-device-width:768px)');
      var isPhone = isiPhone || isMobile &amp;&amp; !isTablet;
      var iOSwebview = browser.isSafari() &amp;&amp; os.isiOS() &amp;&amp; /safari/i.test(userAgent) === false;
      var isDesktop = !isPhone &amp;&amp; !isTablet &amp;&amp; !iOSwebview;
      return {
        isiPad: constant(isiPad),
        isiPhone: constant(isiPhone),
        isTablet: constant(isTablet),
        isPhone: constant(isPhone),
        isTouch: constant(isTouch),
        isAndroid: os.isAndroid,
        isiOS: os.isiOS,
        isWebView: constant(iOSwebview),
        isDesktop: constant(isDesktop)
      };
    };

    var firstMatch = function (regexes, s) {
      for (var i = 0; i &lt; regexes.length; i++) {
        var x = regexes[i];
        if (x.test(s)) {
          return x;
        }
      }
      return undefined;
    };
    var find$1 = function (regexes, agent) {
      var r = firstMatch(regexes, agent);
      if (!r) {
        return {
          major: 0,
          minor: 0
        };
      }
      var group = function (i) {
        return Number(agent.replace(r, '$' + i));
      };
      return nu(group(1), group(2));
    };
    var detect = function (versionRegexes, agent) {
      var cleanedAgent = String(agent).toLowerCase();
      if (versionRegexes.length === 0) {
        return unknown();
      }
      return find$1(versionRegexes, cleanedAgent);
    };
    var unknown = function () {
      return nu(0, 0);
    };
    var nu = function (major, minor) {
      return {
        major: major,
        minor: minor
      };
    };
    var Version = {
      nu: nu,
      detect: detect,
      unknown: unknown
    };

    var detect$1 = function (candidates, userAgent) {
      var agent = String(userAgent).toLowerCase();
      return find(candidates, function (candidate) {
        return candidate.search(agent);
      });
    };
    var detectBrowser = function (browsers, userAgent) {
      return detect$1(browsers, userAgent).map(function (browser) {
        var version = Version.detect(browser.versionRegexes, userAgent);
        return {
          current: browser.name,
          version: version
        };
      });
    };
    var detectOs = function (oses, userAgent) {
      return detect$1(oses, userAgent).map(function (os) {
        var version = Version.detect(os.versionRegexes, userAgent);
        return {
          current: os.name,
          version: version
        };
      });
    };
    var UaString = {
      detectBrowser: detectBrowser,
      detectOs: detectOs
    };

    var removeFromStart = function (str, numChars) {
      return str.substring(numChars);
    };

    var checkRange = function (str, substr, start) {
      return substr === '' || str.length &gt;= substr.length &amp;&amp; str.substr(start, start + substr.length) === substr;
    };
    var removeLeading = function (str, prefix) {
      return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
    };
    var contains$1 = function (str, substr) {
      return str.indexOf(substr) !== -1;
    };
    var startsWith = function (str, prefix) {
      return checkRange(str, prefix, 0);
    };
    var blank = function (r) {
      return function (s) {
        return s.replace(r, '');
      };
    };
    var trim = blank(/^\s+|\s+$/g);
    var lTrim = blank(/^\s+/g);
    var rTrim = blank(/\s+$/g);
    var isNotEmpty = function (s) {
      return s.length &gt; 0;
    };

    var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
    var checkContains = function (target) {
      return function (uastring) {
        return contains$1(uastring, target);
      };
    };
    var browsers = [
      {
        name: 'Edge',
        versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
        search: function (uastring) {
          return contains$1(uastring, 'edge/') &amp;&amp; contains$1(uastring, 'chrome') &amp;&amp; contains$1(uastring, 'safari') &amp;&amp; contains$1(uastring, 'applewebkit');
        }
      },
      {
        name: 'Chrome',
        versionRegexes: [
          /.*?chrome\/([0-9]+)\.([0-9]+).*/,
          normalVersionRegex
        ],
        search: function (uastring) {
          return contains$1(uastring, 'chrome') &amp;&amp; !contains$1(uastring, 'chromeframe');
        }
      },
      {
        name: 'IE',
        versionRegexes: [
          /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
          /.*?rv:([0-9]+)\.([0-9]+).*/
        ],
        search: function (uastring) {
          return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
        }
      },
      {
        name: 'Opera',
        versionRegexes: [
          normalVersionRegex,
          /.*?opera\/([0-9]+)\.([0-9]+).*/
        ],
        search: checkContains('opera')
      },
      {
        name: 'Firefox',
        versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
        search: checkContains('firefox')
      },
      {
        name: 'Safari',
        versionRegexes: [
          normalVersionRegex,
          /.*?cpu os ([0-9]+)_([0-9]+).*/
        ],
        search: function (uastring) {
          return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) &amp;&amp; contains$1(uastring, 'applewebkit');
        }
      }
    ];
    var oses = [
      {
        name: 'Windows',
        search: checkContains('win'),
        versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
      },
      {
        name: 'iOS',
        search: function (uastring) {
          return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
        },
        versionRegexes: [
          /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
          /.*cpu os ([0-9]+)_([0-9]+).*/,
          /.*cpu iphone os ([0-9]+)_([0-9]+).*/
        ]
      },
      {
        name: 'Android',
        search: checkContains('android'),
        versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
      },
      {
        name: 'OSX',
        search: checkContains('mac os x'),
        versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
      },
      {
        name: 'Linux',
        search: checkContains('linux'),
        versionRegexes: []
      },
      {
        name: 'Solaris',
        search: checkContains('sunos'),
        versionRegexes: []
      },
      {
        name: 'FreeBSD',
        search: checkContains('freebsd'),
        versionRegexes: []
      },
      {
        name: 'ChromeOS',
        search: checkContains('cros'),
        versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
      }
    ];
    var PlatformInfo = {
      browsers: constant(browsers),
      oses: constant(oses)
    };

    var edge = 'Edge';
    var chrome = 'Chrome';
    var ie = 'IE';
    var opera = 'Opera';
    var firefox = 'Firefox';
    var safari = 'Safari';
    var unknown$1 = function () {
      return nu$1({
        current: undefined,
        version: Version.unknown()
      });
    };
    var nu$1 = function (info) {
      var current = info.current;
      var version = info.version;
      var isBrowser = function (name) {
        return function () {
          return current === name;
        };
      };
      return {
        current: current,
        version: version,
        isEdge: isBrowser(edge),
        isChrome: isBrowser(chrome),
        isIE: isBrowser(ie),
        isOpera: isBrowser(opera),
        isFirefox: isBrowser(firefox),
        isSafari: isBrowser(safari)
      };
    };
    var Browser = {
      unknown: unknown$1,
      nu: nu$1,
      edge: constant(edge),
      chrome: constant(chrome),
      ie: constant(ie),
      opera: constant(opera),
      firefox: constant(firefox),
      safari: constant(safari)
    };

    var windows = 'Windows';
    var ios = 'iOS';
    var android = 'Android';
    var linux = 'Linux';
    var osx = 'OSX';
    var solaris = 'Solaris';
    var freebsd = 'FreeBSD';
    var chromeos = 'ChromeOS';
    var unknown$2 = function () {
      return nu$2({
        current: undefined,
        version: Version.unknown()
      });
    };
    var nu$2 = function (info) {
      var current = info.current;
      var version = info.version;
      var isOS = function (name) {
        return function () {
          return current === name;
        };
      };
      return {
        current: current,
        version: version,
        isWindows: isOS(windows),
        isiOS: isOS(ios),
        isAndroid: isOS(android),
        isOSX: isOS(osx),
        isLinux: isOS(linux),
        isSolaris: isOS(solaris),
        isFreeBSD: isOS(freebsd),
        isChromeOS: isOS(chromeos)
      };
    };
    var OperatingSystem = {
      unknown: unknown$2,
      nu: nu$2,
      windows: constant(windows),
      ios: constant(ios),
      android: constant(android),
      linux: constant(linux),
      osx: constant(osx),
      solaris: constant(solaris),
      freebsd: constant(freebsd),
      chromeos: constant(chromeos)
    };

    var detect$2 = function (userAgent, mediaMatch) {
      var browsers = PlatformInfo.browsers();
      var oses = PlatformInfo.oses();
      var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
      var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
      var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
      return {
        browser: browser,
        os: os,
        deviceType: deviceType
      };
    };
    var PlatformDetection = { detect: detect$2 };

    var mediaMatch = function (query) {
      return window.matchMedia(query).matches;
    };
    var platform = cached(function () {
      return PlatformDetection.detect(navigator.userAgent, mediaMatch);
    });
    var detect$3 = function () {
      return platform();
    };

    var userAgent = navigator.userAgent;
    var platform$1 = detect$3();
    var browser = platform$1.browser;
    var os = platform$1.os;
    var deviceType = platform$1.deviceType;
    var webkit = /WebKit/.test(userAgent) &amp;&amp; !browser.isEdge();
    var fileApi = 'FormData' in window &amp;&amp; 'FileReader' in window &amp;&amp; 'URL' in window &amp;&amp; !!URL.createObjectURL;
    var windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
    var Env = {
      opera: browser.isOpera(),
      webkit: webkit,
      ie: browser.isIE() || browser.isEdge() ? browser.version.major : false,
      gecko: browser.isFirefox(),
      mac: os.isOSX() || os.isiOS(),
      iOS: deviceType.isiPad() || deviceType.isiPhone(),
      android: os.isAndroid(),
      contentEditable: true,
      transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
      caretAfter: true,
      range: window.getSelection &amp;&amp; 'Range' in window,
      documentMode: browser.isIE() ? document.documentMode || 7 : 10,
      fileApi: fileApi,
      ceFalse: true,
      cacheSuffix: null,
      container: null,
      experimentalShadowDom: false,
      canHaveCSP: !browser.isIE(),
      desktop: deviceType.isDesktop(),
      windowsPhone: windowsPhone,
      browser: {
        current: browser.current,
        version: browser.version,
        isChrome: browser.isChrome,
        isEdge: browser.isEdge,
        isFirefox: browser.isFirefox,
        isIE: browser.isIE,
        isOpera: browser.isOpera,
        isSafari: browser.isSafari
      },
      os: {
        current: os.current,
        version: os.version,
        isAndroid: os.isAndroid,
        isChromeOS: os.isChromeOS,
        isFreeBSD: os.isFreeBSD,
        isiOS: os.isiOS,
        isLinux: os.isLinux,
        isOSX: os.isOSX,
        isSolaris: os.isSolaris,
        isWindows: os.isWindows
      },
      deviceType: {
        isDesktop: deviceType.isDesktop,
        isiPad: deviceType.isiPad,
        isiPhone: deviceType.isiPhone,
        isPhone: deviceType.isPhone,
        isTablet: deviceType.isTablet,
        isTouch: deviceType.isTouch,
        isWebView: deviceType.isWebView
      }
    };

    var whiteSpaceRegExp = /^\s*|\s*$/g;
    var trim$1 = function (str) {
      return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
    };
    var is = function (obj, type) {
      if (!type) {
        return obj !== undefined;
      }
      if (type === 'array' &amp;&amp; isArray$1(obj)) {
        return true;
      }
      return typeof obj === type;
    };
    var makeMap = function (items, delim, map) {
      var i;
      items = items || [];
      delim = delim || ',';
      if (typeof items === 'string') {
        items = items.split(delim);
      }
      map = map || {};
      i = items.length;
      while (i--) {
        map[items[i]] = {};
      }
      return map;
    };
    var hasOwnProperty$1 = function (obj, prop) {
      return Object.prototype.hasOwnProperty.call(obj, prop);
    };
    var create = function (s, p, root) {
      var self = this;
      var sp, scn, c, de = 0;
      s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
      var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
      var ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
      if (ns[cn]) {
        return;
      }
      if (s[2] === 'static') {
        ns[cn] = p;
        if (this.onCreate) {
          this.onCreate(s[2], s[3], ns[cn]);
        }
        return;
      }
      if (!p[cn]) {
        p[cn] = function () {
        };
        de = 1;
      }
      ns[cn] = p[cn];
      self.extend(ns[cn].prototype, p);
      if (s[5]) {
        sp = self.resolve(s[5]).prototype;
        scn = s[5].match(/\.(\w+)$/i)[1];
        c = ns[cn];
        if (de) {
          ns[cn] = function () {
            return sp[scn].apply(this, arguments);
          };
        } else {
          ns[cn] = function () {
            this.parent = sp[scn];
            return c.apply(this, arguments);
          };
        }
        ns[cn].prototype[cn] = ns[cn];
        self.each(sp, function (f, n) {
          ns[cn].prototype[n] = sp[n];
        });
        self.each(p, function (f, n) {
          if (sp[n]) {
            ns[cn].prototype[n] = function () {
              this.parent = sp[n];
              return f.apply(this, arguments);
            };
          } else {
            if (n !== cn) {
              ns[cn].prototype[n] = f;
            }
          }
        });
      }
      self.each(p.static, function (f, n) {
        ns[cn][n] = f;
      });
    };
    var extend = function (obj) {
      var exts = [];
      for (var _i = 1; _i &lt; arguments.length; _i++) {
        exts[_i - 1] = arguments[_i];
      }
      for (var i = 0; i &lt; exts.length; i++) {
        var ext = exts[i];
        for (var name_1 in ext) {
          if (ext.hasOwnProperty(name_1)) {
            var value = ext[name_1];
            if (value !== undefined) {
              obj[name_1] = value;
            }
          }
        }
      }
      return obj;
    };
    var walk = function (o, f, n, s) {
      s = s || this;
      if (o) {
        if (n) {
          o = o[n];
        }
        each$2(o, function (o, i) {
          if (f.call(s, o, i, n) === false) {
            return false;
          }
          walk(o, f, n, s);
        });
      }
    };
    var createNS = function (n, o) {
      var i, v;
      o = o || window;
      n = n.split('.');
      for (i = 0; i &lt; n.length; i++) {
        v = n[i];
        if (!o[v]) {
          o[v] = {};
        }
        o = o[v];
      }
      return o;
    };
    var resolve = function (n, o) {
      var i, l;
      o = o || window;
      n = n.split('.');
      for (i = 0, l = n.length; i &lt; l; i++) {
        o = o[n[i]];
        if (!o) {
          break;
        }
      }
      return o;
    };
    var explode = function (s, d) {
      if (!s || is(s, 'array')) {
        return s;
      }
      return map$2(s.split(d || ','), trim$1);
    };
    var _addCacheSuffix = function (url) {
      var cacheSuffix = Env.cacheSuffix;
      if (cacheSuffix) {
        url += (url.indexOf('?') === -1 ? '?' : '&amp;') + cacheSuffix;
      }
      return url;
    };
    var Tools = {
      trim: trim$1,
      isArray: isArray$1,
      is: is,
      toArray: toArray,
      makeMap: makeMap,
      each: each$2,
      map: map$2,
      grep: filter$2,
      inArray: indexOf$1,
      hasOwn: hasOwnProperty$1,
      extend: extend,
      create: create,
      walk: walk,
      createNS: createNS,
      resolve: resolve,
      explode: explode,
      _addCacheSuffix: _addCacheSuffix
    };

    var fromHtml = function (html, scope) {
      var doc = scope || document;
      var div = doc.createElement('div');
      div.innerHTML = html;
      if (!div.hasChildNodes() || div.childNodes.length &gt; 1) {
        console.error('HTML does not have a single root node', html);
        throw new Error('HTML must have a single root node');
      }
      return fromDom(div.childNodes[0]);
    };
    var fromTag = function (tag, scope) {
      var doc = scope || document;
      var node = doc.createElement(tag);
      return fromDom(node);
    };
    var fromText = function (text, scope) {
      var doc = scope || document;
      var node = doc.createTextNode(text);
      return fromDom(node);
    };
    var fromDom = function (node) {
      if (node === null || node === undefined) {
        throw new Error('Node cannot be null or undefined');
      }
      return { dom: node };
    };
    var fromPoint = function (docElm, x, y) {
      return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
    };
    var SugarElement = {
      fromHtml: fromHtml,
      fromTag: fromTag,
      fromText: fromText,
      fromDom: fromDom,
      fromPoint: fromPoint
    };

    var toArray$1 = function (target, f) {
      var r = [];
      var recurse = function (e) {
        r.push(e);
        return f(e);
      };
      var cur = f(target);
      do {
        cur = cur.bind(recurse);
      } while (cur.isSome());
      return r;
    };

    var compareDocumentPosition = function (a, b, match) {
      return (a.compareDocumentPosition(b) &amp; match) !== 0;
    };
    var documentPositionContainedBy = function (a, b) {
      return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
    };

    var COMMENT = 8;
    var DOCUMENT = 9;
    var DOCUMENT_FRAGMENT = 11;
    var ELEMENT = 1;
    var TEXT = 3;

    var is$1 = function (element, selector) {
      var dom = element.dom;
      if (dom.nodeType !== ELEMENT) {
        return false;
      } else {
        var elem = dom;
        if (elem.matches !== undefined) {
          return elem.matches(selector);
        } else if (elem.msMatchesSelector !== undefined) {
          return elem.msMatchesSelector(selector);
        } else if (elem.webkitMatchesSelector !== undefined) {
          return elem.webkitMatchesSelector(selector);
        } else if (elem.mozMatchesSelector !== undefined) {
          return elem.mozMatchesSelector(selector);
        } else {
          throw new Error('Browser lacks native selectors');
        }
      }
    };
    var bypassSelector = function (dom) {
      return dom.nodeType !== ELEMENT &amp;&amp; dom.nodeType !== DOCUMENT &amp;&amp; dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
    };
    var all = function (selector, scope) {
      var base = scope === undefined ? document : scope.dom;
      return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
    };
    var one = function (selector, scope) {
      var base = scope === undefined ? document : scope.dom;
      return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
    };

    var eq$2 = function (e1, e2) {
      return e1.dom === e2.dom;
    };
    var regularContains = function (e1, e2) {
      var d1 = e1.dom;
      var d2 = e2.dom;
      return d1 === d2 ? false : d1.contains(d2);
    };
    var ieContains = function (e1, e2) {
      return documentPositionContainedBy(e1.dom, e2.dom);
    };
    var contains$2 = function (e1, e2) {
      return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
    };

    var Global = typeof window !== 'undefined' ? window : Function('return this;')();

    var name = function (element) {
      var r = element.dom.nodeName;
      return r.toLowerCase();
    };
    var type = function (element) {
      return element.dom.nodeType;
    };
    var isType$1 = function (t) {
      return function (element) {
        return type(element) === t;
      };
    };
    var isComment = function (element) {
      return type(element) === COMMENT || name(element) === '#comment';
    };
    var isElement = isType$1(ELEMENT);
    var isText = isType$1(TEXT);
    var isDocument = isType$1(DOCUMENT);
    var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT);

    var owner = function (element) {
      return SugarElement.fromDom(element.dom.ownerDocument);
    };
    var documentOrOwner = function (dos) {
      return isDocument(dos) ? dos : owner(dos);
    };
    var documentElement = function (element) {
      return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
    };
    var defaultView = function (element) {
      return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
    };
    var parent = function (element) {
      return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
    };
    var parents = function (element, isRoot) {
      var stop = isFunction(isRoot) ? isRoot : never;
      var dom = element.dom;
      var ret = [];
      while (dom.parentNode !== null &amp;&amp; dom.parentNode !== undefined) {
        var rawParent = dom.parentNode;
        var p = SugarElement.fromDom(rawParent);
        ret.push(p);
        if (stop(p) === true) {
          break;
        } else {
          dom = rawParent;
        }
      }
      return ret;
    };
    var siblings = function (element) {
      var filterSelf = function (elements) {
        return filter(elements, function (x) {
          return !eq$2(element, x);
        });
      };
      return parent(element).map(children).map(filterSelf).getOr([]);
    };
    var prevSibling = function (element) {
      return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
    };
    var nextSibling = function (element) {
      return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
    };
    var prevSiblings = function (element) {
      return reverse(toArray$1(element, prevSibling));
    };
    var nextSiblings = function (element) {
      return toArray$1(element, nextSibling);
    };
    var children = function (element) {
      return map(element.dom.childNodes, SugarElement.fromDom);
    };
    var child = function (element, index) {
      var cs = element.dom.childNodes;
      return Optional.from(cs[index]).map(SugarElement.fromDom);
    };
    var firstChild = function (element) {
      return child(element, 0);
    };
    var lastChild = function (element) {
      return child(element, element.dom.childNodes.length - 1);
    };
    var childNodesCount = function (element) {
      return element.dom.childNodes.length;
    };

    var getHead = function (doc) {
      var b = doc.dom.head;
      if (b === null || b === undefined) {
        throw new Error('Head is not available yet');
      }
      return SugarElement.fromDom(b);
    };

    var isShadowRoot = function (dos) {
      return isDocumentFragment(dos) &amp;&amp; isNonNullable(dos.dom.host);
    };
    var supported = isFunction(Element.prototype.attachShadow) &amp;&amp; isFunction(Node.prototype.getRootNode);
    var isSupported = constant(supported);
    var getRootNode = supported ? function (e) {
      return SugarElement.fromDom(e.dom.getRootNode());
    } : documentOrOwner;
    var getStyleContainer = function (dos) {
      return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
    };
    var getShadowRoot = function (e) {
      var r = getRootNode(e);
      return isShadowRoot(r) ? Optional.some(r) : Optional.none();
    };
    var getShadowHost = function (e) {
      return SugarElement.fromDom(e.dom.host);
    };
    var getOriginalEventTarget = function (event) {
      if (isSupported() &amp;&amp; isNonNullable(event.target)) {
        var el = SugarElement.fromDom(event.target);
        if (isElement(el) &amp;&amp; isOpenShadowHost(el)) {
          if (event.composed &amp;&amp; event.composedPath) {
            var composedPath = event.composedPath();
            if (composedPath) {
              return head(composedPath);
            }
          }
        }
      }
      return Optional.from(event.target);
    };
    var isOpenShadowHost = function (element) {
      return isNonNullable(element.dom.shadowRoot);
    };

    var before = function (marker, element) {
      var parent$1 = parent(marker);
      parent$1.each(function (v) {
        v.dom.insertBefore(element.dom, marker.dom);
      });
    };
    var after = function (marker, element) {
      var sibling = nextSibling(marker);
      sibling.fold(function () {
        var parent$1 = parent(marker);
        parent$1.each(function (v) {
          append(v, element);
        });
      }, function (v) {
        before(v, element);
      });
    };
    var prepend = function (parent, element) {
      var firstChild$1 = firstChild(parent);
      firstChild$1.fold(function () {
        append(parent, element);
      }, function (v) {
        parent.dom.insertBefore(element.dom, v.dom);
      });
    };
    var append = function (parent, element) {
      parent.dom.appendChild(element.dom);
    };
    var wrap = function (element, wrapper) {
      before(element, wrapper);
      append(wrapper, element);
    };

    var before$1 = function (marker, elements) {
      each(elements, function (x) {
        before(marker, x);
      });
    };
    var append$1 = function (parent, elements) {
      each(elements, function (x) {
        append(parent, x);
      });
    };

    var empty = function (element) {
      element.dom.textContent = '';
      each(children(element), function (rogue) {
        remove(rogue);
      });
    };
    var remove = function (element) {
      var dom = element.dom;
      if (dom.parentNode !== null) {
        dom.parentNode.removeChild(dom);
      }
    };
    var unwrap = function (wrapper) {
      var children$1 = children(wrapper);
      if (children$1.length &gt; 0) {
        before$1(wrapper, children$1);
      }
      remove(wrapper);
    };

    var inBody = function (element) {
      var dom = isText(element) ? element.dom.parentNode : element.dom;
      if (dom === undefined || dom === null || dom.ownerDocument === null) {
        return false;
      }
      var doc = dom.ownerDocument;
      return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
        return doc.body.contains(dom);
      }, compose1(inBody, getShadowHost));
    };

    var r = function (left, top) {
      var translate = function (x, y) {
        return r(left + x, top + y);
      };
      return {
        left: left,
        top: top,
        translate: translate
      };
    };
    var SugarPosition = r;

    var boxPosition = function (dom) {
      var box = dom.getBoundingClientRect();
      return SugarPosition(box.left, box.top);
    };
    var firstDefinedOrZero = function (a, b) {
      if (a !== undefined) {
        return a;
      } else {
        return b !== undefined ? b : 0;
      }
    };
    var absolute = function (element) {
      var doc = element.dom.ownerDocument;
      var body = doc.body;
      var win = doc.defaultView;
      var html = doc.documentElement;
      if (body === element.dom) {
        return SugarPosition(body.offsetLeft, body.offsetTop);
      }
      var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
      var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
      var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
      var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
      return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
    };
    var viewport = function (element) {
      var dom = element.dom;
      var doc = dom.ownerDocument;
      var body = doc.body;
      if (body === dom) {
        return SugarPosition(body.offsetLeft, body.offsetTop);
      }
      if (!inBody(element)) {
        return SugarPosition(0, 0);
      }
      return boxPosition(dom);
    };

    var get$2 = function (_DOC) {
      var doc = _DOC !== undefined ? _DOC.dom : document;
      var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
      var y = doc.body.scrollTop || doc.documentElement.scrollTop;
      return SugarPosition(x, y);
    };
    var to = function (x, y, _DOC) {
      var doc = _DOC !== undefined ? _DOC.dom : document;
      var win = doc.defaultView;
      if (win) {
        win.scrollTo(x, y);
      }
    };
    var intoView = function (element, alignToTop) {
      var isSafari = detect$3().browser.isSafari();
      if (isSafari &amp;&amp; isFunction(element.dom.scrollIntoViewIfNeeded)) {
        element.dom.scrollIntoViewIfNeeded(false);
      } else {
        element.dom.scrollIntoView(alignToTop);
      }
    };

    var get$3 = function (_win) {
      var win = _win === undefined ? window : _win;
      return Optional.from(win['visualViewport']);
    };
    var bounds = function (x, y, width, height) {
      return {
        x: x,
        y: y,
        width: width,
        height: height,
        right: x + width,
        bottom: y + height
      };
    };
    var getBounds = function (_win) {
      var win = _win === undefined ? window : _win;
      var doc = win.document;
      var scroll = get$2(SugarElement.fromDom(doc));
      return get$3(win).fold(function () {
        var html = win.document.documentElement;
        var width = html.clientWidth;
        var height = html.clientHeight;
        return bounds(scroll.left, scroll.top, width, height);
      }, function (visualViewport) {
        return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
      });
    };

    var isNodeType = function (type) {
      return function (node) {
        return !!node &amp;&amp; node.nodeType === type;
      };
    };
    var isRestrictedNode = function (node) {
      return !!node &amp;&amp; !Object.getPrototypeOf(node);
    };
    var isElement$1 = isNodeType(1);
    var matchNodeNames = function (names) {
      var lowercasedNames = names.map(function (s) {
        return s.toLowerCase();
      });
      return function (node) {
        if (node &amp;&amp; node.nodeName) {
          var nodeName = node.nodeName.toLowerCase();
          return contains(lowercasedNames, nodeName);
        }
        return false;
      };
    };
    var matchStyleValues = function (name, values) {
      var items = values.toLowerCase().split(' ');
      return function (node) {
        var i, cssValue;
        if (isElement$1(node)) {
          for (i = 0; i &lt; items.length; i++) {
            var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
            cssValue = computed ? computed.getPropertyValue(name) : null;
            if (cssValue === items[i]) {
              return true;
            }
          }
        }
        return false;
      };
    };
    var hasAttribute = function (attrName) {
      return function (node) {
        return isElement$1(node) &amp;&amp; node.hasAttribute(attrName);
      };
    };
    var hasAttributeValue = function (attrName, attrValue) {
      return function (node) {
        return isElement$1(node) &amp;&amp; node.getAttribute(attrName) === attrValue;
      };
    };
    var isBogus = function (node) {
      return isElement$1(node) &amp;&amp; node.hasAttribute('data-mce-bogus');
    };
    var isBogusAll = function (node) {
      return isElement$1(node) &amp;&amp; node.getAttribute('data-mce-bogus') === 'all';
    };
    var isTable = function (node) {
      return isElement$1(node) &amp;&amp; node.tagName === 'TABLE';
    };
    var hasContentEditableState = function (value) {
      return function (node) {
        if (isElement$1(node)) {
          if (node.contentEditable === value) {
            return true;
          }
          if (node.getAttribute('data-mce-contenteditable') === value) {
            return true;
          }
        }
        return false;
      };
    };
    var isTextareaOrInput = matchNodeNames([
      'textarea',
      'input'
    ]);
    var isText$1 = isNodeType(3);
    var isComment$1 = isNodeType(8);
    var isDocument$1 = isNodeType(9);
    var isDocumentFragment$1 = isNodeType(11);
    var isBr = matchNodeNames(['br']);
    var isImg = matchNodeNames(['img']);
    var isContentEditableTrue = hasContentEditableState('true');
    var isContentEditableFalse = hasContentEditableState('false');
    var isTableCell = matchNodeNames([
      'td',
      'th'
    ]);
    var isMedia = matchNodeNames([
      'video',
      'audio',
      'object',
      'embed'
    ]);

    var isSupported$1 = function (dom) {
      return dom.style !== undefined &amp;&amp; isFunction(dom.style.getPropertyValue);
    };

    var rawSet = function (dom, key, value) {
      if (isString(value) || isBoolean(value) || isNumber(value)) {
        dom.setAttribute(key, value + '');
      } else {
        console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
        throw new Error('Attribute value was not simple');
      }
    };
    var set = function (element, key, value) {
      rawSet(element.dom, key, value);
    };
    var setAll = function (element, attrs) {
      var dom = element.dom;
      each$1(attrs, function (v, k) {
        rawSet(dom, k, v);
      });
    };
    var get$4 = function (element, key) {
      var v = element.dom.getAttribute(key);
      return v === null ? undefined : v;
    };
    var getOpt = function (element, key) {
      return Optional.from(get$4(element, key));
    };
    var has$1 = function (element, key) {
      var dom = element.dom;
      return dom &amp;&amp; dom.hasAttribute ? dom.hasAttribute(key) : false;
    };
    var remove$1 = function (element, key) {
      element.dom.removeAttribute(key);
    };
    var clone = function (element) {
      return foldl(element.dom.attributes, function (acc, attr) {
        acc[attr.name] = attr.value;
        return acc;
      }, {});
    };

    var internalSet = function (dom, property, value) {
      if (!isString(value)) {
        console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
        throw new Error('CSS value must be a string: ' + value);
      }
      if (isSupported$1(dom)) {
        dom.style.setProperty(property, value);
      }
    };
    var setAll$1 = function (element, css) {
      var dom = element.dom;
      each$1(css, function (v, k) {
        internalSet(dom, k, v);
      });
    };
    var get$5 = function (element, property) {
      var dom = element.dom;
      var styles = window.getComputedStyle(dom);
      var r = styles.getPropertyValue(property);
      return r === '' &amp;&amp; !inBody(element) ? getUnsafeProperty(dom, property) : r;
    };
    var getUnsafeProperty = function (dom, property) {
      return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
    };
    var getRaw = function (element, property) {
      var dom = element.dom;
      var raw = getUnsafeProperty(dom, property);
      return Optional.from(raw).filter(function (r) {
        return r.length &gt; 0;
      });
    };
    var getAllRaw = function (element) {
      var css = {};
      var dom = element.dom;
      if (isSupported$1(dom)) {
        for (var i = 0; i &lt; dom.style.length; i++) {
          var ruleName = dom.style.item(i);
          css[ruleName] = dom.style[ruleName];
        }
      }
      return css;
    };
    var reflow = function (e) {
      return e.dom.offsetWidth;
    };

    var browser$1 = detect$3().browser;
    var firstElement = function (nodes) {
      return find(nodes, isElement);
    };
    var getTableCaptionDeltaY = function (elm) {
      if (browser$1.isFirefox() &amp;&amp; name(elm) === 'table') {
        return firstElement(children(elm)).filter(function (elm) {
          return name(elm) === 'caption';
        }).bind(function (caption) {
          return firstElement(nextSiblings(caption)).map(function (body) {
            var bodyTop = body.dom.offsetTop;
            var captionTop = caption.dom.offsetTop;
            var captionHeight = caption.dom.offsetHeight;
            return bodyTop &lt;= captionTop ? -captionHeight : 0;
          });
        }).getOr(0);
      } else {
        return 0;
      }
    };
    var hasChild = function (elm, child) {
      return elm.children &amp;&amp; contains(elm.children, child);
    };
    var getPos = function (body, elm, rootElm) {
      var x = 0, y = 0, offsetParent;
      var doc = body.ownerDocument;
      var pos;
      rootElm = rootElm ? rootElm : body;
      if (elm) {
        if (rootElm === body &amp;&amp; elm.getBoundingClientRect &amp;&amp; get$5(SugarElement.fromDom(body), 'position') === 'static') {
          pos = elm.getBoundingClientRect();
          x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
          y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
          return {
            x: x,
            y: y
          };
        }
        offsetParent = elm;
        while (offsetParent &amp;&amp; offsetParent !== rootElm &amp;&amp; offsetParent.nodeType &amp;&amp; !hasChild(offsetParent, rootElm)) {
          x += offsetParent.offsetLeft || 0;
          y += offsetParent.offsetTop || 0;
          offsetParent = offsetParent.offsetParent;
        }
        offsetParent = elm.parentNode;
        while (offsetParent &amp;&amp; offsetParent !== rootElm &amp;&amp; offsetParent.nodeType &amp;&amp; !hasChild(offsetParent, rootElm)) {
          x -= offsetParent.scrollLeft || 0;
          y -= offsetParent.scrollTop || 0;
          offsetParent = offsetParent.parentNode;
        }
        y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
      }
      return {
        x: x,
        y: y
      };
    };

    var exports$1 = {}, module$1 = { exports: exports$1 };
    (function (define, exports, module, require) {
      (function (f) {
        if (typeof exports === 'object' &amp;&amp; typeof module !== 'undefined') {
          module.exports = f();
        } else if (typeof define === 'function' &amp;&amp; define.amd) {
          define([], f);
        } else {
          var g;
          if (typeof window !== 'undefined') {
            g = window;
          } else if (typeof global !== 'undefined') {
            g = global;
          } else if (typeof self !== 'undefined') {
            g = self;
          } else {
            g = this;
          }
          g.EphoxContactWrapper = f();
        }
      }(function () {
        return function () {
          function r(e, n, t) {
            function o(i, f) {
              if (!n[i]) {
                if (!e[i]) {
                  var c = 'function' == typeof require &amp;&amp; require;
                  if (!f &amp;&amp; c)
                    return c(i, !0);
                  if (u)
                    return u(i, !0);
                  var a = new Error('Cannot find module \'' + i + '\'');
                  throw a.code = 'MODULE_NOT_FOUND', a;
                }
                var p = n[i] = { exports: {} };
                e[i][0].call(p.exports, function (r) {
                  var n = e[i][1][r];
                  return o(n || r);
                }, p, p.exports, r, e, n, t);
              }
              return n[i].exports;
            }
            for (var u = 'function' == typeof require &amp;&amp; require, i = 0; i &lt; t.length; i++)
              o(t[i]);
            return o;
          }
          return r;
        }()({
          1: [
            function (require, module, exports) {
              var process = module.exports = {};
              var cachedSetTimeout;
              var cachedClearTimeout;
              function defaultSetTimout() {
                throw new Error('setTimeout has not been defined');
              }
              function defaultClearTimeout() {
                throw new Error('clearTimeout has not been defined');
              }
              (function () {
                try {
                  if (typeof setTimeout === 'function') {
                    cachedSetTimeout = setTimeout;
                  } else {
                    cachedSetTimeout = defaultSetTimout;
                  }
                } catch (e) {
                  cachedSetTimeout = defaultSetTimout;
                }
                try {
                  if (typeof clearTimeout === 'function') {
                    cachedClearTimeout = clearTimeout;
                  } else {
                    cachedClearTimeout = defaultClearTimeout;
                  }
                } catch (e) {
                  cachedClearTimeout = defaultClearTimeout;
                }
              }());
              function runTimeout(fun) {
                if (cachedSetTimeout === setTimeout) {
                  return setTimeout(fun, 0);
                }
                if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) &amp;&amp; setTimeout) {
                  cachedSetTimeout = setTimeout;
                  return setTimeout(fun, 0);
                }
                try {
                  return cachedSetTimeout(fun, 0);
                } catch (e) {
                  try {
                    return cachedSetTimeout.call(null, fun, 0);
                  } catch (e) {
                    return cachedSetTimeout.call(this, fun, 0);
                  }
                }
              }
              function runClearTimeout(marker) {
                if (cachedClearTimeout === clearTimeout) {
                  return clearTimeout(marker);
                }
                if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) &amp;&amp; clearTimeout) {
                  cachedClearTimeout = clearTimeout;
                  return clearTimeout(marker);
                }
                try {
                  return cachedClearTimeout(marker);
                } catch (e) {
                  try {
                    return cachedClearTimeout.call(null, marker);
                  } catch (e) {
                    return cachedClearTimeout.call(this, marker);
                  }
                }
              }
              var queue = [];
              var draining = false;
              var currentQueue;
              var queueIndex = -1;
              function cleanUpNextTick() {
                if (!draining || !currentQueue) {
                  return;
                }
                draining = false;
                if (currentQueue.length) {
                  queue = currentQueue.concat(queue);
                } else {
                  queueIndex = -1;
                }
                if (queue.length) {
                  drainQueue();
                }
              }
              function drainQueue() {
                if (draining) {
                  return;
                }
                var timeout = runTimeout(cleanUpNextTick);
                draining = true;
                var len = queue.length;
                while (len) {
                  currentQueue = queue;
                  queue = [];
                  while (++queueIndex &lt; len) {
                    if (currentQueue) {
                      currentQueue[queueIndex].run();
                    }
                  }
                  queueIndex = -1;
                  len = queue.length;
                }
                currentQueue = null;
                draining = false;
                runClearTimeout(timeout);
              }
              process.nextTick = function (fun) {
                var args = new Array(arguments.length - 1);
                if (arguments.length &gt; 1) {
                  for (var i = 1; i &lt; arguments.length; i++) {
                    args[i - 1] = arguments[i];
                  }
                }
                queue.push(new Item(fun, args));
                if (queue.length === 1 &amp;&amp; !draining) {
                  runTimeout(drainQueue);
                }
              };
              function Item(fun, array) {
                this.fun = fun;
                this.array = array;
              }
              Item.prototype.run = function () {
                this.fun.apply(null, this.array);
              };
              process.title = 'browser';
              process.browser = true;
              process.env = {};
              process.argv = [];
              process.version = '';
              process.versions = {};
              function noop() {
              }
              process.on = noop;
              process.addListener = noop;
              process.once = noop;
              process.off = noop;
              process.removeListener = noop;
              process.removeAllListeners = noop;
              process.emit = noop;
              process.prependListener = noop;
              process.prependOnceListener = noop;
              process.listeners = function (name) {
                return [];
              };
              process.binding = function (name) {
                throw new Error('process.binding is not supported');
              };
              process.cwd = function () {
                return '/';
              };
              process.chdir = function (dir) {
                throw new Error('process.chdir is not supported');
              };
              process.umask = function () {
                return 0;
              };
            },
            {}
          ],
          2: [
            function (require, module, exports) {
              (function (setImmediate) {
                (function (root) {
                  var setTimeoutFunc = setTimeout;
                  function noop() {
                  }
                  function bind(fn, thisArg) {
                    return function () {
                      fn.apply(thisArg, arguments);
                    };
                  }
                  function Promise(fn) {
                    if (typeof this !== 'object')
                      throw new TypeError('Promises must be constructed via new');
                    if (typeof fn !== 'function')
                      throw new TypeError('not a function');
                    this._state = 0;
                    this._handled = false;
                    this._value = undefined;
                    this._deferreds = [];
                    doResolve(fn, this);
                  }
                  function handle(self, deferred) {
                    while (self._state === 3) {
                      self = self._value;
                    }
                    if (self._state === 0) {
                      self._deferreds.push(deferred);
                      return;
                    }
                    self._handled = true;
                    Promise._immediateFn(function () {
                      var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
                      if (cb === null) {
                        (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
                        return;
                      }
                      var ret;
                      try {
                        ret = cb(self._value);
                      } catch (e) {
                        reject(deferred.promise, e);
                        return;
                      }
                      resolve(deferred.promise, ret);
                    });
                  }
                  function resolve(self, newValue) {
                    try {
                      if (newValue === self)
                        throw new TypeError('A promise cannot be resolved with itself.');
                      if (newValue &amp;&amp; (typeof newValue === 'object' || typeof newValue === 'function')) {
                        var then = newValue.then;
                        if (newValue instanceof Promise) {
                          self._state = 3;
                          self._value = newValue;
                          finale(self);
                          return;
                        } else if (typeof then === 'function') {
                          doResolve(bind(then, newValue), self);
                          return;
                        }
                      }
                      self._state = 1;
                      self._value = newValue;
                      finale(self);
                    } catch (e) {
                      reject(self, e);
                    }
                  }
                  function reject(self, newValue) {
                    self._state = 2;
                    self._value = newValue;
                    finale(self);
                  }
                  function finale(self) {
                    if (self._state === 2 &amp;&amp; self._deferreds.length === 0) {
                      Promise._immediateFn(function () {
                        if (!self._handled) {
                          Promise._unhandledRejectionFn(self._value);
                        }
                      });
                    }
                    for (var i = 0, len = self._deferreds.length; i &lt; len; i++) {
                      handle(self, self._deferreds[i]);
                    }
                    self._deferreds = null;
                  }
                  function Handler(onFulfilled, onRejected, promise) {
                    this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
                    this.onRejected = typeof onRejected === 'function' ? onRejected : null;
                    this.promise = promise;
                  }
                  function doResolve(fn, self) {
                    var done = false;
                    try {
                      fn(function (value) {
                        if (done)
                          return;
                        done = true;
                        resolve(self, value);
                      }, function (reason) {
                        if (done)
                          return;
                        done = true;
                        reject(self, reason);
                      });
                    } catch (ex) {
                      if (done)
                        return;
                      done = true;
                      reject(self, ex);
                    }
                  }
                  Promise.prototype['catch'] = function (onRejected) {
                    return this.then(null, onRejected);
                  };
                  Promise.prototype.then = function (onFulfilled, onRejected) {
                    var prom = new this.constructor(noop);
                    handle(this, new Handler(onFulfilled, onRejected, prom));
                    return prom;
                  };
                  Promise.all = function (arr) {
                    var args = Array.prototype.slice.call(arr);
                    return new Promise(function (resolve, reject) {
                      if (args.length === 0)
                        return resolve([]);
                      var remaining = args.length;
                      function res(i, val) {
                        try {
                          if (val &amp;&amp; (typeof val === 'object' || typeof val === 'function')) {
                            var then = val.then;
                            if (typeof then === 'function') {
                              then.call(val, function (val) {
                                res(i, val);
                              }, reject);
                              return;
                            }
                          }
                          args[i] = val;
                          if (--remaining === 0) {
                            resolve(args);
                          }
                        } catch (ex) {
                          reject(ex);
                        }
                      }
                      for (var i = 0; i &lt; args.length; i++) {
                        res(i, args[i]);
                      }
                    });
                  };
                  Promise.resolve = function (value) {
                    if (value &amp;&amp; typeof value === 'object' &amp;&amp; value.constructor === Promise) {
                      return value;
                    }
                    return new Promise(function (resolve) {
                      resolve(value);
                    });
                  };
                  Promise.reject = function (value) {
                    return new Promise(function (resolve, reject) {
                      reject(value);
                    });
                  };
                  Promise.race = function (values) {
                    return new Promise(function (resolve, reject) {
                      for (var i = 0, len = values.length; i &lt; len; i++) {
                        values[i].then(resolve, reject);
                      }
                    });
                  };
                  Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
                    setImmediate(fn);
                  } : function (fn) {
                    setTimeoutFunc(fn, 0);
                  };
                  Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
                    if (typeof console !== 'undefined' &amp;&amp; console) {
                      console.warn('Possible Unhandled Promise Rejection:', err);
                    }
                  };
                  Promise._setImmediateFn = function _setImmediateFn(fn) {
                    Promise._immediateFn = fn;
                  };
                  Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
                    Promise._unhandledRejectionFn = fn;
                  };
                  if (typeof module !== 'undefined' &amp;&amp; module.exports) {
                    module.exports = Promise;
                  } else if (!root.Promise) {
                    root.Promise = Promise;
                  }
                }(this));
              }.call(this, require('timers').setImmediate));
            },
            { 'timers': 3 }
          ],
          3: [
            function (require, module, exports) {
              (function (setImmediate, clearImmediate) {
                var nextTick = require('process/browser.js').nextTick;
                var apply = Function.prototype.apply;
                var slice = Array.prototype.slice;
                var immediateIds = {};
                var nextImmediateId = 0;
                exports.setTimeout = function () {
                  return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
                };
                exports.setInterval = function () {
                  return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
                };
                exports.clearTimeout = exports.clearInterval = function (timeout) {
                  timeout.close();
                };
                function Timeout(id, clearFn) {
                  this._id = id;
                  this._clearFn = clearFn;
                }
                Timeout.prototype.unref = Timeout.prototype.ref = function () {
                };
                Timeout.prototype.close = function () {
                  this._clearFn.call(window, this._id);
                };
                exports.enroll = function (item, msecs) {
                  clearTimeout(item._idleTimeoutId);
                  item._idleTimeout = msecs;
                };
                exports.unenroll = function (item) {
                  clearTimeout(item._idleTimeoutId);
                  item._idleTimeout = -1;
                };
                exports._unrefActive = exports.active = function (item) {
                  clearTimeout(item._idleTimeoutId);
                  var msecs = item._idleTimeout;
                  if (msecs &gt;= 0) {
                    item._idleTimeoutId = setTimeout(function onTimeout() {
                      if (item._onTimeout)
                        item._onTimeout();
                    }, msecs);
                  }
                };
                exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
                  var id = nextImmediateId++;
                  var args = arguments.length &lt; 2 ? false : slice.call(arguments, 1);
                  immediateIds[id] = true;
                  nextTick(function onNextTick() {
                    if (immediateIds[id]) {
                      if (args) {
                        fn.apply(null, args);
                      } else {
                        fn.call(null);
                      }
                      exports.clearImmediate(id);
                    }
                  });
                  return id;
                };
                exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
                  delete immediateIds[id];
                };
              }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
            },
            {
              'process/browser.js': 1,
              'timers': 3
            }
          ],
          4: [
            function (require, module, exports) {
              var promisePolyfill = require('promise-polyfill');
              var Global = function () {
                if (typeof window !== 'undefined') {
                  return window;
                } else {
                  return Function('return this;')();
                }
              }();
              module.exports = { boltExport: Global.Promise || promisePolyfill };
            },
            { 'promise-polyfill': 2 }
          ]
        }, {}, [4])(4);
      }));
    }(undefined, exports$1, module$1, undefined));
    var Promise = module$1.exports.boltExport;

    var nu$3 = function (baseFn) {
      var data = Optional.none();
      var callbacks = [];
      var map = function (f) {
        return nu$3(function (nCallback) {
          get(function (data) {
            nCallback(f(data));
          });
        });
      };
      var get = function (nCallback) {
        if (isReady()) {
          call(nCallback);
        } else {
          callbacks.push(nCallback);
        }
      };
      var set = function (x) {
        if (!isReady()) {
          data = Optional.some(x);
          run(callbacks);
          callbacks = [];
        }
      };
      var isReady = function () {
        return data.isSome();
      };
      var run = function (cbs) {
        each(cbs, call);
      };
      var call = function (cb) {
        data.each(function (x) {
          setTimeout(function () {
            cb(x);
          }, 0);
        });
      };
      baseFn(set);
      return {
        get: get,
        map: map,
        isReady: isReady
      };
    };
    var pure = function (a) {
      return nu$3(function (callback) {
        callback(a);
      });
    };
    var LazyValue = {
      nu: nu$3,
      pure: pure
    };

    var errorReporter = function (err) {
      setTimeout(function () {
        throw err;
      }, 0);
    };
    var make = function (run) {
      var get = function (callback) {
        run().then(callback, errorReporter);
      };
      var map = function (fab) {
        return make(function () {
          return run().then(fab);
        });
      };
      var bind = function (aFutureB) {
        return make(function () {
          return run().then(function (v) {
            return aFutureB(v).toPromise();
          });
        });
      };
      var anonBind = function (futureB) {
        return make(function () {
          return run().then(function () {
            return futureB.toPromise();
          });
        });
      };
      var toLazy = function () {
        return LazyValue.nu(get);
      };
      var toCached = function () {
        var cache = null;
        return make(function () {
          if (cache === null) {
            cache = run();
          }
          return cache;
        });
      };
      var toPromise = run;
      return {
        map: map,
        bind: bind,
        anonBind: anonBind,
        toLazy: toLazy,
        toCached: toCached,
        toPromise: toPromise,
        get: get
      };
    };
    var nu$4 = function (baseFn) {
      return make(function () {
        return new Promise(baseFn);
      });
    };
    var pure$1 = function (a) {
      return make(function () {
        return Promise.resolve(a);
      });
    };
    var Future = {
      nu: nu$4,
      pure: pure$1
    };

    var par = function (asyncValues, nu) {
      return nu(function (callback) {
        var r = [];
        var count = 0;
        var cb = function (i) {
          return function (value) {
            r[i] = value;
            count++;
            if (count &gt;= asyncValues.length) {
              callback(r);
            }
          };
        };
        if (asyncValues.length === 0) {
          callback([]);
        } else {
          each(asyncValues, function (asyncValue, i) {
            asyncValue.get(cb(i));
          });
        }
      });
    };

    var par$1 = function (futures) {
      return par(futures, Future.nu);
    };

    var value = function (o) {
      var is = function (v) {
        return o === v;
      };
      var or = function (_opt) {
        return value(o);
      };
      var orThunk = function (_f) {
        return value(o);
      };
      var map = function (f) {
        return value(f(o));
      };
      var mapError = function (_f) {
        return value(o);
      };
      var each = function (f) {
        f(o);
      };
      var bind = function (f) {
        return f(o);
      };
      var fold = function (_, onValue) {
        return onValue(o);
      };
      var exists = function (f) {
        return f(o);
      };
      var forall = function (f) {
        return f(o);
      };
      var toOptional = function () {
        return Optional.some(o);
      };
      return {
        is: is,
        isValue: always,
        isError: never,
        getOr: constant(o),
        getOrThunk: constant(o),
        getOrDie: constant(o),
        or: or,
        orThunk: orThunk,
        fold: fold,
        map: map,
        mapError: mapError,
        each: each,
        bind: bind,
        exists: exists,
        forall: forall,
        toOptional: toOptional
      };
    };
    var error = function (message) {
      var getOrThunk = function (f) {
        return f();
      };
      var getOrDie = function () {
        return die(String(message))();
      };
      var or = function (opt) {
        return opt;
      };
      var orThunk = function (f) {
        return f();
      };
      var map = function (_f) {
        return error(message);
      };
      var mapError = function (f) {
        return error(f(message));
      };
      var bind = function (_f) {
        return error(message);
      };
      var fold = function (onError, _) {
        return onError(message);
      };
      return {
        is: never,
        isValue: never,
        isError: always,
        getOr: identity,
        getOrThunk: getOrThunk,
        getOrDie: getOrDie,
        or: or,
        orThunk: orThunk,
        fold: fold,
        map: map,
        mapError: mapError,
        each: noop,
        bind: bind,
        exists: never,
        forall: always,
        toOptional: Optional.none
      };
    };
    var fromOption = function (opt, err) {
      return opt.fold(function () {
        return error(err);
      }, value);
    };
    var Result = {
      value: value,
      error: error,
      fromOption: fromOption
    };

    var generate = function (cases) {
      if (!isArray(cases)) {
        throw new Error('cases must be an array');
      }
      if (cases.length === 0) {
        throw new Error('there must be at least one case');
      }
      var constructors = [];
      var adt = {};
      each(cases, function (acase, count) {
        var keys$1 = keys(acase);
        if (keys$1.length !== 1) {
          throw new Error('one and only one name per case');
        }
        var key = keys$1[0];
        var value = acase[key];
        if (adt[key] !== undefined) {
          throw new Error('duplicate key detected:' + key);
        } else if (key === 'cata') {
          throw new Error('cannot have a case named cata (sorry)');
        } else if (!isArray(value)) {
          throw new Error('case arguments must be an array');
        }
        constructors.push(key);
        adt[key] = function () {
          var args = [];
          for (var _i = 0; _i &lt; arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          var argLength = args.length;
          if (argLength !== value.length) {
            throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
          }
          var match = function (branches) {
            var branchKeys = keys(branches);
            if (constructors.length !== branchKeys.length) {
              throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
            }
            var allReqd = forall(constructors, function (reqKey) {
              return contains(branchKeys, reqKey);
            });
            if (!allReqd) {
              throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
            }
            return branches[key].apply(null, args);
          };
          return {
            fold: function () {
              var foldArgs = [];
              for (var _i = 0; _i &lt; arguments.length; _i++) {
                foldArgs[_i] = arguments[_i];
              }
              if (foldArgs.length !== cases.length) {
                throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
              }
              var target = foldArgs[count];
              return target.apply(null, args);
            },
            match: match,
            log: function (label) {
              console.log(label, {
                constructors: constructors,
                constructor: key,
                params: args
              });
            }
          };
        };
      });
      return adt;
    };
    var Adt = { generate: generate };

    var comparison = Adt.generate([
      {
        bothErrors: [
          'error1',
          'error2'
        ]
      },
      {
        firstError: [
          'error1',
          'value2'
        ]
      },
      {
        secondError: [
          'value1',
          'error2'
        ]
      },
      {
        bothValues: [
          'value1',
          'value2'
        ]
      }
    ]);
    var unite = function (result) {
      return result.fold(identity, identity);
    };

    function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
      if (is(scope, a)) {
        return Optional.some(scope);
      } else if (isFunction(isRoot) &amp;&amp; isRoot(scope)) {
        return Optional.none();
      } else {
        return ancestor(scope, a, isRoot);
      }
    }

    var ancestor = function (scope, predicate, isRoot) {
      var element = scope.dom;
      var stop = isFunction(isRoot) ? isRoot : never;
      while (element.parentNode) {
        element = element.parentNode;
        var el = SugarElement.fromDom(element);
        if (predicate(el)) {
          return Optional.some(el);
        } else if (stop(el)) {
          break;
        }
      }
      return Optional.none();
    };
    var closest = function (scope, predicate, isRoot) {
      var is = function (s, test) {
        return test(s);
      };
      return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
    };
    var sibling = function (scope, predicate) {
      var element = scope.dom;
      if (!element.parentNode) {
        return Optional.none();
      }
      return child$1(SugarElement.fromDom(element.parentNode), function (x) {
        return !eq$2(scope, x) &amp;&amp; predicate(x);
      });
    };
    var child$1 = function (scope, predicate) {
      var pred = function (node) {
        return predicate(SugarElement.fromDom(node));
      };
      var result = find(scope.dom.childNodes, pred);
      return result.map(SugarElement.fromDom);
    };

    var ancestor$1 = function (scope, selector, isRoot) {
      return ancestor(scope, function (e) {
        return is$1(e, selector);
      }, isRoot);
    };
    var descendant = function (scope, selector) {
      return one(selector, scope);
    };
    var closest$1 = function (scope, selector, isRoot) {
      var is = function (element, selector) {
        return is$1(element, selector);
      };
      return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
    };

    var promise = function () {
      var bind = function (fn, thisArg) {
        return function () {
          var args = [];
          for (var _i = 0; _i &lt; arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          fn.apply(thisArg, args);
        };
      };
      var isArray = Array.isArray || function (value) {
        return Object.prototype.toString.call(value) === '[object Array]';
      };
      var Promise = function (fn) {
        if (typeof this !== 'object') {
          throw new TypeError('Promises must be constructed via new');
        }
        if (typeof fn !== 'function') {
          throw new TypeError('not a function');
        }
        this._state = null;
        this._value = null;
        this._deferreds = [];
        doResolve(fn, bind(resolve, this), bind(reject, this));
      };
      var asap = Promise.immediateFn || typeof setImmediate === 'function' &amp;&amp; setImmediate || function (fn) {
        return setTimeout(fn, 1);
      };
      function handle(deferred) {
        var me = this;
        if (this._state === null) {
          this._deferreds.push(deferred);
          return;
        }
        asap(function () {
          var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
          if (cb === null) {
            (me._state ? deferred.resolve : deferred.reject)(me._value);
            return;
          }
          var ret;
          try {
            ret = cb(me._value);
          } catch (e) {
            deferred.reject(e);
            return;
          }
          deferred.resolve(ret);
        });
      }
      function resolve(newValue) {
        try {
          if (newValue === this) {
            throw new TypeError('A promise cannot be resolved with itself.');
          }
          if (newValue &amp;&amp; (typeof newValue === 'object' || typeof newValue === 'function')) {
            var then = newValue.then;
            if (typeof then === 'function') {
              doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
              return;
            }
          }
          this._state = true;
          this._value = newValue;
          finale.call(this);
        } catch (e) {
          reject.call(this, e);
        }
      }
      function reject(newValue) {
        this._state = false;
        this._value = newValue;
        finale.call(this);
      }
      function finale() {
        for (var i = 0, len = this._deferreds.length; i &lt; len; i++) {
          handle.call(this, this._deferreds[i]);
        }
        this._deferreds = null;
      }
      function Handler(onFulfilled, onRejected, resolve, reject) {
        this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
        this.onRejected = typeof onRejected === 'function' ? onRejected : null;
        this.resolve = resolve;
        this.reject = reject;
      }
      var doResolve = function (fn, onFulfilled, onRejected) {
        var done = false;
        try {
          fn(function (value) {
            if (done) {
              return;
            }
            done = true;
            onFulfilled(value);
          }, function (reason) {
            if (done) {
              return;
            }
            done = true;
            onRejected(reason);
          });
        } catch (ex) {
          if (done) {
            return;
          }
          done = true;
          onRejected(ex);
        }
      };
      Promise.prototype.catch = function (onRejected) {
        return this.then(null, onRejected);
      };
      Promise.prototype.then = function (onFulfilled, onRejected) {
        var me = this;
        return new Promise(function (resolve, reject) {
          handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
        });
      };
      Promise.all = function () {
        var values = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          values[_i] = arguments[_i];
        }
        var args = Array.prototype.slice.call(values.length === 1 &amp;&amp; isArray(values[0]) ? values[0] : values);
        return new Promise(function (resolve, reject) {
          if (args.length === 0) {
            return resolve([]);
          }
          var remaining = args.length;
          var res = function (i, val) {
            try {
              if (val &amp;&amp; (typeof val === 'object' || typeof val === 'function')) {
                var then = val.then;
                if (typeof then === 'function') {
                  then.call(val, function (val) {
                    res(i, val);
                  }, reject);
                  return;
                }
              }
              args[i] = val;
              if (--remaining === 0) {
                resolve(args);
              }
            } catch (ex) {
              reject(ex);
            }
          };
          for (var i = 0; i &lt; args.length; i++) {
            res(i, args[i]);
          }
        });
      };
      Promise.resolve = function (value) {
        if (value &amp;&amp; typeof value === 'object' &amp;&amp; value.constructor === Promise) {
          return value;
        }
        return new Promise(function (resolve) {
          resolve(value);
        });
      };
      Promise.reject = function (value) {
        return new Promise(function (resolve, reject) {
          reject(value);
        });
      };
      Promise.race = function (values) {
        return new Promise(function (resolve, reject) {
          for (var i = 0, len = values.length; i &lt; len; i++) {
            values[i].then(resolve, reject);
          }
        });
      };
      return Promise;
    };
    var promiseObj = window.Promise ? window.Promise : promise();

    var requestAnimationFramePromise;
    var requestAnimationFrame = function (callback, element) {
      var requestAnimationFrameFunc = window.requestAnimationFrame;
      var vendors = [
        'ms',
        'moz',
        'webkit'
      ];
      var featurefill = function (cb) {
        window.setTimeout(cb, 0);
      };
      for (var i = 0; i &lt; vendors.length &amp;&amp; !requestAnimationFrameFunc; i++) {
        requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
      }
      if (!requestAnimationFrameFunc) {
        requestAnimationFrameFunc = featurefill;
      }
      requestAnimationFrameFunc(callback, element);
    };
    var wrappedSetTimeout = function (callback, time) {
      if (typeof time !== 'number') {
        time = 0;
      }
      return setTimeout(callback, time);
    };
    var wrappedSetInterval = function (callback, time) {
      if (typeof time !== 'number') {
        time = 1;
      }
      return setInterval(callback, time);
    };
    var wrappedClearTimeout = function (id) {
      return clearTimeout(id);
    };
    var wrappedClearInterval = function (id) {
      return clearInterval(id);
    };
    var debounce = function (callback, time) {
      var timer;
      var func = function () {
        var args = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        clearTimeout(timer);
        timer = wrappedSetTimeout(function () {
          callback.apply(this, args);
        }, time);
      };
      func.stop = function () {
        clearTimeout(timer);
      };
      return func;
    };
    var Delay = {
      requestAnimationFrame: function (callback, element) {
        if (requestAnimationFramePromise) {
          requestAnimationFramePromise.then(callback);
          return;
        }
        requestAnimationFramePromise = new promiseObj(function (resolve) {
          if (!element) {
            element = document.body;
          }
          requestAnimationFrame(resolve, element);
        }).then(callback);
      },
      setTimeout: wrappedSetTimeout,
      setInterval: wrappedSetInterval,
      setEditorTimeout: function (editor, callback, time) {
        return wrappedSetTimeout(function () {
          if (!editor.removed) {
            callback();
          }
        }, time);
      },
      setEditorInterval: function (editor, callback, time) {
        var timer = wrappedSetInterval(function () {
          if (!editor.removed) {
            callback();
          } else {
            clearInterval(timer);
          }
        }, time);
        return timer;
      },
      debounce: debounce,
      throttle: debounce,
      clearInterval: wrappedClearInterval,
      clearTimeout: wrappedClearTimeout
    };

    var StyleSheetLoader = function (documentOrShadowRoot, settings) {
      if (settings === void 0) {
        settings = {};
      }
      var idCount = 0;
      var loadedStates = {};
      var edos = SugarElement.fromDom(documentOrShadowRoot);
      var doc = documentOrOwner(edos);
      var maxLoadTime = settings.maxLoadTime || 5000;
      var _setReferrerPolicy = function (referrerPolicy) {
        settings.referrerPolicy = referrerPolicy;
      };
      var addStyle = function (element) {
        append(getStyleContainer(edos), element);
      };
      var removeStyle = function (id) {
        var styleContainer = getStyleContainer(edos);
        descendant(styleContainer, '#' + id).each(remove);
      };
      var getOrCreateState = function (url) {
        return get$1(loadedStates, url).getOrThunk(function () {
          return {
            id: 'mce-u' + idCount++,
            passed: [],
            failed: [],
            count: 0
          };
        });
      };
      var load = function (url, success, failure) {
        var link;
        var urlWithSuffix = Tools._addCacheSuffix(url);
        var state = getOrCreateState(urlWithSuffix);
        loadedStates[urlWithSuffix] = state;
        state.count++;
        var resolve = function (callbacks, status) {
          var i = callbacks.length;
          while (i--) {
            callbacks[i]();
          }
          state.status = status;
          state.passed = [];
          state.failed = [];
          if (link) {
            link.onload = null;
            link.onerror = null;
            link = null;
          }
        };
        var passed = function () {
          return resolve(state.passed, 2);
        };
        var failed = function () {
          return resolve(state.failed, 3);
        };
        var wait = function (testCallback, waitCallback) {
          if (!testCallback()) {
            if (Date.now() - startTime &lt; maxLoadTime) {
              Delay.setTimeout(waitCallback);
            } else {
              failed();
            }
          }
        };
        var waitForWebKitLinkLoaded = function () {
          wait(function () {
            var styleSheets = documentOrShadowRoot.styleSheets;
            var i = styleSheets.length;
            while (i--) {
              var styleSheet = styleSheets[i];
              var owner = styleSheet.ownerNode;
              if (owner &amp;&amp; owner.id === link.id) {
                passed();
                return true;
              }
            }
            return false;
          }, waitForWebKitLinkLoaded);
        };
        if (success) {
          state.passed.push(success);
        }
        if (failure) {
          state.failed.push(failure);
        }
        if (state.status === 1) {
          return;
        }
        if (state.status === 2) {
          passed();
          return;
        }
        if (state.status === 3) {
          failed();
          return;
        }
        state.status = 1;
        var linkElem = SugarElement.fromTag('link', doc.dom);
        setAll(linkElem, {
          rel: 'stylesheet',
          type: 'text/css',
          id: state.id
        });
        var startTime = Date.now();
        if (settings.contentCssCors) {
          set(linkElem, 'crossOrigin', 'anonymous');
        }
        if (settings.referrerPolicy) {
          set(linkElem, 'referrerpolicy', settings.referrerPolicy);
        }
        link = linkElem.dom;
        link.onload = waitForWebKitLinkLoaded;
        link.onerror = failed;
        addStyle(linkElem);
        set(linkElem, 'href', urlWithSuffix);
      };
      var loadF = function (url) {
        return Future.nu(function (resolve) {
          load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
        });
      };
      var loadAll = function (urls, success, failure) {
        par$1(map(urls, loadF)).get(function (result) {
          var parts = partition(result, function (r) {
            return r.isValue();
          });
          if (parts.fail.length &gt; 0) {
            failure(parts.fail.map(unite));
          } else {
            success(parts.pass.map(unite));
          }
        });
      };
      var unload = function (url) {
        var urlWithSuffix = Tools._addCacheSuffix(url);
        get$1(loadedStates, urlWithSuffix).each(function (state) {
          var count = --state.count;
          if (count === 0) {
            delete loadedStates[urlWithSuffix];
            removeStyle(state.id);
          }
        });
      };
      var unloadAll = function (urls) {
        each(urls, function (url) {
          unload(url);
        });
      };
      return {
        load: load,
        loadAll: loadAll,
        unload: unload,
        unloadAll: unloadAll,
        _setReferrerPolicy: _setReferrerPolicy
      };
    };

    var create$1 = function () {
      var map = new WeakMap();
      var forElement = function (referenceElement, settings) {
        var root = getRootNode(referenceElement);
        var rootDom = root.dom;
        return Optional.from(map.get(rootDom)).getOrThunk(function () {
          var sl = StyleSheetLoader(rootDom, settings);
          map.set(rootDom, sl);
          return sl;
        });
      };
      return { forElement: forElement };
    };
    var instance = create$1();

    var DomTreeWalker = function () {
      function DomTreeWalker(startNode, rootNode) {
        this.node = startNode;
        this.rootNode = rootNode;
        this.current = this.current.bind(this);
        this.next = this.next.bind(this);
        this.prev = this.prev.bind(this);
        this.prev2 = this.prev2.bind(this);
      }
      DomTreeWalker.prototype.current = function () {
        return this.node;
      };
      DomTreeWalker.prototype.next = function (shallow) {
        this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
        return this.node;
      };
      DomTreeWalker.prototype.prev = function (shallow) {
        this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
        return this.node;
      };
      DomTreeWalker.prototype.prev2 = function (shallow) {
        this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
        return this.node;
      };
      DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
        var sibling, parent;
        if (node) {
          if (!shallow &amp;&amp; node[startName]) {
            return node[startName];
          }
          if (node !== this.rootNode) {
            sibling = node[siblingName];
            if (sibling) {
              return sibling;
            }
            for (parent = node.parentNode; parent &amp;&amp; parent !== this.rootNode; parent = parent.parentNode) {
              sibling = parent[siblingName];
              if (sibling) {
                return sibling;
              }
            }
          }
        }
      };
      DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
        var sibling, parent, child;
        if (node) {
          sibling = node[siblingName];
          if (this.rootNode &amp;&amp; sibling === this.rootNode) {
            return;
          }
          if (sibling) {
            if (!shallow) {
              for (child = sibling[startName]; child; child = child[startName]) {
                if (!child[startName]) {
                  return child;
                }
              }
            }
            return sibling;
          }
          parent = node.parentNode;
          if (parent &amp;&amp; parent !== this.rootNode) {
            return parent;
          }
        }
      };
      return DomTreeWalker;
    }();

    var blocks = [
      'article',
      'aside',
      'details',
      'div',
      'dt',
      'figcaption',
      'footer',
      'form',
      'fieldset',
      'header',
      'hgroup',
      'html',
      'main',
      'nav',
      'section',
      'summary',
      'body',
      'p',
      'dl',
      'multicol',
      'dd',
      'figure',
      'address',
      'center',
      'blockquote',
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6',
      'listing',
      'xmp',
      'pre',
      'plaintext',
      'menu',
      'dir',
      'ul',
      'ol',
      'li',
      'hr',
      'table',
      'tbody',
      'thead',
      'tfoot',
      'th',
      'tr',
      'td',
      'caption'
    ];
    var tableCells = [
      'td',
      'th'
    ];
    var tableSections = [
      'thead',
      'tbody',
      'tfoot'
    ];
    var textBlocks = [
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6',
      'p',
      'div',
      'address',
      'pre',
      'form',
      'blockquote',
      'center',
      'dir',
      'fieldset',
      'header',
      'footer',
      'article',
      'section',
      'hgroup',
      'aside',
      'nav',
      'figure'
    ];
    var headings = [
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6'
    ];
    var listItems = [
      'li',
      'dd',
      'dt'
    ];
    var lists = [
      'ul',
      'ol',
      'dl'
    ];
    var wsElements = [
      'pre',
      'script',
      'textarea',
      'style'
    ];
    var lazyLookup = function (items) {
      var lookup;
      return function (node) {
        lookup = lookup ? lookup : mapToObject(items, always);
        return lookup.hasOwnProperty(name(node));
      };
    };
    var isHeading = lazyLookup(headings);
    var isBlock = lazyLookup(blocks);
    var isTable$1 = function (node) {
      return name(node) === 'table';
    };
    var isInline = function (node) {
      return isElement(node) &amp;&amp; !isBlock(node);
    };
    var isBr$1 = function (node) {
      return isElement(node) &amp;&amp; name(node) === 'br';
    };
    var isTextBlock = lazyLookup(textBlocks);
    var isList = lazyLookup(lists);
    var isListItem = lazyLookup(listItems);
    var isTableSection = lazyLookup(tableSections);
    var isTableCell$1 = lazyLookup(tableCells);
    var isWsPreserveElement = lazyLookup(wsElements);

    var ancestor$2 = function (scope, selector, isRoot) {
      return ancestor$1(scope, selector, isRoot).isSome();
    };

    var zeroWidth = '\uFEFF';
    var nbsp = '\xA0';
    var isZwsp = function (char) {
      return char === zeroWidth;
    };
    var removeZwsp = function (s) {
      return s.replace(/\uFEFF/g, '');
    };

    var ZWSP = zeroWidth;
    var isZwsp$1 = isZwsp;
    var trim$2 = removeZwsp;

    var isElement$2 = isElement$1;
    var isText$2 = isText$1;
    var isCaretContainerBlock = function (node) {
      if (isText$2(node)) {
        node = node.parentNode;
      }
      return isElement$2(node) &amp;&amp; node.hasAttribute('data-mce-caret');
    };
    var isCaretContainerInline = function (node) {
      return isText$2(node) &amp;&amp; isZwsp$1(node.data);
    };
    var isCaretContainer = function (node) {
      return isCaretContainerBlock(node) || isCaretContainerInline(node);
    };
    var hasContent = function (node) {
      return node.firstChild !== node.lastChild || !isBr(node.firstChild);
    };
    var insertInline = function (node, before) {
      var sibling;
      var doc = node.ownerDocument;
      var textNode = doc.createTextNode(ZWSP);
      var parentNode = node.parentNode;
      if (!before) {
        sibling = node.nextSibling;
        if (isText$2(sibling)) {
          if (isCaretContainer(sibling)) {
            return sibling;
          }
          if (startsWithCaretContainer(sibling)) {
            sibling.splitText(1);
            return sibling;
          }
        }
        if (node.nextSibling) {
          parentNode.insertBefore(textNode, node.nextSibling);
        } else {
          parentNode.appendChild(textNode);
        }
      } else {
        sibling = node.previousSibling;
        if (isText$2(sibling)) {
          if (isCaretContainer(sibling)) {
            return sibling;
          }
          if (endsWithCaretContainer(sibling)) {
            return sibling.splitText(sibling.data.length - 1);
          }
        }
        parentNode.insertBefore(textNode, node);
      }
      return textNode;
    };
    var isBeforeInline = function (pos) {
      var container = pos.container();
      if (!isText$1(container)) {
        return false;
      }
      return container.data.charAt(pos.offset()) === ZWSP || pos.isAtStart() &amp;&amp; isCaretContainerInline(container.previousSibling);
    };
    var isAfterInline = function (pos) {
      var container = pos.container();
      if (!isText$1(container)) {
        return false;
      }
      return container.data.charAt(pos.offset() - 1) === ZWSP || pos.isAtEnd() &amp;&amp; isCaretContainerInline(container.nextSibling);
    };
    var createBogusBr = function () {
      var br = document.createElement('br');
      br.setAttribute('data-mce-bogus', '1');
      return br;
    };
    var insertBlock = function (blockName, node, before) {
      var doc = node.ownerDocument;
      var blockNode = doc.createElement(blockName);
      blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
      blockNode.setAttribute('data-mce-bogus', 'all');
      blockNode.appendChild(createBogusBr());
      var parentNode = node.parentNode;
      if (!before) {
        if (node.nextSibling) {
          parentNode.insertBefore(blockNode, node.nextSibling);
        } else {
          parentNode.appendChild(blockNode);
        }
      } else {
        parentNode.insertBefore(blockNode, node);
      }
      return blockNode;
    };
    var startsWithCaretContainer = function (node) {
      return isText$2(node) &amp;&amp; node.data[0] === ZWSP;
    };
    var endsWithCaretContainer = function (node) {
      return isText$2(node) &amp;&amp; node.data[node.data.length - 1] === ZWSP;
    };
    var trimBogusBr = function (elm) {
      var brs = elm.getElementsByTagName('br');
      var lastBr = brs[brs.length - 1];
      if (isBogus(lastBr)) {
        lastBr.parentNode.removeChild(lastBr);
      }
    };
    var showCaretContainerBlock = function (caretContainer) {
      if (caretContainer &amp;&amp; caretContainer.hasAttribute('data-mce-caret')) {
        trimBogusBr(caretContainer);
        caretContainer.removeAttribute('data-mce-caret');
        caretContainer.removeAttribute('data-mce-bogus');
        caretContainer.removeAttribute('style');
        caretContainer.removeAttribute('_moz_abspos');
        return caretContainer;
      }
      return null;
    };
    var isRangeInCaretContainerBlock = function (range) {
      return isCaretContainerBlock(range.startContainer);
    };

    var isContentEditableTrue$1 = isContentEditableTrue;
    var isContentEditableFalse$1 = isContentEditableFalse;
    var isBr$2 = isBr;
    var isText$3 = isText$1;
    var isInvalidTextElement = matchNodeNames([
      'script',
      'style',
      'textarea'
    ]);
    var isAtomicInline = matchNodeNames([
      'img',
      'input',
      'textarea',
      'hr',
      'iframe',
      'video',
      'audio',
      'object',
      'embed'
    ]);
    var isTable$2 = matchNodeNames(['table']);
    var isCaretContainer$1 = isCaretContainer;
    var isCaretCandidate = function (node) {
      if (isCaretContainer$1(node)) {
        return false;
      }
      if (isText$3(node)) {
        return !isInvalidTextElement(node.parentNode);
      }
      return isAtomicInline(node) || isBr$2(node) || isTable$2(node) || isNonUiContentEditableFalse(node);
    };
    var isUnselectable = function (node) {
      return isElement$1(node) &amp;&amp; node.getAttribute('unselectable') === 'true';
    };
    var isNonUiContentEditableFalse = function (node) {
      return isUnselectable(node) === false &amp;&amp; isContentEditableFalse$1(node);
    };
    var isInEditable = function (node, root) {
      for (node = node.parentNode; node &amp;&amp; node !== root; node = node.parentNode) {
        if (isNonUiContentEditableFalse(node)) {
          return false;
        }
        if (isContentEditableTrue$1(node)) {
          return true;
        }
      }
      return true;
    };
    var isAtomicContentEditableFalse = function (node) {
      if (!isNonUiContentEditableFalse(node)) {
        return false;
      }
      return foldl(from$1(node.getElementsByTagName('*')), function (result, elm) {
        return result || isContentEditableTrue$1(elm);
      }, false) !== true;
    };
    var isAtomic = function (node) {
      return isAtomicInline(node) || isAtomicContentEditableFalse(node);
    };
    var isEditableCaretCandidate = function (node, root) {
      return isCaretCandidate(node) &amp;&amp; isInEditable(node, root);
    };

    var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
    var isWhitespaceText = function (text) {
      return whiteSpaceRegExp$1.test(text);
    };

    var hasWhitespacePreserveParent = function (node, rootNode) {
      var rootElement = SugarElement.fromDom(rootNode);
      var startNode = SugarElement.fromDom(node);
      return ancestor$2(startNode, 'pre,code', curry(eq$2, rootElement));
    };
    var isWhitespace = function (node, rootNode) {
      return isText$1(node) &amp;&amp; isWhitespaceText(node.data) &amp;&amp; hasWhitespacePreserveParent(node, rootNode) === false;
    };
    var isNamedAnchor = function (node) {
      return isElement$1(node) &amp;&amp; node.nodeName === 'A' &amp;&amp; !node.hasAttribute('href') &amp;&amp; (node.hasAttribute('name') || node.hasAttribute('id'));
    };
    var isContent = function (node, rootNode) {
      return isCaretCandidate(node) &amp;&amp; isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
    };
    var isBookmark = hasAttribute('data-mce-bookmark');
    var isBogus$1 = hasAttribute('data-mce-bogus');
    var isBogusAll$1 = hasAttributeValue('data-mce-bogus', 'all');
    var isEmptyNode = function (targetNode, skipBogus) {
      var node, brCount = 0;
      if (isContent(targetNode, targetNode)) {
        return false;
      } else {
        node = targetNode.firstChild;
        if (!node) {
          return true;
        }
        var walker = new DomTreeWalker(node, targetNode);
        do {
          if (skipBogus) {
            if (isBogusAll$1(node)) {
              node = walker.next(true);
              continue;
            }
            if (isBogus$1(node)) {
              node = walker.next();
              continue;
            }
          }
          if (isBr(node)) {
            brCount++;
            node = walker.next();
            continue;
          }
          if (isContent(node, targetNode)) {
            return false;
          }
          node = walker.next();
        } while (node);
        return brCount &lt;= 1;
      }
    };
    var isEmpty = function (elm, skipBogus) {
      if (skipBogus === void 0) {
        skipBogus = true;
      }
      return isEmptyNode(elm.dom, skipBogus);
    };

    var isSpan = function (node) {
      return node.nodeName.toLowerCase() === 'span';
    };
    var isInlineContent = function (node, root) {
      return isNonNullable(node) &amp;&amp; (isContent(node, root) || isInline(SugarElement.fromDom(node)));
    };
    var surroundedByInlineContent = function (node, root) {
      var prev = new DomTreeWalker(node, root).prev(false);
      var next = new DomTreeWalker(node, root).next(false);
      var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
      var nextIsInline = isUndefined(next) || isInlineContent(next, root);
      return prevIsInline &amp;&amp; nextIsInline;
    };
    var isBookmarkNode = function (node) {
      return isSpan(node) &amp;&amp; node.getAttribute('data-mce-type') === 'bookmark';
    };
    var isKeepTextNode = function (node, root) {
      return isText$1(node) &amp;&amp; node.data.length &gt; 0 &amp;&amp; surroundedByInlineContent(node, root);
    };
    var isKeepElement = function (node) {
      return isElement$1(node) ? node.childNodes.length &gt; 0 : false;
    };
    var isDocument$2 = function (node) {
      return isDocumentFragment$1(node) || isDocument$1(node);
    };
    var trimNode = function (dom, node, root) {
      var rootNode = root || node;
      if (isElement$1(node) &amp;&amp; isBookmarkNode(node)) {
        return node;
      }
      var children = node.childNodes;
      for (var i = children.length - 1; i &gt;= 0; i--) {
        trimNode(dom, children[i], rootNode);
      }
      if (isElement$1(node)) {
        var currentChildren = node.childNodes;
        if (currentChildren.length === 1 &amp;&amp; isBookmarkNode(currentChildren[0])) {
          node.parentNode.insertBefore(currentChildren[0], node);
        }
      }
      if (!isDocument$2(node) &amp;&amp; !isContent(node, rootNode) &amp;&amp; !isKeepElement(node) &amp;&amp; !isKeepTextNode(node, rootNode)) {
        dom.remove(node);
      }
      return node;
    };

    var makeMap$1 = Tools.makeMap;
    var attrsCharsRegExp = /[&amp;&lt;&gt;\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    var textCharsRegExp = /[&lt;&gt;&amp;\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    var rawCharsRegExp = /[&lt;&gt;&amp;\"\']/g;
    var entityRegExp = /&amp;#([a-z0-9]+);?|&amp;([a-z0-9]+);/gi;
    var 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',
      142: '\u017d',
      145: '\u2018',
      146: '\u2019',
      147: '\u201C',
      148: '\u201D',
      149: '\u2022',
      150: '\u2013',
      151: '\u2014',
      152: '\u02DC',
      153: '\u2122',
      154: '\u0161',
      155: '\u203A',
      156: '\u0153',
      158: '\u017e',
      159: '\u0178'
    };
    var baseEntities = {
      '"': '&amp;quot;',
      '\'': '&amp;#39;',
      '&lt;': '&amp;lt;',
      '&gt;': '&amp;gt;',
      '&amp;': '&amp;amp;',
      '`': '&amp;#96;'
    };
    var reverseEntities = {
      '&amp;lt;': '&lt;',
      '&amp;gt;': '&gt;',
      '&amp;amp;': '&amp;',
      '&amp;quot;': '"',
      '&amp;apos;': '\''
    };
    var nativeDecode = function (text) {
      var elm = SugarElement.fromTag('div').dom;
      elm.innerHTML = text;
      return elm.textContent || elm.innerText || text;
    };
    var buildEntitiesLookup = function (items, radix) {
      var i, chr, entity;
      var lookup = {};
      if (items) {
        items = items.split(',');
        radix = radix || 10;
        for (i = 0; i &lt; items.length; i += 2) {
          chr = String.fromCharCode(parseInt(items[i], radix));
          if (!baseEntities[chr]) {
            entity = '&amp;' + items[i + 1] + ';';
            lookup[chr] = entity;
            lookup[entity] = chr;
          }
        }
        return lookup;
      }
    };
    var namedEntities = buildEntitiesLookup('50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + '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);
    var encodeRaw = function (text, attr) {
      return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
        return baseEntities[chr] || chr;
      });
    };
    var encodeAllRaw = function (text) {
      return ('' + text).replace(rawCharsRegExp, function (chr) {
        return baseEntities[chr] || chr;
      });
    };
    var encodeNumeric = function (text, attr) {
      return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
        if (chr.length &gt; 1) {
          return '&amp;#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
        }
        return baseEntities[chr] || '&amp;#' + chr.charCodeAt(0) + ';';
      });
    };
    var encodeNamed = function (text, attr, entities) {
      entities = entities || namedEntities;
      return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
        return baseEntities[chr] || entities[chr] || chr;
      });
    };
    var getEncodeFunc = function (name, entities) {
      var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
      var encodeNamedAndNumeric = function (text, attr) {
        return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
          if (baseEntities[chr] !== undefined) {
            return baseEntities[chr];
          }
          if (entitiesMap[chr] !== undefined) {
            return entitiesMap[chr];
          }
          if (chr.length &gt; 1) {
            return '&amp;#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
          }
          return '&amp;#' + chr.charCodeAt(0) + ';';
        });
      };
      var encodeCustomNamed = function (text, attr) {
        return encodeNamed(text, attr, entitiesMap);
      };
      var nameMap = makeMap$1(name.replace(/\+/g, ','));
      if (nameMap.named &amp;&amp; nameMap.numeric) {
        return encodeNamedAndNumeric;
      }
      if (nameMap.named) {
        if (entities) {
          return encodeCustomNamed;
        }
        return encodeNamed;
      }
      if (nameMap.numeric) {
        return encodeNumeric;
      }
      return encodeRaw;
    };
    var decode = function (text) {
      return text.replace(entityRegExp, function (all, numeric) {
        if (numeric) {
          if (numeric.charAt(0).toLowerCase() === 'x') {
            numeric = parseInt(numeric.substr(1), 16);
          } else {
            numeric = parseInt(numeric, 10);
          }
          if (numeric &gt; 65535) {
            numeric -= 65536;
            return String.fromCharCode(55296 + (numeric &gt;&gt; 10), 56320 + (numeric &amp; 1023));
          }
          return asciiMap[numeric] || String.fromCharCode(numeric);
        }
        return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
      });
    };
    var Entities = {
      encodeRaw: encodeRaw,
      encodeAllRaw: encodeAllRaw,
      encodeNumeric: encodeNumeric,
      encodeNamed: encodeNamed,
      getEncodeFunc: getEncodeFunc,
      decode: decode
    };

    var mapCache = {}, dummyObj = {};
    var makeMap$2 = Tools.makeMap, each$3 = Tools.each, extend$1 = Tools.extend, explode$1 = Tools.explode, inArray = Tools.inArray;
    var split = function (items, delim) {
      items = Tools.trim(items);
      return items ? items.split(delim || ' ') : [];
    };
    var compileSchema = function (type) {
      var schema = {};
      var globalAttributes, blockContent;
      var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
      var add = function (name, attributes, children) {
        var ni, attributesOrder, element;
        var arrayToMap = function (array, obj) {
          var map = {};
          var i, l;
          for (i = 0, l = array.length; i &lt; l; i++) {
            map[array[i]] = obj || {};
          }
          return map;
        };
        children = children || [];
        attributes = attributes || '';
        if (typeof children === 'string') {
          children = split(children);
        }
        var names = split(name);
        ni = names.length;
        while (ni--) {
          attributesOrder = split([
            globalAttributes,
            attributes
          ].join(' '));
          element = {
            attributes: arrayToMap(attributesOrder),
            attributesOrder: attributesOrder,
            children: arrayToMap(children, dummyObj)
          };
          schema[names[ni]] = element;
        }
      };
      var addAttrs = function (name, attributes) {
        var ni, schemaItem, i, l;
        var names = split(name);
        ni = names.length;
        var attrs = split(attributes);
        while (ni--) {
          schemaItem = schema[names[ni]];
          for (i = 0, l = attrs.length; i &lt; l; i++) {
            schemaItem.attributes[attrs[i]] = {};
            schemaItem.attributesOrder.push(attrs[i]);
          }
        }
      };
      if (mapCache[type]) {
        return mapCache[type];
      }
      globalAttributes = 'id accesskey class dir lang style tabindex title role';
      blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
      phrasingContent = 'a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd ' + 'label map noscript object q s samp script select small span strong sub sup ' + 'textarea u var #text #comment';
      if (type !== 'html4') {
        globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
        blockContent += ' article aside details dialog figure main header footer hgroup section nav';
        phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
      }
      if (type !== 'html5-strict') {
        globalAttributes += ' xml:lang';
        html4PhrasingContent = 'acronym applet basefont big font strike tt';
        phrasingContent = [
          phrasingContent,
          html4PhrasingContent
        ].join(' ');
        each$3(split(html4PhrasingContent), function (name) {
          add(name, '', phrasingContent);
        });
        html4BlockContent = 'center dir isindex noframes';
        blockContent = [
          blockContent,
          html4BlockContent
        ].join(' ');
        flowContent = [
          blockContent,
          phrasingContent
        ].join(' ');
        each$3(split(html4BlockContent), function (name) {
          add(name, '', flowContent);
        });
      }
      flowContent = flowContent || [
        blockContent,
        phrasingContent
      ].join(' ');
      add('html', 'manifest', 'head body');
      add('head', '', 'base command link meta noscript script style title');
      add('title hr noscript br');
      add('base', 'href target');
      add('link', 'href rel media hreflang type sizes hreflang');
      add('meta', 'name http-equiv content charset');
      add('style', 'media type scoped');
      add('script', 'src async defer type charset');
      add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
      add('address dt dd div caption', '', flowContent);
      add('h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn', '', phrasingContent);
      add('blockquote', 'cite', flowContent);
      add('ol', 'reversed start type', 'li');
      add('ul', '', 'li');
      add('li', 'value', flowContent);
      add('dl', '', 'dt dd');
      add('a', 'href target rel media hreflang type', phrasingContent);
      add('q', 'cite', phrasingContent);
      add('ins del', 'cite datetime', flowContent);
      add('img', 'src sizes srcset alt usemap ismap width height');
      add('iframe', 'src name width height', flowContent);
      add('embed', 'src type width height');
      add('object', 'data type typemustmatch name usemap form width height', [
        flowContent,
        'param'
      ].join(' '));
      add('param', 'name value');
      add('map', 'name', [
        flowContent,
        'area'
      ].join(' '));
      add('area', 'alt coords shape href target rel media hreflang type');
      add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
      add('colgroup', 'span', 'col');
      add('col', 'span');
      add('tbody thead tfoot', '', 'tr');
      add('tr', '', 'td th');
      add('td', 'colspan rowspan headers', flowContent);
      add('th', 'colspan rowspan headers scope abbr', flowContent);
      add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
      add('fieldset', 'disabled form name', [
        flowContent,
        'legend'
      ].join(' '));
      add('label', 'form for', phrasingContent);
      add('input', 'accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate ' + 'formtarget height list max maxlength min multiple name pattern readonly required size src step type value width');
      add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
      add('select', 'disabled form multiple name required size', 'option optgroup');
      add('optgroup', 'disabled label', 'option');
      add('option', 'disabled label selected value');
      add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
      add('menu', 'type label', [
        flowContent,
        'li'
      ].join(' '));
      add('noscript', '', flowContent);
      if (type !== 'html4') {
        add('wbr');
        add('ruby', '', [
          phrasingContent,
          'rt rp'
        ].join(' '));
        add('figcaption', '', flowContent);
        add('mark rt rp summary bdi', '', phrasingContent);
        add('canvas', 'width height', flowContent);
        add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
          flowContent,
          'track source'
        ].join(' '));
        add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
          flowContent,
          'track source'
        ].join(' '));
        add('picture', '', 'img source');
        add('source', 'src srcset type media sizes');
        add('track', 'kind src srclang label default');
        add('datalist', '', [
          phrasingContent,
          'option'
        ].join(' '));
        add('article section nav aside main header footer', '', flowContent);
        add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
        add('figure', '', [
          flowContent,
          'figcaption'
        ].join(' '));
        add('time', 'datetime', phrasingContent);
        add('dialog', 'open', flowContent);
        add('command', 'type label icon disabled checked radiogroup command');
        add('output', 'for form name', phrasingContent);
        add('progress', 'value max', phrasingContent);
        add('meter', 'value min max low high optimum', phrasingContent);
        add('details', 'open', [
          flowContent,
          'summary'
        ].join(' '));
        add('keygen', 'autofocus challenge disabled form keytype name');
      }
      if (type !== 'html5-strict') {
        addAttrs('script', 'language xml:space');
        addAttrs('style', 'xml:space');
        addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
        addAttrs('embed', 'align name hspace vspace');
        addAttrs('param', 'valuetype type');
        addAttrs('a', 'charset name rev shape coords');
        addAttrs('br', 'clear');
        addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
        addAttrs('img', 'name longdesc align border hspace vspace');
        addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
        addAttrs('font basefont', 'size color face');
        addAttrs('input', 'usemap align');
        addAttrs('select');
        addAttrs('textarea');
        addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
        addAttrs('ul', 'type compact');
        addAttrs('li', 'type');
        addAttrs('ol dl menu dir', 'compact');
        addAttrs('pre', 'width xml:space');
        addAttrs('hr', 'align noshade size width');
        addAttrs('isindex', 'prompt');
        addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
        addAttrs('col', 'width align char charoff valign');
        addAttrs('colgroup', 'width align char charoff valign');
        addAttrs('thead', 'align char charoff valign');
        addAttrs('tr', 'align char charoff valign bgcolor');
        addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
        addAttrs('form', 'accept');
        addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
        addAttrs('tfoot', 'align char charoff valign');
        addAttrs('tbody', 'align char charoff valign');
        addAttrs('area', 'nohref');
        addAttrs('body', 'background bgcolor text link vlink alink');
      }
      if (type !== 'html4') {
        addAttrs('input button select textarea', 'autofocus');
        addAttrs('input textarea', 'placeholder');
        addAttrs('a', 'download');
        addAttrs('link script img', 'crossorigin');
        addAttrs('img', 'loading');
        addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
      }
      each$3(split('a form meter progress dfn'), function (name) {
        if (schema[name]) {
          delete schema[name].children[name];
        }
      });
      delete schema.caption.children.table;
      delete schema.script;
      mapCache[type] = schema;
      return schema;
    };
    var compileElementMap = function (value, mode) {
      var styles;
      if (value) {
        styles = {};
        if (typeof value === 'string') {
          value = { '*': value };
        }
        each$3(value, function (value, key) {
          styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$1(value, /[, ]/);
        });
      }
      return styles;
    };
    var Schema = function (settings) {
      var elements = {};
      var children = {};
      var patternElements = [];
      var customElementsMap = {}, specialElements = {};
      var createLookupTable = function (option, defaultValue, extendWith) {
        var value = settings[option];
        if (!value) {
          value = mapCache[option];
          if (!value) {
            value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
            value = extend$1(value, extendWith);
            mapCache[option] = value;
          }
        } else {
          value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
        }
        return value;
      };
      settings = settings || {};
      var schemaItems = compileSchema(settings.schema);
      if (settings.verify_html === false) {
        settings.valid_elements = '*[*]';
      }
      var validStyles = compileElementMap(settings.valid_styles);
      var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
      var validClasses = compileElementMap(settings.valid_classes, 'map');
      var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
      var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
      var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
      var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
      var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
      var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
      var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
      var textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside main nav figure');
      var blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option ' + 'datalist select optgroup figcaption details summary', textBlockElementsMap);
      var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
      each$3((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
        specialElements[name] = new RegExp('&lt;/' + name + '[^&gt;]*&gt;', 'gi');
      });
      var patternToRegExp = function (str) {
        return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
      };
      var addValidElements = function (validElements) {
        var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
        var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:&lt;]+)?(?:([=:&lt;])(.*))?$/, hasPatternsRegExp = /[*?+]/;
        if (validElements) {
          var validElementsArr = split(validElements, ',');
          if (elements['@']) {
            globalAttributes = elements['@'].attributes;
            globalAttributesOrder = elements['@'].attributesOrder;
          }
          for (ei = 0, el = validElementsArr.length; ei &lt; el; ei++) {
            matches = elementRuleRegExp.exec(validElementsArr[ei]);
            if (matches) {
              prefix = matches[1];
              elementName = matches[2];
              outputName = matches[3];
              attrData = matches[5];
              attributes = {};
              attributesOrder = [];
              element = {
                attributes: attributes,
                attributesOrder: attributesOrder
              };
              if (prefix === '#') {
                element.paddEmpty = true;
              }
              if (prefix === '-') {
                element.removeEmpty = true;
              }
              if (matches[4] === '!') {
                element.removeEmptyAttrs = true;
              }
              if (globalAttributes) {
                each$1(globalAttributes, function (value, key) {
                  attributes[key] = value;
                });
                attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
              }
              if (attrData) {
                attrData = split(attrData, '|');
                for (ai = 0, al = attrData.length; ai &lt; al; ai++) {
                  matches = attrRuleRegExp.exec(attrData[ai]);
                  if (matches) {
                    attr = {};
                    attrType = matches[1];
                    attrName = matches[2].replace(/[\\:]:/g, ':');
                    prefix = matches[3];
                    value = matches[4];
                    if (attrType === '!') {
                      element.attributesRequired = element.attributesRequired || [];
                      element.attributesRequired.push(attrName);
                      attr.required = true;
                    }
                    if (attrType === '-') {
                      delete attributes[attrName];
                      attributesOrder.splice(inArray(attributesOrder, attrName), 1);
                      continue;
                    }
                    if (prefix) {
                      if (prefix === '=') {
                        element.attributesDefault = element.attributesDefault || [];
                        element.attributesDefault.push({
                          name: attrName,
                          value: value
                        });
                        attr.defaultValue = value;
                      }
                      if (prefix === ':') {
                        element.attributesForced = element.attributesForced || [];
                        element.attributesForced.push({
                          name: attrName,
                          value: value
                        });
                        attr.forcedValue = value;
                      }
                      if (prefix === '&lt;') {
                        attr.validValues = makeMap$2(value, '?');
                      }
                    }
                    if (hasPatternsRegExp.test(attrName)) {
                      element.attributePatterns = element.attributePatterns || [];
                      attr.pattern = patternToRegExp(attrName);
                      element.attributePatterns.push(attr);
                    } else {
                      if (!attributes[attrName]) {
                        attributesOrder.push(attrName);
                      }
                      attributes[attrName] = attr;
                    }
                  }
                }
              }
              if (!globalAttributes &amp;&amp; elementName === '@') {
                globalAttributes = attributes;
                globalAttributesOrder = attributesOrder;
              }
              if (outputName) {
                element.outputName = elementName;
                elements[outputName] = element;
              }
              if (hasPatternsRegExp.test(elementName)) {
                element.pattern = patternToRegExp(elementName);
                patternElements.push(element);
              } else {
                elements[elementName] = element;
              }
            }
          }
        }
      };
      var setValidElements = function (validElements) {
        elements = {};
        patternElements = [];
        addValidElements(validElements);
        each$3(schemaItems, function (element, name) {
          children[name] = element.children;
        });
      };
      var addCustomElements = function (customElements) {
        var customElementRegExp = /^(~)?(.+)$/;
        if (customElements) {
          mapCache.text_block_elements = mapCache.block_elements = null;
          each$3(split(customElements, ','), function (rule) {
            var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
            children[name] = children[cloneName];
            customElementsMap[name] = cloneName;
            if (!inline) {
              blockElementsMap[name.toUpperCase()] = {};
              blockElementsMap[name] = {};
            }
            if (!elements[name]) {
              var customRule = elements[cloneName];
              customRule = extend$1({}, customRule);
              delete customRule.removeEmptyAttrs;
              delete customRule.removeEmpty;
              elements[name] = customRule;
            }
            each$3(children, function (element, elmName) {
              if (element[cloneName]) {
                children[elmName] = element = extend$1({}, children[elmName]);
                element[name] = element[cloneName];
              }
            });
          });
        }
      };
      var addValidChildren = function (validChildren) {
        var childRuleRegExp = /^([+\-]?)([A-Za-z0-9_\-.\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+)\[([^\]]+)]$/;
        mapCache[settings.schema] = null;
        if (validChildren) {
          each$3(split(validChildren, ','), function (rule) {
            var matches = childRuleRegExp.exec(rule);
            var parent, prefix;
            if (matches) {
              prefix = matches[1];
              if (prefix) {
                parent = children[matches[2]];
              } else {
                parent = children[matches[2]] = { '#comment': {} };
              }
              parent = children[matches[2]];
              each$3(split(matches[3], '|'), function (child) {
                if (prefix === '-') {
                  delete parent[child];
                } else {
                  parent[child] = {};
                }
              });
            }
          });
        }
      };
      var getElementRule = function (name) {
        var element = elements[name], i;
        if (element) {
          return element;
        }
        i = patternElements.length;
        while (i--) {
          element = patternElements[i];
          if (element.pattern.test(name)) {
            return element;
          }
        }
      };
      if (!settings.valid_elements) {
        each$3(schemaItems, function (element, name) {
          elements[name] = {
            attributes: element.attributes,
            attributesOrder: element.attributesOrder
          };
          children[name] = element.children;
        });
        if (settings.schema !== 'html5') {
          each$3(split('strong/b em/i'), function (item) {
            var items = split(item, '/');
            elements[items[1]].outputName = items[0];
          });
        }
        each$3(split('ol ul sub sup blockquote span font a table tbody strong em b i'), function (name) {
          if (elements[name]) {
            elements[name].removeEmpty = true;
          }
        });
        each$3(split('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
          elements[name].paddEmpty = true;
        });
        each$3(split('span'), function (name) {
          elements[name].removeEmptyAttrs = true;
        });
      } else {
        setValidElements(settings.valid_elements);
      }
      addCustomElements(settings.custom_elements);
      addValidChildren(settings.valid_children);
      addValidElements(settings.extended_valid_elements);
      addValidChildren('+ol[ul|ol],+ul[ul|ol]');
      each$3({
        dd: 'dl',
        dt: 'dl',
        li: 'ul ol',
        td: 'tr',
        th: 'tr',
        tr: 'tbody thead tfoot',
        tbody: 'table',
        thead: 'table',
        tfoot: 'table',
        legend: 'fieldset',
        area: 'map',
        param: 'video audio object'
      }, function (parents, item) {
        if (elements[item]) {
          elements[item].parentsRequired = split(parents);
        }
      });
      if (settings.invalid_elements) {
        each$3(explode$1(settings.invalid_elements), function (item) {
          if (elements[item]) {
            delete elements[item];
          }
        });
      }
      if (!getElementRule('span')) {
        addValidElements('span[!data-mce-type|*]');
      }
      var getValidStyles = function () {
        return validStyles;
      };
      var getInvalidStyles = function () {
        return invalidStyles;
      };
      var getValidClasses = function () {
        return validClasses;
      };
      var getBoolAttrs = function () {
        return boolAttrMap;
      };
      var getBlockElements = function () {
        return blockElementsMap;
      };
      var getTextBlockElements = function () {
        return textBlockElementsMap;
      };
      var getTextInlineElements = function () {
        return textInlineElementsMap;
      };
      var getShortEndedElements = function () {
        return shortEndedElementsMap;
      };
      var getSelfClosingElements = function () {
        return selfClosingElementsMap;
      };
      var getNonEmptyElements = function () {
        return nonEmptyElementsMap;
      };
      var getMoveCaretBeforeOnEnterElements = function () {
        return moveCaretBeforeOnEnterElementsMap;
      };
      var getWhiteSpaceElements = function () {
        return whiteSpaceElementsMap;
      };
      var getSpecialElements = function () {
        return specialElements;
      };
      var isValidChild = function (name, child) {
        var parent = children[name.toLowerCase()];
        return !!(parent &amp;&amp; parent[child.toLowerCase()]);
      };
      var isValid = function (name, attr) {
        var attrPatterns, i;
        var rule = getElementRule(name);
        if (rule) {
          if (attr) {
            if (rule.attributes[attr]) {
              return true;
            }
            attrPatterns = rule.attributePatterns;
            if (attrPatterns) {
              i = attrPatterns.length;
              while (i--) {
                if (attrPatterns[i].pattern.test(name)) {
                  return true;
                }
              }
            }
          } else {
            return true;
          }
        }
        return false;
      };
      var getCustomElements = function () {
        return customElementsMap;
      };
      return {
        children: children,
        elements: elements,
        getValidStyles: getValidStyles,
        getValidClasses: getValidClasses,
        getBlockElements: getBlockElements,
        getInvalidStyles: getInvalidStyles,
        getShortEndedElements: getShortEndedElements,
        getTextBlockElements: getTextBlockElements,
        getTextInlineElements: getTextInlineElements,
        getBoolAttrs: getBoolAttrs,
        getElementRule: getElementRule,
        getSelfClosingElements: getSelfClosingElements,
        getNonEmptyElements: getNonEmptyElements,
        getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
        getWhiteSpaceElements: getWhiteSpaceElements,
        getSpecialElements: getSpecialElements,
        isValidChild: isValidChild,
        isValid: isValid,
        getCustomElements: getCustomElements,
        addValidElements: addValidElements,
        setValidElements: setValidElements,
        addCustomElements: addCustomElements,
        addValidChildren: addValidChildren
      };
    };

    var toHex = function (match, r, g, b) {
      var hex = function (val) {
        val = parseInt(val, 10).toString(16);
        return val.length &gt; 1 ? val : '0' + val;
      };
      return '#' + hex(r) + hex(g) + hex(b);
    };
    var Styles = function (settings, schema) {
      var _this = this;
      var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
      var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
      var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
      var trimRightRegExp = /\s+$/;
      var i;
      var encodingLookup = {};
      var validStyles;
      var invalidStyles;
      var invisibleChar = zeroWidth;
      settings = settings || {};
      if (schema) {
        validStyles = schema.getValidStyles();
        invalidStyles = schema.getInvalidStyles();
      }
      var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
      for (i = 0; i &lt; encodingItems.length; i++) {
        encodingLookup[encodingItems[i]] = invisibleChar + i;
        encodingLookup[invisibleChar + i] = encodingItems[i];
      }
      return {
        toHex: function (color) {
          return color.replace(rgbRegExp, toHex);
        },
        parse: function (css) {
          var styles = {};
          var matches, name, value, isEncoded;
          var urlConverter = settings.url_converter;
          var urlConverterScope = settings.url_converter_scope || _this;
          var compress = function (prefix, suffix, noJoin) {
            var top = styles[prefix + '-top' + suffix];
            if (!top) {
              return;
            }
            var right = styles[prefix + '-right' + suffix];
            if (!right) {
              return;
            }
            var bottom = styles[prefix + '-bottom' + suffix];
            if (!bottom) {
              return;
            }
            var left = styles[prefix + '-left' + suffix];
            if (!left) {
              return;
            }
            var box = [
              top,
              right,
              bottom,
              left
            ];
            i = box.length - 1;
            while (i--) {
              if (box[i] !== box[i + 1]) {
                break;
              }
            }
            if (i &gt; -1 &amp;&amp; noJoin) {
              return;
            }
            styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
            delete styles[prefix + '-top' + suffix];
            delete styles[prefix + '-right' + suffix];
            delete styles[prefix + '-bottom' + suffix];
            delete styles[prefix + '-left' + suffix];
          };
          var canCompress = function (key) {
            var value = styles[key], i;
            if (!value) {
              return;
            }
            value = value.split(' ');
            i = value.length;
            while (i--) {
              if (value[i] !== value[0]) {
                return false;
              }
            }
            styles[key] = value[0];
            return true;
          };
          var compress2 = function (target, a, b, c) {
            if (!canCompress(a)) {
              return;
            }
            if (!canCompress(b)) {
              return;
            }
            if (!canCompress(c)) {
              return;
            }
            styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
            delete styles[a];
            delete styles[b];
            delete styles[c];
          };
          var encode = function (str) {
            isEncoded = true;
            return encodingLookup[str];
          };
          var decode = function (str, keepSlashes) {
            if (isEncoded) {
              str = str.replace(/\uFEFF[0-9]/g, function (str) {
                return encodingLookup[str];
              });
            }
            if (!keepSlashes) {
              str = str.replace(/\\([\'\";:])/g, '$1');
            }
            return str;
          };
          var decodeSingleHexSequence = function (escSeq) {
            return String.fromCharCode(parseInt(escSeq.slice(1), 16));
          };
          var decodeHexSequences = function (value) {
            return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
          };
          var processUrl = function (match, url, url2, url3, str, str2) {
            str = str || str2;
            if (str) {
              str = decode(str);
              return '\'' + str.replace(/\'/g, '\\\'') + '\'';
            }
            url = decode(url || url2 || url3);
            if (!settings.allow_script_urls) {
              var scriptUrl = url.replace(/[\s\r\n]+/g, '');
              if (/(java|vb)script:/i.test(scriptUrl)) {
                return '';
              }
              if (!settings.allow_svg_data_urls &amp;&amp; /^data:image\/svg/i.test(scriptUrl)) {
                return '';
              }
            }
            if (urlConverter) {
              url = urlConverter.call(urlConverterScope, url, 'style');
            }
            return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
          };
          if (css) {
            css = css.replace(/[\u0000-\u001F]/g, '');
            css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
              return str.replace(/[;:]/g, encode);
            });
            while (matches = styleRegExp.exec(css)) {
              styleRegExp.lastIndex = matches.index + matches[0].length;
              name = matches[1].replace(trimRightRegExp, '').toLowerCase();
              value = matches[2].replace(trimRightRegExp, '');
              if (name &amp;&amp; value) {
                name = decodeHexSequences(name);
                value = decodeHexSequences(value);
                if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
                  continue;
                }
                if (!settings.allow_script_urls &amp;&amp; (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
                  continue;
                }
                if (name === 'font-weight' &amp;&amp; value === '700') {
                  value = 'bold';
                } else if (name === 'color' || name === 'background-color') {
                  value = value.toLowerCase();
                }
                value = value.replace(rgbRegExp, toHex);
                value = value.replace(urlOrStrRegExp, processUrl);
                styles[name] = isEncoded ? decode(value, true) : value;
              }
            }
            compress('border', '', true);
            compress('border', '-width');
            compress('border', '-color');
            compress('border', '-style');
            compress('padding', '');
            compress('margin', '');
            compress2('border', 'border-width', 'border-style', 'border-color');
            if (styles.border === 'medium none') {
              delete styles.border;
            }
            if (styles['border-image'] === 'none') {
              delete styles['border-image'];
            }
          }
          return styles;
        },
        serialize: function (styles, elementName) {
          var css = '';
          var serializeStyles = function (name) {
            var value;
            var styleList = validStyles[name];
            if (styleList) {
              for (var i_1 = 0, l = styleList.length; i_1 &lt; l; i_1++) {
                name = styleList[i_1];
                value = styles[name];
                if (value) {
                  css += (css.length &gt; 0 ? ' ' : '') + name + ': ' + value + ';';
                }
              }
            }
          };
          var isValid = function (name, elementName) {
            var styleMap = invalidStyles['*'];
            if (styleMap &amp;&amp; styleMap[name]) {
              return false;
            }
            styleMap = invalidStyles[elementName];
            return !(styleMap &amp;&amp; styleMap[name]);
          };
          if (elementName &amp;&amp; validStyles) {
            serializeStyles('*');
            serializeStyles(elementName);
          } else {
            each$1(styles, function (value, name) {
              if (value &amp;&amp; (!invalidStyles || isValid(name, elementName))) {
                css += (css.length &gt; 0 ? ' ' : '') + name + ': ' + value + ';';
              }
            });
          }
          return css;
        }
      };
    };

    var eventExpandoPrefix = 'mce-data-';
    var mouseEventRe = /^(?:mouse|contextmenu)|click/;
    var deprecated = {
      keyLocation: 1,
      layerX: 1,
      layerY: 1,
      returnValue: 1,
      webkitMovementX: 1,
      webkitMovementY: 1,
      keyIdentifier: 1,
      mozPressure: 1
    };
    var hasIsDefaultPrevented = function (event) {
      return event.isDefaultPrevented === returnTrue || event.isDefaultPrevented === returnFalse;
    };
    var returnFalse = never;
    var returnTrue = always;
    var addEvent = function (target, name, callback, capture) {
      if (target.addEventListener) {
        target.addEventListener(name, callback, capture || false);
      } else if (target.attachEvent) {
        target.attachEvent('on' + name, callback);
      }
    };
    var removeEvent = function (target, name, callback, capture) {
      if (target.removeEventListener) {
        target.removeEventListener(name, callback, capture || false);
      } else if (target.detachEvent) {
        target.detachEvent('on' + name, callback);
      }
    };
    var isMouseEvent = function (event) {
      return mouseEventRe.test(event.type);
    };
    var fix = function (originalEvent, data) {
      var name;
      var event = data || {};
      for (name in originalEvent) {
        if (!deprecated[name]) {
          event[name] = originalEvent[name];
        }
      }
      if (!event.target) {
        event.target = event.srcElement || document;
      }
      if (event.composedPath) {
        event.composedPath = function () {
          return originalEvent.composedPath();
        };
      }
      if (originalEvent &amp;&amp; isMouseEvent(originalEvent) &amp;&amp; originalEvent.pageX === undefined &amp;&amp; originalEvent.clientX !== undefined) {
        var eventDoc = event.target.ownerDocument || document;
        var doc = eventDoc.documentElement;
        var body = eventDoc.body;
        event.pageX = originalEvent.clientX + (doc &amp;&amp; doc.scrollLeft || body &amp;&amp; body.scrollLeft || 0) - (doc &amp;&amp; doc.clientLeft || body &amp;&amp; body.clientLeft || 0);
        event.pageY = originalEvent.clientY + (doc &amp;&amp; doc.scrollTop || body &amp;&amp; body.scrollTop || 0) - (doc &amp;&amp; doc.clientTop || body &amp;&amp; body.clientTop || 0);
      }
      event.preventDefault = function () {
        event.defaultPrevented = true;
        event.isDefaultPrevented = returnTrue;
        if (originalEvent) {
          if (originalEvent.preventDefault) {
            originalEvent.preventDefault();
          } else {
            originalEvent.returnValue = false;
          }
        }
      };
      event.stopPropagation = function () {
        event.cancelBubble = true;
        event.isPropagationStopped = returnTrue;
        if (originalEvent) {
          if (originalEvent.stopPropagation) {
            originalEvent.stopPropagation();
          } else {
            originalEvent.cancelBubble = true;
          }
        }
      };
      event.stopImmediatePropagation = function () {
        event.isImmediatePropagationStopped = returnTrue;
        event.stopPropagation();
      };
      if (hasIsDefaultPrevented(event) === false) {
        event.isDefaultPrevented = event.defaultPrevented === true ? returnTrue : returnFalse;
        event.isPropagationStopped = event.cancelBubble === true ? returnTrue : returnFalse;
        event.isImmediatePropagationStopped = returnFalse;
      }
      if (typeof event.metaKey === 'undefined') {
        event.metaKey = false;
      }
      return event;
    };
    var bindOnReady = function (win, callback, eventUtils) {
      var doc = win.document, event = { type: 'ready' };
      if (eventUtils.domLoaded) {
        callback(event);
        return;
      }
      var isDocReady = function () {
        return doc.readyState === 'complete' || doc.readyState === 'interactive' &amp;&amp; doc.body;
      };
      var readyHandler = function () {
        removeEvent(win, 'DOMContentLoaded', readyHandler);
        removeEvent(win, 'load', readyHandler);
        if (!eventUtils.domLoaded) {
          eventUtils.domLoaded = true;
          callback(event);
        }
        win = null;
      };
      if (isDocReady()) {
        readyHandler();
      } else {
        addEvent(win, 'DOMContentLoaded', readyHandler);
      }
      if (!eventUtils.domLoaded) {
        addEvent(win, 'load', readyHandler);
      }
    };
    var EventUtils = function () {
      function EventUtils() {
        this.domLoaded = false;
        this.events = {};
        this.count = 1;
        this.expando = eventExpandoPrefix + (+new Date()).toString(32);
        this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
        this.hasFocusIn = 'onfocusin' in document.documentElement;
        this.count = 1;
      }
      EventUtils.prototype.bind = function (target, names, callback, scope) {
        var self = this;
        var id, callbackList, i, name, fakeName, nativeHandler, capture;
        var win = window;
        var defaultNativeHandler = function (evt) {
          self.executeHandlers(fix(evt || win.event), id);
        };
        if (!target || target.nodeType === 3 || target.nodeType === 8) {
          return;
        }
        if (!target[self.expando]) {
          id = self.count++;
          target[self.expando] = id;
          self.events[id] = {};
        } else {
          id = target[self.expando];
        }
        scope = scope || target;
        var namesList = names.split(' ');
        i = namesList.length;
        while (i--) {
          name = namesList[i];
          nativeHandler = defaultNativeHandler;
          fakeName = capture = false;
          if (name === 'DOMContentLoaded') {
            name = 'ready';
          }
          if (self.domLoaded &amp;&amp; name === 'ready' &amp;&amp; target.readyState === 'complete') {
            callback.call(scope, fix({ type: name }));
            continue;
          }
          if (!self.hasMouseEnterLeave) {
            fakeName = self.mouseEnterLeave[name];
            if (fakeName) {
              nativeHandler = function (evt) {
                var current = evt.currentTarget;
                var related = evt.relatedTarget;
                if (related &amp;&amp; current.contains) {
                  related = current.contains(related);
                } else {
                  while (related &amp;&amp; related !== current) {
                    related = related.parentNode;
                  }
                }
                if (!related) {
                  evt = fix(evt || win.event);
                  evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
                  evt.target = current;
                  self.executeHandlers(evt, id);
                }
              };
            }
          }
          if (!self.hasFocusIn &amp;&amp; (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';
              self.executeHandlers(evt, id);
            };
          }
          callbackList = self.events[id][name];
          if (!callbackList) {
            self.events[id][name] = callbackList = [{
                func: callback,
                scope: scope
              }];
            callbackList.fakeName = fakeName;
            callbackList.capture = capture;
            callbackList.nativeHandler = nativeHandler;
            if (name === 'ready') {
              bindOnReady(target, nativeHandler, self);
            } else {
              addEvent(target, fakeName || name, nativeHandler, capture);
            }
          } else {
            if (name === 'ready' &amp;&amp; self.domLoaded) {
              callback(fix({ type: name }));
            } else {
              callbackList.push({
                func: callback,
                scope: scope
              });
            }
          }
        }
        target = callbackList = null;
        return callback;
      };
      EventUtils.prototype.unbind = function (target, names, callback) {
        var callbackList, i, ci, name, eventMap;
        if (!target || target.nodeType === 3 || target.nodeType === 8) {
          return this;
        }
        var id = target[this.expando];
        if (id) {
          eventMap = this.events[id];
          if (names) {
            var namesList = names.split(' ');
            i = namesList.length;
            while (i--) {
              name = namesList[i];
              callbackList = eventMap[name];
              if (callbackList) {
                if (callback) {
                  ci = callbackList.length;
                  while (ci--) {
                    if (callbackList[ci].func === callback) {
                      var nativeHandler = callbackList.nativeHandler;
                      var fakeName = callbackList.fakeName, capture = callbackList.capture;
                      callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
                      callbackList.nativeHandler = nativeHandler;
                      callbackList.fakeName = fakeName;
                      callbackList.capture = capture;
                      eventMap[name] = callbackList;
                    }
                  }
                }
                if (!callback || callbackList.length === 0) {
                  delete eventMap[name];
                  removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
                }
              }
            }
          } else {
            each$1(eventMap, function (callbackList, name) {
              removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
            });
            eventMap = {};
          }
          for (name in eventMap) {
            if (has(eventMap, name)) {
              return this;
            }
          }
          delete this.events[id];
          try {
            delete target[this.expando];
          } catch (ex) {
            target[this.expando] = null;
          }
        }
        return this;
      };
      EventUtils.prototype.fire = function (target, name, args) {
        var id;
        if (!target || target.nodeType === 3 || target.nodeType === 8) {
          return this;
        }
        var event = fix(null, args);
        event.type = name;
        event.target = target;
        do {
          id = target[this.expando];
          if (id) {
            this.executeHandlers(event, id);
          }
          target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
        } while (target &amp;&amp; !event.isPropagationStopped());
        return this;
      };
      EventUtils.prototype.clean = function (target) {
        var i, children;
        if (!target || target.nodeType === 3 || target.nodeType === 8) {
          return this;
        }
        if (target[this.expando]) {
          this.unbind(target);
        }
        if (!target.getElementsByTagName) {
          target = target.document;
        }
        if (target &amp;&amp; target.getElementsByTagName) {
          this.unbind(target);
          children = target.getElementsByTagName('*');
          i = children.length;
          while (i--) {
            target = children[i];
            if (target[this.expando]) {
              this.unbind(target);
            }
          }
        }
        return this;
      };
      EventUtils.prototype.destroy = function () {
        this.events = {};
      };
      EventUtils.prototype.cancel = function (e) {
        if (e) {
          e.preventDefault();
          e.stopImmediatePropagation();
        }
        return false;
      };
      EventUtils.prototype.executeHandlers = function (evt, id) {
        var container = this.events[id];
        var callbackList = container &amp;&amp; container[evt.type];
        if (callbackList) {
          for (var i = 0, l = callbackList.length; i &lt; l; i++) {
            var callback = callbackList[i];
            if (callback &amp;&amp; callback.func.call(callback.scope, evt) === false) {
              evt.preventDefault();
            }
            if (evt.isImmediatePropagationStopped()) {
              return;
            }
          }
        }
      };
      EventUtils.Event = new EventUtils();
      return EventUtils;
    }();

    var support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, setDocument, document$1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains$3, expando = 'sizzle' + -new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function (a, b) {
        if (a === b) {
          hasDuplicate = true;
        }
        return 0;
      }, strundefined = typeof undefined, MAX_NEGATIVE = 1 &lt;&lt; 31, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, indexOf$2 = arr.indexOf || function (elem) {
        var i = 0, len = this.length;
        for (; i &lt; len; i++) {
          if (this[i] === elem) {
            return i;
          }
        }
        return -1;
      }, booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped', whitespace = '[\\x20\\t\\r\\n\\f]', identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', attributes = '\\[' + whitespace + '*(' + identifier + ')(?:' + whitespace + '*([*^$|!~]?=)' + whitespace + '*(?:\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)"|(' + identifier + '))|)' + whitespace + '*\\]', pseudos = ':(' + identifier + ')(?:\\((' + '(\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)")|' + '((?:\\\\.|[^\\\\()[\\]]|' + attributes + ')*)|' + '.*' + ')\\)|)', rtrim = new RegExp('^' + whitespace + '+|((?:^|[^\\\\])(?:\\\\.)*)' + whitespace + '+$', 'g'), rcomma = new RegExp('^' + whitespace + '*,' + whitespace + '*'), rcombinators = new RegExp('^' + whitespace + '*([&gt;+~]|' + whitespace + ')' + whitespace + '*'), rattributeQuotes = new RegExp('=' + whitespace + '*([^\\]\'"]*?)' + whitespace + '*\\]', 'g'), rpseudo = new RegExp(pseudos), ridentifier = new RegExp('^' + identifier + '$'), matchExpr = {
        ID: new RegExp('^#(' + identifier + ')'),
        CLASS: new RegExp('^\\.(' + identifier + ')'),
        TAG: new RegExp('^(' + identifier + '|[*])'),
        ATTR: new RegExp('^' + attributes),
        PSEUDO: new RegExp('^' + pseudos),
        CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
        bool: new RegExp('^(?:' + booleans + ')$', 'i'),
        needsContext: new RegExp('^' + whitespace + '*[&gt;+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
      }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, runescape = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig'), funescape = function (_, escaped, escapedWhitespace) {
        var high = '0x' + escaped - 65536;
        return high !== high || escapedWhitespace ? escaped : high &lt; 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high &gt;&gt; 10 | 55296, high &amp; 1023 | 56320);
      };
    try {
      push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);
      arr[preferredDoc.childNodes.length].nodeType;
    } catch (e) {
      push = {
        apply: arr.length ? function (target, els) {
          push_native.apply(target, slice.call(els));
        } : function (target, els) {
          var j = target.length, i = 0;
          while (target[j++] = els[i++]) {
          }
          target.length = j - 1;
        }
      };
    }
    var Sizzle = function (selector, context, results, seed) {
      var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
      if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
        setDocument(context);
      }
      context = context || document$1;
      results = results || [];
      if (!selector || typeof selector !== 'string') {
        return results;
      }
      if ((nodeType = context.nodeType) !== 1 &amp;&amp; nodeType !== 9) {
        return [];
      }
      if (documentIsHTML &amp;&amp; !seed) {
        if (match = rquickExpr.exec(selector)) {
          if (m = match[1]) {
            if (nodeType === 9) {
              elem = context.getElementById(m);
              if (elem &amp;&amp; elem.parentNode) {
                if (elem.id === m) {
                  results.push(elem);
                  return results;
                }
              } else {
                return results;
              }
            } else {
              if (context.ownerDocument &amp;&amp; (elem = context.ownerDocument.getElementById(m)) &amp;&amp; contains$3(context, elem) &amp;&amp; elem.id === m) {
                results.push(elem);
                return results;
              }
            }
          } else if (match[2]) {
            push.apply(results, context.getElementsByTagName(selector));
            return results;
          } else if ((m = match[3]) &amp;&amp; support.getElementsByClassName) {
            push.apply(results, context.getElementsByClassName(m));
            return results;
          }
        }
        if (support.qsa &amp;&amp; (!rbuggyQSA || !rbuggyQSA.test(selector))) {
          nid = old = expando;
          newContext = context;
          newSelector = nodeType === 9 &amp;&amp; selector;
          if (nodeType === 1 &amp;&amp; context.nodeName.toLowerCase() !== 'object') {
            groups = tokenize(selector);
            if (old = context.getAttribute('id')) {
              nid = old.replace(rescape, '\\$&amp;');
            } else {
              context.setAttribute('id', nid);
            }
            nid = '[id=\'' + nid + '\'] ';
            i = groups.length;
            while (i--) {
              groups[i] = nid + toSelector(groups[i]);
            }
            newContext = rsibling.test(selector) &amp;&amp; testContext(context.parentNode) || context;
            newSelector = groups.join(',');
          }
          if (newSelector) {
            try {
              push.apply(results, newContext.querySelectorAll(newSelector));
              return results;
            } catch (qsaError) {
            } finally {
              if (!old) {
                context.removeAttribute('id');
              }
            }
          }
        }
      }
      return select(selector.replace(rtrim, '$1'), context, results, seed);
    };
    function createCache() {
      var keys = [];
      function cache(key, value) {
        if (keys.push(key + ' ') &gt; Expr.cacheLength) {
          delete cache[keys.shift()];
        }
        return cache[key + ' '] = value;
      }
      return cache;
    }
    function markFunction(fn) {
      fn[expando] = true;
      return fn;
    }
    function siblingCheck(a, b) {
      var cur = b &amp;&amp; a, diff = cur &amp;&amp; a.nodeType === 1 &amp;&amp; b.nodeType === 1 &amp;&amp; (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
      if (diff) {
        return diff;
      }
      if (cur) {
        while (cur = cur.nextSibling) {
          if (cur === b) {
            return -1;
          }
        }
      }
      return a ? 1 : -1;
    }
    function createInputPseudo(type) {
      return function (elem) {
        var name = elem.nodeName.toLowerCase();
        return name === 'input' &amp;&amp; elem.type === type;
      };
    }
    function createButtonPseudo(type) {
      return function (elem) {
        var name = elem.nodeName.toLowerCase();
        return (name === 'input' || name === 'button') &amp;&amp; elem.type === type;
      };
    }
    function createPositionalPseudo(fn) {
      return markFunction(function (argument) {
        argument = +argument;
        return markFunction(function (seed, matches) {
          var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
          while (i--) {
            if (seed[j = matchIndexes[i]]) {
              seed[j] = !(matches[j] = seed[j]);
            }
          }
        });
      });
    }
    function testContext(context) {
      return context &amp;&amp; typeof context.getElementsByTagName !== strundefined &amp;&amp; context;
    }
    support = Sizzle.support = {};
    isXML = Sizzle.isXML = function (elem) {
      var documentElement = elem &amp;&amp; (elem.ownerDocument || elem).documentElement;
      return documentElement ? documentElement.nodeName !== 'HTML' : false;
    };
    setDocument = Sizzle.setDocument = function (node) {
      var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
      function getTop(win) {
        try {
          return win.top;
        } catch (ex) {
        }
        return null;
      }
      if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
        return document$1;
      }
      document$1 = doc;
      docElem = doc.documentElement;
      documentIsHTML = !isXML(doc);
      if (parent &amp;&amp; parent !== getTop(parent)) {
        if (parent.addEventListener) {
          parent.addEventListener('unload', function () {
            setDocument();
          }, false);
        } else if (parent.attachEvent) {
          parent.attachEvent('onunload', function () {
            setDocument();
          });
        }
      }
      support.attributes = true;
      support.getElementsByTagName = true;
      support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
      support.getById = true;
      Expr.find.ID = function (id, context) {
        if (typeof context.getElementById !== strundefined &amp;&amp; documentIsHTML) {
          var m = context.getElementById(id);
          return m &amp;&amp; m.parentNode ? [m] : [];
        }
      };
      Expr.filter.ID = function (id) {
        var attrId = id.replace(runescape, funescape);
        return function (elem) {
          return elem.getAttribute('id') === attrId;
        };
      };
      Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
        if (typeof context.getElementsByTagName !== strundefined) {
          return context.getElementsByTagName(tag);
        }
      } : function (tag, context) {
        var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
        if (tag === '*') {
          while (elem = results[i++]) {
            if (elem.nodeType === 1) {
              tmp.push(elem);
            }
          }
          return tmp;
        }
        return results;
      };
      Expr.find.CLASS = support.getElementsByClassName &amp;&amp; function (className, context) {
        if (documentIsHTML) {
          return context.getElementsByClassName(className);
        }
      };
      rbuggyMatches = [];
      rbuggyQSA = [];
      support.disconnectedMatch = true;
      rbuggyQSA = rbuggyQSA.length &amp;&amp; new RegExp(rbuggyQSA.join('|'));
      rbuggyMatches = rbuggyMatches.length &amp;&amp; new RegExp(rbuggyMatches.join('|'));
      hasCompare = rnative.test(docElem.compareDocumentPosition);
      contains$3 = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
        var adown = a.nodeType === 9 ? a.documentElement : a, bup = b &amp;&amp; b.parentNode;
        return a === bup || !!(bup &amp;&amp; bup.nodeType === 1 &amp;&amp; (adown.contains ? adown.contains(bup) : a.compareDocumentPosition &amp;&amp; a.compareDocumentPosition(bup) &amp; 16));
      } : function (a, b) {
        if (b) {
          while (b = b.parentNode) {
            if (b === a) {
              return true;
            }
          }
        }
        return false;
      };
      sortOrder = hasCompare ? function (a, b) {
        if (a === b) {
          hasDuplicate = true;
          return 0;
        }
        var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
        if (compare) {
          return compare;
        }
        compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
        if (compare &amp; 1 || !support.sortDetached &amp;&amp; b.compareDocumentPosition(a) === compare) {
          if (a === doc || a.ownerDocument === preferredDoc &amp;&amp; contains$3(preferredDoc, a)) {
            return -1;
          }
          if (b === doc || b.ownerDocument === preferredDoc &amp;&amp; contains$3(preferredDoc, b)) {
            return 1;
          }
          return sortInput ? indexOf$2.call(sortInput, a) - indexOf$2.call(sortInput, b) : 0;
        }
        return compare &amp; 4 ? -1 : 1;
      } : function (a, b) {
        if (a === b) {
          hasDuplicate = true;
          return 0;
        }
        var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
        if (!aup || !bup) {
          return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf$2.call(sortInput, a) - indexOf$2.call(sortInput, b) : 0;
        } else if (aup === bup) {
          return siblingCheck(a, b);
        }
        cur = a;
        while (cur = cur.parentNode) {
          ap.unshift(cur);
        }
        cur = b;
        while (cur = cur.parentNode) {
          bp.unshift(cur);
        }
        while (ap[i] === bp[i]) {
          i++;
        }
        return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
      };
      return doc;
    };
    Sizzle.matches = function (expr, elements) {
      return Sizzle(expr, null, null, elements);
    };
    Sizzle.matchesSelector = function (elem, expr) {
      if ((elem.ownerDocument || elem) !== document$1) {
        setDocument(elem);
      }
      expr = expr.replace(rattributeQuotes, '=\'$1\']');
      if (support.matchesSelector &amp;&amp; documentIsHTML &amp;&amp; (!rbuggyMatches || !rbuggyMatches.test(expr)) &amp;&amp; (!rbuggyQSA || !rbuggyQSA.test(expr))) {
        try {
          var ret = matches.call(elem, expr);
          if (ret || support.disconnectedMatch || elem.document &amp;&amp; elem.document.nodeType !== 11) {
            return ret;
          }
        } catch (e) {
        }
      }
      return Sizzle(expr, document$1, null, [elem]).length &gt; 0;
    };
    Sizzle.contains = function (context, elem) {
      if ((context.ownerDocument || context) !== document$1) {
        setDocument(context);
      }
      return contains$3(context, elem);
    };
    Sizzle.attr = function (elem, name) {
      if ((elem.ownerDocument || elem) !== document$1) {
        setDocument(elem);
      }
      var fn = Expr.attrHandle[name.toLowerCase()], val = fn &amp;&amp; hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
      return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) &amp;&amp; val.specified ? val.value : null;
    };
    Sizzle.error = function (msg) {
      throw new Error('Syntax error, unrecognized expression: ' + msg);
    };
    Sizzle.uniqueSort = function (results) {
      var elem, duplicates = [], j = 0, i = 0;
      hasDuplicate = !support.detectDuplicates;
      sortInput = !support.sortStable &amp;&amp; results.slice(0);
      results.sort(sortOrder);
      if (hasDuplicate) {
        while (elem = results[i++]) {
          if (elem === results[i]) {
            j = duplicates.push(i);
          }
        }
        while (j--) {
          results.splice(duplicates[j], 1);
        }
      }
      sortInput = null;
      return results;
    };
    getText = Sizzle.getText = function (elem) {
      var node, ret = '', i = 0, nodeType = elem.nodeType;
      if (!nodeType) {
        while (node = elem[i++]) {
          ret += getText(node);
        }
      } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
        if (typeof elem.textContent === 'string') {
          return elem.textContent;
        } else {
          for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
            ret += getText(elem);
          }
        }
      } else if (nodeType === 3 || nodeType === 4) {
        return elem.nodeValue;
      }
      return ret;
    };
    Expr = Sizzle.selectors = {
      cacheLength: 50,
      createPseudo: markFunction,
      match: matchExpr,
      attrHandle: {},
      find: {},
      relative: {
        '&gt;': {
          dir: 'parentNode',
          first: true
        },
        ' ': { dir: 'parentNode' },
        '+': {
          dir: 'previousSibling',
          first: true
        },
        '~': { dir: 'previousSibling' }
      },
      preFilter: {
        ATTR: function (match) {
          match[1] = match[1].replace(runescape, funescape);
          match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
          if (match[2] === '~=') {
            match[3] = ' ' + match[3] + ' ';
          }
          return match.slice(0, 4);
        },
        CHILD: function (match) {
          match[1] = match[1].toLowerCase();
          if (match[1].slice(0, 3) === 'nth') {
            if (!match[3]) {
              Sizzle.error(match[0]);
            }
            match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
            match[5] = +(match[7] + match[8] || match[3] === 'odd');
          } else if (match[3]) {
            Sizzle.error(match[0]);
          }
          return match;
        },
        PSEUDO: function (match) {
          var excess, unquoted = !match[6] &amp;&amp; match[2];
          if (matchExpr.CHILD.test(match[0])) {
            return null;
          }
          if (match[3]) {
            match[2] = match[4] || match[5] || '';
          } else if (unquoted &amp;&amp; rpseudo.test(unquoted) &amp;&amp; (excess = tokenize(unquoted, true)) &amp;&amp; (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
            match[0] = match[0].slice(0, excess);
            match[2] = unquoted.slice(0, excess);
          }
          return match.slice(0, 3);
        }
      },
      filter: {
        TAG: function (nodeNameSelector) {
          var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
          return nodeNameSelector === '*' ? function () {
            return true;
          } : function (elem) {
            return elem.nodeName &amp;&amp; elem.nodeName.toLowerCase() === nodeName;
          };
        },
        CLASS: function (className) {
          var pattern = classCache[className + ' '];
          return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) &amp;&amp; classCache(className, function (elem) {
            return pattern.test(typeof elem.className === 'string' &amp;&amp; elem.className || typeof elem.getAttribute !== strundefined &amp;&amp; elem.getAttribute('class') || '');
          });
        },
        ATTR: function (name, operator, check) {
          return function (elem) {
            var result = Sizzle.attr(elem, name);
            if (result == null) {
              return operator === '!=';
            }
            if (!operator) {
              return true;
            }
            result += '';
            return operator === '=' ? result === check : operator === '!=' ? result !== check : operator === '^=' ? check &amp;&amp; result.indexOf(check) === 0 : operator === '*=' ? check &amp;&amp; result.indexOf(check) &gt; -1 : operator === '$=' ? check &amp;&amp; result.slice(-check.length) === check : operator === '~=' ? (' ' + result + ' ').indexOf(check) &gt; -1 : operator === '|=' ? result === check || result.slice(0, check.length + 1) === check + '-' : false;
          };
        },
        CHILD: function (type, what, argument, first, last) {
          var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
          return first === 1 &amp;&amp; last === 0 ? function (elem) {
            return !!elem.parentNode;
          } : function (elem, context, xml) {
            var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType &amp;&amp; elem.nodeName.toLowerCase(), useCache = !xml &amp;&amp; !ofType;
            if (parent) {
              if (simple) {
                while (dir) {
                  node = elem;
                  while (node = node[dir]) {
                    if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
                      return false;
                    }
                  }
                  start = dir = type === 'only' &amp;&amp; !start &amp;&amp; 'nextSibling';
                }
                return true;
              }
              start = [forward ? parent.firstChild : parent.lastChild];
              if (forward &amp;&amp; useCache) {
                outerCache = parent[expando] || (parent[expando] = {});
                cache = outerCache[type] || [];
                nodeIndex = cache[0] === dirruns &amp;&amp; cache[1];
                diff = cache[0] === dirruns &amp;&amp; cache[2];
                node = nodeIndex &amp;&amp; parent.childNodes[nodeIndex];
                while (node = ++nodeIndex &amp;&amp; node &amp;&amp; node[dir] || (diff = nodeIndex = 0) || start.pop()) {
                  if (node.nodeType === 1 &amp;&amp; ++diff &amp;&amp; node === elem) {
                    outerCache[type] = [
                      dirruns,
                      nodeIndex,
                      diff
                    ];
                    break;
                  }
                }
              } else if (useCache &amp;&amp; (cache = (elem[expando] || (elem[expando] = {}))[type]) &amp;&amp; cache[0] === dirruns) {
                diff = cache[1];
              } else {
                while (node = ++nodeIndex &amp;&amp; node &amp;&amp; node[dir] || (diff = nodeIndex = 0) || start.pop()) {
                  if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) &amp;&amp; ++diff) {
                    if (useCache) {
                      (node[expando] || (node[expando] = {}))[type] = [
                        dirruns,
                        diff
                      ];
                    }
                    if (node === elem) {
                      break;
                    }
                  }
                }
              }
              diff -= last;
              return diff === first || diff % first === 0 &amp;&amp; diff / first &gt;= 0;
            }
          };
        },
        PSEUDO: function (pseudo, argument) {
          var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
          if (fn[expando]) {
            return fn(argument);
          }
          if (fn.length &gt; 1) {
            args = [
              pseudo,
              pseudo,
              '',
              argument
            ];
            return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
              var idx, matched = fn(seed, argument), i = matched.length;
              while (i--) {
                idx = indexOf$2.call(seed, matched[i]);
                seed[idx] = !(matches[idx] = matched[i]);
              }
            }) : function (elem) {
              return fn(elem, 0, args);
            };
          }
          return fn;
        }
      },
      pseudos: {
        not: markFunction(function (selector) {
          var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
          return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
            var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
            while (i--) {
              if (elem = unmatched[i]) {
                seed[i] = !(matches[i] = elem);
              }
            }
          }) : function (elem, context, xml) {
            input[0] = elem;
            matcher(input, null, xml, results);
            input[0] = null;
            return !results.pop();
          };
        }),
        has: markFunction(function (selector) {
          return function (elem) {
            return Sizzle(selector, elem).length &gt; 0;
          };
        }),
        contains: markFunction(function (text) {
          text = text.replace(runescape, funescape);
          return function (elem) {
            return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) &gt; -1;
          };
        }),
        lang: markFunction(function (lang) {
          if (!ridentifier.test(lang || '')) {
            Sizzle.error('unsupported lang: ' + lang);
          }
          lang = lang.replace(runescape, funescape).toLowerCase();
          return function (elem) {
            var elemLang;
            do {
              if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
                elemLang = elemLang.toLowerCase();
                return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
              }
            } while ((elem = elem.parentNode) &amp;&amp; elem.nodeType === 1);
            return false;
          };
        }),
        target: function (elem) {
          var hash = window.location &amp;&amp; window.location.hash;
          return hash &amp;&amp; hash.slice(1) === elem.id;
        },
        root: function (elem) {
          return elem === docElem;
        },
        focus: function (elem) {
          return elem === document$1.activeElement &amp;&amp; (!document$1.hasFocus || document$1.hasFocus()) &amp;&amp; !!(elem.type || elem.href || ~elem.tabIndex);
        },
        enabled: function (elem) {
          return elem.disabled === false;
        },
        disabled: function (elem) {
          return elem.disabled === true;
        },
        checked: function (elem) {
          var nodeName = elem.nodeName.toLowerCase();
          return nodeName === 'input' &amp;&amp; !!elem.checked || nodeName === 'option' &amp;&amp; !!elem.selected;
        },
        selected: function (elem) {
          if (elem.parentNode) {
            elem.parentNode.selectedIndex;
          }
          return elem.selected === true;
        },
        empty: function (elem) {
          for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
            if (elem.nodeType &lt; 6) {
              return false;
            }
          }
          return true;
        },
        parent: function (elem) {
          return !Expr.pseudos.empty(elem);
        },
        header: function (elem) {
          return rheader.test(elem.nodeName);
        },
        input: function (elem) {
          return rinputs.test(elem.nodeName);
        },
        button: function (elem) {
          var name = elem.nodeName.toLowerCase();
          return name === 'input' &amp;&amp; elem.type === 'button' || name === 'button';
        },
        text: function (elem) {
          var attr;
          return elem.nodeName.toLowerCase() === 'input' &amp;&amp; elem.type === 'text' &amp;&amp; ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
        },
        first: createPositionalPseudo(function () {
          return [0];
        }),
        last: createPositionalPseudo(function (matchIndexes, length) {
          return [length - 1];
        }),
        eq: createPositionalPseudo(function (matchIndexes, length, argument) {
          return [argument &lt; 0 ? argument + length : argument];
        }),
        even: createPositionalPseudo(function (matchIndexes, length) {
          var i = 0;
          for (; i &lt; length; i += 2) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        }),
        odd: createPositionalPseudo(function (matchIndexes, length) {
          var i = 1;
          for (; i &lt; length; i += 2) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        }),
        lt: createPositionalPseudo(function (matchIndexes, length, argument) {
          var i = argument &lt; 0 ? argument + length : argument;
          for (; --i &gt;= 0;) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        }),
        gt: createPositionalPseudo(function (matchIndexes, length, argument) {
          var i = argument &lt; 0 ? argument + length : argument;
          for (; ++i &lt; length;) {
            matchIndexes.push(i);
          }
          return matchIndexes;
        })
      }
    };
    Expr.pseudos.nth = Expr.pseudos.eq;
    each([
      'radio',
      'checkbox',
      'file',
      'password',
      'image'
    ], function (i) {
      Expr.pseudos[i] = createInputPseudo(i);
    });
    each([
      'submit',
      'reset'
    ], function (i) {
      Expr.pseudos[i] = createButtonPseudo(i);
    });
    function setFilters() {
    }
    setFilters.prototype = Expr.filters = Expr.pseudos;
    Expr.setFilters = new setFilters();
    tokenize = Sizzle.tokenize = function (selector, parseOnly) {
      var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
      if (cached) {
        return parseOnly ? 0 : cached.slice(0);
      }
      soFar = selector;
      groups = [];
      preFilters = Expr.preFilter;
      while (soFar) {
        if (!matched || (match = rcomma.exec(soFar))) {
          if (match) {
            soFar = soFar.slice(match[0].length) || soFar;
          }
          groups.push(tokens = []);
        }
        matched = false;
        if (match = rcombinators.exec(soFar)) {
          matched = match.shift();
          tokens.push({
            value: matched,
            type: match[0].replace(rtrim, ' ')
          });
          soFar = soFar.slice(matched.length);
        }
        for (type in Expr.filter) {
          if (!Expr.filter.hasOwnProperty(type)) {
            continue;
          }
          if ((match = matchExpr[type].exec(soFar)) &amp;&amp; (!preFilters[type] || (match = preFilters[type](match)))) {
            matched = match.shift();
            tokens.push({
              value: matched,
              type: type,
              matches: match
            });
            soFar = soFar.slice(matched.length);
          }
        }
        if (!matched) {
          break;
        }
      }
      return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
    };
    function toSelector(tokens) {
      var i = 0, len = tokens.length, selector = '';
      for (; i &lt; len; i++) {
        selector += tokens[i].value;
      }
      return selector;
    }
    function addCombinator(matcher, combinator, base) {
      var dir = combinator.dir, checkNonElements = base &amp;&amp; dir === 'parentNode', doneName = done++;
      return combinator.first ? function (elem, context, xml) {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            return matcher(elem, context, xml);
          }
        }
      } : function (elem, context, xml) {
        var oldCache, outerCache, newCache = [
            dirruns,
            doneName
          ];
        if (xml) {
          while (elem = elem[dir]) {
            if (elem.nodeType === 1 || checkNonElements) {
              if (matcher(elem, context, xml)) {
                return true;
              }
            }
          }
        } else {
          while (elem = elem[dir]) {
            if (elem.nodeType === 1 || checkNonElements) {
              outerCache = elem[expando] || (elem[expando] = {});
              if ((oldCache = outerCache[dir]) &amp;&amp; oldCache[0] === dirruns &amp;&amp; oldCache[1] === doneName) {
                return newCache[2] = oldCache[2];
              } else {
                outerCache[dir] = newCache;
                if (newCache[2] = matcher(elem, context, xml)) {
                  return true;
                }
              }
            }
          }
        }
      };
    }
    function elementMatcher(matchers) {
      return matchers.length &gt; 1 ? function (elem, context, xml) {
        var i = matchers.length;
        while (i--) {
          if (!matchers[i](elem, context, xml)) {
            return false;
          }
        }
        return true;
      } : matchers[0];
    }
    function multipleContexts(selector, contexts, results) {
      var i = 0, len = contexts.length;
      for (; i &lt; len; i++) {
        Sizzle(selector, contexts[i], results);
      }
      return results;
    }
    function condense(unmatched, map, filter, context, xml) {
      var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
      for (; i &lt; len; i++) {
        if (elem = unmatched[i]) {
          if (!filter || filter(elem, context, xml)) {
            newUnmatched.push(elem);
            if (mapped) {
              map.push(i);
            }
          }
        }
      }
      return newUnmatched;
    }
    function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
      if (postFilter &amp;&amp; !postFilter[expando]) {
        postFilter = setMatcher(postFilter);
      }
      if (postFinder &amp;&amp; !postFinder[expando]) {
        postFinder = setMatcher(postFinder, postSelector);
      }
      return markFunction(function (seed, results, context, xml) {
        var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || '*', context.nodeType ? [context] : context, []), matcherIn = preFilter &amp;&amp; (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
        if (matcher) {
          matcher(matcherIn, matcherOut, context, xml);
        }
        if (postFilter) {
          temp = condense(matcherOut, postMap);
          postFilter(temp, [], context, xml);
          i = temp.length;
          while (i--) {
            if (elem = temp[i]) {
              matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
            }
          }
        }
        if (seed) {
          if (postFinder || preFilter) {
            if (postFinder) {
              temp = [];
              i = matcherOut.length;
              while (i--) {
                if (elem = matcherOut[i]) {
                  temp.push(matcherIn[i] = elem);
                }
              }
              postFinder(null, matcherOut = [], temp, xml);
            }
            i = matcherOut.length;
            while (i--) {
              if ((elem = matcherOut[i]) &amp;&amp; (temp = postFinder ? indexOf$2.call(seed, elem) : preMap[i]) &gt; -1) {
                seed[temp] = !(results[temp] = elem);
              }
            }
          }
        } else {
          matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
          if (postFinder) {
            postFinder(null, results, matcherOut, xml);
          } else {
            push.apply(results, matcherOut);
          }
        }
      });
    }
    function matcherFromTokens(tokens) {
      var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[' '], i = leadingRelative ? 1 : 0, matchContext = addCombinator(function (elem) {
          return elem === checkContext;
        }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
          return indexOf$2.call(checkContext, elem) &gt; -1;
        }, implicitRelative, true), matchers = [function (elem, context, xml) {
            var ret = !leadingRelative &amp;&amp; (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
            checkContext = null;
            return ret;
          }];
      for (; i &lt; len; i++) {
        if (matcher = Expr.relative[tokens[i].type]) {
          matchers = [addCombinator(elementMatcher(matchers), matcher)];
        } else {
          matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
          if (matcher[expando]) {
            j = ++i;
            for (; j &lt; len; j++) {
              if (Expr.relative[tokens[j].type]) {
                break;
              }
            }
            return setMatcher(i &gt; 1 &amp;&amp; elementMatcher(matchers), i &gt; 1 &amp;&amp; toSelector(tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === ' ' ? '*' : '' })).replace(rtrim, '$1'), matcher, i &lt; j &amp;&amp; matcherFromTokens(tokens.slice(i, j)), j &lt; len &amp;&amp; matcherFromTokens(tokens = tokens.slice(j)), j &lt; len &amp;&amp; toSelector(tokens));
          }
          matchers.push(matcher);
        }
      }
      return elementMatcher(matchers);
    }
    function matcherFromGroupMatchers(elementMatchers, setMatchers) {
      var bySet = setMatchers.length &gt; 0, byElement = elementMatchers.length &gt; 0, superMatcher = function (seed, context, xml, results, outermost) {
          var elem, j, matcher, matchedCount = 0, i = '0', unmatched = seed &amp;&amp; [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement &amp;&amp; Expr.find.TAG('*', outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
          if (outermost) {
            outermostContext = context !== document$1 &amp;&amp; context;
          }
          for (; i !== len &amp;&amp; (elem = elems[i]) != null; i++) {
            if (byElement &amp;&amp; elem) {
              j = 0;
              while (matcher = elementMatchers[j++]) {
                if (matcher(elem, context, xml)) {
                  results.push(elem);
                  break;
                }
              }
              if (outermost) {
                dirruns = dirrunsUnique;
              }
            }
            if (bySet) {
              if (elem = !matcher &amp;&amp; elem) {
                matchedCount--;
              }
              if (seed) {
                unmatched.push(elem);
              }
            }
          }
          matchedCount += i;
          if (bySet &amp;&amp; i !== matchedCount) {
            j = 0;
            while (matcher = setMatchers[j++]) {
              matcher(unmatched, setMatched, context, xml);
            }
            if (seed) {
              if (matchedCount &gt; 0) {
                while (i--) {
                  if (!(unmatched[i] || setMatched[i])) {
                    setMatched[i] = pop.call(results);
                  }
                }
              }
              setMatched = condense(setMatched);
            }
            push.apply(results, setMatched);
            if (outermost &amp;&amp; !seed &amp;&amp; setMatched.length &gt; 0 &amp;&amp; matchedCount + setMatchers.length &gt; 1) {
              Sizzle.uniqueSort(results);
            }
          }
          if (outermost) {
            dirruns = dirrunsUnique;
            outermostContext = contextBackup;
          }
          return unmatched;
        };
      return bySet ? markFunction(superMatcher) : superMatcher;
    }
    compile = Sizzle.compile = function (selector, match) {
      var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
      if (!cached) {
        if (!match) {
          match = tokenize(selector);
        }
        i = match.length;
        while (i--) {
          cached = matcherFromTokens(match[i]);
          if (cached[expando]) {
            setMatchers.push(cached);
          } else {
            elementMatchers.push(cached);
          }
        }
        cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
        cached.selector = selector;
      }
      return cached;
    };
    select = Sizzle.select = function (selector, context, results, seed) {
      var i, tokens, token, type, find, compiled = typeof selector === 'function' &amp;&amp; selector, match = !seed &amp;&amp; tokenize(selector = compiled.selector || selector);
      results = results || [];
      if (match.length === 1) {
        tokens = match[0] = match[0].slice(0);
        if (tokens.length &gt; 2 &amp;&amp; (token = tokens[0]).type === 'ID' &amp;&amp; support.getById &amp;&amp; context.nodeType === 9 &amp;&amp; documentIsHTML &amp;&amp; Expr.relative[tokens[1].type]) {
          context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
          if (!context) {
            return results;
          } else if (compiled) {
            context = context.parentNode;
          }
          selector = selector.slice(tokens.shift().value.length);
        }
        i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
        while (i--) {
          token = tokens[i];
          if (Expr.relative[type = token.type]) {
            break;
          }
          if (find = Expr.find[type]) {
            if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) &amp;&amp; testContext(context.parentNode) || context)) {
              tokens.splice(i, 1);
              selector = seed.length &amp;&amp; toSelector(tokens);
              if (!selector) {
                push.apply(results, seed);
                return results;
              }
              break;
            }
          }
        }
      }
      (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) &amp;&amp; testContext(context.parentNode) || context);
      return results;
    };
    support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
    support.detectDuplicates = !!hasDuplicate;
    setDocument();
    support.sortDetached = true;

    var doc = document;
    var push$1 = Array.prototype.push;
    var slice$1 = Array.prototype.slice;
    var rquickExpr$1 = /^(?:[^#&lt;]*(&lt;[\w\W]+&gt;)[^&gt;]*$|#([\w\-]*)$)/;
    var Event = EventUtils.Event;
    var skipUniques = Tools.makeMap('children,contents,next,prev');
    var isDefined = function (obj) {
      return typeof obj !== 'undefined';
    };
    var isString$1 = function (obj) {
      return typeof obj === 'string';
    };
    var isWindow = function (obj) {
      return obj &amp;&amp; obj === obj.window;
    };
    var createFragment = function (html, fragDoc) {
      fragDoc = fragDoc || doc;
      var container = fragDoc.createElement('div');
      var frag = fragDoc.createDocumentFragment();
      container.innerHTML = html;
      var node;
      while (node = container.firstChild) {
        frag.appendChild(node);
      }
      return frag;
    };
    var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
      var i;
      if (isString$1(sourceItem)) {
        sourceItem = createFragment(sourceItem, getElementDocument(targetNodes[0]));
      } else if (sourceItem.length &amp;&amp; !sourceItem.nodeType) {
        sourceItem = DomQuery.makeArray(sourceItem);
        if (reverse) {
          for (i = sourceItem.length - 1; i &gt;= 0; i--) {
            domManipulate(targetNodes, sourceItem[i], callback, reverse);
          }
        } else {
          for (i = 0; i &lt; sourceItem.length; i++) {
            domManipulate(targetNodes, sourceItem[i], callback, reverse);
          }
        }
        return targetNodes;
      }
      if (sourceItem.nodeType) {
        i = targetNodes.length;
        while (i--) {
          callback.call(targetNodes[i], sourceItem);
        }
      }
      return targetNodes;
    };
    var hasClass = function (node, className) {
      return node &amp;&amp; className &amp;&amp; (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
    };
    var wrap$1 = function (elements, wrapper, all) {
      var lastParent, newWrapper;
      wrapper = DomQuery(wrapper)[0];
      elements.each(function () {
        var self = this;
        if (!all || lastParent !== self.parentNode) {
          lastParent = self.parentNode;
          newWrapper = wrapper.cloneNode(false);
          self.parentNode.insertBefore(newWrapper, self);
          newWrapper.appendChild(self);
        } else {
          newWrapper.appendChild(self);
        }
      });
      return elements;
    };
    var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
    var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
    var propFix = {
      for: 'htmlFor',
      class: 'className',
      readonly: 'readOnly'
    };
    var cssFix = { float: 'cssFloat' };
    var attrHooks = {}, cssHooks = {};
    var DomQueryConstructor = function (selector, context) {
      return new DomQuery.fn.init(selector, context);
    };
    var inArray$1 = function (item, array) {
      var i;
      if (array.indexOf) {
        return array.indexOf(item);
      }
      i = array.length;
      while (i--) {
        if (array[i] === item) {
          return i;
        }
      }
      return -1;
    };
    var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
    var trim$3 = function (str) {
      return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$2, '');
    };
    var each$4 = function (obj, callback) {
      var length, key, i, value;
      if (obj) {
        length = obj.length;
        if (length === undefined) {
          for (key in obj) {
            if (obj.hasOwnProperty(key)) {
              value = obj[key];
              if (callback.call(value, key, value) === false) {
                break;
              }
            }
          }
        } else {
          for (i = 0; i &lt; length; i++) {
            value = obj[i];
            if (callback.call(value, i, value) === false) {
              break;
            }
          }
        }
      }
      return obj;
    };
    var grep = function (array, callback) {
      var out = [];
      each$4(array, function (i, item) {
        if (callback(item, i)) {
          out.push(item);
        }
      });
      return out;
    };
    var getElementDocument = function (element) {
      if (!element) {
        return doc;
      }
      if (element.nodeType === 9) {
        return element;
      }
      return element.ownerDocument;
    };
    DomQueryConstructor.fn = DomQueryConstructor.prototype = {
      constructor: DomQueryConstructor,
      selector: '',
      context: null,
      length: 0,
      init: function (selector, context) {
        var self = this;
        var match, node;
        if (!selector) {
          return self;
        }
        if (selector.nodeType) {
          self.context = self[0] = selector;
          self.length = 1;
          return self;
        }
        if (context &amp;&amp; context.nodeType) {
          self.context = context;
        } else {
          if (context) {
            return DomQuery(selector).attr(context);
          }
          self.context = context = document;
        }
        if (isString$1(selector)) {
          self.selector = selector;
          if (selector.charAt(0) === '&lt;' &amp;&amp; selector.charAt(selector.length - 1) === '&gt;' &amp;&amp; selector.length &gt;= 3) {
            match = [
              null,
              selector,
              null
            ];
          } else {
            match = rquickExpr$1.exec(selector);
          }
          if (match) {
            if (match[1]) {
              node = createFragment(selector, getElementDocument(context)).firstChild;
              while (node) {
                push$1.call(self, node);
                node = node.nextSibling;
              }
            } else {
              node = getElementDocument(context).getElementById(match[2]);
              if (!node) {
                return self;
              }
              if (node.id !== match[2]) {
                return self.find(selector);
              }
              self.length = 1;
              self[0] = node;
            }
          } else {
            return DomQuery(context).find(selector);
          }
        } else {
          this.add(selector, false);
        }
        return self;
      },
      toArray: function () {
        return Tools.toArray(this);
      },
      add: function (items, sort) {
        var self = this;
        var nodes, i;
        if (isString$1(items)) {
          return self.add(DomQuery(items));
        }
        if (sort !== false) {
          nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
          self.length = nodes.length;
          for (i = 0; i &lt; nodes.length; i++) {
            self[i] = nodes[i];
          }
        } else {
          push$1.apply(self, DomQuery.makeArray(items));
        }
        return self;
      },
      attr: function (name, value) {
        var self = this;
        var hook;
        if (typeof name === 'object') {
          each$4(name, function (name, value) {
            self.attr(name, value);
          });
        } else if (isDefined(value)) {
          this.each(function () {
            var hook;
            if (this.nodeType === 1) {
              hook = attrHooks[name];
              if (hook &amp;&amp; hook.set) {
                hook.set(this, value);
                return;
              }
              if (value === null) {
                this.removeAttribute(name, 2);
              } else {
                this.setAttribute(name, value, 2);
              }
            }
          });
        } else {
          if (self[0] &amp;&amp; self[0].nodeType === 1) {
            hook = attrHooks[name];
            if (hook &amp;&amp; hook.get) {
              return hook.get(self[0], name);
            }
            if (booleanMap[name]) {
              return self.prop(name) ? name : undefined;
            }
            value = self[0].getAttribute(name, 2);
            if (value === null) {
              value = undefined;
            }
          }
          return value;
        }
        return self;
      },
      removeAttr: function (name) {
        return this.attr(name, null);
      },
      prop: function (name, value) {
        var self = this;
        name = propFix[name] || name;
        if (typeof name === 'object') {
          each$4(name, function (name, value) {
            self.prop(name, value);
          });
        } else if (isDefined(value)) {
          this.each(function () {
            if (this.nodeType === 1) {
              this[name] = value;
            }
          });
        } else {
          if (self[0] &amp;&amp; self[0].nodeType &amp;&amp; name in self[0]) {
            return self[0][name];
          }
          return value;
        }
        return self;
      },
      css: function (name, value) {
        var self = this;
        var elm, hook;
        var camel = function (name) {
          return name.replace(/-(\D)/g, function (a, b) {
            return b.toUpperCase();
          });
        };
        var dashed = function (name) {
          return name.replace(/[A-Z]/g, function (a) {
            return '-' + a;
          });
        };
        if (typeof name === 'object') {
          each$4(name, function (name, value) {
            self.css(name, value);
          });
        } else {
          if (isDefined(value)) {
            name = camel(name);
            if (typeof value === 'number' &amp;&amp; !numericCssMap[name]) {
              value = value.toString() + 'px';
            }
            self.each(function () {
              var style = this.style;
              hook = cssHooks[name];
              if (hook &amp;&amp; hook.set) {
                hook.set(this, value);
                return;
              }
              try {
                this.style[cssFix[name] || name] = value;
              } catch (ex) {
              }
              if (value === null || value === '') {
                if (style.removeProperty) {
                  style.removeProperty(dashed(name));
                } else {
                  style.removeAttribute(name);
                }
              }
            });
          } else {
            elm = self[0];
            hook = cssHooks[name];
            if (hook &amp;&amp; hook.get) {
              return hook.get(elm);
            }
            if (elm.ownerDocument.defaultView) {
              try {
                return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
              } catch (ex) {
                return undefined;
              }
            } else if (elm.currentStyle) {
              return elm.currentStyle[camel(name)];
            } else {
              return '';
            }
          }
        }
        return self;
      },
      remove: function () {
        var self = this;
        var node, i = this.length;
        while (i--) {
          node = self[i];
          Event.clean(node);
          if (node.parentNode) {
            node.parentNode.removeChild(node);
          }
        }
        return this;
      },
      empty: function () {
        var self = this;
        var node, i = this.length;
        while (i--) {
          node = self[i];
          while (node.firstChild) {
            node.removeChild(node.firstChild);
          }
        }
        return this;
      },
      html: function (value) {
        var self = this;
        var i;
        if (isDefined(value)) {
          i = self.length;
          try {
            while (i--) {
              self[i].innerHTML = value;
            }
          } catch (ex) {
            DomQuery(self[i]).empty().append(value);
          }
          return self;
        }
        return self[0] ? self[0].innerHTML : '';
      },
      text: function (value) {
        var self = this;
        var i;
        if (isDefined(value)) {
          i = self.length;
          while (i--) {
            if ('innerText' in self[i]) {
              self[i].innerText = value;
            } else {
              self[0].textContent = value;
            }
          }
          return self;
        }
        return self[0] ? self[0].innerText || self[0].textContent : '';
      },
      append: function () {
        return domManipulate(this, arguments, function (node) {
          if (this.nodeType === 1 || this.host &amp;&amp; this.host.nodeType === 1) {
            this.appendChild(node);
          }
        });
      },
      prepend: function () {
        return domManipulate(this, arguments, function (node) {
          if (this.nodeType === 1 || this.host &amp;&amp; this.host.nodeType === 1) {
            this.insertBefore(node, this.firstChild);
          }
        }, true);
      },
      before: function () {
        var self = this;
        if (self[0] &amp;&amp; self[0].parentNode) {
          return domManipulate(self, arguments, function (node) {
            this.parentNode.insertBefore(node, this);
          });
        }
        return self;
      },
      after: function () {
        var self = this;
        if (self[0] &amp;&amp; self[0].parentNode) {
          return domManipulate(self, arguments, function (node) {
            this.parentNode.insertBefore(node, this.nextSibling);
          }, true);
        }
        return self;
      },
      appendTo: function (val) {
        DomQuery(val).append(this);
        return this;
      },
      prependTo: function (val) {
        DomQuery(val).prepend(this);
        return this;
      },
      replaceWith: function (content) {
        return this.before(content).remove();
      },
      wrap: function (content) {
        return wrap$1(this, content);
      },
      wrapAll: function (content) {
        return wrap$1(this, content, true);
      },
      wrapInner: function (content) {
        this.each(function () {
          DomQuery(this).contents().wrapAll(content);
        });
        return this;
      },
      unwrap: function () {
        return this.parent().each(function () {
          DomQuery(this).replaceWith(this.childNodes);
        });
      },
      clone: function () {
        var result = [];
        this.each(function () {
          result.push(this.cloneNode(true));
        });
        return DomQuery(result);
      },
      addClass: function (className) {
        return this.toggleClass(className, true);
      },
      removeClass: function (className) {
        return this.toggleClass(className, false);
      },
      toggleClass: function (className, state) {
        var self = this;
        if (typeof className !== 'string') {
          return self;
        }
        if (className.indexOf(' ') !== -1) {
          each$4(className.split(' '), function () {
            self.toggleClass(this, state);
          });
        } else {
          self.each(function (index, node) {
            var classState = hasClass(node, className);
            if (classState !== state) {
              var existingClassName = node.className;
              if (classState) {
                node.className = trim$3((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
              } else {
                node.className += existingClassName ? ' ' + className : className;
              }
            }
          });
        }
        return self;
      },
      hasClass: function (className) {
        return hasClass(this[0], className);
      },
      each: function (callback) {
        return each$4(this, callback);
      },
      on: function (name, callback) {
        return this.each(function () {
          Event.bind(this, name, callback);
        });
      },
      off: function (name, callback) {
        return this.each(function () {
          Event.unbind(this, name, callback);
        });
      },
      trigger: function (name) {
        return this.each(function () {
          if (typeof name === 'object') {
            Event.fire(this, name.type, name);
          } else {
            Event.fire(this, name);
          }
        });
      },
      show: function () {
        return this.css('display', '');
      },
      hide: function () {
        return this.css('display', 'none');
      },
      slice: function () {
        return DomQuery(slice$1.apply(this, arguments));
      },
      eq: function (index) {
        return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
      },
      first: function () {
        return this.eq(0);
      },
      last: function () {
        return this.eq(-1);
      },
      find: function (selector) {
        var i, l;
        var ret = [];
        for (i = 0, l = this.length; i &lt; l; i++) {
          DomQuery.find(selector, this[i], ret);
        }
        return DomQuery(ret);
      },
      filter: function (selector) {
        if (typeof selector === 'function') {
          return DomQuery(grep(this.toArray(), function (item, i) {
            return selector(i, item);
          }));
        }
        return DomQuery(DomQuery.filter(selector, this.toArray()));
      },
      closest: function (selector) {
        var result = [];
        if (selector instanceof DomQuery) {
          selector = selector[0];
        }
        this.each(function (i, node) {
          while (node) {
            if (typeof selector === 'string' &amp;&amp; DomQuery(node).is(selector)) {
              result.push(node);
              break;
            } else if (node === selector) {
              result.push(node);
              break;
            }
            node = node.parentNode;
          }
        });
        return DomQuery(result);
      },
      offset: function (offset) {
        var elm, doc, docElm;
        var x = 0, y = 0, pos;
        if (!offset) {
          elm = this[0];
          if (elm) {
            doc = elm.ownerDocument;
            docElm = doc.documentElement;
            if (elm.getBoundingClientRect) {
              pos = elm.getBoundingClientRect();
              x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
              y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
            }
          }
          return {
            left: x,
            top: y
          };
        }
        return this.css(offset);
      },
      push: push$1,
      sort: Array.prototype.sort,
      splice: Array.prototype.splice
    };
    Tools.extend(DomQueryConstructor, {
      extend: Tools.extend,
      makeArray: function (object) {
        if (isWindow(object) || object.nodeType) {
          return [object];
        }
        return Tools.toArray(object);
      },
      inArray: inArray$1,
      isArray: Tools.isArray,
      each: each$4,
      trim: trim$3,
      grep: grep,
      find: Sizzle,
      expr: Sizzle.selectors,
      unique: Sizzle.uniqueSort,
      text: Sizzle.getText,
      contains: Sizzle.contains,
      filter: function (expr, elems, not) {
        var i = elems.length;
        if (not) {
          expr = ':not(' + expr + ')';
        }
        while (i--) {
          if (elems[i].nodeType !== 1) {
            elems.splice(i, 1);
          }
        }
        if (elems.length === 1) {
          elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
        } else {
          elems = DomQuery.find.matches(expr, elems);
        }
        return elems;
      }
    });
    var dir = function (el, prop, until) {
      var matched = [];
      var cur = el[prop];
      if (typeof until !== 'string' &amp;&amp; until instanceof DomQuery) {
        until = until[0];
      }
      while (cur &amp;&amp; cur.nodeType !== 9) {
        if (until !== undefined) {
          if (cur === until) {
            break;
          }
          if (typeof until === 'string' &amp;&amp; DomQuery(cur).is(until)) {
            break;
          }
        }
        if (cur.nodeType === 1) {
          matched.push(cur);
        }
        cur = cur[prop];
      }
      return matched;
    };
    var sibling$1 = function (node, siblingName, nodeType, until) {
      var result = [];
      if (until instanceof DomQuery) {
        until = until[0];
      }
      for (; node; node = node[siblingName]) {
        if (nodeType &amp;&amp; node.nodeType !== nodeType) {
          continue;
        }
        if (until !== undefined) {
          if (node === until) {
            break;
          }
          if (typeof until === 'string' &amp;&amp; DomQuery(node).is(until)) {
            break;
          }
        }
        result.push(node);
      }
      return result;
    };
    var firstSibling = function (node, siblingName, nodeType) {
      for (node = node[siblingName]; node; node = node[siblingName]) {
        if (node.nodeType === nodeType) {
          return node;
        }
      }
      return null;
    };
    each$4({
      parent: function (node) {
        var parent = node.parentNode;
        return parent &amp;&amp; parent.nodeType !== 11 ? parent : null;
      },
      parents: function (node) {
        return dir(node, 'parentNode');
      },
      next: function (node) {
        return firstSibling(node, 'nextSibling', 1);
      },
      prev: function (node) {
        return firstSibling(node, 'previousSibling', 1);
      },
      children: function (node) {
        return sibling$1(node.firstChild, 'nextSibling', 1);
      },
      contents: function (node) {
        return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
      }
    }, function (name, fn) {
      DomQueryConstructor.fn[name] = function (selector) {
        var self = this;
        var result = [];
        self.each(function () {
          var nodes = fn.call(result, this, selector, result);
          if (nodes) {
            if (DomQuery.isArray(nodes)) {
              result.push.apply(result, nodes);
            } else {
              result.push(nodes);
            }
          }
        });
        if (this.length &gt; 1) {
          if (!skipUniques[name]) {
            result = DomQuery.unique(result);
          }
          if (name.indexOf('parents') === 0) {
            result = result.reverse();
          }
        }
        var wrappedResult = DomQuery(result);
        if (selector) {
          return wrappedResult.filter(selector);
        }
        return wrappedResult;
      };
    });
    each$4({
      parentsUntil: function (node, until) {
        return dir(node, 'parentNode', until);
      },
      nextUntil: function (node, until) {
        return sibling$1(node, 'nextSibling', 1, until).slice(1);
      },
      prevUntil: function (node, until) {
        return sibling$1(node, 'previousSibling', 1, until).slice(1);
      }
    }, function (name, fn) {
      DomQueryConstructor.fn[name] = function (selector, filter) {
        var self = this;
        var result = [];
        self.each(function () {
          var nodes = fn.call(result, this, selector, result);
          if (nodes) {
            if (DomQuery.isArray(nodes)) {
              result.push.apply(result, nodes);
            } else {
              result.push(nodes);
            }
          }
        });
        if (this.length &gt; 1) {
          result = DomQuery.unique(result);
          if (name.indexOf('parents') === 0 || name === 'prevUntil') {
            result = result.reverse();
          }
        }
        var wrappedResult = DomQuery(result);
        if (filter) {
          return wrappedResult.filter(filter);
        }
        return wrappedResult;
      };
    });
    DomQueryConstructor.fn.is = function (selector) {
      return !!selector &amp;&amp; this.filter(selector).length &gt; 0;
    };
    DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
    DomQueryConstructor.overrideDefaults = function (callback) {
      var defaults;
      var sub = function (selector, context) {
        defaults = defaults || callback();
        if (arguments.length === 0) {
          selector = defaults.element;
        }
        if (!context) {
          context = defaults.context;
        }
        return new sub.fn.init(selector, context);
      };
      DomQuery.extend(sub, this);
      return sub;
    };
    DomQueryConstructor.attrHooks = attrHooks;
    DomQueryConstructor.cssHooks = cssHooks;
    var DomQuery = DomQueryConstructor;

    var each$5 = Tools.each;
    var grep$1 = Tools.grep;
    var isIE = Env.ie;
    var simpleSelectorRe = /^([a-z0-9],?)+$/i;
    var setupAttrHooks = function (styles, settings, getContext) {
      var keepValues = settings.keep_values;
      var keepUrlHook = {
        set: function ($elm, value, name) {
          if (settings.url_converter) {
            value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
          }
          $elm.attr('data-mce-' + name, value).attr(name, value);
        },
        get: function ($elm, name) {
          return $elm.attr('data-mce-' + name) || $elm.attr(name);
        }
      };
      var attrHooks = {
        style: {
          set: function ($elm, value) {
            if (value !== null &amp;&amp; typeof value === 'object') {
              $elm.css(value);
              return;
            }
            if (keepValues) {
              $elm.attr('data-mce-style', value);
            }
            if (value !== null &amp;&amp; typeof value === 'string') {
              $elm.removeAttr('style');
              $elm.css(styles.parse(value));
            } else {
              $elm.attr('style', value);
            }
          },
          get: function ($elm) {
            var value = $elm.attr('data-mce-style') || $elm.attr('style');
            value = styles.serialize(styles.parse(value), $elm[0].nodeName);
            return value;
          }
        }
      };
      if (keepValues) {
        attrHooks.href = attrHooks.src = keepUrlHook;
      }
      return attrHooks;
    };
    var updateInternalStyleAttr = function (styles, $elm) {
      var rawValue = $elm.attr('style');
      var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
      if (!value) {
        value = null;
      }
      $elm.attr('data-mce-style', value);
    };
    var findNodeIndex = function (node, normalized) {
      var idx = 0, lastNodeType, nodeType;
      if (node) {
        for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
          nodeType = node.nodeType;
          if (normalized &amp;&amp; nodeType === 3) {
            if (nodeType === lastNodeType || !node.nodeValue.length) {
              continue;
            }
          }
          idx++;
          lastNodeType = nodeType;
        }
      }
      return idx;
    };
    var DOMUtils = function (doc, settings) {
      if (settings === void 0) {
        settings = {};
      }
      var addedStyles = {};
      var win = window;
      var files = {};
      var counter = 0;
      var stdMode = true;
      var boxModel = true;
      var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
        contentCssCors: settings.contentCssCors,
        referrerPolicy: settings.referrerPolicy
      });
      var boundEvents = [];
      var schema = settings.schema ? settings.schema : Schema({});
      var styles = Styles({
        url_converter: settings.url_converter,
        url_converter_scope: settings.url_converter_scope
      }, settings.schema);
      var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
      var blockElementsMap = schema.getBlockElements();
      var $ = DomQuery.overrideDefaults(function () {
        return {
          context: doc,
          element: self.getRoot()
        };
      });
      var isBlock = function (node) {
        if (typeof node === 'string') {
          return !!blockElementsMap[node];
        } else if (node) {
          var type = node.nodeType;
          if (type) {
            return !!(type === 1 &amp;&amp; blockElementsMap[node.nodeName]);
          }
        }
        return false;
      };
      var get = function (elm) {
        return elm &amp;&amp; doc &amp;&amp; isString(elm) ? doc.getElementById(elm) : elm;
      };
      var $$ = function (elm) {
        return $(typeof elm === 'string' ? get(elm) : elm);
      };
      var getAttrib = function (elm, name, defaultVal) {
        var hook, value;
        var $elm = $$(elm);
        if ($elm.length) {
          hook = attrHooks[name];
          if (hook &amp;&amp; hook.get) {
            value = hook.get($elm, name);
          } else {
            value = $elm.attr(name);
          }
        }
        if (typeof value === 'undefined') {
          value = defaultVal || '';
        }
        return value;
      };
      var getAttribs = function (elm) {
        var node = get(elm);
        if (!node) {
          return [];
        }
        return node.attributes;
      };
      var setAttrib = function (elm, name, value) {
        if (value === '') {
          value = null;
        }
        var $elm = $$(elm);
        var originalValue = $elm.attr(name);
        if (!$elm.length) {
          return;
        }
        var hook = attrHooks[name];
        if (hook &amp;&amp; hook.set) {
          hook.set($elm, value, name);
        } else {
          $elm.attr(name, value);
        }
        if (originalValue !== value &amp;&amp; settings.onSetAttrib) {
          settings.onSetAttrib({
            attrElm: $elm,
            attrName: name,
            attrValue: value
          });
        }
      };
      var clone = function (node, deep) {
        if (!isIE || node.nodeType !== 1 || deep) {
          return node.cloneNode(deep);
        } else {
          var clone_1 = doc.createElement(node.nodeName);
          each$5(getAttribs(node), function (attr) {
            setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
          });
          return clone_1;
        }
      };
      var getRoot = function () {
        return settings.root_element || doc.body;
      };
      var getViewPort = function (argWin) {
        var vp = getBounds(argWin);
        return {
          x: vp.x,
          y: vp.y,
          w: vp.width,
          h: vp.height
        };
      };
      var getPos$1 = function (elm, rootElm) {
        return getPos(doc.body, get(elm), rootElm);
      };
      var setStyle = function (elm, name, value) {
        var $elm = isString(name) ? $$(elm).css(name, value) : $$(elm).css(name);
        if (settings.update_styles) {
          updateInternalStyleAttr(styles, $elm);
        }
      };
      var setStyles = function (elm, stylesArg) {
        var $elm = $$(elm).css(stylesArg);
        if (settings.update_styles) {
          updateInternalStyleAttr(styles, $elm);
        }
      };
      var getStyle = function (elm, name, computed) {
        var $elm = $$(elm);
        if (computed) {
          return $elm.css(name);
        }
        name = name.replace(/-(\D)/g, function (a, b) {
          return b.toUpperCase();
        });
        if (name === 'float') {
          name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
        }
        return $elm[0] &amp;&amp; $elm[0].style ? $elm[0].style[name] : undefined;
      };
      var getSize = function (elm) {
        var w, h;
        elm = get(elm);
        w = getStyle(elm, 'width');
        h = getStyle(elm, 'height');
        if (w.indexOf('px') === -1) {
          w = 0;
        }
        if (h.indexOf('px') === -1) {
          h = 0;
        }
        return {
          w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
          h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
        };
      };
      var getRect = function (elm) {
        elm = get(elm);
        var pos = getPos$1(elm);
        var size = getSize(elm);
        return {
          x: pos.x,
          y: pos.y,
          w: size.w,
          h: size.h
        };
      };
      var is = function (elm, selector) {
        var i;
        if (!elm) {
          return false;
        }
        if (!Array.isArray(elm)) {
          if (selector === '*') {
            return elm.nodeType === 1;
          }
          if (simpleSelectorRe.test(selector)) {
            var selectors = selector.toLowerCase().split(/,/);
            var elmName = elm.nodeName.toLowerCase();
            for (i = selectors.length - 1; i &gt;= 0; i--) {
              if (selectors[i] === elmName) {
                return true;
              }
            }
            return false;
          }
          if (elm.nodeType &amp;&amp; elm.nodeType !== 1) {
            return false;
          }
        }
        var elms = !Array.isArray(elm) ? [elm] : elm;
        return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length &gt; 0;
      };
      var getParents = function (elm, selector, root, collect) {
        var result = [];
        var selectorVal;
        var node = get(elm);
        collect = collect === undefined;
        root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
        if (Tools.is(selector, 'string')) {
          selectorVal = selector;
          if (selector === '*') {
            selector = function (node) {
              return node.nodeType === 1;
            };
          } else {
            selector = function (node) {
              return is(node, selectorVal);
            };
          }
        }
        while (node) {
          if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment$1(node)) {
            break;
          }
          if (!selector || typeof selector === 'function' &amp;&amp; selector(node)) {
            if (collect) {
              result.push(node);
            } else {
              return [node];
            }
          }
          node = node.parentNode;
        }
        return collect ? result : null;
      };
      var getParent = function (node, selector, root) {
        var parents = getParents(node, selector, root, false);
        return parents &amp;&amp; parents.length &gt; 0 ? parents[0] : null;
      };
      var _findSib = function (node, selector, name) {
        var func = selector;
        if (node) {
          if (typeof selector === 'string') {
            func = function (node) {
              return is(node, selector);
            };
          }
          for (node = node[name]; node; node = node[name]) {
            if (typeof func === 'function' &amp;&amp; func(node)) {
              return node;
            }
          }
        }
        return null;
      };
      var getNext = function (node, selector) {
        return _findSib(node, selector, 'nextSibling');
      };
      var getPrev = function (node, selector) {
        return _findSib(node, selector, 'previousSibling');
      };
      var select = function (selector, scope) {
        return Sizzle(selector, get(scope) || settings.root_element || doc, []);
      };
      var run = function (elm, func, scope) {
        var result;
        var node = typeof elm === 'string' ? get(elm) : elm;
        if (!node) {
          return false;
        }
        if (Tools.isArray(node) &amp;&amp; (node.length || node.length === 0)) {
          result = [];
          each$5(node, function (elm, i) {
            if (elm) {
              result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
            }
          });
          return result;
        }
        var context = scope ? scope : this;
        return func.call(context, node);
      };
      var setAttribs = function (elm, attrs) {
        $$(elm).each(function (i, node) {
          each$5(attrs, function (value, name) {
            setAttrib(node, name, value);
          });
        });
      };
      var setHTML = function (elm, html) {
        var $elm = $$(elm);
        if (isIE) {
          $elm.each(function (i, target) {
            if (target.canHaveHTML === false) {
              return;
            }
            while (target.firstChild) {
              target.removeChild(target.firstChild);
            }
            try {
              target.innerHTML = '&lt;br&gt;' + html;
              target.removeChild(target.firstChild);
            } catch (ex) {
              DomQuery('&lt;div&gt;&lt;/div&gt;').html('&lt;br&gt;' + html).contents().slice(1).appendTo(target);
            }
            return html;
          });
        } else {
          $elm.html(html);
        }
      };
      var add = function (parentElm, name, attrs, html, create) {
        return run(parentElm, function (parentElm) {
          var newElm = typeof name === 'string' ? doc.createElement(name) : name;
          setAttribs(newElm, attrs);
          if (html) {
            if (typeof html !== 'string' &amp;&amp; html.nodeType) {
              newElm.appendChild(html);
            } else if (typeof html === 'string') {
              setHTML(newElm, html);
            }
          }
          return !create ? parentElm.appendChild(newElm) : newElm;
        });
      };
      var create = function (name, attrs, html) {
        return add(doc.createElement(name), name, attrs, html, true);
      };
      var decode = Entities.decode;
      var encode = Entities.encodeAllRaw;
      var createHTML = function (name, attrs, html) {
        var outHtml = '', key;
        outHtml += '&lt;' + name;
        for (key in attrs) {
          if (attrs.hasOwnProperty(key) &amp;&amp; attrs[key] !== null &amp;&amp; typeof attrs[key] !== 'undefined') {
            outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
          }
        }
        if (typeof html !== 'undefined') {
          return outHtml + '&gt;' + html + '&lt;/' + name + '&gt;';
        }
        return outHtml + ' /&gt;';
      };
      var createFragment = function (html) {
        var node;
        var container = doc.createElement('div');
        var frag = doc.createDocumentFragment();
        frag.appendChild(container);
        if (html) {
          container.innerHTML = html;
        }
        while (node = container.firstChild) {
          frag.appendChild(node);
        }
        frag.removeChild(container);
        return frag;
      };
      var remove = function (node, keepChildren) {
        var $node = $$(node);
        if (keepChildren) {
          $node.each(function () {
            var child;
            while (child = this.firstChild) {
              if (child.nodeType === 3 &amp;&amp; child.data.length === 0) {
                this.removeChild(child);
              } else {
                this.parentNode.insertBefore(child, this);
              }
            }
          }).remove();
        } else {
          $node.remove();
        }
        return $node.length &gt; 1 ? $node.toArray() : $node[0];
      };
      var removeAllAttribs = function (e) {
        return run(e, function (e) {
          var i;
          var attrs = e.attributes;
          for (i = attrs.length - 1; i &gt;= 0; i--) {
            e.removeAttributeNode(attrs.item(i));
          }
        });
      };
      var parseStyle = function (cssText) {
        return styles.parse(cssText);
      };
      var serializeStyle = function (stylesArg, name) {
        return styles.serialize(stylesArg, name);
      };
      var addStyle = function (cssText) {
        var head, styleElm;
        if (self !== DOMUtils.DOM &amp;&amp; doc === document) {
          if (addedStyles[cssText]) {
            return;
          }
          addedStyles[cssText] = true;
        }
        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);
          }
        }
        if (styleElm.styleSheet) {
          styleElm.styleSheet.cssText += cssText;
        } else {
          styleElm.appendChild(doc.createTextNode(cssText));
        }
      };
      var loadCSS = function (urls) {
        if (!urls) {
          urls = '';
        }
        each(urls.split(','), function (url) {
          files[url] = true;
          styleSheetLoader.load(url, noop);
        });
      };
      var toggleClass = function (elm, cls, state) {
        $$(elm).toggleClass(cls, state).each(function () {
          if (this.className === '') {
            DomQuery(this).attr('class', null);
          }
        });
      };
      var addClass = function (elm, cls) {
        $$(elm).addClass(cls);
      };
      var removeClass = function (elm, cls) {
        toggleClass(elm, cls, false);
      };
      var hasClass = function (elm, cls) {
        return $$(elm).hasClass(cls);
      };
      var show = function (elm) {
        $$(elm).show();
      };
      var hide = function (elm) {
        $$(elm).hide();
      };
      var isHidden = function (elm) {
        return $$(elm).css('display') === 'none';
      };
      var uniqueId = function (prefix) {
        return (!prefix ? 'mce_' : prefix) + counter++;
      };
      var getOuterHTML = function (elm) {
        var node = typeof elm === 'string' ? get(elm) : elm;
        return isElement$1(node) ? node.outerHTML : DomQuery('&lt;div&gt;&lt;/div&gt;').append(DomQuery(node).clone()).html();
      };
      var setOuterHTML = function (elm, html) {
        $$(elm).each(function () {
          try {
            if ('outerHTML' in this) {
              this.outerHTML = html;
              return;
            }
          } catch (ex) {
          }
          remove(DomQuery(this).html(html), true);
        });
      };
      var insertAfter = function (node, reference) {
        var referenceNode = get(reference);
        return run(node, function (node) {
          var parent = referenceNode.parentNode;
          var nextSibling = referenceNode.nextSibling;
          if (nextSibling) {
            parent.insertBefore(node, nextSibling);
          } else {
            parent.appendChild(node);
          }
          return node;
        });
      };
      var replace = function (newElm, oldElm, keepChildren) {
        return run(oldElm, function (oldElm) {
          if (Tools.is(oldElm, 'array')) {
            newElm = newElm.cloneNode(true);
          }
          if (keepChildren) {
            each$5(grep$1(oldElm.childNodes), function (node) {
              newElm.appendChild(node);
            });
          }
          return oldElm.parentNode.replaceChild(newElm, oldElm);
        });
      };
      var rename = function (elm, name) {
        var newElm;
        if (elm.nodeName !== name.toUpperCase()) {
          newElm = create(name);
          each$5(getAttribs(elm), function (attrNode) {
            setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
          });
          replace(newElm, elm, true);
        }
        return newElm || elm;
      };
      var findCommonAncestor = function (a, b) {
        var ps = a, pe;
        while (ps) {
          pe = b;
          while (pe &amp;&amp; ps !== pe) {
            pe = pe.parentNode;
          }
          if (ps === pe) {
            break;
          }
          ps = ps.parentNode;
        }
        if (!ps &amp;&amp; a.ownerDocument) {
          return a.ownerDocument.documentElement;
        }
        return ps;
      };
      var toHex = function (rgbVal) {
        return styles.toHex(Tools.trim(rgbVal));
      };
      var isNonEmptyElement = function (node) {
        if (isElement$1(node)) {
          var isNamedAnchor = node.nodeName.toLowerCase() === 'a' &amp;&amp; !getAttrib(node, 'href') &amp;&amp; getAttrib(node, 'id');
          if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
            return true;
          }
        }
        return false;
      };
      var isEmpty = function (node, elements) {
        var type, name, brCount = 0;
        if (isNonEmptyElement(node)) {
          return false;
        }
        node = node.firstChild;
        if (node) {
          var walker = new DomTreeWalker(node, node.parentNode);
          var whitespace = schema ? schema.getWhiteSpaceElements() : {};
          elements = elements || (schema ? schema.getNonEmptyElements() : null);
          do {
            type = node.nodeType;
            if (isElement$1(node)) {
              var bogusVal = node.getAttribute('data-mce-bogus');
              if (bogusVal) {
                node = walker.next(bogusVal === 'all');
                continue;
              }
              name = node.nodeName.toLowerCase();
              if (elements &amp;&amp; elements[name]) {
                if (name === 'br') {
                  brCount++;
                  node = walker.next();
                  continue;
                }
                return false;
              }
              if (isNonEmptyElement(node)) {
                return false;
              }
            }
            if (type === 8) {
              return false;
            }
            if (type === 3 &amp;&amp; !isWhitespaceText(node.nodeValue)) {
              return false;
            }
            if (type === 3 &amp;&amp; node.parentNode &amp;&amp; whitespace[node.parentNode.nodeName] &amp;&amp; isWhitespaceText(node.nodeValue)) {
              return false;
            }
            node = walker.next();
          } while (node);
        }
        return brCount &lt;= 1;
      };
      var createRng = function () {
        return doc.createRange();
      };
      var split = function (parentElm, splitElm, replacementElm) {
        var range = createRng();
        var beforeFragment;
        var afterFragment;
        var parentNode;
        if (parentElm &amp;&amp; splitElm) {
          range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
          range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
          beforeFragment = range.extractContents();
          range = createRng();
          range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
          range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
          afterFragment = range.extractContents();
          parentNode = parentElm.parentNode;
          parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
          if (replacementElm) {
            parentNode.insertBefore(replacementElm, parentElm);
          } else {
            parentNode.insertBefore(splitElm, parentElm);
          }
          parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
          remove(parentElm);
          return replacementElm || splitElm;
        }
      };
      var bind = function (target, name, func, scope) {
        if (Tools.isArray(target)) {
          var i = target.length;
          var rv = [];
          while (i--) {
            rv[i] = bind(target[i], name, func, scope);
          }
          return rv;
        }
        if (settings.collect &amp;&amp; (target === doc || target === win)) {
          boundEvents.push([
            target,
            name,
            func,
            scope
          ]);
        }
        var output = events.bind(target, name, func, scope || self);
        return output;
      };
      var unbind = function (target, name, func) {
        if (Tools.isArray(target)) {
          var i = target.length;
          var rv = [];
          while (i--) {
            rv[i] = unbind(target[i], name, func);
          }
          return rv;
        } else {
          if (boundEvents.length &gt; 0 &amp;&amp; (target === doc || target === win)) {
            var i = boundEvents.length;
            while (i--) {
              var item = boundEvents[i];
              if (target === item[0] &amp;&amp; (!name || name === item[1]) &amp;&amp; (!func || func === item[2])) {
                events.unbind(item[0], item[1], item[2]);
              }
            }
          }
          return events.unbind(target, name, func);
        }
      };
      var fire = function (target, name, evt) {
        return events.fire(target, name, evt);
      };
      var getContentEditable = function (node) {
        if (node &amp;&amp; isElement$1(node)) {
          var contentEditable = node.getAttribute('data-mce-contenteditable');
          if (contentEditable &amp;&amp; contentEditable !== 'inherit') {
            return contentEditable;
          }
          return node.contentEditable !== 'inherit' ? node.contentEditable : null;
        } else {
          return null;
        }
      };
      var getContentEditableParent = function (node) {
        var root = getRoot();
        var state = null;
        for (; node &amp;&amp; node !== root; node = node.parentNode) {
          state = getContentEditable(node);
          if (state !== null) {
            break;
          }
        }
        return state;
      };
      var destroy = function () {
        if (boundEvents.length &gt; 0) {
          var i = boundEvents.length;
          while (i--) {
            var item = boundEvents[i];
            events.unbind(item[0], item[1], item[2]);
          }
        }
        each$1(files, function (_, url) {
          styleSheetLoader.unload(url);
          delete files[url];
        });
        if (Sizzle.setDocument) {
          Sizzle.setDocument();
        }
      };
      var isChildOf = function (node, parent) {
        while (node) {
          if (parent === node) {
            return true;
          }
          node = node.parentNode;
        }
        return false;
      };
      var dumpRng = function (r) {
        return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
      };
      var self = {
        doc: doc,
        settings: settings,
        win: win,
        files: files,
        stdMode: stdMode,
        boxModel: boxModel,
        styleSheetLoader: styleSheetLoader,
        boundEvents: boundEvents,
        styles: styles,
        schema: schema,
        events: events,
        isBlock: isBlock,
        $: $,
        $$: $$,
        root: null,
        clone: clone,
        getRoot: getRoot,
        getViewPort: getViewPort,
        getRect: getRect,
        getSize: getSize,
        getParent: getParent,
        getParents: getParents,
        get: get,
        getNext: getNext,
        getPrev: getPrev,
        select: select,
        is: is,
        add: add,
        create: create,
        createHTML: createHTML,
        createFragment: createFragment,
        remove: remove,
        setStyle: setStyle,
        getStyle: getStyle,
        setStyles: setStyles,
        removeAllAttribs: removeAllAttribs,
        setAttrib: setAttrib,
        setAttribs: setAttribs,
        getAttrib: getAttrib,
        getPos: getPos$1,
        parseStyle: parseStyle,
        serializeStyle: serializeStyle,
        addStyle: addStyle,
        loadCSS: loadCSS,
        addClass: addClass,
        removeClass: removeClass,
        hasClass: hasClass,
        toggleClass: toggleClass,
        show: show,
        hide: hide,
        isHidden: isHidden,
        uniqueId: uniqueId,
        setHTML: setHTML,
        getOuterHTML: getOuterHTML,
        setOuterHTML: setOuterHTML,
        decode: decode,
        encode: encode,
        insertAfter: insertAfter,
        replace: replace,
        rename: rename,
        findCommonAncestor: findCommonAncestor,
        toHex: toHex,
        run: run,
        getAttribs: getAttribs,
        isEmpty: isEmpty,
        createRng: createRng,
        nodeIndex: findNodeIndex,
        split: split,
        bind: bind,
        unbind: unbind,
        fire: fire,
        getContentEditable: getContentEditable,
        getContentEditableParent: getContentEditableParent,
        destroy: destroy,
        isChildOf: isChildOf,
        dumpRng: dumpRng
      };
      var attrHooks = setupAttrHooks(styles, settings, function () {
        return self;
      });
      return self;
    };
    DOMUtils.DOM = DOMUtils(document);
    DOMUtils.nodeIndex = findNodeIndex;

    var DOM = DOMUtils.DOM;
    var each$6 = Tools.each, grep$2 = Tools.grep;
    var QUEUED = 0;
    var LOADING = 1;
    var LOADED = 2;
    var FAILED = 3;
    var ScriptLoader = function () {
      function ScriptLoader(settings) {
        if (settings === void 0) {
          settings = {};
        }
        this.states = {};
        this.queue = [];
        this.scriptLoadedCallbacks = {};
        this.queueLoadedCallbacks = [];
        this.loading = 0;
        this.settings = settings;
      }
      ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
        this.settings.referrerPolicy = referrerPolicy;
      };
      ScriptLoader.prototype.loadScript = function (url, success, failure) {
        var dom = DOM;
        var elm;
        var cleanup = function () {
          dom.remove(id);
          if (elm) {
            elm.onerror = elm.onload = elm = null;
          }
        };
        var done = function () {
          cleanup();
          success();
        };
        var error = function () {
          cleanup();
          if (isFunction(failure)) {
            failure();
          } else {
            if (typeof console !== 'undefined' &amp;&amp; console.log) {
              console.log('Failed to load script: ' + url);
            }
          }
        };
        var id = dom.uniqueId();
        elm = document.createElement('script');
        elm.id = id;
        elm.type = 'text/javascript';
        elm.src = Tools._addCacheSuffix(url);
        if (this.settings.referrerPolicy) {
          dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
        }
        elm.onload = done;
        elm.onerror = error;
        (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
      };
      ScriptLoader.prototype.isDone = function (url) {
        return this.states[url] === LOADED;
      };
      ScriptLoader.prototype.markDone = function (url) {
        this.states[url] = LOADED;
      };
      ScriptLoader.prototype.add = function (url, success, scope, failure) {
        var state = this.states[url];
        this.queue.push(url);
        if (state === undefined) {
          this.states[url] = QUEUED;
        }
        if (success) {
          if (!this.scriptLoadedCallbacks[url]) {
            this.scriptLoadedCallbacks[url] = [];
          }
          this.scriptLoadedCallbacks[url].push({
            success: success,
            failure: failure,
            scope: scope || this
          });
        }
      };
      ScriptLoader.prototype.load = function (url, success, scope, failure) {
        return this.add(url, success, scope, failure);
      };
      ScriptLoader.prototype.remove = function (url) {
        delete this.states[url];
        delete this.scriptLoadedCallbacks[url];
      };
      ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
        this.loadScripts(this.queue, success, scope, failure);
      };
      ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
        var self = this;
        var failures = [];
        var execCallbacks = function (name, url) {
          each$6(self.scriptLoadedCallbacks[url], function (callback) {
            if (isFunction(callback[name])) {
              callback[name].call(callback.scope);
            }
          });
          self.scriptLoadedCallbacks[url] = undefined;
        };
        self.queueLoadedCallbacks.push({
          success: success,
          failure: failure,
          scope: scope || this
        });
        var loadScripts = function () {
          var loadingScripts = grep$2(scripts);
          scripts.length = 0;
          each$6(loadingScripts, function (url) {
            if (self.states[url] === LOADED) {
              execCallbacks('success', url);
              return;
            }
            if (self.states[url] === FAILED) {
              execCallbacks('failure', url);
              return;
            }
            if (self.states[url] !== LOADING) {
              self.states[url] = LOADING;
              self.loading++;
              self.loadScript(url, function () {
                self.states[url] = LOADED;
                self.loading--;
                execCallbacks('success', url);
                loadScripts();
              }, function () {
                self.states[url] = FAILED;
                self.loading--;
                failures.push(url);
                execCallbacks('failure', url);
                loadScripts();
              });
            }
          });
          if (!self.loading) {
            var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
            self.queueLoadedCallbacks.length = 0;
            each$6(notifyCallbacks, function (callback) {
              if (failures.length === 0) {
                if (isFunction(callback.success)) {
                  callback.success.call(callback.scope);
                }
              } else {
                if (isFunction(callback.failure)) {
                  callback.failure.call(callback.scope, failures);
                }
              }
            });
          }
        };
        loadScripts();
      };
      ScriptLoader.ScriptLoader = new ScriptLoader();
      return ScriptLoader;
    }();

    var Cell = function (initial) {
      var value = initial;
      var get = function () {
        return value;
      };
      var set = function (v) {
        value = v;
      };
      return {
        get: get,
        set: set
      };
    };

    var isRaw = function (str) {
      return isObject(str) &amp;&amp; has(str, 'raw');
    };
    var isTokenised = function (str) {
      return isArray(str) &amp;&amp; str.length &gt; 1;
    };
    var data = {};
    var currentCode = Cell('en');
    var getLanguageData = function () {
      return get$1(data, currentCode.get());
    };
    var getData = function () {
      return map$1(data, function (value) {
        return __assign({}, value);
      });
    };
    var setCode = function (newCode) {
      if (newCode) {
        currentCode.set(newCode);
      }
    };
    var getCode = function () {
      return currentCode.get();
    };
    var add = function (code, items) {
      var langData = data[code];
      if (!langData) {
        data[code] = langData = {};
      }
      each$1(items, function (translation, name) {
        langData[name.toLowerCase()] = translation;
      });
    };
    var translate = function (text) {
      var langData = getLanguageData().getOr({});
      var toString = function (obj) {
        if (isFunction(obj)) {
          return Object.prototype.toString.call(obj);
        }
        return !isEmpty(obj) ? '' + obj : '';
      };
      var isEmpty = function (text) {
        return text === '' || text === null || text === undefined;
      };
      var getLangData = function (text) {
        var textstr = toString(text);
        return get$1(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
      };
      var removeContext = function (str) {
        return str.replace(/{context:\w+}$/, '');
      };
      if (isEmpty(text)) {
        return '';
      }
      if (isRaw(text)) {
        return toString(text.raw);
      }
      if (isTokenised(text)) {
        var values_1 = text.slice(1);
        var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
          return has(values_1, $2) ? toString(values_1[$2]) : $1;
        });
        return removeContext(substitued);
      }
      return removeContext(getLangData(text));
    };
    var isRtl = function () {
      return getLanguageData().bind(function (items) {
        return get$1(items, '_dir');
      }).exists(function (dir) {
        return dir === 'rtl';
      });
    };
    var hasCode = function (code) {
      return has(data, code);
    };
    var I18n = {
      getData: getData,
      setCode: setCode,
      getCode: getCode,
      add: add,
      translate: translate,
      isRtl: isRtl,
      hasCode: hasCode
    };

    var AddOnManager = function () {
      var items = [];
      var urls = {};
      var lookup = {};
      var _listeners = [];
      var runListeners = function (name, state) {
        var matchedListeners = filter(_listeners, function (listener) {
          return listener.name === name &amp;&amp; listener.state === state;
        });
        each(matchedListeners, function (listener) {
          return listener.callback();
        });
      };
      var get = function (name) {
        if (lookup[name]) {
          return lookup[name].instance;
        }
        return undefined;
      };
      var dependencies = function (name) {
        var result;
        if (lookup[name]) {
          result = lookup[name].dependencies;
        }
        return result || [];
      };
      var requireLangPack = function (name, languages) {
        if (AddOnManager.languageLoad !== false) {
          waitFor(name, function () {
            var language = I18n.getCode();
            var wrappedLanguages = ',' + (languages || '') + ',';
            if (!language || languages &amp;&amp; wrappedLanguages.indexOf(',' + language + ',') === -1) {
              return;
            }
            ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
          }, 'loaded');
        }
      };
      var add = function (id, addOn, dependencies) {
        var addOnConstructor = addOn;
        items.push(addOnConstructor);
        lookup[id] = {
          instance: addOnConstructor,
          dependencies: dependencies
        };
        runListeners(id, 'added');
        return addOnConstructor;
      };
      var remove = function (name) {
        delete urls[name];
        delete lookup[name];
      };
      var createUrl = function (baseUrl, dep) {
        if (typeof dep === 'object') {
          return dep;
        }
        return typeof baseUrl === 'string' ? {
          prefix: '',
          resource: dep,
          suffix: ''
        } : {
          prefix: baseUrl.prefix,
          resource: dep,
          suffix: baseUrl.suffix
        };
      };
      var addComponents = function (pluginName, scripts) {
        var pluginUrl = urls[pluginName];
        each(scripts, function (script) {
          ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
        });
      };
      var loadDependencies = function (name, addOnUrl, success, scope) {
        var deps = dependencies(name);
        each(deps, function (dep) {
          var newUrl = createUrl(addOnUrl, dep);
          load(newUrl.resource, newUrl, undefined, undefined);
        });
        if (success) {
          if (scope) {
            success.call(scope);
          } else {
            success.call(ScriptLoader);
          }
        }
      };
      var load = function (name, addOnUrl, success, scope, failure) {
        if (urls[name]) {
          return;
        }
        var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
        if (urlString.indexOf('/') !== 0 &amp;&amp; urlString.indexOf('://') === -1) {
          urlString = AddOnManager.baseURL + '/' + urlString;
        }
        urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
        var done = function () {
          runListeners(name, 'loaded');
          loadDependencies(name, addOnUrl, success, scope);
        };
        if (lookup[name]) {
          done();
        } else {
          ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
        }
      };
      var waitFor = function (name, callback, state) {
        if (state === void 0) {
          state = 'added';
        }
        if (has(lookup, name) &amp;&amp; state === 'added') {
          callback();
        } else if (has(urls, name) &amp;&amp; state === 'loaded') {
          callback();
        } else {
          _listeners.push({
            name: name,
            state: state,
            callback: callback
          });
        }
      };
      return {
        items: items,
        urls: urls,
        lookup: lookup,
        _listeners: _listeners,
        get: get,
        dependencies: dependencies,
        requireLangPack: requireLangPack,
        add: add,
        remove: remove,
        createUrl: createUrl,
        addComponents: addComponents,
        load: load,
        waitFor: waitFor
      };
    };
    AddOnManager.languageLoad = true;
    AddOnManager.baseURL = '';
    AddOnManager.PluginManager = AddOnManager();
    AddOnManager.ThemeManager = AddOnManager();

    var first = function (fn, rate) {
      var timer = null;
      var cancel = function () {
        if (timer !== null) {
          clearTimeout(timer);
          timer = null;
        }
      };
      var throttle = function () {
        var args = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        if (timer === null) {
          timer = setTimeout(function () {
            fn.apply(null, args);
            timer = null;
          }, rate);
        }
      };
      return {
        cancel: cancel,
        throttle: throttle
      };
    };
    var last$2 = function (fn, rate) {
      var timer = null;
      var cancel = function () {
        if (timer !== null) {
          clearTimeout(timer);
          timer = null;
        }
      };
      var throttle = function () {
        var args = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        if (timer !== null) {
          clearTimeout(timer);
        }
        timer = setTimeout(function () {
          fn.apply(null, args);
          timer = null;
        }, rate);
      };
      return {
        cancel: cancel,
        throttle: throttle
      };
    };

    var read = function (element, attr) {
      var value = get$4(element, attr);
      return value === undefined || value === '' ? [] : value.split(' ');
    };
    var add$1 = function (element, attr, id) {
      var old = read(element, attr);
      var nu = old.concat([id]);
      set(element, attr, nu.join(' '));
      return true;
    };
    var remove$2 = function (element, attr, id) {
      var nu = filter(read(element, attr), function (v) {
        return v !== id;
      });
      if (nu.length &gt; 0) {
        set(element, attr, nu.join(' '));
      } else {
        remove$1(element, attr);
      }
      return false;
    };

    var supports = function (element) {
      return element.dom.classList !== undefined;
    };
    var get$6 = function (element) {
      return read(element, 'class');
    };
    var add$2 = function (element, clazz) {
      return add$1(element, 'class', clazz);
    };
    var remove$3 = function (element, clazz) {
      return remove$2(element, 'class', clazz);
    };

    var add$3 = function (element, clazz) {
      if (supports(element)) {
        element.dom.classList.add(clazz);
      } else {
        add$2(element, clazz);
      }
    };
    var cleanClass = function (element) {
      var classList = supports(element) ? element.dom.classList : get$6(element);
      if (classList.length === 0) {
        remove$1(element, 'class');
      }
    };
    var remove$4 = function (element, clazz) {
      if (supports(element)) {
        var classList = element.dom.classList;
        classList.remove(clazz);
      } else {
        remove$3(element, clazz);
      }
      cleanClass(element);
    };
    var has$2 = function (element, clazz) {
      return supports(element) &amp;&amp; element.dom.classList.contains(clazz);
    };

    var descendants = function (scope, predicate) {
      var result = [];
      each(children(scope), function (x) {
        if (predicate(x)) {
          result = result.concat([x]);
        }
        result = result.concat(descendants(x, predicate));
      });
      return result;
    };

    var descendants$1 = function (scope, selector) {
      return all(selector, scope);
    };

    var annotation = constant('mce-annotation');
    var dataAnnotation = constant('data-mce-annotation');
    var dataAnnotationId = constant('data-mce-annotation-uid');

    var identify = function (editor, annotationName) {
      var rng = editor.selection.getRng();
      var start = SugarElement.fromDom(rng.startContainer);
      var root = SugarElement.fromDom(editor.getBody());
      var selector = annotationName.fold(function () {
        return '.' + annotation();
      }, function (an) {
        return '[' + dataAnnotation() + '="' + an + '"]';
      });
      var newStart = child(start, rng.startOffset).getOr(start);
      var closest = closest$1(newStart, selector, function (n) {
        return eq$2(n, root);
      });
      var getAttr = function (c, property) {
        if (has$1(c, property)) {
          return Optional.some(get$4(c, property));
        } else {
          return Optional.none();
        }
      };
      return closest.bind(function (c) {
        return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
          return getAttr(c, '' + dataAnnotation()).map(function (name) {
            var elements = findMarkers(editor, uid);
            return {
              uid: uid,
              name: name,
              elements: elements
            };
          });
        });
      });
    };
    var isAnnotation = function (elem) {
      return isElement(elem) &amp;&amp; has$2(elem, annotation());
    };
    var findMarkers = function (editor, uid) {
      var body = SugarElement.fromDom(editor.getBody());
      return descendants$1(body, '[' + dataAnnotationId() + '="' + uid + '"]');
    };
    var findAll = function (editor, name) {
      var body = SugarElement.fromDom(editor.getBody());
      var markers = descendants$1(body, '[' + dataAnnotation() + '="' + name + '"]');
      var directory = {};
      each(markers, function (m) {
        var uid = get$4(m, dataAnnotationId());
        var nodesAlready = directory.hasOwnProperty(uid) ? directory[uid] : [];
        directory[uid] = nodesAlready.concat([m]);
      });
      return directory;
    };

    var setup = function (editor, _registry) {
      var changeCallbacks = Cell({});
      var initData = function () {
        return {
          listeners: [],
          previous: Cell(Optional.none())
        };
      };
      var withCallbacks = function (name, f) {
        updateCallbacks(name, function (data) {
          f(data);
          return data;
        });
      };
      var updateCallbacks = function (name, f) {
        var callbackMap = changeCallbacks.get();
        var data = callbackMap.hasOwnProperty(name) ? callbackMap[name] : initData();
        var outputData = f(data);
        callbackMap[name] = outputData;
        changeCallbacks.set(callbackMap);
      };
      var fireCallbacks = function (name, uid, elements) {
        withCallbacks(name, function (data) {
          each(data.listeners, function (f) {
            return f(true, name, {
              uid: uid,
              nodes: map(elements, function (elem) {
                return elem.dom;
              })
            });
          });
        });
      };
      var fireNoAnnotation = function (name) {
        withCallbacks(name, function (data) {
          each(data.listeners, function (f) {
            return f(false, name);
          });
        });
      };
      var onNodeChange = last$2(function () {
        var callbackMap = changeCallbacks.get();
        var annotations = sort$1(keys(callbackMap));
        each(annotations, function (name) {
          updateCallbacks(name, function (data) {
            var prev = data.previous.get();
            identify(editor, Optional.some(name)).fold(function () {
              if (prev.isSome()) {
                fireNoAnnotation(name);
                data.previous.set(Optional.none());
              }
            }, function (_a) {
              var uid = _a.uid, name = _a.name, elements = _a.elements;
              if (!prev.is(uid)) {
                fireCallbacks(name, uid, elements);
                data.previous.set(Optional.some(uid));
              }
            });
            return {
              previous: data.previous,
              listeners: data.listeners
            };
          });
        });
      }, 30);
      editor.on('remove', function () {
        onNodeChange.cancel();
      });
      editor.on('NodeChange', function () {
        onNodeChange.throttle();
      });
      var addListener = function (name, f) {
        updateCallbacks(name, function (data) {
          return {
            previous: data.previous,
            listeners: data.listeners.concat([f])
          };
        });
      };
      return { addListener: addListener };
    };

    var setup$1 = function (editor, registry) {
      var identifyParserNode = function (span) {
        return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
      };
      editor.on('init', function () {
        editor.serializer.addNodeFilter('span', function (spans) {
          each(spans, function (span) {
            identifyParserNode(span).each(function (settings) {
              if (settings.persistent === false) {
                span.unwrap();
              }
            });
          });
        });
      });
    };

    var create$2 = function () {
      var annotations = {};
      var register = function (name, settings) {
        annotations[name] = {
          name: name,
          settings: settings
        };
      };
      var lookup = function (name) {
        return annotations.hasOwnProperty(name) ? Optional.from(annotations[name]).map(function (a) {
          return a.settings;
        }) : Optional.none();
      };
      return {
        register: register,
        lookup: lookup
      };
    };

    var unique = 0;
    var generate$1 = function (prefix) {
      var date = new Date();
      var time = date.getTime();
      var random = Math.floor(Math.random() * 1000000000);
      unique++;
      return prefix + '_' + random + unique + String(time);
    };

    var add$4 = function (element, classes) {
      each(classes, function (x) {
        add$3(element, x);
      });
    };

    var fromHtml$1 = function (html, scope) {
      var doc = scope || document;
      var div = doc.createElement('div');
      div.innerHTML = html;
      return children(SugarElement.fromDom(div));
    };

    var get$7 = function (element) {
      return element.dom.innerHTML;
    };
    var set$1 = function (element, content) {
      var owner$1 = owner(element);
      var docDom = owner$1.dom;
      var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
      var contentElements = fromHtml$1(content, docDom);
      append$1(fragment, contentElements);
      empty(element);
      append(element, fragment);
    };

    var clone$1 = function (original, isDeep) {
      return SugarElement.fromDom(original.dom.cloneNode(isDeep));
    };
    var shallow = function (original) {
      return clone$1(original, false);
    };
    var deep = function (original) {
      return clone$1(original, true);
    };

    var TextWalker = function (startNode, rootNode, isBoundary) {
      if (isBoundary === void 0) {
        isBoundary = never;
      }
      var walker = new DomTreeWalker(startNode, rootNode);
      var walk = function (direction) {
        var next;
        do {
          next = walker[direction]();
        } while (next &amp;&amp; !isText$1(next) &amp;&amp; !isBoundary(next));
        return Optional.from(next).filter(isText$1);
      };
      return {
        current: function () {
          return Optional.from(walker.current()).filter(isText$1);
        },
        next: function () {
          return walk('next');
        },
        prev: function () {
          return walk('prev');
        },
        prev2: function () {
          return walk('prev2');
        }
      };
    };

    var TextSeeker = function (dom, isBoundary) {
      var isBlockBoundary = isBoundary ? isBoundary : function (node) {
        return dom.isBlock(node) || isBr(node) || isContentEditableFalse(node);
      };
      var walk = function (node, offset, walker, process) {
        if (isText$1(node)) {
          var newOffset = process(node, offset, node.data);
          if (newOffset !== -1) {
            return Optional.some({
              container: node,
              offset: newOffset
            });
          }
        }
        return walker().bind(function (next) {
          return walk(next.container, next.offset, walker, process);
        });
      };
      var backwards = function (node, offset, process, root) {
        var walker = TextWalker(node, root, isBlockBoundary);
        return walk(node, offset, function () {
          return walker.prev().map(function (prev) {
            return {
              container: prev,
              offset: prev.length
            };
          });
        }, process).getOrNull();
      };
      var forwards = function (node, offset, process, root) {
        var walker = TextWalker(node, root, isBlockBoundary);
        return walk(node, offset, function () {
          return walker.next().map(function (next) {
            return {
              container: next,
              offset: 0
            };
          });
        }, process).getOrNull();
      };
      return {
        backwards: backwards,
        forwards: forwards
      };
    };

    var cat = function (arr) {
      var r = [];
      var push = function (x) {
        r.push(x);
      };
      for (var i = 0; i &lt; arr.length; i++) {
        arr[i].each(push);
      }
      return r;
    };
    var lift2 = function (oa, ob, f) {
      return oa.isSome() &amp;&amp; ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
    };
    var lift3 = function (oa, ob, oc, f) {
      return oa.isSome() &amp;&amp; ob.isSome() &amp;&amp; oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
    };
    var someIf = function (b, a) {
      return b ? Optional.some(a) : Optional.none();
    };

    var round = Math.round;
    var clone$2 = function (rect) {
      if (!rect) {
        return {
          left: 0,
          top: 0,
          bottom: 0,
          right: 0,
          width: 0,
          height: 0
        };
      }
      return {
        left: round(rect.left),
        top: round(rect.top),
        bottom: round(rect.bottom),
        right: round(rect.right),
        width: round(rect.width),
        height: round(rect.height)
      };
    };
    var collapse = function (rect, toStart) {
      rect = clone$2(rect);
      if (toStart) {
        rect.right = rect.left;
      } else {
        rect.left = rect.left + rect.width;
        rect.right = rect.left;
      }
      rect.width = 0;
      return rect;
    };
    var isEqual = function (rect1, rect2) {
      return rect1.left === rect2.left &amp;&amp; rect1.top === rect2.top &amp;&amp; rect1.bottom === rect2.bottom &amp;&amp; rect1.right === rect2.right;
    };
    var isValidOverflow = function (overflowY, rect1, rect2) {
      return overflowY &gt;= 0 &amp;&amp; overflowY &lt;= Math.min(rect1.height, rect2.height) / 2;
    };
    var isAbove = function (rect1, rect2) {
      var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
      if (rect1.bottom - halfHeight &lt; rect2.top) {
        return true;
      }
      if (rect1.top &gt; rect2.bottom) {
        return false;
      }
      return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
    };
    var isBelow = function (rect1, rect2) {
      if (rect1.top &gt; rect2.bottom) {
        return true;
      }
      if (rect1.bottom &lt; rect2.top) {
        return false;
      }
      return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
    };
    var containsXY = function (rect, clientX, clientY) {
      return clientX &gt;= rect.left &amp;&amp; clientX &lt;= rect.right &amp;&amp; clientY &gt;= rect.top &amp;&amp; clientY &lt;= rect.bottom;
    };

    var getSelectedNode = function (range) {
      var startContainer = range.startContainer, startOffset = range.startOffset;
      if (startContainer.hasChildNodes() &amp;&amp; range.endOffset === startOffset + 1) {
        return startContainer.childNodes[startOffset];
      }
      return null;
    };
    var getNode = function (container, offset) {
      if (container.nodeType === 1 &amp;&amp; container.hasChildNodes()) {
        if (offset &gt;= container.childNodes.length) {
          offset = container.childNodes.length - 1;
        }
        container = container.childNodes[offset];
      }
      return container;
    };

    var extendingChars = new RegExp('[\u0300-\u036f\u0483-\u0487\u0488-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a' + '\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0' + '\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e3-\u0902\u093a\u093c' + '\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2-\u09e3' + '\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc' + '\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57' + '\u0b62-\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c00\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56' + '\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0d01\u0d3e\u0d41-\u0d44' + '\u0d4d\u0d57\u0d62-\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9' + '\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97' + '\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074' + '\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5' + '\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18' + '\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1ABE\u1b00-\u1b03\u1b34' + '\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9' + '\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9' + '\u1dc0-\u1df5\u1dfc-\u1dff\u200c-\u200d\u20d0-\u20dc\u20DD-\u20E0\u20e1\u20E2-\u20E4\u20e5-\u20f0\u2cef-\u2cf1' + '\u2d7f\u2de0-\u2dff\u302a-\u302d\u302e-\u302f\u3099-\u309a\ua66f\uA670-\uA672\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1' + '\ua802\ua806\ua80b\ua825-\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc' + '\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1' + '\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\uff9e-\uff9f]');
    var isExtendingChar = function (ch) {
      return typeof ch === 'string' &amp;&amp; ch.charCodeAt(0) &gt;= 768 &amp;&amp; extendingChars.test(ch);
    };

    var or = function () {
      var args = [];
      for (var _i = 0; _i &lt; arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return function (x) {
        for (var i = 0; i &lt; args.length; i++) {
          if (args[i](x)) {
            return true;
          }
        }
        return false;
      };
    };
    var and = function () {
      var args = [];
      for (var _i = 0; _i &lt; arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return function (x) {
        for (var i = 0; i &lt; args.length; i++) {
          if (!args[i](x)) {
            return false;
          }
        }
        return true;
      };
    };

    var isElement$3 = isElement$1;
    var isCaretCandidate$1 = isCaretCandidate;
    var isBlock$1 = matchStyleValues('display', 'block table');
    var isFloated = matchStyleValues('float', 'left right');
    var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$1, not(isFloated));
    var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
    var isText$4 = isText$1;
    var isBr$3 = isBr;
    var nodeIndex = DOMUtils.nodeIndex;
    var resolveIndex = getNode;
    var createRange = function (doc) {
      return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
    };
    var isWhiteSpace = function (chr) {
      return chr &amp;&amp; /[\r\n\t ]/.test(chr);
    };
    var isRange = function (rng) {
      return !!rng.setStart &amp;&amp; !!rng.setEnd;
    };
    var isHiddenWhiteSpaceRange = function (range) {
      var container = range.startContainer;
      var offset = range.startOffset;
      var text;
      if (isWhiteSpace(range.toString()) &amp;&amp; isNotPre(container.parentNode) &amp;&amp; isText$1(container)) {
        text = container.data;
        if (isWhiteSpace(text[offset - 1]) || isWhiteSpace(text[offset + 1])) {
          return true;
        }
      }
      return false;
    };
    var getBrClientRect = function (brNode) {
      var doc = brNode.ownerDocument;
      var rng = createRange(doc);
      var nbsp$1 = doc.createTextNode(nbsp);
      var parentNode = brNode.parentNode;
      parentNode.insertBefore(nbsp$1, brNode);
      rng.setStart(nbsp$1, 0);
      rng.setEnd(nbsp$1, 1);
      var clientRect = clone$2(rng.getBoundingClientRect());
      parentNode.removeChild(nbsp$1);
      return clientRect;
    };
    var getBoundingClientRectWebKitText = function (rng) {
      var sc = rng.startContainer;
      var ec = rng.endContainer;
      var so = rng.startOffset;
      var eo = rng.endOffset;
      if (sc === ec &amp;&amp; isText$1(ec) &amp;&amp; so === 0 &amp;&amp; eo === 1) {
        var newRng = rng.cloneRange();
        newRng.setEndAfter(ec);
        return getBoundingClientRect(newRng);
      } else {
        return null;
      }
    };
    var isZeroRect = function (r) {
      return r.left === 0 &amp;&amp; r.right === 0 &amp;&amp; r.top === 0 &amp;&amp; r.bottom === 0;
    };
    var getBoundingClientRect = function (item) {
      var clientRect;
      var clientRects = item.getClientRects();
      if (clientRects.length &gt; 0) {
        clientRect = clone$2(clientRects[0]);
      } else {
        clientRect = clone$2(item.getBoundingClientRect());
      }
      if (!isRange(item) &amp;&amp; isBr$3(item) &amp;&amp; isZeroRect(clientRect)) {
        return getBrClientRect(item);
      }
      if (isZeroRect(clientRect) &amp;&amp; isRange(item)) {
        return getBoundingClientRectWebKitText(item);
      }
      return clientRect;
    };
    var collapseAndInflateWidth = function (clientRect, toStart) {
      var newClientRect = collapse(clientRect, toStart);
      newClientRect.width = 1;
      newClientRect.right = newClientRect.left + 1;
      return newClientRect;
    };
    var getCaretPositionClientRects = function (caretPosition) {
      var clientRects = [];
      var beforeNode, node;
      var addUniqueAndValidRect = function (clientRect) {
        if (clientRect.height === 0) {
          return;
        }
        if (clientRects.length &gt; 0) {
          if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
            return;
          }
        }
        clientRects.push(clientRect);
      };
      var addCharacterOffset = function (container, offset) {
        var range = createRange(container.ownerDocument);
        if (offset &lt; container.data.length) {
          if (isExtendingChar(container.data[offset])) {
            return clientRects;
          }
          if (isExtendingChar(container.data[offset - 1])) {
            range.setStart(container, offset);
            range.setEnd(container, offset + 1);
            if (!isHiddenWhiteSpaceRange(range)) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
              return clientRects;
            }
          }
        }
        if (offset &gt; 0) {
          range.setStart(container, offset - 1);
          range.setEnd(container, offset);
          if (!isHiddenWhiteSpaceRange(range)) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
          }
        }
        if (offset &lt; container.data.length) {
          range.setStart(container, offset);
          range.setEnd(container, offset + 1);
          if (!isHiddenWhiteSpaceRange(range)) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), true));
          }
        }
      };
      if (isText$4(caretPosition.container())) {
        addCharacterOffset(caretPosition.container(), caretPosition.offset());
        return clientRects;
      }
      if (isElement$3(caretPosition.container())) {
        if (caretPosition.isAtEnd()) {
          node = resolveIndex(caretPosition.container(), caretPosition.offset());
          if (isText$4(node)) {
            addCharacterOffset(node, node.data.length);
          }
          if (isValidElementCaretCandidate(node) &amp;&amp; !isBr$3(node)) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
          }
        } else {
          node = resolveIndex(caretPosition.container(), caretPosition.offset());
          if (isText$4(node)) {
            addCharacterOffset(node, 0);
          }
          if (isValidElementCaretCandidate(node) &amp;&amp; caretPosition.isAtEnd()) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
            return clientRects;
          }
          beforeNode = resolveIndex(caretPosition.container(), caretPosition.offset() - 1);
          if (isValidElementCaretCandidate(beforeNode) &amp;&amp; !isBr$3(beforeNode)) {
            if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(beforeNode), false));
            }
          }
          if (isValidElementCaretCandidate(node)) {
            addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), true));
          }
        }
      }
      return clientRects;
    };
    var CaretPosition = function (container, offset, clientRects) {
      var isAtStart = function () {
        if (isText$4(container)) {
          return offset === 0;
        }
        return offset === 0;
      };
      var isAtEnd = function () {
        if (isText$4(container)) {
          return offset &gt;= container.data.length;
        }
        return offset &gt;= container.childNodes.length;
      };
      var toRange = function () {
        var range = createRange(container.ownerDocument);
        range.setStart(container, offset);
        range.setEnd(container, offset);
        return range;
      };
      var getClientRects = function () {
        if (!clientRects) {
          clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
        }
        return clientRects;
      };
      var isVisible = function () {
        return getClientRects().length &gt; 0;
      };
      var isEqual = function (caretPosition) {
        return caretPosition &amp;&amp; container === caretPosition.container() &amp;&amp; offset === caretPosition.offset();
      };
      var getNode = function (before) {
        return resolveIndex(container, before ? offset - 1 : offset);
      };
      return {
        container: constant(container),
        offset: constant(offset),
        toRange: toRange,
        getClientRects: getClientRects,
        isVisible: isVisible,
        isAtStart: isAtStart,
        isAtEnd: isAtEnd,
        isEqual: isEqual,
        getNode: getNode
      };
    };
    CaretPosition.fromRangeStart = function (range) {
      return CaretPosition(range.startContainer, range.startOffset);
    };
    CaretPosition.fromRangeEnd = function (range) {
      return CaretPosition(range.endContainer, range.endOffset);
    };
    CaretPosition.after = function (node) {
      return CaretPosition(node.parentNode, nodeIndex(node) + 1);
    };
    CaretPosition.before = function (node) {
      return CaretPosition(node.parentNode, nodeIndex(node));
    };
    CaretPosition.isAbove = function (pos1, pos2) {
      return lift2(head(pos2.getClientRects()), last(pos1.getClientRects()), isAbove).getOr(false);
    };
    CaretPosition.isBelow = function (pos1, pos2) {
      return lift2(last(pos2.getClientRects()), head(pos1.getClientRects()), isBelow).getOr(false);
    };
    CaretPosition.isAtStart = function (pos) {
      return pos ? pos.isAtStart() : false;
    };
    CaretPosition.isAtEnd = function (pos) {
      return pos ? pos.isAtEnd() : false;
    };
    CaretPosition.isTextPosition = function (pos) {
      return pos ? isText$1(pos.container()) : false;
    };
    CaretPosition.isElementPosition = function (pos) {
      return CaretPosition.isTextPosition(pos) === false;
    };

    var trimEmptyTextNode = function (dom, node) {
      if (isText$1(node) &amp;&amp; node.data.length === 0) {
        dom.remove(node);
      }
    };
    var insertNode = function (dom, rng, node) {
      rng.insertNode(node);
      trimEmptyTextNode(dom, node.previousSibling);
      trimEmptyTextNode(dom, node.nextSibling);
    };
    var insertFragment = function (dom, rng, frag) {
      var firstChild = Optional.from(frag.firstChild);
      var lastChild = Optional.from(frag.lastChild);
      rng.insertNode(frag);
      firstChild.each(function (child) {
        return trimEmptyTextNode(dom, child.previousSibling);
      });
      lastChild.each(function (child) {
        return trimEmptyTextNode(dom, child.nextSibling);
      });
    };
    var rangeInsertNode = function (dom, rng, node) {
      if (isDocumentFragment$1(node)) {
        insertFragment(dom, rng, node);
      } else {
        insertNode(dom, rng, node);
      }
    };

    var isText$5 = isText$1;
    var isBogus$2 = isBogus;
    var nodeIndex$1 = DOMUtils.nodeIndex;
    var normalizedParent = function (node) {
      var parentNode = node.parentNode;
      if (isBogus$2(parentNode)) {
        return normalizedParent(parentNode);
      }
      return parentNode;
    };
    var getChildNodes = function (node) {
      if (!node) {
        return [];
      }
      return reduce(node.childNodes, function (result, node) {
        if (isBogus$2(node) &amp;&amp; node.nodeName !== 'BR') {
          result = result.concat(getChildNodes(node));
        } else {
          result.push(node);
        }
        return result;
      }, []);
    };
    var normalizedTextOffset = function (node, offset) {
      while (node = node.previousSibling) {
        if (!isText$5(node)) {
          break;
        }
        offset += node.data.length;
      }
      return offset;
    };
    var equal$1 = function (a) {
      return function (b) {
        return a === b;
      };
    };
    var normalizedNodeIndex = function (node) {
      var nodes, index;
      nodes = getChildNodes(normalizedParent(node));
      index = findIndex$1(nodes, equal$1(node), node);
      nodes = nodes.slice(0, index + 1);
      var numTextFragments = reduce(nodes, function (result, node, i) {
        if (isText$5(node) &amp;&amp; isText$5(nodes[i - 1])) {
          result++;
        }
        return result;
      }, 0);
      nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
      index = findIndex$1(nodes, equal$1(node), node);
      return index - numTextFragments;
    };
    var createPathItem = function (node) {
      var name;
      if (isText$5(node)) {
        name = 'text()';
      } else {
        name = node.nodeName.toLowerCase();
      }
      return name + '[' + normalizedNodeIndex(node) + ']';
    };
    var parentsUntil = function (root, node, predicate) {
      var parents = [];
      for (node = node.parentNode; node !== root; node = node.parentNode) {
        if (predicate &amp;&amp; predicate(node)) {
          break;
        }
        parents.push(node);
      }
      return parents;
    };
    var create$3 = function (root, caretPosition) {
      var container, offset, path = [], outputOffset, childNodes, parents;
      container = caretPosition.container();
      offset = caretPosition.offset();
      if (isText$5(container)) {
        outputOffset = normalizedTextOffset(container, offset);
      } else {
        childNodes = container.childNodes;
        if (offset &gt;= childNodes.length) {
          outputOffset = 'after';
          offset = childNodes.length - 1;
        } else {
          outputOffset = 'before';
        }
        container = childNodes[offset];
      }
      path.push(createPathItem(container));
      parents = parentsUntil(root, container);
      parents = filter$2(parents, not(isBogus));
      path = path.concat(map$2(parents, function (node) {
        return createPathItem(node);
      }));
      return path.reverse().join('/') + ',' + outputOffset;
    };
    var resolvePathItem = function (node, name, index) {
      var nodes = getChildNodes(node);
      nodes = filter$2(nodes, function (node, index) {
        return !isText$5(node) || !isText$5(nodes[index - 1]);
      });
      nodes = filter$2(nodes, matchNodeNames([name]));
      return nodes[index];
    };
    var findTextPosition = function (container, offset) {
      var node = container, targetOffset = 0, dataLen;
      while (isText$5(node)) {
        dataLen = node.data.length;
        if (offset &gt;= targetOffset &amp;&amp; offset &lt;= targetOffset + dataLen) {
          container = node;
          offset = offset - targetOffset;
          break;
        }
        if (!isText$5(node.nextSibling)) {
          container = node;
          offset = dataLen;
          break;
        }
        targetOffset += dataLen;
        node = node.nextSibling;
      }
      if (isText$5(container) &amp;&amp; offset &gt; container.data.length) {
        offset = container.data.length;
      }
      return CaretPosition(container, offset);
    };
    var resolve$1 = function (root, path) {
      var offset;
      if (!path) {
        return null;
      }
      var parts = path.split(',');
      var paths = parts[0].split('/');
      offset = parts.length &gt; 1 ? parts[1] : 'before';
      var container = reduce(paths, function (result, value) {
        var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
        if (!match) {
          return null;
        }
        if (match[1] === 'text()') {
          match[1] = '#text';
        }
        return resolvePathItem(result, match[1], parseInt(match[2], 10));
      }, root);
      if (!container) {
        return null;
      }
      if (!isText$5(container)) {
        if (offset === 'after') {
          offset = nodeIndex$1(container) + 1;
        } else {
          offset = nodeIndex$1(container);
        }
        return CaretPosition(container.parentNode, offset);
      }
      return findTextPosition(container, parseInt(offset, 10));
    };

    var isContentEditableFalse$2 = isContentEditableFalse;
    var getNormalizedTextOffset = function (trim, container, offset) {
      var node, trimmedOffset;
      trimmedOffset = trim(container.data.slice(0, offset)).length;
      for (node = container.previousSibling; node &amp;&amp; isText$1(node); node = node.previousSibling) {
        trimmedOffset += trim(node.data).length;
      }
      return trimmedOffset;
    };
    var getPoint = function (dom, trim, normalized, rng, start) {
      var container = rng[start ? 'startContainer' : 'endContainer'];
      var offset = rng[start ? 'startOffset' : 'endOffset'];
      var point = [];
      var childNodes, after = 0;
      var root = dom.getRoot();
      if (isText$1(container)) {
        point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
      } else {
        childNodes = container.childNodes;
        if (offset &gt;= childNodes.length &amp;&amp; childNodes.length) {
          after = 1;
          offset = Math.max(0, childNodes.length - 1);
        }
        point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
      }
      for (; container &amp;&amp; container !== root; container = container.parentNode) {
        point.push(dom.nodeIndex(container, normalized));
      }
      return point;
    };
    var getLocation = function (trim, selection, normalized, rng) {
      var dom = selection.dom, bookmark = {};
      bookmark.start = getPoint(dom, trim, normalized, rng, true);
      if (!selection.isCollapsed()) {
        bookmark.end = getPoint(dom, trim, normalized, rng, false);
      }
      return bookmark;
    };
    var findIndex$2 = function (dom, name, element) {
      var count = 0;
      Tools.each(dom.select(name), function (node) {
        if (node.getAttribute('data-mce-bogus') === 'all') {
          return;
        }
        if (node === element) {
          return false;
        }
        count++;
      });
      return count;
    };
    var moveEndPoint = function (rng, start) {
      var container, offset, childNodes;
      var prefix = start ? 'start' : 'end';
      container = rng[prefix + 'Container'];
      offset = rng[prefix + 'Offset'];
      if (isElement$1(container) &amp;&amp; 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);
        }
      }
    };
    var normalizeTableCellSelection = function (rng) {
      moveEndPoint(rng, true);
      moveEndPoint(rng, false);
      return rng;
    };
    var findSibling = function (node, offset) {
      var sibling;
      if (isElement$1(node)) {
        node = getNode(node, offset);
        if (isContentEditableFalse$2(node)) {
          return node;
        }
      }
      if (isCaretContainer(node)) {
        if (isText$1(node) &amp;&amp; isCaretContainerBlock(node)) {
          node = node.parentNode;
        }
        sibling = node.previousSibling;
        if (isContentEditableFalse$2(sibling)) {
          return sibling;
        }
        sibling = node.nextSibling;
        if (isContentEditableFalse$2(sibling)) {
          return sibling;
        }
      }
    };
    var findAdjacentContentEditableFalseElm = function (rng) {
      return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
    };
    var getOffsetBookmark = function (trim, normalized, selection) {
      var element = selection.getNode();
      var name = element ? element.nodeName : null;
      var rng = selection.getRng();
      if (isContentEditableFalse$2(element) || name === 'IMG') {
        return {
          name: name,
          index: findIndex$2(selection.dom, name, element)
        };
      }
      var sibling = findAdjacentContentEditableFalseElm(rng);
      if (sibling) {
        name = sibling.tagName;
        return {
          name: name,
          index: findIndex$2(selection.dom, name, sibling)
        };
      }
      return getLocation(trim, selection, normalized, rng);
    };
    var getCaretBookmark = function (selection) {
      var rng = selection.getRng();
      return {
        start: create$3(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
        end: create$3(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
      };
    };
    var getRangeBookmark = function (selection) {
      return { rng: selection.getRng() };
    };
    var createBookmarkSpan = function (dom, id, filled) {
      var args = {
        'data-mce-type': 'bookmark',
        id: id,
        'style': 'overflow:hidden;line-height:0px'
      };
      return filled ? dom.create('span', args, '&amp;#xFEFF;') : dom.create('span', args);
    };
    var getPersistentBookmark = function (selection, filled) {
      var dom = selection.dom;
      var rng = selection.getRng();
      var id = dom.uniqueId();
      var collapsed = selection.isCollapsed();
      var element = selection.getNode();
      var name = element.nodeName;
      if (name === 'IMG') {
        return {
          name: name,
          index: findIndex$2(dom, name, element)
        };
      }
      var rng2 = normalizeTableCellSelection(rng.cloneRange());
      if (!collapsed) {
        rng2.collapse(false);
        var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
        rangeInsertNode(dom, rng2, endBookmarkNode);
      }
      rng = normalizeTableCellSelection(rng);
      rng.collapse(true);
      var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
      rangeInsertNode(dom, rng, startBookmarkNode);
      selection.moveToBookmark({
        id: id,
        keep: true
      });
      return { id: id };
    };
    var getBookmark = function (selection, type, normalized) {
      if (type === 2) {
        return getOffsetBookmark(trim$2, normalized, selection);
      } else if (type === 3) {
        return getCaretBookmark(selection);
      } else if (type) {
        return getRangeBookmark(selection);
      } else {
        return getPersistentBookmark(selection, false);
      }
    };
    var getUndoBookmark = curry(getOffsetBookmark, identity, true);

    var DOM$1 = DOMUtils.DOM;
    var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
    var getBodySetting = function (editor, name, defaultValue) {
      var value = editor.getParam(name, defaultValue);
      if (value.indexOf('=') !== -1) {
        var bodyObj = editor.getParam(name, '', 'hash');
        return bodyObj.hasOwnProperty(editor.id) ? bodyObj[editor.id] : defaultValue;
      } else {
        return value;
      }
    };
    var getIframeAttrs = function (editor) {
      return editor.getParam('iframe_attrs', {});
    };
    var getDocType = function (editor) {
      return editor.getParam('doctype', '&lt;!DOCTYPE html&gt;');
    };
    var getDocumentBaseUrl = function (editor) {
      return editor.getParam('document_base_url', '');
    };
    var getBodyId = function (editor) {
      return getBodySetting(editor, 'body_id', 'tinymce');
    };
    var getBodyClass = function (editor) {
      return getBodySetting(editor, 'body_class', '');
    };
    var getContentSecurityPolicy = function (editor) {
      return editor.getParam('content_security_policy', '');
    };
    var shouldPutBrInPre = function (editor) {
      return editor.getParam('br_in_pre', true);
    };
    var getForcedRootBlock = function (editor) {
      if (editor.getParam('force_p_newlines', false)) {
        return 'p';
      }
      var block = editor.getParam('forced_root_block', 'p');
      if (block === false) {
        return '';
      } else if (block === true) {
        return 'p';
      } else {
        return block;
      }
    };
    var getForcedRootBlockAttrs = function (editor) {
      return editor.getParam('forced_root_block_attrs', {});
    };
    var getBrNewLineSelector = function (editor) {
      return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
    };
    var getNoNewLineSelector = function (editor) {
      return editor.getParam('no_newline_selector', '');
    };
    var shouldKeepStyles = function (editor) {
      return editor.getParam('keep_styles', true);
    };
    var shouldEndContainerOnEmptyBlock = function (editor) {
      return editor.getParam('end_container_on_empty_block', false);
    };
    var getFontStyleValues = function (editor) {
      return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
    };
    var getFontSizeClasses = function (editor) {
      return Tools.explode(editor.getParam('font_size_classes', ''));
    };
    var getImagesDataImgFilter = function (editor) {
      return editor.getParam('images_dataimg_filter', always, 'function');
    };
    var isAutomaticUploadsEnabled = function (editor) {
      return editor.getParam('automatic_uploads', true, 'boolean');
    };
    var shouldReuseFileName = function (editor) {
      return editor.getParam('images_reuse_filename', false, 'boolean');
    };
    var shouldReplaceBlobUris = function (editor) {
      return editor.getParam('images_replace_blob_uris', true, 'boolean');
    };
    var getIconPackName = function (editor) {
      return editor.getParam('icons', '', 'string');
    };
    var getIconsUrl = function (editor) {
      return editor.getParam('icons_url', '', 'string');
    };
    var getImageUploadUrl = function (editor) {
      return editor.getParam('images_upload_url', '', 'string');
    };
    var getImageUploadBasePath = function (editor) {
      return editor.getParam('images_upload_base_path', '', 'string');
    };
    var getImagesUploadCredentials = function (editor) {
      return editor.getParam('images_upload_credentials', false, 'boolean');
    };
    var getImagesUploadHandler = function (editor) {
      return editor.getParam('images_upload_handler', null, 'function');
    };
    var shouldUseContentCssCors = function (editor) {
      return editor.getParam('content_css_cors', false, 'boolean');
    };
    var getReferrerPolicy = function (editor) {
      return editor.getParam('referrer_policy', '', 'string');
    };
    var getLanguageCode = function (editor) {
      return editor.getParam('language', 'en', 'string');
    };
    var getLanguageUrl = function (editor) {
      return editor.getParam('language_url', '', 'string');
    };
    var shouldIndentUseMargin = function (editor) {
      return editor.getParam('indent_use_margin', false);
    };
    var getIndentation = function (editor) {
      return editor.getParam('indentation', '40px', 'string');
    };
    var getContentCss = function (editor) {
      var contentCss = editor.getParam('content_css');
      if (isString(contentCss)) {
        return map(contentCss.split(','), trim);
      } else if (isArray(contentCss)) {
        return contentCss;
      } else if (contentCss === false || editor.inline) {
        return [];
      } else {
        return ['default'];
      }
    };
    var getFontCss = function (editor) {
      var fontCss = editor.getParam('font_css', []);
      return isArray(fontCss) ? fontCss : map(fontCss.split(','), trim);
    };
    var getDirectionality = function (editor) {
      return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
    };
    var getInlineBoundarySelector = function (editor) {
      return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
    };
    var getObjectResizing = function (editor) {
      var selector = editor.getParam('object_resizing');
      if (selector === false || Env.iOS) {
        return false;
      } else {
        return isString(selector) ? selector : 'table,img,figure.image,div,video,iframe';
      }
    };
    var getResizeImgProportional = function (editor) {
      return editor.getParam('resize_img_proportional', true, 'boolean');
    };
    var getPlaceholder = function (editor) {
      return editor.getParam('placeholder', DOM$1.getAttrib(editor.getElement(), 'placeholder'), 'string');
    };
    var getEventRoot = function (editor) {
      return editor.getParam('event_root');
    };
    var getServiceMessage = function (editor) {
      return editor.getParam('service_message');
    };
    var getTheme = function (editor) {
      return editor.getParam('theme');
    };
    var shouldValidate = function (editor) {
      return editor.getParam('validate');
    };
    var isInlineBoundariesEnabled = function (editor) {
      return editor.getParam('inline_boundaries') !== false;
    };
    var getFormats = function (editor) {
      return editor.getParam('formats');
    };
    var getPreviewStyles = function (editor) {
      var style = editor.getParam('preview_styles', defaultPreviewStyles);
      if (isString(style)) {
        return style;
      } else {
        return '';
      }
    };
    var canFormatEmptyLines = function (editor) {
      return editor.getParam('format_empty_lines', false, 'boolean');
    };
    var getCustomUiSelector = function (editor) {
      return editor.getParam('custom_ui_selector', '', 'string');
    };
    var getThemeUrl = function (editor) {
      return editor.getParam('theme_url');
    };
    var isInline$1 = function (editor) {
      return editor.getParam('inline');
    };
    var hasHiddenInput = function (editor) {
      return editor.getParam('hidden_input');
    };
    var shouldPatchSubmit = function (editor) {
      return editor.getParam('submit_patch');
    };
    var isEncodingXml = function (editor) {
      return editor.getParam('encoding') === 'xml';
    };
    var shouldAddFormSubmitTrigger = function (editor) {
      return editor.getParam('add_form_submit_trigger');
    };
    var shouldAddUnloadTrigger = function (editor) {
      return editor.getParam('add_unload_trigger');
    };
    var hasForcedRootBlock = function (editor) {
      return getForcedRootBlock(editor) !== '';
    };
    var getCustomUndoRedoLevels = function (editor) {
      return editor.getParam('custom_undo_redo_levels', 0, 'number');
    };
    var shouldDisableNodeChange = function (editor) {
      return editor.getParam('disable_nodechange');
    };
    var isReadOnly = function (editor) {
      return editor.getParam('readonly');
    };
    var hasContentCssCors = function (editor) {
      return editor.getParam('content_css_cors');
    };
    var getPlugins = function (editor) {
      return editor.getParam('plugins', '', 'string');
    };
    var getExternalPlugins = function (editor) {
      return editor.getParam('external_plugins');
    };
    var shouldBlockUnsupportedDrop = function (editor) {
      return editor.getParam('block_unsupported_drop', true, 'boolean');
    };
    var isVisualAidsEnabled = function (editor) {
      return editor.getParam('visual', true, 'boolean');
    };
    var getVisualAidsTableClass = function (editor) {
      return editor.getParam('visual_table_class', 'mce-item-table', 'string');
    };
    var getVisualAidsAnchorClass = function (editor) {
      return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
    };

    var isElement$4 = isElement$1;
    var isText$6 = isText$1;
    var removeNode = function (node) {
      var parentNode = node.parentNode;
      if (parentNode) {
        parentNode.removeChild(node);
      }
    };
    var trimCount = function (text) {
      var trimmedText = trim$2(text);
      return {
        count: text.length - trimmedText.length,
        text: trimmedText
      };
    };
    var deleteZwspChars = function (caretContainer) {
      var idx;
      while ((idx = caretContainer.data.lastIndexOf(ZWSP)) !== -1) {
        caretContainer.deleteData(idx, 1);
      }
    };
    var removeUnchanged = function (caretContainer, pos) {
      remove$5(caretContainer);
      return pos;
    };
    var removeTextAndReposition = function (caretContainer, pos) {
      var before = trimCount(caretContainer.data.substr(0, pos.offset()));
      var after = trimCount(caretContainer.data.substr(pos.offset()));
      var text = before.text + after.text;
      if (text.length &gt; 0) {
        deleteZwspChars(caretContainer);
        return CaretPosition(caretContainer, pos.offset() - before.count);
      } else {
        return pos;
      }
    };
    var removeElementAndReposition = function (caretContainer, pos) {
      var parentNode = pos.container();
      var newPosition = indexOf(from$1(parentNode.childNodes), caretContainer).map(function (index) {
        return index &lt; pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
      }).getOr(pos);
      remove$5(caretContainer);
      return newPosition;
    };
    var removeTextCaretContainer = function (caretContainer, pos) {
      return isText$6(caretContainer) &amp;&amp; pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
    };
    var removeElementCaretContainer = function (caretContainer, pos) {
      return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
    };
    var removeAndReposition = function (container, pos) {
      return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
    };
    var remove$5 = function (caretContainerNode) {
      if (isElement$4(caretContainerNode) &amp;&amp; isCaretContainer(caretContainerNode)) {
        if (hasContent(caretContainerNode)) {
          caretContainerNode.removeAttribute('data-mce-caret');
        } else {
          removeNode(caretContainerNode);
        }
      }
      if (isText$6(caretContainerNode)) {
        deleteZwspChars(caretContainerNode);
        if (caretContainerNode.data.length === 0) {
          removeNode(caretContainerNode);
        }
      }
    };

    var browser$2 = detect$3().browser;
    var isContentEditableFalse$3 = isContentEditableFalse;
    var isMedia$1 = isMedia;
    var isTableCell$2 = isTableCell;
    var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
    var getAbsoluteClientRect = function (root, element, before) {
      var clientRect = collapse(element.getBoundingClientRect(), before);
      var docElm, scrollX, scrollY, margin, rootRect;
      if (root.tagName === 'BODY') {
        docElm = root.ownerDocument.documentElement;
        scrollX = root.scrollLeft || docElm.scrollLeft;
        scrollY = root.scrollTop || docElm.scrollTop;
      } else {
        rootRect = root.getBoundingClientRect();
        scrollX = root.scrollLeft - rootRect.left;
        scrollY = root.scrollTop - rootRect.top;
      }
      clientRect.left += scrollX;
      clientRect.right += scrollX;
      clientRect.top += scrollY;
      clientRect.bottom += scrollY;
      clientRect.width = 1;
      margin = element.offsetWidth - element.clientWidth;
      if (margin &gt; 0) {
        if (before) {
          margin *= -1;
        }
        clientRect.left += margin;
        clientRect.right += margin;
      }
      return clientRect;
    };
    var trimInlineCaretContainers = function (root) {
      var fakeCaretTargetNodes = descendants$1(SugarElement.fromDom(root), inlineFakeCaretSelector);
      for (var i = 0; i &lt; fakeCaretTargetNodes.length; i++) {
        var node = fakeCaretTargetNodes[i].dom;
        var sibling = node.previousSibling;
        if (endsWithCaretContainer(sibling)) {
          var data = sibling.data;
          if (data.length === 1) {
            sibling.parentNode.removeChild(sibling);
          } else {
            sibling.deleteData(data.length - 1, 1);
          }
        }
        sibling = node.nextSibling;
        if (startsWithCaretContainer(sibling)) {
          var data = sibling.data;
          if (data.length === 1) {
            sibling.parentNode.removeChild(sibling);
          } else {
            sibling.deleteData(0, 1);
          }
        }
      }
    };
    var FakeCaret = function (editor, root, isBlock, hasFocus) {
      var lastVisualCaret = Cell(Optional.none());
      var cursorInterval, caretContainerNode;
      var rootBlock = getForcedRootBlock(editor);
      var caretBlock = rootBlock.length &gt; 0 ? rootBlock : 'p';
      var show = function (before, element) {
        var clientRect, rng;
        hide();
        if (isTableCell$2(element)) {
          return null;
        }
        if (isBlock(element)) {
          caretContainerNode = insertBlock(caretBlock, element, before);
          clientRect = getAbsoluteClientRect(root, element, before);
          DomQuery(caretContainerNode).css('top', clientRect.top);
          var caret = DomQuery('&lt;div class="mce-visual-caret" data-mce-bogus="all"&gt;&lt;/div&gt;').css(clientRect).appendTo(root)[0];
          lastVisualCaret.set(Optional.some({
            caret: caret,
            element: element,
            before: before
          }));
          lastVisualCaret.get().each(function (caretState) {
            if (before) {
              DomQuery(caretState.caret).addClass('mce-visual-caret-before');
            }
          });
          startBlink();
          rng = element.ownerDocument.createRange();
          rng.setStart(caretContainerNode, 0);
          rng.setEnd(caretContainerNode, 0);
        } else {
          caretContainerNode = insertInline(element, before);
          rng = element.ownerDocument.createRange();
          if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
            rng.setStart(caretContainerNode, 0);
            rng.setEnd(caretContainerNode, 0);
          } else {
            rng.setStart(caretContainerNode, 1);
            rng.setEnd(caretContainerNode, 1);
          }
          return rng;
        }
        return rng;
      };
      var hide = function () {
        trimInlineCaretContainers(root);
        if (caretContainerNode) {
          remove$5(caretContainerNode);
          caretContainerNode = null;
        }
        lastVisualCaret.get().each(function (caretState) {
          DomQuery(caretState.caret).remove();
          lastVisualCaret.set(Optional.none());
        });
        if (cursorInterval) {
          Delay.clearInterval(cursorInterval);
          cursorInterval = null;
        }
      };
      var startBlink = function () {
        cursorInterval = Delay.setInterval(function () {
          if (hasFocus()) {
            DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
          } else {
            DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
          }
        }, 500);
      };
      var reposition = function () {
        lastVisualCaret.get().each(function (caretState) {
          var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
          DomQuery(caretState.caret).css(__assign({}, clientRect));
        });
      };
      var destroy = function () {
        return Delay.clearInterval(cursorInterval);
      };
      var getCss = function () {
        return '.mce-visual-caret {' + 'position: absolute;' + 'background-color: black;' + 'background-color: currentcolor;' + '}' + '.mce-visual-caret-hidden {' + 'display: none;' + '}' + '*[data-mce-caret] {' + 'position: absolute;' + 'left: -1000px;' + 'right: auto;' + 'top: 0;' + 'margin: 0;' + 'padding: 0;' + '}';
      };
      return {
        show: show,
        hide: hide,
        getCss: getCss,
        reposition: reposition,
        destroy: destroy
      };
    };
    var isFakeCaretTableBrowser = function () {
      return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
    };
    var isInlineFakeCaretTarget = function (node) {
      return isContentEditableFalse$3(node) || isMedia$1(node);
    };
    var isFakeCaretTarget = function (node) {
      return isInlineFakeCaretTarget(node) || isTable(node) &amp;&amp; isFakeCaretTableBrowser();
    };

    var isContentEditableFalse$4 = isContentEditableFalse;
    var isMedia$2 = isMedia;
    var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
    var isCaretContainer$2 = isCaretContainer;
    var isCaretContainerBlock$1 = isCaretContainerBlock;
    var isElement$5 = isElement$1;
    var isCaretCandidate$2 = isCaretCandidate;
    var isForwards = function (direction) {
      return direction &gt; 0;
    };
    var isBackwards = function (direction) {
      return direction &lt; 0;
    };
    var skipCaretContainers = function (walk, shallow) {
      var node;
      while (node = walk(shallow)) {
        if (!isCaretContainerBlock$1(node)) {
          return node;
        }
      }
      return null;
    };
    var findNode = function (node, direction, predicateFn, rootNode, shallow) {
      var walker = new DomTreeWalker(node, rootNode);
      var isCefOrCaretContainer = isContentEditableFalse$4(node) || isCaretContainerBlock$1(node);
      if (isBackwards(direction)) {
        if (isCefOrCaretContainer) {
          node = skipCaretContainers(walker.prev.bind(walker), true);
          if (predicateFn(node)) {
            return node;
          }
        }
        while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
          if (predicateFn(node)) {
            return node;
          }
        }
      }
      if (isForwards(direction)) {
        if (isCefOrCaretContainer) {
          node = skipCaretContainers(walker.next.bind(walker), true);
          if (predicateFn(node)) {
            return node;
          }
        }
        while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
          if (predicateFn(node)) {
            return node;
          }
        }
      }
      return null;
    };
    var getParentBlock = function (node, rootNode) {
      while (node &amp;&amp; node !== rootNode) {
        if (isBlockLike(node)) {
          return node;
        }
        node = node.parentNode;
      }
      return null;
    };
    var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
      return getParentBlock(caretPosition1.container(), rootNode) === getParentBlock(caretPosition2.container(), rootNode);
    };
    var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
      if (!caretPosition) {
        return null;
      }
      var container = caretPosition.container();
      var offset = caretPosition.offset();
      if (!isElement$5(container)) {
        return null;
      }
      return container.childNodes[offset + relativeOffset];
    };
    var beforeAfter = function (before, node) {
      var range = node.ownerDocument.createRange();
      if (before) {
        range.setStartBefore(node);
        range.setEndBefore(node);
      } else {
        range.setStartAfter(node);
        range.setEndAfter(node);
      }
      return range;
    };
    var isNodesInSameBlock = function (root, node1, node2) {
      return getParentBlock(node1, root) === getParentBlock(node2, root);
    };
    var lean = function (left, root, node) {
      var sibling, siblingName;
      if (left) {
        siblingName = 'previousSibling';
      } else {
        siblingName = 'nextSibling';
      }
      while (node &amp;&amp; node !== root) {
        sibling = node[siblingName];
        if (isCaretContainer$2(sibling)) {
          sibling = sibling[siblingName];
        }
        if (isContentEditableFalse$4(sibling) || isMedia$2(sibling)) {
          if (isNodesInSameBlock(root, sibling, node)) {
            return sibling;
          }
          break;
        }
        if (isCaretCandidate$2(sibling)) {
          break;
        }
        node = node.parentNode;
      }
      return null;
    };
    var before$2 = curry(beforeAfter, true);
    var after$1 = curry(beforeAfter, false);
    var normalizeRange = function (direction, root, range) {
      var node, container, location;
      var leanLeft = curry(lean, true, root);
      var leanRight = curry(lean, false, root);
      container = range.startContainer;
      var offset = range.startOffset;
      if (isCaretContainerBlock(container)) {
        if (!isElement$5(container)) {
          container = container.parentNode;
        }
        location = container.getAttribute('data-mce-caret');
        if (location === 'before') {
          node = container.nextSibling;
          if (isFakeCaretTarget(node)) {
            return before$2(node);
          }
        }
        if (location === 'after') {
          node = container.previousSibling;
          if (isFakeCaretTarget(node)) {
            return after$1(node);
          }
        }
      }
      if (!range.collapsed) {
        return range;
      }
      if (isText$1(container)) {
        if (isCaretContainer$2(container)) {
          if (direction === 1) {
            node = leanRight(container);
            if (node) {
              return before$2(node);
            }
            node = leanLeft(container);
            if (node) {
              return after$1(node);
            }
          }
          if (direction === -1) {
            node = leanLeft(container);
            if (node) {
              return after$1(node);
            }
            node = leanRight(container);
            if (node) {
              return before$2(node);
            }
          }
          return range;
        }
        if (endsWithCaretContainer(container) &amp;&amp; offset &gt;= container.data.length - 1) {
          if (direction === 1) {
            node = leanRight(container);
            if (node) {
              return before$2(node);
            }
          }
          return range;
        }
        if (startsWithCaretContainer(container) &amp;&amp; offset &lt;= 1) {
          if (direction === -1) {
            node = leanLeft(container);
            if (node) {
              return after$1(node);
            }
          }
          return range;
        }
        if (offset === container.data.length) {
          node = leanRight(container);
          if (node) {
            return before$2(node);
          }
          return range;
        }
        if (offset === 0) {
          node = leanLeft(container);
          if (node) {
            return after$1(node);
          }
          return range;
        }
      }
      return range;
    };
    var getRelativeCefElm = function (forward, caretPosition) {
      return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$4);
    };
    var getNormalizedRangeEndPoint = function (direction, root, range) {
      var normalizedRange = normalizeRange(direction, root, range);
      if (direction === -1) {
        return CaretPosition.fromRangeStart(normalizedRange);
      }
      return CaretPosition.fromRangeEnd(normalizedRange);
    };
    var getElementFromPosition = function (pos) {
      return Optional.from(pos.getNode()).map(SugarElement.fromDom);
    };
    var getElementFromPrevPosition = function (pos) {
      return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
    };
    var getVisualCaretPosition = function (walkFn, caretPosition) {
      while (caretPosition = walkFn(caretPosition)) {
        if (caretPosition.isVisible()) {
          return caretPosition;
        }
      }
      return caretPosition;
    };
    var isMoveInsideSameBlock = function (from, to) {
      var inSameBlock = isInSameBlock(from, to);
      if (!inSameBlock &amp;&amp; isBr(from.getNode())) {
        return true;
      }
      return inSameBlock;
    };

    var HDirection;
    (function (HDirection) {
      HDirection[HDirection['Backwards'] = -1] = 'Backwards';
      HDirection[HDirection['Forwards'] = 1] = 'Forwards';
    }(HDirection || (HDirection = {})));
    var isContentEditableFalse$5 = isContentEditableFalse;
    var isText$7 = isText$1;
    var isElement$6 = isElement$1;
    var isBr$4 = isBr;
    var isCaretCandidate$3 = isCaretCandidate;
    var isAtomic$1 = isAtomic;
    var isEditableCaretCandidate$1 = isEditableCaretCandidate;
    var getParents = function (node, root) {
      var parents = [];
      while (node &amp;&amp; node !== root) {
        parents.push(node);
        node = node.parentNode;
      }
      return parents;
    };
    var nodeAtIndex = function (container, offset) {
      if (container.hasChildNodes() &amp;&amp; offset &lt; container.childNodes.length) {
        return container.childNodes[offset];
      }
      return null;
    };
    var getCaretCandidatePosition = function (direction, node) {
      if (isForwards(direction)) {
        if (isCaretCandidate$3(node.previousSibling) &amp;&amp; !isText$7(node.previousSibling)) {
          return CaretPosition.before(node);
        }
        if (isText$7(node)) {
          return CaretPosition(node, 0);
        }
      }
      if (isBackwards(direction)) {
        if (isCaretCandidate$3(node.nextSibling) &amp;&amp; !isText$7(node.nextSibling)) {
          return CaretPosition.after(node);
        }
        if (isText$7(node)) {
          return CaretPosition(node, node.data.length);
        }
      }
      if (isBackwards(direction)) {
        if (isBr$4(node)) {
          return CaretPosition.before(node);
        }
        return CaretPosition.after(node);
      }
      return CaretPosition.before(node);
    };
    var moveForwardFromBr = function (root, nextNode) {
      var nextSibling = nextNode.nextSibling;
      if (nextSibling &amp;&amp; isCaretCandidate$3(nextSibling)) {
        if (isText$7(nextSibling)) {
          return CaretPosition(nextSibling, 0);
        } else {
          return CaretPosition.before(nextSibling);
        }
      } else {
        return findCaretPosition(HDirection.Forwards, CaretPosition.after(nextNode), root);
      }
    };
    var findCaretPosition = function (direction, startPos, root) {
      var node, nextNode, innerNode;
      var caretPosition;
      if (!isElement$6(root) || !startPos) {
        return null;
      }
      if (startPos.isEqual(CaretPosition.after(root)) &amp;&amp; root.lastChild) {
        caretPosition = CaretPosition.after(root.lastChild);
        if (isBackwards(direction) &amp;&amp; isCaretCandidate$3(root.lastChild) &amp;&amp; isElement$6(root.lastChild)) {
          return isBr$4(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
        }
      } else {
        caretPosition = startPos;
      }
      var container = caretPosition.container();
      var offset = caretPosition.offset();
      if (isText$7(container)) {
        if (isBackwards(direction) &amp;&amp; offset &gt; 0) {
          return CaretPosition(container, --offset);
        }
        if (isForwards(direction) &amp;&amp; offset &lt; container.length) {
          return CaretPosition(container, ++offset);
        }
        node = container;
      } else {
        if (isBackwards(direction) &amp;&amp; offset &gt; 0) {
          nextNode = nodeAtIndex(container, offset - 1);
          if (isCaretCandidate$3(nextNode)) {
            if (!isAtomic$1(nextNode)) {
              innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
              if (innerNode) {
                if (isText$7(innerNode)) {
                  return CaretPosition(innerNode, innerNode.data.length);
                }
                return CaretPosition.after(innerNode);
              }
            }
            if (isText$7(nextNode)) {
              return CaretPosition(nextNode, nextNode.data.length);
            }
            return CaretPosition.before(nextNode);
          }
        }
        if (isForwards(direction) &amp;&amp; offset &lt; container.childNodes.length) {
          nextNode = nodeAtIndex(container, offset);
          if (isCaretCandidate$3(nextNode)) {
            if (isBr$4(nextNode)) {
              return moveForwardFromBr(root, nextNode);
            }
            if (!isAtomic$1(nextNode)) {
              innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
              if (innerNode) {
                if (isText$7(innerNode)) {
                  return CaretPosition(innerNode, 0);
                }
                return CaretPosition.before(innerNode);
              }
            }
            if (isText$7(nextNode)) {
              return CaretPosition(nextNode, 0);
            }
            return CaretPosition.after(nextNode);
          }
        }
        node = nextNode ? nextNode : caretPosition.getNode();
      }
      if (isForwards(direction) &amp;&amp; caretPosition.isAtEnd() || isBackwards(direction) &amp;&amp; caretPosition.isAtStart()) {
        node = findNode(node, direction, always, root, true);
        if (isEditableCaretCandidate$1(node, root)) {
          return getCaretCandidatePosition(direction, node);
        }
      }
      nextNode = findNode(node, direction, isEditableCaretCandidate$1, root);
      var rootContentEditableFalseElm = last$1(filter(getParents(container, root), isContentEditableFalse$5));
      if (rootContentEditableFalseElm &amp;&amp; (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
        if (isForwards(direction)) {
          caretPosition = CaretPosition.after(rootContentEditableFalseElm);
        } else {
          caretPosition = CaretPosition.before(rootContentEditableFalseElm);
        }
        return caretPosition;
      }
      if (nextNode) {
        return getCaretCandidatePosition(direction, nextNode);
      }
      return null;
    };
    var CaretWalker = function (root) {
      return {
        next: function (caretPosition) {
          return findCaretPosition(HDirection.Forwards, caretPosition, root);
        },
        prev: function (caretPosition) {
          return findCaretPosition(HDirection.Backwards, caretPosition, root);
        }
      };
    };

    var walkToPositionIn = function (forward, root, start) {
      var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
      return fromPosition(forward, root, position);
    };
    var afterElement = function (node) {
      return isBr(node) ? CaretPosition.before(node) : CaretPosition.after(node);
    };
    var isBeforeOrStart = function (position) {
      if (CaretPosition.isTextPosition(position)) {
        return position.offset() === 0;
      } else {
        return isCaretCandidate(position.getNode());
      }
    };
    var isAfterOrEnd = function (position) {
      if (CaretPosition.isTextPosition(position)) {
        var container = position.container();
        return position.offset() === container.data.length;
      } else {
        return isCaretCandidate(position.getNode(true));
      }
    };
    var isBeforeAfterSameElement = function (from, to) {
      return !CaretPosition.isTextPosition(from) &amp;&amp; !CaretPosition.isTextPosition(to) &amp;&amp; from.getNode() === to.getNode(true);
    };
    var isAtBr = function (position) {
      return !CaretPosition.isTextPosition(position) &amp;&amp; isBr(position.getNode());
    };
    var shouldSkipPosition = function (forward, from, to) {
      if (forward) {
        return !isBeforeAfterSameElement(from, to) &amp;&amp; !isAtBr(from) &amp;&amp; isAfterOrEnd(from) &amp;&amp; isBeforeOrStart(to);
      } else {
        return !isBeforeAfterSameElement(to, from) &amp;&amp; isBeforeOrStart(from) &amp;&amp; isAfterOrEnd(to);
      }
    };
    var fromPosition = function (forward, root, pos) {
      var walker = CaretWalker(root);
      return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
    };
    var navigate = function (forward, root, from) {
      return fromPosition(forward, root, from).bind(function (to) {
        if (isInSameBlock(from, to, root) &amp;&amp; shouldSkipPosition(forward, from, to)) {
          return fromPosition(forward, root, to);
        } else {
          return Optional.some(to);
        }
      });
    };
    var navigateIgnore = function (forward, root, from, ignoreFilter) {
      return navigate(forward, root, from).bind(function (pos) {
        return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
      });
    };
    var positionIn = function (forward, element) {
      var startNode = forward ? element.firstChild : element.lastChild;
      if (isText$1(startNode)) {
        return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
      } else if (startNode) {
        if (isCaretCandidate(startNode)) {
          return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
        } else {
          return walkToPositionIn(forward, element, startNode);
        }
      } else {
        return Optional.none();
      }
    };
    var nextPosition = curry(fromPosition, true);
    var prevPosition = curry(fromPosition, false);
    var firstPositionIn = curry(positionIn, true);
    var lastPositionIn = curry(positionIn, false);

    var CARET_ID = '_mce_caret';
    var isCaretNode = function (node) {
      return isElement$1(node) &amp;&amp; node.id === CARET_ID;
    };
    var getParentCaretContainer = function (body, node) {
      while (node &amp;&amp; node !== body) {
        if (node.id === CARET_ID) {
          return node;
        }
        node = node.parentNode;
      }
      return null;
    };

    var isStringPathBookmark = function (bookmark) {
      return isString(bookmark.start);
    };
    var isRangeBookmark = function (bookmark) {
      return bookmark.hasOwnProperty('rng');
    };
    var isIdBookmark = function (bookmark) {
      return bookmark.hasOwnProperty('id');
    };
    var isIndexBookmark = function (bookmark) {
      return bookmark.hasOwnProperty('name');
    };
    var isPathBookmark = function (bookmark) {
      return Tools.isArray(bookmark.start);
    };

    var addBogus = function (dom, node) {
      if (isElement$1(node) &amp;&amp; dom.isBlock(node) &amp;&amp; !node.innerHTML &amp;&amp; !Env.ie) {
        node.innerHTML = '&lt;br data-mce-bogus="1" /&gt;';
      }
      return node;
    };
    var resolveCaretPositionBookmark = function (dom, bookmark) {
      var pos;
      var rng = dom.createRng();
      pos = resolve$1(dom.getRoot(), bookmark.start);
      rng.setStart(pos.container(), pos.offset());
      pos = resolve$1(dom.getRoot(), bookmark.end);
      rng.setEnd(pos.container(), pos.offset());
      return rng;
    };
    var insertZwsp = function (node, rng) {
      var textNode = node.ownerDocument.createTextNode(ZWSP);
      node.appendChild(textNode);
      rng.setStart(textNode, 0);
      rng.setEnd(textNode, 0);
    };
    var isEmpty$1 = function (node) {
      return node.hasChildNodes() === false;
    };
    var tryFindRangePosition = function (node, rng) {
      return lastPositionIn(node).fold(never, function (pos) {
        rng.setStart(pos.container(), pos.offset());
        rng.setEnd(pos.container(), pos.offset());
        return true;
      });
    };
    var padEmptyCaretContainer = function (root, node, rng) {
      if (isEmpty$1(node) &amp;&amp; getParentCaretContainer(root, node)) {
        insertZwsp(node, rng);
        return true;
      } else {
        return false;
      }
    };
    var setEndPoint = function (dom, start, bookmark, rng) {
      var point = bookmark[start ? 'start' : 'end'];
      var i, node, offset, children;
      var root = dom.getRoot();
      if (point) {
        offset = point[0];
        for (node = root, i = point.length - 1; i &gt;= 1; i--) {
          children = node.childNodes;
          if (padEmptyCaretContainer(root, node, rng)) {
            return true;
          }
          if (point[i] &gt; children.length - 1) {
            if (padEmptyCaretContainer(root, node, rng)) {
              return true;
            }
            return tryFindRangePosition(node, rng);
          }
          node = children[point[i]];
        }
        if (node.nodeType === 3) {
          offset = Math.min(point[0], node.nodeValue.length);
        }
        if (node.nodeType === 1) {
          offset = Math.min(point[0], node.childNodes.length);
        }
        if (start) {
          rng.setStart(node, offset);
        } else {
          rng.setEnd(node, offset);
        }
      }
      return true;
    };
    var isValidTextNode = function (node) {
      return isText$1(node) &amp;&amp; node.data.length &gt; 0;
    };
    var restoreEndPoint = function (dom, suffix, bookmark) {
      var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
      var keep = bookmark.keep;
      var container, offset;
      if (marker) {
        node = marker.parentNode;
        if (suffix === 'start') {
          if (!keep) {
            idx = dom.nodeIndex(marker);
          } else {
            if (marker.hasChildNodes()) {
              node = marker.firstChild;
              idx = 1;
            } else if (isValidTextNode(marker.nextSibling)) {
              node = marker.nextSibling;
              idx = 0;
            } else if (isValidTextNode(marker.previousSibling)) {
              node = marker.previousSibling;
              idx = marker.previousSibling.data.length;
            } else {
              node = marker.parentNode;
              idx = dom.nodeIndex(marker) + 1;
            }
          }
          container = node;
          offset = idx;
        } else {
          if (!keep) {
            idx = dom.nodeIndex(marker);
          } else {
            if (marker.hasChildNodes()) {
              node = marker.firstChild;
              idx = 1;
            } else if (isValidTextNode(marker.previousSibling)) {
              node = marker.previousSibling;
              idx = marker.previousSibling.data.length;
            } else {
              node = marker.parentNode;
              idx = dom.nodeIndex(marker);
            }
          }
          container = node;
          offset = idx;
        }
        if (!keep) {
          prev = marker.previousSibling;
          next = marker.nextSibling;
          Tools.each(Tools.grep(marker.childNodes), function (node) {
            if (isText$1(node)) {
              node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
            }
          });
          while (marker = dom.get(bookmark.id + '_' + suffix)) {
            dom.remove(marker, true);
          }
          if (prev &amp;&amp; next &amp;&amp; prev.nodeType === next.nodeType &amp;&amp; isText$1(prev) &amp;&amp; !Env.opera) {
            idx = prev.nodeValue.length;
            prev.appendData(next.nodeValue);
            dom.remove(next);
            container = prev;
            offset = idx;
          }
        }
        return Optional.some(CaretPosition(container, offset));
      } else {
        return Optional.none();
      }
    };
    var resolvePaths = function (dom, bookmark) {
      var rng = dom.createRng();
      if (setEndPoint(dom, true, bookmark, rng) &amp;&amp; setEndPoint(dom, false, bookmark, rng)) {
        return Optional.some(rng);
      } else {
        return Optional.none();
      }
    };
    var resolveId = function (dom, bookmark) {
      var startPos = restoreEndPoint(dom, 'start', bookmark);
      var endPos = restoreEndPoint(dom, 'end', bookmark);
      return lift2(startPos, endPos.or(startPos), function (spos, epos) {
        var rng = dom.createRng();
        rng.setStart(addBogus(dom, spos.container()), spos.offset());
        rng.setEnd(addBogus(dom, epos.container()), epos.offset());
        return rng;
      });
    };
    var resolveIndex$1 = function (dom, bookmark) {
      return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
        var rng = dom.createRng();
        rng.selectNode(elm);
        return rng;
      });
    };
    var resolve$2 = function (selection, bookmark) {
      var dom = selection.dom;
      if (bookmark) {
        if (isPathBookmark(bookmark)) {
          return resolvePaths(dom, bookmark);
        } else if (isStringPathBookmark(bookmark)) {
          return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
        } else if (isIdBookmark(bookmark)) {
          return resolveId(dom, bookmark);
        } else if (isIndexBookmark(bookmark)) {
          return resolveIndex$1(dom, bookmark);
        } else if (isRangeBookmark(bookmark)) {
          return Optional.some(bookmark.rng);
        }
      }
      return Optional.none();
    };

    var getBookmark$1 = function (selection, type, normalized) {
      return getBookmark(selection, type, normalized);
    };
    var moveToBookmark = function (selection, bookmark) {
      resolve$2(selection, bookmark).each(function (rng) {
        selection.setRng(rng);
      });
    };
    var isBookmarkNode$1 = function (node) {
      return isElement$1(node) &amp;&amp; node.tagName === 'SPAN' &amp;&amp; node.getAttribute('data-mce-type') === 'bookmark';
    };

    var is$2 = function (expected) {
      return function (actual) {
        return expected === actual;
      };
    };
    var isNbsp = is$2(nbsp);
    var isWhiteSpace$1 = function (chr) {
      return chr !== '' &amp;&amp; ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
    };
    var isContent$1 = function (chr) {
      return !isWhiteSpace$1(chr) &amp;&amp; !isNbsp(chr);
    };

    var isNode = function (node) {
      return !!node.nodeType;
    };
    var isInlineBlock = function (node) {
      return node &amp;&amp; /^(IMG)$/.test(node.nodeName);
    };
    var moveStart = function (dom, selection, rng) {
      var offset = rng.startOffset;
      var container = rng.startContainer, walker, node, nodes;
      if (rng.startContainer === rng.endContainer) {
        if (isInlineBlock(rng.startContainer.childNodes[rng.startOffset])) {
          return;
        }
      }
      if (container.nodeType === 1) {
        nodes = container.childNodes;
        if (offset &lt; nodes.length) {
          container = nodes[offset];
          walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
        } else {
          container = nodes[nodes.length - 1];
          walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
          walker.next(true);
        }
        for (node = walker.current(); node; node = walker.next()) {
          if (node.nodeType === 3 &amp;&amp; !isWhiteSpaceNode(node)) {
            rng.setStart(node, 0);
            selection.setRng(rng);
            return;
          }
        }
      }
    };
    var getNonWhiteSpaceSibling = function (node, next, inc) {
      if (node) {
        var nextName = next ? 'nextSibling' : 'previousSibling';
        for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
          if (node.nodeType === 1 || !isWhiteSpaceNode(node)) {
            return node;
          }
        }
      }
    };
    var isTextBlock$1 = function (editor, name) {
      if (isNode(name)) {
        name = name.nodeName;
      }
      return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
    };
    var isValid = function (ed, parent, child) {
      return ed.schema.isValidChild(parent, child);
    };
    var isWhiteSpaceNode = function (node, allowSpaces) {
      if (allowSpaces === void 0) {
        allowSpaces = false;
      }
      if (isNonNullable(node) &amp;&amp; isText$1(node)) {
        var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
        return isWhitespaceText(data);
      } else {
        return false;
      }
    };
    var isEmptyTextNode = function (node) {
      return isNonNullable(node) &amp;&amp; isText$1(node) &amp;&amp; node.length === 0;
    };
    var replaceVars = function (value, vars) {
      if (typeof value !== 'string') {
        value = value(vars);
      } else if (vars) {
        value = value.replace(/%(\w+)/g, function (str, name) {
          return vars[name] || str;
        });
      }
      return value;
    };
    var isEq = function (str1, str2) {
      str1 = str1 || '';
      str2 = str2 || '';
      str1 = '' + (str1.nodeName || str1);
      str2 = '' + (str2.nodeName || str2);
      return str1.toLowerCase() === str2.toLowerCase();
    };
    var normalizeStyleValue = function (dom, value, name) {
      if (name === 'color' || name === 'backgroundColor') {
        value = dom.toHex(value);
      }
      if (name === 'fontWeight' &amp;&amp; value === 700) {
        value = 'bold';
      }
      if (name === 'fontFamily') {
        value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
      }
      return '' + value;
    };
    var getStyle = function (dom, node, name) {
      return normalizeStyleValue(dom, dom.getStyle(node, name), name);
    };
    var getTextDecoration = function (dom, node) {
      var decoration;
      dom.getParent(node, function (n) {
        decoration = dom.getStyle(n, 'text-decoration');
        return decoration &amp;&amp; decoration !== 'none';
      });
      return decoration;
    };
    var getParents$1 = function (dom, node, selector) {
      return dom.getParents(node, selector, dom.getRoot());
    };
    var isVariableFormatName = function (editor, formatName) {
      var hasVariableValues = function (format) {
        var isVariableValue = function (val) {
          return val.length &gt; 1 &amp;&amp; val.charAt(0) === '%';
        };
        return exists([
          'styles',
          'attributes'
        ], function (key) {
          return get$1(format, key).exists(function (field) {
            var fieldValues = isArray(field) ? field : values(field);
            return exists(fieldValues, isVariableValue);
          });
        });
      };
      return exists(editor.formatter.get(formatName), hasVariableValues);
    };
    var areSimilarFormats = function (editor, formatName, otherFormatName) {
      var validKeys = [
        'inline',
        'block',
        'selector',
        'attributes',
        'styles',
        'classes'
      ];
      var filterObj = function (format) {
        return filter$1(format, function (_, key) {
          return exists(validKeys, function (validKey) {
            return validKey === key;
          });
        });
      };
      return exists(editor.formatter.get(formatName), function (fmt1) {
        var filteredFmt1 = filterObj(fmt1);
        return exists(editor.formatter.get(otherFormatName), function (fmt2) {
          var filteredFmt2 = filterObj(fmt2);
          return equal(filteredFmt1, filteredFmt2);
        });
      });
    };
    var isBlockFormat = function (format) {
      return hasNonNullableKey(format, 'block');
    };
    var isSelectorFormat = function (format) {
      return hasNonNullableKey(format, 'selector');
    };
    var isInlineFormat = function (format) {
      return hasNonNullableKey(format, 'inline');
    };
    var hasBlockChildren = function (dom, elm) {
      return exists(elm.childNodes, dom.isBlock);
    };

    var isBookmarkNode$2 = isBookmarkNode$1;
    var getParents$2 = getParents$1;
    var isWhiteSpaceNode$1 = isWhiteSpaceNode;
    var isTextBlock$2 = isTextBlock$1;
    var isBogusBr = function (node) {
      return isBr(node) &amp;&amp; node.getAttribute('data-mce-bogus') &amp;&amp; !node.nextSibling;
    };
    var findParentContentEditable = function (dom, node) {
      var parent = node;
      while (parent) {
        if (isElement$1(parent) &amp;&amp; dom.getContentEditable(parent)) {
          return dom.getContentEditable(parent) === 'false' ? parent : node;
        }
        parent = parent.parentNode;
      }
      return node;
    };
    var walkText = function (start, node, offset, predicate) {
      var str = node.data;
      for (var i = offset; start ? i &gt;= 0 : i &lt; str.length; start ? i-- : i++) {
        if (predicate(str.charAt(i))) {
          return start ? i + 1 : i;
        }
      }
      return -1;
    };
    var findSpace = function (start, node, offset) {
      return walkText(start, node, offset, function (c) {
        return isNbsp(c) || isWhiteSpace$1(c);
      });
    };
    var findContent = function (start, node, offset) {
      return walkText(start, node, offset, isContent$1);
    };
    var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
      var lastTextNode;
      var rootNode = dom.getParent(container, dom.isBlock) || body;
      var walk = function (container, offset, pred) {
        var textSeeker = TextSeeker(dom);
        var walker = start ? textSeeker.backwards : textSeeker.forwards;
        return Optional.from(walker(container, offset, function (text, textOffset) {
          if (isBookmarkNode$2(text.parentNode)) {
            return -1;
          } else {
            lastTextNode = text;
            return pred(start, text, textOffset);
          }
        }, rootNode));
      };
      var spaceResult = walk(container, offset, findSpace);
      return spaceResult.bind(function (result) {
        return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
      }).orThunk(function () {
        return lastTextNode ? Optional.some({
          container: lastTextNode,
          offset: start ? 0 : lastTextNode.length
        }) : Optional.none();
      });
    };
    var findSelectorEndPoint = function (dom, format, rng, container, siblingName) {
      if (isText$1(container) &amp;&amp; container.nodeValue.length === 0 &amp;&amp; container[siblingName]) {
        container = container[siblingName];
      }
      var parents = getParents$2(dom, container);
      for (var i = 0; i &lt; parents.length; i++) {
        for (var y = 0; y &lt; format.length; y++) {
          var curFormat = format[y];
          if ('collapsed' in curFormat &amp;&amp; curFormat.collapsed !== rng.collapsed) {
            continue;
          }
          if (dom.is(parents[i], curFormat.selector)) {
            return parents[i];
          }
        }
      }
      return container;
    };
    var findBlockEndPoint = function (editor, format, container, siblingName) {
      var node;
      var dom = editor.dom;
      var root = dom.getRoot();
      if (!format[0].wrapper) {
        node = dom.getParent(container, format[0].block, root);
      }
      if (!node) {
        var scopeRoot = dom.getParent(container, 'LI,TD,TH');
        node = dom.getParent(isText$1(container) ? container.parentNode : container, function (node) {
          return node !== root &amp;&amp; isTextBlock$2(editor, node);
        }, scopeRoot);
      }
      if (node &amp;&amp; format[0].wrapper) {
        node = getParents$2(dom, node, 'ul,ol').reverse()[0] || node;
      }
      if (!node) {
        node = container;
        while (node[siblingName] &amp;&amp; !dom.isBlock(node[siblingName])) {
          node = node[siblingName];
          if (isEq(node, 'br')) {
            break;
          }
        }
      }
      return node || container;
    };
    var isAtBlockBoundary = function (dom, root, container, siblingName) {
      var parent = container.parentNode;
      if (isNonNullable(container[siblingName])) {
        return false;
      } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
        return true;
      } else {
        return isAtBlockBoundary(dom, root, parent, siblingName);
      }
    };
    var findParentContainer = function (dom, format, container, offset, start) {
      var parent = container;
      var sibling;
      var siblingName = start ? 'previousSibling' : 'nextSibling';
      var root = dom.getRoot();
      if (isText$1(container) &amp;&amp; !isWhiteSpaceNode$1(container)) {
        if (start ? offset &gt; 0 : offset &lt; container.data.length) {
          return container;
        }
      }
      while (true) {
        if (!format[0].block_expand &amp;&amp; dom.isBlock(parent)) {
          return parent;
        }
        for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
          var allowSpaces = isText$1(sibling) &amp;&amp; !isAtBlockBoundary(dom, root, sibling, siblingName);
          if (!isBookmarkNode$2(sibling) &amp;&amp; !isBogusBr(sibling) &amp;&amp; !isWhiteSpaceNode$1(sibling, allowSpaces)) {
            return parent;
          }
        }
        if (parent === root || parent.parentNode === root) {
          container = parent;
          break;
        }
        parent = parent.parentNode;
      }
      return container;
    };
    var isSelfOrParentBookmark = function (container) {
      return isBookmarkNode$2(container.parentNode) || isBookmarkNode$2(container);
    };
    var expandRng = function (editor, rng, format, includeTrailingSpace) {
      if (includeTrailingSpace === void 0) {
        includeTrailingSpace = false;
      }
      var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
      var dom = editor.dom;
      if (isElement$1(startContainer) &amp;&amp; startContainer.hasChildNodes()) {
        startContainer = getNode(startContainer, startOffset);
        if (isText$1(startContainer)) {
          startOffset = 0;
        }
      }
      if (isElement$1(endContainer) &amp;&amp; endContainer.hasChildNodes()) {
        endContainer = getNode(endContainer, rng.collapsed ? endOffset : endOffset - 1);
        if (isText$1(endContainer)) {
          endOffset = endContainer.nodeValue.length;
        }
      }
      startContainer = findParentContentEditable(dom, startContainer);
      endContainer = findParentContentEditable(dom, endContainer);
      if (isSelfOrParentBookmark(startContainer)) {
        startContainer = isBookmarkNode$2(startContainer) ? startContainer : startContainer.parentNode;
        if (rng.collapsed) {
          startContainer = startContainer.previousSibling || startContainer;
        } else {
          startContainer = startContainer.nextSibling || startContainer;
        }
        if (isText$1(startContainer)) {
          startOffset = rng.collapsed ? startContainer.length : 0;
        }
      }
      if (isSelfOrParentBookmark(endContainer)) {
        endContainer = isBookmarkNode$2(endContainer) ? endContainer : endContainer.parentNode;
        if (rng.collapsed) {
          endContainer = endContainer.nextSibling || endContainer;
        } else {
          endContainer = endContainer.previousSibling || endContainer;
        }
        if (isText$1(endContainer)) {
          endOffset = rng.collapsed ? 0 : endContainer.length;
        }
      }
      if (rng.collapsed) {
        var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
        startPoint.each(function (_a) {
          var container = _a.container, offset = _a.offset;
          startContainer = container;
          startOffset = offset;
        });
        var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
        endPoint.each(function (_a) {
          var container = _a.container, offset = _a.offset;
          endContainer = container;
          endOffset = offset;
        });
      }
      if (format[0].inline || format[0].block_expand) {
        if (!format[0].inline || (!isText$1(startContainer) || startOffset === 0)) {
          startContainer = findParentContainer(dom, format, startContainer, startOffset, true);
        }
        if (!format[0].inline || (!isText$1(endContainer) || endOffset === endContainer.nodeValue.length)) {
          endContainer = findParentContainer(dom, format, endContainer, endOffset, false);
        }
      }
      if (format[0].selector &amp;&amp; format[0].expand !== false &amp;&amp; !format[0].inline) {
        startContainer = findSelectorEndPoint(dom, format, rng, startContainer, 'previousSibling');
        endContainer = findSelectorEndPoint(dom, format, rng, endContainer, 'nextSibling');
      }
      if (format[0].block || format[0].selector) {
        startContainer = findBlockEndPoint(editor, format, startContainer, 'previousSibling');
        endContainer = findBlockEndPoint(editor, format, endContainer, 'nextSibling');
        if (format[0].block) {
          if (!dom.isBlock(startContainer)) {
            startContainer = findParentContainer(dom, format, startContainer, startOffset, true);
          }
          if (!dom.isBlock(endContainer)) {
            endContainer = findParentContainer(dom, format, endContainer, endOffset, false);
          }
        }
      }
      if (isElement$1(startContainer)) {
        startOffset = dom.nodeIndex(startContainer);
        startContainer = startContainer.parentNode;
      }
      if (isElement$1(endContainer)) {
        endOffset = dom.nodeIndex(endContainer) + 1;
        endContainer = endContainer.parentNode;
      }
      return {
        startContainer: startContainer,
        startOffset: startOffset,
        endContainer: endContainer,
        endOffset: endOffset
      };
    };

    var clampToExistingChildren = function (container, index) {
      var childNodes = container.childNodes;
      if (index &gt;= childNodes.length) {
        index = childNodes.length - 1;
      } else if (index &lt; 0) {
        index = 0;
      }
      return childNodes[index] || container;
    };
    var getEndChild = function (container, index) {
      return clampToExistingChildren(container, index - 1);
    };
    var walk$1 = function (dom, rng, callback) {
      var startContainer = rng.startContainer;
      var startOffset = rng.startOffset;
      var endContainer = rng.endContainer;
      var endOffset = rng.endOffset;
      var exclude = function (nodes) {
        var node;
        node = nodes[0];
        if (node.nodeType === 3 &amp;&amp; node === startContainer &amp;&amp; startOffset &gt;= node.nodeValue.length) {
          nodes.splice(0, 1);
        }
        node = nodes[nodes.length - 1];
        if (endOffset === 0 &amp;&amp; nodes.length &gt; 0 &amp;&amp; node === endContainer &amp;&amp; node.nodeType === 3) {
          nodes.splice(nodes.length - 1, 1);
        }
        return nodes;
      };
      var collectSiblings = function (node, name, endNode) {
        var siblings = [];
        for (; node &amp;&amp; node !== endNode; node = node[name]) {
          siblings.push(node);
        }
        return siblings;
      };
      var findEndPoint = function (node, root) {
        do {
          if (node.parentNode === root) {
            return node;
          }
          node = node.parentNode;
        } while (node);
      };
      var walkBoundary = function (startNode, endNode, next) {
        var siblingName = next ? 'nextSibling' : 'previousSibling';
        for (var node = startNode, parent_1 = node.parentNode; node &amp;&amp; node !== endNode; node = parent_1) {
          parent_1 = node.parentNode;
          var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
          if (siblings_1.length) {
            if (!next) {
              siblings_1.reverse();
            }
            callback(exclude(siblings_1));
          }
        }
      };
      if (startContainer.nodeType === 1 &amp;&amp; startContainer.hasChildNodes()) {
        startContainer = clampToExistingChildren(startContainer, startOffset);
      }
      if (endContainer.nodeType === 1 &amp;&amp; endContainer.hasChildNodes()) {
        endContainer = getEndChild(endContainer, endOffset);
      }
      if (startContainer === endContainer) {
        return callback(exclude([startContainer]));
      }
      var ancestor = dom.findCommonAncestor(startContainer, endContainer);
      for (var node = startContainer; node; node = node.parentNode) {
        if (node === endContainer) {
          return walkBoundary(startContainer, ancestor, true);
        }
        if (node === ancestor) {
          break;
        }
      }
      for (var node = endContainer; node; node = node.parentNode) {
        if (node === startContainer) {
          return walkBoundary(endContainer, ancestor);
        }
        if (node === ancestor) {
          break;
        }
      }
      var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
      var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
      walkBoundary(startContainer, startPoint, true);
      var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
      if (siblings.length) {
        callback(exclude(siblings));
      }
      walkBoundary(endContainer, endPoint);
    };

    var getRanges = function (selection) {
      var ranges = [];
      if (selection) {
        for (var i = 0; i &lt; selection.rangeCount; i++) {
          ranges.push(selection.getRangeAt(i));
        }
      }
      return ranges;
    };
    var getSelectedNodes = function (ranges) {
      return bind(ranges, function (range) {
        var node = getSelectedNode(range);
        return node ? [SugarElement.fromDom(node)] : [];
      });
    };
    var hasMultipleRanges = function (selection) {
      return getRanges(selection).length &gt; 1;
    };

    var getCellsFromRanges = function (ranges) {
      return filter(getSelectedNodes(ranges), isTableCell$1);
    };
    var getCellsFromElement = function (elm) {
      return descendants$1(elm, 'td[data-mce-selected],th[data-mce-selected]');
    };
    var getCellsFromElementOrRanges = function (ranges, element) {
      var selectedCells = getCellsFromElement(element);
      return selectedCells.length &gt; 0 ? selectedCells : getCellsFromRanges(ranges);
    };
    var getCellsFromEditor = function (editor) {
      return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
    };

    var getStartNode = function (rng) {
      var sc = rng.startContainer, so = rng.startOffset;
      if (isText$1(sc)) {
        return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
      } else {
        return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
      }
    };
    var getEndNode = function (rng) {
      var ec = rng.endContainer, eo = rng.endOffset;
      if (isText$1(ec)) {
        return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
      } else {
        return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
      }
    };
    var getFirstChildren = function (node) {
      return firstChild(node).fold(constant([node]), function (child) {
        return [node].concat(getFirstChildren(child));
      });
    };
    var getLastChildren = function (node) {
      return lastChild(node).fold(constant([node]), function (child) {
        if (name(child) === 'br') {
          return prevSibling(child).map(function (sibling) {
            return [node].concat(getLastChildren(sibling));
          }).getOr([]);
        } else {
          return [node].concat(getLastChildren(child));
        }
      });
    };
    var hasAllContentsSelected = function (elm, rng) {
      return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
        var start = find(getFirstChildren(elm), curry(eq$2, startNode));
        var end = find(getLastChildren(elm), curry(eq$2, endNode));
        return start.isSome() &amp;&amp; end.isSome();
      }).getOr(false);
    };
    var moveEndPoint$1 = function (dom, rng, node, start) {
      var root = node, walker = new DomTreeWalker(node, root);
      var moveCaretBeforeOnEnterElementsMap = filter$1(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
        return !contains([
          'td',
          'th',
          'table'
        ], name.toLowerCase());
      });
      do {
        if (isText$1(node) &amp;&amp; Tools.trim(node.nodeValue).length !== 0) {
          if (start) {
            rng.setStart(node, 0);
          } else {
            rng.setEnd(node, node.nodeValue.length);
          }
          return;
        }
        if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
          if (start) {
            rng.setStartBefore(node);
          } else {
            if (node.nodeName === 'BR') {
              rng.setEndBefore(node);
            } else {
              rng.setEndAfter(node);
            }
          }
          return;
        }
      } while (node = start ? walker.next() : walker.prev());
      if (root.nodeName === 'BODY') {
        if (start) {
          rng.setStart(root, 0);
        } else {
          rng.setEnd(root, root.childNodes.length);
        }
      }
    };
    var hasAnyRanges = function (editor) {
      var sel = editor.selection.getSel();
      return sel &amp;&amp; sel.rangeCount &gt; 0;
    };
    var runOnRanges = function (editor, executor) {
      var fakeSelectionNodes = getCellsFromEditor(editor);
      if (fakeSelectionNodes.length &gt; 0) {
        each(fakeSelectionNodes, function (elem) {
          var node = elem.dom;
          var fakeNodeRng = editor.dom.createRng();
          fakeNodeRng.setStartBefore(node);
          fakeNodeRng.setEndAfter(node);
          executor(fakeNodeRng, true);
        });
      } else {
        executor(editor.selection.getRng(), false);
      }
    };
    var preserve = function (selection, fillBookmark, executor) {
      var bookmark = getPersistentBookmark(selection, fillBookmark);
      executor(bookmark);
      selection.moveToBookmark(bookmark);
    };

    var NodeValue = function (is, name) {
      var get = function (element) {
        if (!is(element)) {
          throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
        }
        return getOption(element).getOr('');
      };
      var getOption = function (element) {
        return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
      };
      var set = function (element, value) {
        if (!is(element)) {
          throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
        }
        element.dom.nodeValue = value;
      };
      return {
        get: get,
        getOption: getOption,
        set: set
      };
    };

    var api = NodeValue(isText, 'text');
    var get$8 = function (element) {
      return api.get(element);
    };

    var isZeroWidth = function (elem) {
      return isText(elem) &amp;&amp; get$8(elem) === ZWSP;
    };
    var context = function (editor, elem, wrapName, nodeName) {
      return parent(elem).fold(function () {
        return 'skipping';
      }, function (parent) {
        if (nodeName === 'br' || isZeroWidth(elem)) {
          return 'valid';
        } else if (isAnnotation(elem)) {
          return 'existing';
        } else if (isCaretNode(elem.dom)) {
          return 'caret';
        } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
          return 'invalid-child';
        } else {
          return 'valid';
        }
      });
    };

    var applyWordGrab = function (editor, rng) {
      var r = expandRng(editor, rng, [{ inline: true }]);
      rng.setStart(r.startContainer, r.startOffset);
      rng.setEnd(r.endContainer, r.endOffset);
      editor.selection.setRng(rng);
    };
    var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
      var _b = _a.uid, uid = _b === void 0 ? generate$1('mce-annotation') : _b, data = __rest(_a, ['uid']);
      var master = SugarElement.fromTag('span', eDoc);
      add$3(master, annotation());
      set(master, '' + dataAnnotationId(), uid);
      set(master, '' + dataAnnotation(), annotationName);
      var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
      setAll(master, attributes);
      add$4(master, classes);
      return master;
    };
    var annotate = function (editor, rng, annotationName, decorate, data) {
      var newWrappers = [];
      var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
      var wrapper = Cell(Optional.none());
      var finishWrapper = function () {
        wrapper.set(Optional.none());
      };
      var getOrOpenWrapper = function () {
        return wrapper.get().getOrThunk(function () {
          var nu = shallow(master);
          newWrappers.push(nu);
          wrapper.set(Optional.some(nu));
          return nu;
        });
      };
      var processElements = function (elems) {
        each(elems, processElement);
      };
      var processElement = function (elem) {
        var ctx = context(editor, elem, 'span', name(elem));
        switch (ctx) {
        case 'invalid-child': {
            finishWrapper();
            var children$1 = children(elem);
            processElements(children$1);
            finishWrapper();
            break;
          }
        case 'valid': {
            var w = getOrOpenWrapper();
            wrap(elem, w);
            break;
          }
        }
      };
      var processNodes = function (nodes) {
        var elems = map(nodes, SugarElement.fromDom);
        processElements(elems);
      };
      walk$1(editor.dom, rng, function (nodes) {
        finishWrapper();
        processNodes(nodes);
      });
      return newWrappers;
    };
    var annotateWithBookmark = function (editor, name, settings, data) {
      editor.undoManager.transact(function () {
        var selection = editor.selection;
        var initialRng = selection.getRng();
        var hasFakeSelection = getCellsFromEditor(editor).length &gt; 0;
        if (initialRng.collapsed &amp;&amp; !hasFakeSelection) {
          applyWordGrab(editor, initialRng);
        }
        if (selection.getRng().collapsed &amp;&amp; !hasFakeSelection) {
          var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
          set$1(wrapper, nbsp);
          selection.getRng().insertNode(wrapper.dom);
          selection.select(wrapper.dom);
        } else {
          preserve(selection, false, function () {
            runOnRanges(editor, function (selectionRng) {
              annotate(editor, selectionRng, name, settings.decorate, data);
            });
          });
        }
      });
    };

    var Annotator = function (editor) {
      var registry = create$2();
      setup$1(editor, registry);
      var changes = setup(editor);
      return {
        register: function (name, settings) {
          registry.register(name, settings);
        },
        annotate: function (name, data) {
          registry.lookup(name).each(function (settings) {
            annotateWithBookmark(editor, name, settings, data);
          });
        },
        annotationChanged: function (name, callback) {
          changes.addListener(name, callback);
        },
        remove: function (name) {
          identify(editor, Optional.some(name)).each(function (_a) {
            var elements = _a.elements;
            each(elements, unwrap);
          });
        },
        getAll: function (name) {
          var directory = findAll(editor, name);
          return map$1(directory, function (elems) {
            return map(elems, function (elem) {
              return elem.dom;
            });
          });
        }
      };
    };

    var BookmarkManager = function (selection) {
      return {
        getBookmark: curry(getBookmark$1, selection),
        moveToBookmark: curry(moveToBookmark, selection)
      };
    };
    BookmarkManager.isBookmarkNode = isBookmarkNode$1;

    var getContentEditableRoot = function (root, node) {
      while (node &amp;&amp; node !== root) {
        if (isContentEditableTrue(node) || isContentEditableFalse(node)) {
          return node;
        }
        node = node.parentNode;
      }
      return null;
    };

    var isXYWithinRange = function (clientX, clientY, range) {
      if (range.collapsed) {
        return false;
      }
      if (Env.browser.isIE() &amp;&amp; range.startOffset === range.endOffset - 1 &amp;&amp; range.startContainer === range.endContainer) {
        var elm = range.startContainer.childNodes[range.startOffset];
        if (isElement$1(elm)) {
          return exists(elm.getClientRects(), function (rect) {
            return containsXY(rect, clientX, clientY);
          });
        }
      }
      return exists(range.getClientRects(), function (rect) {
        return containsXY(rect, clientX, clientY);
      });
    };

    var firePreProcess = function (editor, args) {
      return editor.fire('PreProcess', args);
    };
    var firePostProcess = function (editor, args) {
      return editor.fire('PostProcess', args);
    };
    var fireRemove = function (editor) {
      return editor.fire('remove');
    };
    var fireDetach = function (editor) {
      return editor.fire('detach');
    };
    var fireSwitchMode = function (editor, mode) {
      return editor.fire('SwitchMode', { mode: mode });
    };
    var fireObjectResizeStart = function (editor, target, width, height, origin) {
      editor.fire('ObjectResizeStart', {
        target: target,
        width: width,
        height: height,
        origin: origin
      });
    };
    var fireObjectResized = function (editor, target, width, height, origin) {
      editor.fire('ObjectResized', {
        target: target,
        width: width,
        height: height,
        origin: origin
      });
    };
    var firePreInit = function (editor) {
      return editor.fire('PreInit');
    };
    var firePostRender = function (editor) {
      return editor.fire('PostRender');
    };
    var fireInit = function (editor) {
      return editor.fire('Init');
    };
    var firePlaceholderToggle = function (editor, state) {
      return editor.fire('PlaceholderToggle', { state: state });
    };
    var fireError = function (editor, errorType, error) {
      return editor.fire(errorType, error);
    };

    var VK = {
      BACKSPACE: 8,
      DELETE: 46,
      DOWN: 40,
      ENTER: 13,
      LEFT: 37,
      RIGHT: 39,
      SPACEBAR: 32,
      TAB: 9,
      UP: 38,
      PAGE_UP: 33,
      PAGE_DOWN: 34,
      END: 35,
      HOME: 36,
      modifierPressed: function (e) {
        return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
      },
      metaKeyPressed: function (e) {
        return Env.mac ? e.metaKey : e.ctrlKey &amp;&amp; !e.altKey;
      }
    };

    var isContentEditableFalse$6 = isContentEditableFalse;
    var ControlSelection = function (selection, editor) {
      var elementSelectionAttr = 'data-mce-selected';
      var dom = editor.dom, each$2 = Tools.each;
      var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
      var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
      var width, height;
      var editableDoc = editor.getDoc(), rootDocument = document;
      var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
      var startScrollWidth, startScrollHeight;
      var resizeHandles = {
        nw: [
          0,
          0,
          -1,
          -1
        ],
        ne: [
          1,
          0,
          1,
          -1
        ],
        se: [
          1,
          1,
          1,
          1
        ],
        sw: [
          0,
          1,
          -1,
          1
        ]
      };
      var isImage = function (elm) {
        return elm &amp;&amp; (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
      };
      var isMedia$1 = function (elm) {
        return isMedia(elm) || dom.hasClass(elm, 'mce-preview-object');
      };
      var isEventOnImageOutsideRange = function (evt, range) {
        if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
          var touch = evt.touches[0];
          return isImage(evt.target) &amp;&amp; !isXYWithinRange(touch.clientX, touch.clientY, range);
        } else {
          return isImage(evt.target) &amp;&amp; !isXYWithinRange(evt.clientX, evt.clientY, range);
        }
      };
      var contextMenuSelectImage = function (evt) {
        var target = evt.target;
        if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) &amp;&amp; !evt.isDefaultPrevented()) {
          editor.selection.select(target);
        }
      };
      var getResizeTargets = function (elm) {
        if (dom.is(elm, 'figure.image')) {
          return [elm.querySelector('img')];
        } else if (dom.hasClass(elm, 'mce-preview-object') &amp;&amp; isNonNullable(elm.firstElementChild)) {
          return [
            elm,
            elm.firstElementChild
          ];
        } else {
          return [elm];
        }
      };
      var isResizable = function (elm) {
        var selector = getObjectResizing(editor);
        if (!selector) {
          return false;
        }
        if (elm.getAttribute('data-mce-resize') === 'false') {
          return false;
        }
        if (elm === editor.getBody()) {
          return false;
        }
        if (dom.hasClass(elm, 'mce-preview-object')) {
          return is$1(SugarElement.fromDom(elm.firstElementChild), selector);
        } else {
          return is$1(SugarElement.fromDom(elm), selector);
        }
      };
      var createGhostElement = function (elm) {
        if (isMedia$1(elm)) {
          return dom.create('img', { src: Env.transparentSrc });
        } else {
          return elm.cloneNode(true);
        }
      };
      var setSizeProp = function (element, name, value) {
        if (isNonNullable(value)) {
          var targets = getResizeTargets(element);
          each(targets, function (target) {
            if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
              dom.setStyle(target, name, value);
            } else {
              dom.setAttrib(target, name, '' + value);
            }
          });
        }
      };
      var setGhostElmSize = function (ghostElm, width, height) {
        setSizeProp(ghostElm, 'width', width);
        setSizeProp(ghostElm, 'height', height);
      };
      var resizeGhostElement = function (e) {
        var deltaX, deltaY, proportional;
        var resizeHelperX, resizeHelperY;
        deltaX = e.screenX - startX;
        deltaY = e.screenY - startY;
        width = deltaX * selectedHandle[2] + startW;
        height = deltaY * selectedHandle[3] + startH;
        width = width &lt; 5 ? 5 : width;
        height = height &lt; 5 ? 5 : height;
        if ((isImage(selectedElm) || isMedia$1(selectedElm)) &amp;&amp; getResizeImgProportional(editor) !== false) {
          proportional = !VK.modifierPressed(e);
        } else {
          proportional = VK.modifierPressed(e);
        }
        if (proportional) {
          if (abs(deltaX) &gt; abs(deltaY)) {
            height = round(width * ratio);
            width = round(height / ratio);
          } else {
            width = round(height / ratio);
            height = round(width * ratio);
          }
        }
        setGhostElmSize(selectedElmGhost, width, height);
        resizeHelperX = selectedHandle.startPos.x + deltaX;
        resizeHelperY = selectedHandle.startPos.y + deltaY;
        resizeHelperX = resizeHelperX &gt; 0 ? resizeHelperX : 0;
        resizeHelperY = resizeHelperY &gt; 0 ? resizeHelperY : 0;
        dom.setStyles(resizeHelper, {
          left: resizeHelperX,
          top: resizeHelperY,
          display: 'block'
        });
        resizeHelper.innerHTML = width + ' &amp;times; ' + height;
        if (selectedHandle[2] &lt; 0 &amp;&amp; selectedElmGhost.clientWidth &lt;= width) {
          dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
        }
        if (selectedHandle[3] &lt; 0 &amp;&amp; selectedElmGhost.clientHeight &lt;= height) {
          dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
        }
        deltaX = rootElement.scrollWidth - startScrollWidth;
        deltaY = rootElement.scrollHeight - startScrollHeight;
        if (deltaX + deltaY !== 0) {
          dom.setStyles(resizeHelper, {
            left: resizeHelperX - deltaX,
            top: resizeHelperY - deltaY
          });
        }
        if (!resizeStarted) {
          fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
          resizeStarted = true;
        }
      };
      var endGhostResize = function () {
        var wasResizeStarted = resizeStarted;
        resizeStarted = false;
        if (wasResizeStarted) {
          setSizeProp(selectedElm, 'width', width);
          setSizeProp(selectedElm, 'height', height);
        }
        dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
        dom.unbind(editableDoc, 'mouseup', endGhostResize);
        if (rootDocument !== editableDoc) {
          dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
          dom.unbind(rootDocument, 'mouseup', endGhostResize);
        }
        dom.remove(selectedElmGhost);
        dom.remove(resizeHelper);
        dom.remove(resizeBackdrop);
        showResizeRect(selectedElm);
        if (wasResizeStarted) {
          fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
          dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
        }
        editor.nodeChanged();
      };
      var showResizeRect = function (targetElm) {
        unbindResizeHandleEvents();
        var position = dom.getPos(targetElm, rootElement);
        var selectedElmX = position.x;
        var selectedElmY = position.y;
        var rect = targetElm.getBoundingClientRect();
        var targetWidth = rect.width || rect.right - rect.left;
        var targetHeight = rect.height || rect.bottom - rect.top;
        if (selectedElm !== targetElm) {
          hideResizeRect();
          selectedElm = targetElm;
          width = height = 0;
        }
        var e = editor.fire('ObjectSelected', { target: targetElm });
        var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
        if (isResizable(targetElm) &amp;&amp; !e.isDefaultPrevented()) {
          each$2(resizeHandles, function (handle, name) {
            var handleElm;
            var startDrag = function (e) {
              var target = getResizeTargets(selectedElm)[0];
              startX = e.screenX;
              startY = e.screenY;
              startW = target.clientWidth;
              startH = target.clientHeight;
              ratio = startH / startW;
              selectedHandle = handle;
              selectedHandle.name = name;
              selectedHandle.startPos = {
                x: targetWidth * handle[0] + selectedElmX,
                y: targetHeight * handle[1] + selectedElmY
              };
              startScrollWidth = rootElement.scrollWidth;
              startScrollHeight = rootElement.scrollHeight;
              resizeBackdrop = dom.add(rootElement, 'div', { class: 'mce-resize-backdrop' });
              dom.setStyles(resizeBackdrop, {
                position: 'fixed',
                left: '0',
                top: '0',
                width: '100%',
                height: '100%'
              });
              selectedElmGhost = createGhostElement(selectedElm);
              dom.addClass(selectedElmGhost, 'mce-clonedresizable');
              dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
              selectedElmGhost.contentEditable = 'false';
              dom.setStyles(selectedElmGhost, {
                left: selectedElmX,
                top: selectedElmY,
                margin: 0
              });
              setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
              selectedElmGhost.removeAttribute(elementSelectionAttr);
              rootElement.appendChild(selectedElmGhost);
              dom.bind(editableDoc, 'mousemove', resizeGhostElement);
              dom.bind(editableDoc, 'mouseup', endGhostResize);
              if (rootDocument !== editableDoc) {
                dom.bind(rootDocument, 'mousemove', resizeGhostElement);
                dom.bind(rootDocument, 'mouseup', endGhostResize);
              }
              resizeHelper = dom.add(rootElement, 'div', {
                'class': 'mce-resize-helper',
                'data-mce-bogus': 'all'
              }, startW + ' &amp;times; ' + startH);
            };
            handleElm = dom.get('mceResizeHandle' + name);
            if (handleElm) {
              dom.remove(handleElm);
            }
            handleElm = dom.add(rootElement, 'div', {
              'id': 'mceResizeHandle' + name,
              'data-mce-bogus': 'all',
              'class': 'mce-resizehandle',
              'unselectable': true,
              'style': 'cursor:' + name + '-resize; margin:0; padding:0'
            });
            if (Env.ie === 11) {
              handleElm.contentEditable = false;
            }
            dom.bind(handleElm, 'mousedown', function (e) {
              e.stopImmediatePropagation();
              e.preventDefault();
              startDrag(e);
            });
            handle.elm = handleElm;
            dom.setStyles(handleElm, {
              left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
              top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
            });
          });
        } else {
          hideResizeRect();
        }
        if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
          selectedElm.setAttribute(elementSelectionAttr, selectedValue);
        }
      };
      var hideResizeRect = function () {
        unbindResizeHandleEvents();
        if (selectedElm) {
          selectedElm.removeAttribute(elementSelectionAttr);
        }
        each$1(resizeHandles, function (value, name) {
          var handleElm = dom.get('mceResizeHandle' + name);
          if (handleElm) {
            dom.unbind(handleElm);
            dom.remove(handleElm);
          }
        });
      };
      var updateResizeRect = function (e) {
        var startElm, controlElm;
        var isChildOrEqual = function (node, parent) {
          if (node) {
            do {
              if (node === parent) {
                return true;
              }
            } while (node = node.parentNode);
          }
        };
        if (resizeStarted || editor.removed) {
          return;
        }
        each$2(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
          img.removeAttribute(elementSelectionAttr);
        });
        controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
        controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
        if (isChildOrEqual(controlElm, rootElement)) {
          disableGeckoResize();
          startElm = selection.getStart(true);
          if (isChildOrEqual(startElm, controlElm) &amp;&amp; isChildOrEqual(selection.getEnd(true), controlElm)) {
            showResizeRect(controlElm);
            return;
          }
        }
        hideResizeRect();
      };
      var isWithinContentEditableFalse = function (elm) {
        return isContentEditableFalse$6(getContentEditableRoot(editor.getBody(), elm));
      };
      var unbindResizeHandleEvents = function () {
        each$1(resizeHandles, function (handle) {
          if (handle.elm) {
            dom.unbind(handle.elm);
            delete handle.elm;
          }
        });
      };
      var disableGeckoResize = function () {
        try {
          editor.getDoc().execCommand('enableObjectResizing', false, 'false');
        } catch (ex) {
        }
      };
      editor.on('init', function () {
        disableGeckoResize();
        if (Env.browser.isIE() || Env.browser.isEdge()) {
          editor.on('mousedown click', function (e) {
            var target = e.target, nodeName = target.nodeName;
            if (!resizeStarted &amp;&amp; /^(TABLE|IMG|HR)$/.test(nodeName) &amp;&amp; !isWithinContentEditableFalse(target)) {
              if (e.button !== 2) {
                editor.selection.select(target, nodeName === 'TABLE');
              }
              if (e.type === 'mousedown') {
                editor.nodeChanged();
              }
            }
          });
          var handleMSControlSelect_1 = function (e) {
            var delayedSelect = function (node) {
              Delay.setEditorTimeout(editor, function () {
                return editor.selection.select(node);
              });
            };
            if (isWithinContentEditableFalse(e.target) || isMedia(e.target)) {
              e.preventDefault();
              delayedSelect(e.target);
              return;
            }
            if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
              e.preventDefault();
              if (e.target.tagName === 'IMG') {
                delayedSelect(e.target);
              }
            }
          };
          dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
          editor.on('remove', function () {
            return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
          });
        }
        var throttledUpdateResizeRect = Delay.throttle(function (e) {
          if (!editor.composing) {
            updateResizeRect(e);
          }
        });
        editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
        editor.on('keyup compositionend', function (e) {
          if (selectedElm &amp;&amp; selectedElm.nodeName === 'TABLE') {
            throttledUpdateResizeRect(e);
          }
        });
        editor.on('hide blur', hideResizeRect);
        editor.on('contextmenu longpress', contextMenuSelectImage, true);
      });
      editor.on('remove', unbindResizeHandleEvents);
      var destroy = function () {
        selectedElm = selectedElmGhost = resizeBackdrop = null;
      };
      return {
        isResizable: isResizable,
        showResizeRect: showResizeRect,
        hideResizeRect: hideResizeRect,
        updateResizeRect: updateResizeRect,
        destroy: destroy
      };
    };

    var hasCeProperty = function (node) {
      return isContentEditableTrue(node) || isContentEditableFalse(node);
    };
    var findParent = function (node, rootNode, predicate) {
      while (node &amp;&amp; node !== rootNode) {
        if (predicate(node)) {
          return node;
        }
        node = node.parentNode;
      }
      return null;
    };
    var findClosestIeRange = function (clientX, clientY, doc) {
      var rects;
      var element = doc.elementFromPoint(clientX, clientY);
      var rng = doc.body.createTextRange();
      if (!element || element.tagName === 'HTML') {
        element = doc.body;
      }
      rng.moveToElementText(element);
      rects = Tools.toArray(rng.getClientRects());
      rects = rects.sort(function (a, b) {
        a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
        b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
        return a - b;
      });
      if (rects.length &gt; 0) {
        clientY = (rects[0].bottom + rects[0].top) / 2;
        try {
          rng.moveToPoint(clientX, clientY);
          rng.collapse(true);
          return rng;
        } catch (ex) {
        }
      }
      return null;
    };
    var moveOutOfContentEditableFalse = function (rng, rootNode) {
      var parentElement = rng &amp;&amp; rng.parentElement ? rng.parentElement() : null;
      return isContentEditableFalse(findParent(parentElement, rootNode, hasCeProperty)) ? null : rng;
    };
    var fromPoint$1 = function (clientX, clientY, doc) {
      var rng, point;
      var pointDoc = doc;
      if (pointDoc.caretPositionFromPoint) {
        point = pointDoc.caretPositionFromPoint(clientX, clientY);
        if (point) {
          rng = doc.createRange();
          rng.setStart(point.offsetNode, point.offset);
          rng.collapse(true);
        }
      } else if (doc.caretRangeFromPoint) {
        rng = doc.caretRangeFromPoint(clientX, clientY);
      } else if (pointDoc.body.createTextRange) {
        rng = pointDoc.body.createTextRange();
        try {
          rng.moveToPoint(clientX, clientY);
          rng.collapse(true);
        } catch (ex) {
          rng = findClosestIeRange(clientX, clientY, doc);
        }
        return moveOutOfContentEditableFalse(rng, doc.body);
      }
      return rng;
    };

    var isEq$1 = function (rng1, rng2) {
      return rng1 &amp;&amp; rng2 &amp;&amp; (rng1.startContainer === rng2.startContainer &amp;&amp; rng1.startOffset === rng2.startOffset) &amp;&amp; (rng1.endContainer === rng2.endContainer &amp;&amp; rng1.endOffset === rng2.endOffset);
    };

    var findParent$1 = function (node, rootNode, predicate) {
      while (node &amp;&amp; node !== rootNode) {
        if (predicate(node)) {
          return node;
        }
        node = node.parentNode;
      }
      return null;
    };
    var hasParent = function (node, rootNode, predicate) {
      return findParent$1(node, rootNode, predicate) !== null;
    };
    var hasParentWithName = function (node, rootNode, name) {
      return hasParent(node, rootNode, function (node) {
        return node.nodeName === name;
      });
    };
    var isTable$3 = function (node) {
      return node &amp;&amp; node.nodeName === 'TABLE';
    };
    var isTableCell$3 = function (node) {
      return node &amp;&amp; /^(TD|TH|CAPTION)$/.test(node.nodeName);
    };
    var isCeFalseCaretContainer = function (node, rootNode) {
      return isCaretContainer(node) &amp;&amp; hasParent(node, rootNode, isCaretNode) === false;
    };
    var hasBrBeforeAfter = function (dom, node, left) {
      var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
      while (node = walker[left ? 'prev' : 'next']()) {
        if (isBr(node)) {
          return true;
        }
      }
    };
    var isPrevNode = function (node, name) {
      return node.previousSibling &amp;&amp; node.previousSibling.nodeName === name;
    };
    var hasContentEditableFalseParent = function (body, node) {
      while (node &amp;&amp; node !== body) {
        if (isContentEditableFalse(node)) {
          return true;
        }
        node = node.parentNode;
      }
      return false;
    };
    var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
      var lastInlineElement;
      var body = dom.getRoot();
      var node;
      var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
      var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
      if (left &amp;&amp; isBr(startNode) &amp;&amp; isAfterNode &amp;&amp; dom.isEmpty(parentBlockContainer)) {
        return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
      }
      var walker = new DomTreeWalker(startNode, parentBlockContainer);
      while (node = walker[left ? 'prev' : 'next']()) {
        if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
          return Optional.none();
        }
        if (isText$1(node) &amp;&amp; node.nodeValue.length &gt; 0) {
          if (hasParentWithName(node, body, 'A') === false) {
            return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
          }
          return Optional.none();
        }
        if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
          return Optional.none();
        }
        lastInlineElement = node;
      }
      if (collapsed &amp;&amp; lastInlineElement) {
        return Optional.some(CaretPosition(lastInlineElement, 0));
      }
      return Optional.none();
    };
    var normalizeEndPoint = function (dom, collapsed, start, rng) {
      var container, offset;
      var body = dom.getRoot();
      var node;
      var directionLeft, normalized = false;
      container = rng[(start ? 'start' : 'end') + 'Container'];
      offset = rng[(start ? 'start' : 'end') + 'Offset'];
      var isAfterNode = isElement$1(container) &amp;&amp; offset === container.childNodes.length;
      var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
      directionLeft = start;
      if (isCaretContainer(container)) {
        return Optional.none();
      }
      if (isElement$1(container) &amp;&amp; offset &gt; container.childNodes.length - 1) {
        directionLeft = false;
      }
      if (isDocument$1(container)) {
        container = body;
        offset = 0;
      }
      if (container === body) {
        if (directionLeft) {
          node = container.childNodes[offset &gt; 0 ? offset - 1 : 0];
          if (node) {
            if (isCaretContainer(node)) {
              return Optional.none();
            }
            if (nonEmptyElementsMap[node.nodeName] || isTable$3(node)) {
              return Optional.none();
            }
          }
        }
        if (container.hasChildNodes()) {
          offset = Math.min(!directionLeft &amp;&amp; offset &gt; 0 ? offset - 1 : offset, container.childNodes.length - 1);
          container = container.childNodes[offset];
          offset = isText$1(container) &amp;&amp; isAfterNode ? container.data.length : 0;
          if (!collapsed &amp;&amp; container === body.lastChild &amp;&amp; isTable$3(container)) {
            return Optional.none();
          }
          if (hasContentEditableFalseParent(body, container) || isCaretContainer(container)) {
            return Optional.none();
          }
          if (container.hasChildNodes() &amp;&amp; isTable$3(container) === false) {
            node = container;
            var walker = new DomTreeWalker(container, body);
            do {
              if (isContentEditableFalse(node) || isCaretContainer(node)) {
                normalized = false;
                break;
              }
              if (isText$1(node) &amp;&amp; node.nodeValue.length &gt; 0) {
                offset = directionLeft ? 0 : node.nodeValue.length;
                container = node;
                normalized = true;
                break;
              }
              if (nonEmptyElementsMap[node.nodeName.toLowerCase()] &amp;&amp; !isTableCell$3(node)) {
                offset = dom.nodeIndex(node);
                container = node.parentNode;
                if (!directionLeft) {
                  offset++;
                }
                normalized = true;
                break;
              }
            } while (node = directionLeft ? walker.next() : walker.prev());
          }
        }
      }
      if (collapsed) {
        if (isText$1(container) &amp;&amp; offset === 0) {
          findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
            container = pos.container();
            offset = pos.offset();
            normalized = true;
          });
        }
        if (isElement$1(container)) {
          node = container.childNodes[offset];
          if (!node) {
            node = container.childNodes[offset - 1];
          }
          if (node &amp;&amp; isBr(node) &amp;&amp; !isPrevNode(node, 'A') &amp;&amp; !hasBrBeforeAfter(dom, node, false) &amp;&amp; !hasBrBeforeAfter(dom, node, true)) {
            findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
              container = pos.container();
              offset = pos.offset();
              normalized = true;
            });
          }
        }
      }
      if (directionLeft &amp;&amp; !collapsed &amp;&amp; isText$1(container) &amp;&amp; offset === container.nodeValue.length) {
        findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
          container = pos.container();
          offset = pos.offset();
          normalized = true;
        });
      }
      return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
    };
    var normalize = function (dom, rng) {
      var collapsed = rng.collapsed, normRng = rng.cloneRange();
      var startPos = CaretPosition.fromRangeStart(rng);
      normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
        if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
          normRng.setStart(pos.container(), pos.offset());
        }
      });
      if (!collapsed) {
        normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
          normRng.setEnd(pos.container(), pos.offset());
        });
      }
      if (collapsed) {
        normRng.collapse(true);
      }
      return isEq$1(rng, normRng) ? Optional.none() : Optional.some(normRng);
    };

    var splitText = function (node, offset) {
      return node.splitText(offset);
    };
    var split$1 = function (rng) {
      var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
      if (startContainer === endContainer &amp;&amp; isText$1(startContainer)) {
        if (startOffset &gt; 0 &amp;&amp; startOffset &lt; startContainer.nodeValue.length) {
          endContainer = splitText(startContainer, startOffset);
          startContainer = endContainer.previousSibling;
          if (endOffset &gt; startOffset) {
            endOffset = endOffset - startOffset;
            startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
            endOffset = endContainer.nodeValue.length;
            startOffset = 0;
          } else {
            endOffset = 0;
          }
        }
      } else {
        if (isText$1(startContainer) &amp;&amp; startOffset &gt; 0 &amp;&amp; startOffset &lt; startContainer.nodeValue.length) {
          startContainer = splitText(startContainer, startOffset);
          startOffset = 0;
        }
        if (isText$1(endContainer) &amp;&amp; endOffset &gt; 0 &amp;&amp; endOffset &lt; endContainer.nodeValue.length) {
          endContainer = splitText(endContainer, endOffset).previousSibling;
          endOffset = endContainer.nodeValue.length;
        }
      }
      return {
        startContainer: startContainer,
        startOffset: startOffset,
        endContainer: endContainer,
        endOffset: endOffset
      };
    };

    var RangeUtils = function (dom) {
      var walk = function (rng, callback) {
        return walk$1(dom, rng, callback);
      };
      var split = split$1;
      var normalize$1 = function (rng) {
        return normalize(dom, rng).fold(never, function (normalizedRng) {
          rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
          rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
          return true;
        });
      };
      return {
        walk: walk,
        split: split,
        normalize: normalize$1
      };
    };
    RangeUtils.compareRanges = isEq$1;
    RangeUtils.getCaretRangeFromPoint = fromPoint$1;
    RangeUtils.getSelectedNode = getSelectedNode;
    RangeUtils.getNode = getNode;

    var Dimension = function (name, getOffset) {
      var set = function (element, h) {
        if (!isNumber(h) &amp;&amp; !h.match(/^[0-9]+$/)) {
          throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
        }
        var dom = element.dom;
        if (isSupported$1(dom)) {
          dom.style[name] = h + 'px';
        }
      };
      var get = function (element) {
        var r = getOffset(element);
        if (r &lt;= 0 || r === null) {
          var css = get$5(element, name);
          return parseFloat(css) || 0;
        }
        return r;
      };
      var getOuter = get;
      var aggregate = function (element, properties) {
        return foldl(properties, function (acc, property) {
          var val = get$5(element, property);
          var value = val === undefined ? 0 : parseInt(val, 10);
          return isNaN(value) ? acc : acc + value;
        }, 0);
      };
      var max = function (element, value, properties) {
        var cumulativeInclusions = aggregate(element, properties);
        var absoluteMax = value &gt; cumulativeInclusions ? value - cumulativeInclusions : 0;
        return absoluteMax;
      };
      return {
        set: set,
        get: get,
        getOuter: getOuter,
        aggregate: aggregate,
        max: max
      };
    };

    var api$1 = Dimension('height', function (element) {
      var dom = element.dom;
      return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
    });
    var get$9 = function (element) {
      return api$1.get(element);
    };

    var walkUp = function (navigation, doc) {
      var frame = navigation.view(doc);
      return frame.fold(constant([]), function (f) {
        var parent = navigation.owner(f);
        var rest = walkUp(navigation, parent);
        return [f].concat(rest);
      });
    };
    var pathTo = function (element, navigation) {
      var d = navigation.owner(element);
      return walkUp(navigation, d);
    };

    var view = function (doc) {
      var _a;
      var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
      return element.map(SugarElement.fromDom);
    };
    var owner$1 = function (element) {
      return documentOrOwner(element);
    };

    var Navigation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        view: view,
        owner: owner$1
    });

    var find$2 = function (element) {
      var doc = SugarElement.fromDom(document);
      var scroll = get$2(doc);
      var frames = pathTo(element, Navigation);
      var offset = viewport(element);
      var r = foldr(frames, function (b, a) {
        var loc = viewport(a);
        return {
          left: b.left + loc.left,
          top: b.top + loc.top
        };
      }, {
        left: 0,
        top: 0
      });
      return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
    };

    var excludeFromDescend = function (element) {
      return name(element) === 'textarea';
    };
    var fireScrollIntoViewEvent = function (editor, data) {
      var scrollEvent = editor.fire('ScrollIntoView', data);
      return scrollEvent.isDefaultPrevented();
    };
    var fireAfterScrollIntoViewEvent = function (editor, data) {
      editor.fire('AfterScrollIntoView', data);
    };
    var descend = function (element, offset) {
      var children$1 = children(element);
      if (children$1.length === 0 || excludeFromDescend(element)) {
        return {
          element: element,
          offset: offset
        };
      } else if (offset &lt; children$1.length &amp;&amp; !excludeFromDescend(children$1[offset])) {
        return {
          element: children$1[offset],
          offset: 0
        };
      } else {
        var last = children$1[children$1.length - 1];
        if (excludeFromDescend(last)) {
          return {
            element: element,
            offset: offset
          };
        } else {
          if (name(last) === 'img') {
            return {
              element: last,
              offset: 1
            };
          } else if (isText(last)) {
            return {
              element: last,
              offset: get$8(last).length
            };
          } else {
            return {
              element: last,
              offset: children(last).length
            };
          }
        }
      }
    };
    var markerInfo = function (element, cleanupFun) {
      var pos = absolute(element);
      var height = get$9(element);
      return {
        element: element,
        bottom: pos.top + height,
        height: height,
        pos: pos,
        cleanup: cleanupFun
      };
    };
    var createMarker = function (element, offset) {
      var startPoint = descend(element, offset);
      var span = SugarElement.fromHtml('&lt;span data-mce-bogus="all"&gt;' + ZWSP + '&lt;/span&gt;');
      before(startPoint.element, span);
      return markerInfo(span, function () {
        return remove(span);
      });
    };
    var elementMarker = function (element) {
      return markerInfo(SugarElement.fromDom(element), noop);
    };
    var withMarker = function (editor, f, rng, alignToTop) {
      preserveWith(editor, function (_s, _e) {
        return applyWithMarker(editor, f, rng, alignToTop);
      }, rng);
    };
    var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
      var data = {
        elm: marker.element.dom,
        alignToTop: alignToTop
      };
      if (fireScrollIntoViewEvent(editor, data)) {
        return;
      }
      var scrollTop = get$2(doc).top;
      f(doc, scrollTop, marker, alignToTop);
      fireAfterScrollIntoViewEvent(editor, data);
    };
    var applyWithMarker = function (editor, f, rng, alignToTop) {
      var body = SugarElement.fromDom(editor.getBody());
      var doc = SugarElement.fromDom(editor.getDoc());
      reflow(body);
      var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
      withScrollEvents(editor, doc, f, marker, alignToTop);
      marker.cleanup();
    };
    var withElement = function (editor, element, f, alignToTop) {
      var doc = SugarElement.fromDom(editor.getDoc());
      withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
    };
    var preserveWith = function (editor, f, rng) {
      var startElement = rng.startContainer;
      var startOffset = rng.startOffset;
      var endElement = rng.endContainer;
      var endOffset = rng.endOffset;
      f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
      var newRng = editor.dom.createRng();
      newRng.setStart(startElement, startOffset);
      newRng.setEnd(endElement, endOffset);
      editor.selection.setRng(rng);
    };
    var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
      var pos = marker.pos;
      if (alignToTop) {
        to(pos.left, pos.top, doc);
      } else {
        var y = pos.top - viewHeight + marker.height;
        to(pos.left, y, doc);
      }
    };
    var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
      var viewportBottom = viewHeight + scrollTop;
      var markerTop = marker.pos.top;
      var markerBottom = marker.bottom;
      var largerThanViewport = markerBottom - markerTop &gt;= viewHeight;
      if (markerTop &lt; scrollTop) {
        scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
      } else if (markerTop &gt; viewportBottom) {
        var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
        scrollToMarker(marker, viewHeight, align, doc);
      } else if (markerBottom &gt; viewportBottom &amp;&amp; !largerThanViewport) {
        scrollToMarker(marker, viewHeight, alignToTop === true, doc);
      }
    };
    var intoWindow = function (doc, scrollTop, marker, alignToTop) {
      var viewHeight = doc.dom.defaultView.innerHeight;
      intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
    };
    var intoFrame = function (doc, scrollTop, marker, alignToTop) {
      var frameViewHeight = doc.dom.defaultView.innerHeight;
      intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
      var op = find$2(marker.element);
      var viewportBounds = getBounds(window);
      if (op.top &lt; viewportBounds.y) {
        intoView(marker.element, alignToTop !== false);
      } else if (op.top &gt; viewportBounds.bottom) {
        intoView(marker.element, alignToTop === true);
      }
    };
    var rangeIntoWindow = function (editor, rng, alignToTop) {
      return withMarker(editor, intoWindow, rng, alignToTop);
    };
    var elementIntoWindow = function (editor, element, alignToTop) {
      return withElement(editor, element, intoWindow, alignToTop);
    };
    var rangeIntoFrame = function (editor, rng, alignToTop) {
      return withMarker(editor, intoFrame, rng, alignToTop);
    };
    var elementIntoFrame = function (editor, element, alignToTop) {
      return withElement(editor, element, intoFrame, alignToTop);
    };
    var scrollElementIntoView = function (editor, element, alignToTop) {
      var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
      scroller(editor, element, alignToTop);
    };
    var scrollRangeIntoView = function (editor, rng, alignToTop) {
      var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
      scroller(editor, rng, alignToTop);
    };

    var getDocument = function () {
      return SugarElement.fromDom(document);
    };

    var focus = function (element) {
      return element.dom.focus();
    };
    var hasFocus = function (element) {
      var root = getRootNode(element).dom;
      return element.dom === root.activeElement;
    };
    var active = function (root) {
      if (root === void 0) {
        root = getDocument();
      }
      return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
    };
    var search = function (element) {
      return active(getRootNode(element)).filter(function (e) {
        return element.dom.contains(e.dom);
      });
    };

    var create$4 = function (start, soffset, finish, foffset) {
      return {
        start: start,
        soffset: soffset,
        finish: finish,
        foffset: foffset
      };
    };
    var SimRange = { create: create$4 };

    var adt = Adt.generate([
      { before: ['element'] },
      {
        on: [
          'element',
          'offset'
        ]
      },
      { after: ['element'] }
    ]);
    var cata = function (subject, onBefore, onOn, onAfter) {
      return subject.fold(onBefore, onOn, onAfter);
    };
    var getStart = function (situ) {
      return situ.fold(identity, identity, identity);
    };
    var before$3 = adt.before;
    var on = adt.on;
    var after$2 = adt.after;
    var Situ = {
      before: before$3,
      on: on,
      after: after$2,
      cata: cata,
      getStart: getStart
    };

    var adt$1 = Adt.generate([
      { domRange: ['rng'] },
      {
        relative: [
          'startSitu',
          'finishSitu'
        ]
      },
      {
        exact: [
          'start',
          'soffset',
          'finish',
          'foffset'
        ]
      }
    ]);
    var exactFromRange = function (simRange) {
      return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
    };
    var getStart$1 = function (selection) {
      return selection.match({
        domRange: function (rng) {
          return SugarElement.fromDom(rng.startContainer);
        },
        relative: function (startSitu, _finishSitu) {
          return Situ.getStart(startSitu);
        },
        exact: function (start, _soffset, _finish, _foffset) {
          return start;
        }
      });
    };
    var domRange = adt$1.domRange;
    var relative = adt$1.relative;
    var exact = adt$1.exact;
    var getWin = function (selection) {
      var start = getStart$1(selection);
      return defaultView(start);
    };
    var range = SimRange.create;
    var SimSelection = {
      domRange: domRange,
      relative: relative,
      exact: exact,
      exactFromRange: exactFromRange,
      getWin: getWin,
      range: range
    };

    var browser$3 = detect$3().browser;
    var clamp = function (offset, element) {
      var max = isText(element) ? get$8(element).length : children(element).length + 1;
      if (offset &gt; max) {
        return max;
      } else if (offset &lt; 0) {
        return 0;
      }
      return offset;
    };
    var normalizeRng = function (rng) {
      return SimSelection.range(rng.start, clamp(rng.soffset, rng.start), rng.finish, clamp(rng.foffset, rng.finish));
    };
    var isOrContains = function (root, elm) {
      return !isRestrictedNode(elm.dom) &amp;&amp; (contains$2(root, elm) || eq$2(root, elm));
    };
    var isRngInRoot = function (root) {
      return function (rng) {
        return isOrContains(root, rng.start) &amp;&amp; isOrContains(root, rng.finish);
      };
    };
    var shouldStore = function (editor) {
      return editor.inline === true || browser$3.isIE();
    };
    var nativeRangeToSelectionRange = function (r) {
      return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
    };
    var readRange = function (win) {
      var selection = win.getSelection();
      var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
      return rng.map(nativeRangeToSelectionRange);
    };
    var getBookmark$2 = function (root) {
      var win = defaultView(root);
      return readRange(win.dom).filter(isRngInRoot(root));
    };
    var validate = function (root, bookmark) {
      return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
    };
    var bookmarkToNativeRng = function (bookmark) {
      var rng = document.createRange();
      try {
        rng.setStart(bookmark.start.dom, bookmark.soffset);
        rng.setEnd(bookmark.finish.dom, bookmark.foffset);
        return Optional.some(rng);
      } catch (_) {
        return Optional.none();
      }
    };
    var store = function (editor) {
      var newBookmark = shouldStore(editor) ? getBookmark$2(SugarElement.fromDom(editor.getBody())) : Optional.none();
      editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
    };
    var storeNative = function (editor, rng) {
      var root = SugarElement.fromDom(editor.getBody());
      var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
      var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
      editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
    };
    var getRng = function (editor) {
      var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
      return bookmark.bind(function (x) {
        return validate(SugarElement.fromDom(editor.getBody()), x);
      }).bind(bookmarkToNativeRng);
    };
    var restore = function (editor) {
      getRng(editor).each(function (rng) {
        return editor.selection.setRng(rng);
      });
    };

    var isEditorUIElement = function (elm) {
      var className = elm.className.toString();
      return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
    };
    var FocusManager = { isEditorUIElement: isEditorUIElement };

    var isManualNodeChange = function (e) {
      return e.type === 'nodechange' &amp;&amp; e.selectionChange;
    };
    var registerPageMouseUp = function (editor, throttledStore) {
      var mouseUpPage = function () {
        throttledStore.throttle();
      };
      DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
      editor.on('remove', function () {
        DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
      });
    };
    var registerFocusOut = function (editor) {
      editor.on('focusout', function () {
        store(editor);
      });
    };
    var registerMouseUp = function (editor, throttledStore) {
      editor.on('mouseup touchend', function (_e) {
        throttledStore.throttle();
      });
    };
    var registerEditorEvents = function (editor, throttledStore) {
      var browser = detect$3().browser;
      if (browser.isIE()) {
        registerFocusOut(editor);
      } else {
        registerMouseUp(editor, throttledStore);
      }
      editor.on('keyup NodeChange', function (e) {
        if (!isManualNodeChange(e)) {
          store(editor);
        }
      });
    };
    var register = function (editor) {
      var throttledStore = first(function () {
        store(editor);
      }, 0);
      editor.on('init', function () {
        if (editor.inline) {
          registerPageMouseUp(editor, throttledStore);
        }
        registerEditorEvents(editor, throttledStore);
      });
      editor.on('remove', function () {
        throttledStore.cancel();
      });
    };

    var documentFocusInHandler;
    var DOM$2 = DOMUtils.DOM;
    var isEditorUIElement$1 = function (elm) {
      return FocusManager.isEditorUIElement(elm);
    };
    var isEditorContentAreaElement = function (elm) {
      var classList = elm.classList;
      if (classList !== undefined) {
        return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
      } else {
        return false;
      }
    };
    var isUIElement = function (editor, elm) {
      var customSelector = getCustomUiSelector(editor);
      var parent = DOM$2.getParent(elm, function (elm) {
        return isEditorUIElement$1(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
      });
      return parent !== null;
    };
    var getActiveElement = function (editor) {
      try {
        var root = getRootNode(SugarElement.fromDom(editor.getElement()));
        return active(root).fold(function () {
          return document.body;
        }, function (x) {
          return x.dom;
        });
      } catch (ex) {
        return document.body;
      }
    };
    var registerEvents = function (editorManager, e) {
      var editor = e.editor;
      register(editor);
      editor.on('focusin', function () {
        var focusedEditor = editorManager.focusedEditor;
        if (focusedEditor !== editor) {
          if (focusedEditor) {
            focusedEditor.fire('blur', { focusedEditor: editor });
          }
          editorManager.setActive(editor);
          editorManager.focusedEditor = editor;
          editor.fire('focus', { blurredEditor: focusedEditor });
          editor.focus(true);
        }
      });
      editor.on('focusout', function () {
        Delay.setEditorTimeout(editor, function () {
          var focusedEditor = editorManager.focusedEditor;
          if (!isUIElement(editor, getActiveElement(editor)) &amp;&amp; focusedEditor === editor) {
            editor.fire('blur', { focusedEditor: null });
            editorManager.focusedEditor = null;
          }
        });
      });
      if (!documentFocusInHandler) {
        documentFocusInHandler = function (e) {
          var activeEditor = editorManager.activeEditor;
          if (activeEditor) {
            getOriginalEventTarget(e).each(function (target) {
              if (target.ownerDocument === document) {
                if (target !== document.body &amp;&amp; !isUIElement(activeEditor, target) &amp;&amp; editorManager.focusedEditor === activeEditor) {
                  activeEditor.fire('blur', { focusedEditor: null });
                  editorManager.focusedEditor = null;
                }
              }
            });
          }
        };
        DOM$2.bind(document, 'focusin', documentFocusInHandler);
      }
    };
    var unregisterDocumentEvents = function (editorManager, e) {
      if (editorManager.focusedEditor === e.editor) {
        editorManager.focusedEditor = null;
      }
      if (!editorManager.activeEditor) {
        DOM$2.unbind(document, 'focusin', documentFocusInHandler);
        documentFocusInHandler = null;
      }
    };
    var setup$2 = function (editorManager) {
      editorManager.on('AddEditor', curry(registerEvents, editorManager));
      editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
    };

    var getContentEditableHost = function (editor, node) {
      return editor.dom.getParent(node, function (node) {
        return editor.dom.getContentEditable(node) === 'true';
      });
    };
    var getCollapsedNode = function (rng) {
      return rng.collapsed ? Optional.from(getNode(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
    };
    var getFocusInElement = function (root, rng) {
      return getCollapsedNode(rng).bind(function (node) {
        if (isTableSection(node)) {
          return Optional.some(node);
        } else if (contains$2(root, node) === false) {
          return Optional.some(root);
        } else {
          return Optional.none();
        }
      });
    };
    var normalizeSelection = function (editor, rng) {
      getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
        return firstPositionIn(elm.dom);
      }).fold(function () {
        editor.selection.normalize();
        return;
      }, function (caretPos) {
        return editor.selection.setRng(caretPos.toRange());
      });
    };
    var focusBody = function (body) {
      if (body.setActive) {
        try {
          body.setActive();
        } catch (ex) {
          body.focus();
        }
      } else {
        body.focus();
      }
    };
    var hasElementFocus = function (elm) {
      return hasFocus(elm) || search(elm).isSome();
    };
    var hasIframeFocus = function (editor) {
      return editor.iframeElement &amp;&amp; hasFocus(SugarElement.fromDom(editor.iframeElement));
    };
    var hasInlineFocus = function (editor) {
      var rawBody = editor.getBody();
      return rawBody &amp;&amp; hasElementFocus(SugarElement.fromDom(rawBody));
    };
    var hasUiFocus = function (editor) {
      var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
      return active(dos).filter(function (elem) {
        return !isEditorContentAreaElement(elem.dom) &amp;&amp; isUIElement(editor, elem.dom);
      }).isSome();
    };
    var hasFocus$1 = function (editor) {
      return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
    };
    var hasEditorOrUiFocus = function (editor) {
      return hasFocus$1(editor) || hasUiFocus(editor);
    };
    var focusEditor = function (editor) {
      var selection = editor.selection;
      var body = editor.getBody();
      var rng = selection.getRng();
      editor.quirks.refreshContentEditable();
      if (editor.bookmark !== undefined &amp;&amp; hasFocus$1(editor) === false) {
        getRng(editor).each(function (bookmarkRng) {
          editor.selection.setRng(bookmarkRng);
          rng = bookmarkRng;
        });
      }
      var contentEditableHost = getContentEditableHost(editor, selection.getNode());
      if (editor.$.contains(body, contentEditableHost)) {
        focusBody(contentEditableHost);
        normalizeSelection(editor, rng);
        activateEditor(editor);
        return;
      }
      if (!editor.inline) {
        if (!Env.opera) {
          focusBody(body);
        }
        editor.getWin().focus();
      }
      if (Env.gecko || editor.inline) {
        focusBody(body);
        normalizeSelection(editor, rng);
      }
      activateEditor(editor);
    };
    var activateEditor = function (editor) {
      return editor.editorManager.setActive(editor);
    };
    var focus$1 = function (editor, skipFocus) {
      if (editor.removed) {
        return;
      }
      skipFocus ? activateEditor(editor) : focusEditor(editor);
    };

    var getEndpointElement = function (root, rng, start, real, resolve) {
      var container = start ? rng.startContainer : rng.endContainer;
      var offset = start ? rng.startOffset : rng.endOffset;
      return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
        return !real || !rng.collapsed ? child(elm, resolve(elm, offset)).getOr(elm) : elm;
      }).bind(function (elm) {
        return isElement(elm) ? Optional.some(elm) : parent(elm).filter(isElement);
      }).map(function (elm) {
        return elm.dom;
      }).getOr(root);
    };
    var getStart$2 = function (root, rng, real) {
      return getEndpointElement(root, rng, true, real, function (elm, offset) {
        return Math.min(childNodesCount(elm), offset);
      });
    };
    var getEnd = function (root, rng, real) {
      return getEndpointElement(root, rng, false, real, function (elm, offset) {
        return offset &gt; 0 ? offset - 1 : offset;
      });
    };
    var skipEmptyTextNodes = function (node, forwards) {
      var orig = node;
      while (node &amp;&amp; isText$1(node) &amp;&amp; node.length === 0) {
        node = forwards ? node.nextSibling : node.previousSibling;
      }
      return node || orig;
    };
    var getNode$1 = function (root, rng) {
      var elm, startContainer, endContainer;
      if (!rng) {
        return root;
      }
      startContainer = rng.startContainer;
      endContainer = rng.endContainer;
      var startOffset = rng.startOffset;
      var endOffset = rng.endOffset;
      elm = rng.commonAncestorContainer;
      if (!rng.collapsed) {
        if (startContainer === endContainer) {
          if (endOffset - startOffset &lt; 2) {
            if (startContainer.hasChildNodes()) {
              elm = startContainer.childNodes[startOffset];
            }
          }
        }
        if (startContainer.nodeType === 3 &amp;&amp; endContainer.nodeType === 3) {
          if (startContainer.length === startOffset) {
            startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
          } else {
            startContainer = startContainer.parentNode;
          }
          if (endOffset === 0) {
            endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
          } else {
            endContainer = endContainer.parentNode;
          }
          if (startContainer &amp;&amp; startContainer === endContainer) {
            return startContainer;
          }
        }
      }
      if (elm &amp;&amp; elm.nodeType === 3) {
        return elm.parentNode;
      }
      return elm;
    };
    var getSelectedBlocks = function (dom, rng, startElm, endElm) {
      var node;
      var selectedBlocks = [];
      var root = dom.getRoot();
      startElm = dom.getParent(startElm || getStart$2(root, rng, rng.collapsed), dom.isBlock);
      endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
      if (startElm &amp;&amp; startElm !== root) {
        selectedBlocks.push(startElm);
      }
      if (startElm &amp;&amp; endElm &amp;&amp; startElm !== endElm) {
        node = startElm;
        var walker = new DomTreeWalker(startElm, root);
        while ((node = walker.next()) &amp;&amp; node !== endElm) {
          if (dom.isBlock(node)) {
            selectedBlocks.push(node);
          }
        }
      }
      if (endElm &amp;&amp; startElm !== endElm &amp;&amp; endElm !== root) {
        selectedBlocks.push(endElm);
      }
      return selectedBlocks;
    };
    var select$1 = function (dom, node, content) {
      return Optional.from(node).map(function (node) {
        var idx = dom.nodeIndex(node);
        var rng = dom.createRng();
        rng.setStart(node.parentNode, idx);
        rng.setEnd(node.parentNode, idx + 1);
        if (content) {
          moveEndPoint$1(dom, rng, node, true);
          moveEndPoint$1(dom, rng, node, false);
        }
        return rng;
      });
    };

    var processRanges = function (editor, ranges) {
      return map(ranges, function (range) {
        var evt = editor.fire('GetSelectionRange', { range: range });
        return evt.range !== range ? evt.range : range;
      });
    };

    var typeLookup = {
      '#text': 3,
      '#comment': 8,
      '#cdata': 4,
      '#pi': 7,
      '#doctype': 10,
      '#document-fragment': 11
    };
    var walk$2 = function (node, root, prev) {
      var startName = prev ? 'lastChild' : 'firstChild';
      var siblingName = prev ? 'prev' : 'next';
      if (node[startName]) {
        return node[startName];
      }
      if (node !== root) {
        var sibling = node[siblingName];
        if (sibling) {
          return sibling;
        }
        for (var parent_1 = node.parent; parent_1 &amp;&amp; parent_1 !== root; parent_1 = parent_1.parent) {
          sibling = parent_1[siblingName];
          if (sibling) {
            return sibling;
          }
        }
      }
    };
    var isEmptyTextNode$1 = function (node) {
      if (!isWhitespaceText(node.value)) {
        return false;
      }
      var parentNode = node.parent;
      if (parentNode &amp;&amp; (parentNode.name !== 'span' || parentNode.attr('style')) &amp;&amp; /^[ ]+$/.test(node.value)) {
        return false;
      }
      return true;
    };
    var isNonEmptyElement = function (node) {
      var isNamedAnchor = node.name === 'a' &amp;&amp; !node.attr('href') &amp;&amp; node.attr('id');
      return node.attr('name') || node.attr('id') &amp;&amp; !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
    };
    var AstNode = function () {
      function AstNode(name, type) {
        this.name = name;
        this.type = type;
        if (type === 1) {
          this.attributes = [];
          this.attributes.map = {};
        }
      }
      AstNode.create = function (name, attrs) {
        var node = new AstNode(name, typeLookup[name] || 1);
        if (attrs) {
          each$1(attrs, function (value, attrName) {
            node.attr(attrName, value);
          });
        }
        return node;
      };
      AstNode.prototype.replace = function (node) {
        var self = this;
        if (node.parent) {
          node.remove();
        }
        self.insert(node, self);
        self.remove();
        return self;
      };
      AstNode.prototype.attr = function (name, value) {
        var self = this;
        var attrs;
        if (typeof name !== 'string') {
          if (name !== undefined &amp;&amp; name !== null) {
            each$1(name, function (value, key) {
              self.attr(key, value);
            });
          }
          return self;
        }
        if (attrs = self.attributes) {
          if (value !== undefined) {
            if (value === null) {
              if (name in attrs.map) {
                delete attrs.map[name];
                var i = attrs.length;
                while (i--) {
                  if (attrs[i].name === name) {
                    attrs.splice(i, 1);
                    return self;
                  }
                }
              }
              return self;
            }
            if (name in attrs.map) {
              var i = attrs.length;
              while (i--) {
                if (attrs[i].name === name) {
                  attrs[i].value = value;
                  break;
                }
              }
            } else {
              attrs.push({
                name: name,
                value: value
              });
            }
            attrs.map[name] = value;
            return self;
          }
          return attrs.map[name];
        }
      };
      AstNode.prototype.clone = function () {
        var self = this;
        var clone = new AstNode(self.name, self.type);
        var selfAttrs;
        if (selfAttrs = self.attributes) {
          var cloneAttrs = [];
          cloneAttrs.map = {};
          for (var i = 0, l = selfAttrs.length; i &lt; l; i++) {
            var selfAttr = selfAttrs[i];
            if (selfAttr.name !== 'id') {
              cloneAttrs[cloneAttrs.length] = {
                name: selfAttr.name,
                value: selfAttr.value
              };
              cloneAttrs.map[selfAttr.name] = selfAttr.value;
            }
          }
          clone.attributes = cloneAttrs;
        }
        clone.value = self.value;
        clone.shortEnded = self.shortEnded;
        return clone;
      };
      AstNode.prototype.wrap = function (wrapper) {
        var self = this;
        self.parent.insert(wrapper, self);
        wrapper.append(self);
        return self;
      };
      AstNode.prototype.unwrap = function () {
        var self = this;
        for (var node = self.firstChild; node;) {
          var next = node.next;
          self.insert(node, self, true);
          node = next;
        }
        self.remove();
      };
      AstNode.prototype.remove = function () {
        var self = this, parent = self.parent, next = self.next, prev = self.prev;
        if (parent) {
          if (parent.firstChild === self) {
            parent.firstChild = next;
            if (next) {
              next.prev = null;
            }
          } else {
            prev.next = next;
          }
          if (parent.lastChild === self) {
            parent.lastChild = prev;
            if (prev) {
              prev.next = null;
            }
          } else {
            next.prev = prev;
          }
          self.parent = self.next = self.prev = null;
        }
        return self;
      };
      AstNode.prototype.append = function (node) {
        var self = this;
        if (node.parent) {
          node.remove();
        }
        var last = self.lastChild;
        if (last) {
          last.next = node;
          node.prev = last;
          self.lastChild = node;
        } else {
          self.lastChild = self.firstChild = node;
        }
        node.parent = self;
        return node;
      };
      AstNode.prototype.insert = function (node, refNode, before) {
        if (node.parent) {
          node.remove();
        }
        var parent = refNode.parent || this;
        if (before) {
          if (refNode === parent.firstChild) {
            parent.firstChild = node;
          } else {
            refNode.prev.next = node;
          }
          node.prev = refNode.prev;
          node.next = refNode;
          refNode.prev = node;
        } else {
          if (refNode === parent.lastChild) {
            parent.lastChild = node;
          } else {
            refNode.next.prev = node;
          }
          node.next = refNode.next;
          node.prev = refNode;
          refNode.next = node;
        }
        node.parent = parent;
        return node;
      };
      AstNode.prototype.getAll = function (name) {
        var self = this;
        var collection = [];
        for (var node = self.firstChild; node; node = walk$2(node, self)) {
          if (node.name === name) {
            collection.push(node);
          }
        }
        return collection;
      };
      AstNode.prototype.empty = function () {
        var self = this;
        if (self.firstChild) {
          var nodes = [];
          for (var node = self.firstChild; node; node = walk$2(node, self)) {
            nodes.push(node);
          }
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
          }
        }
        self.firstChild = self.lastChild = null;
        return self;
      };
      AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
        if (whitespace === void 0) {
          whitespace = {};
        }
        var self = this;
        var node = self.firstChild;
        if (isNonEmptyElement(self)) {
          return false;
        }
        if (node) {
          do {
            if (node.type === 1) {
              if (node.attr('data-mce-bogus')) {
                continue;
              }
              if (elements[node.name]) {
                return false;
              }
              if (isNonEmptyElement(node)) {
                return false;
              }
            }
            if (node.type === 8) {
              return false;
            }
            if (node.type === 3 &amp;&amp; !isEmptyTextNode$1(node)) {
              return false;
            }
            if (node.type === 3 &amp;&amp; node.parent &amp;&amp; whitespace[node.parent.name] &amp;&amp; isWhitespaceText(node.value)) {
              return false;
            }
            if (predicate &amp;&amp; predicate(node)) {
              return false;
            }
          } while (node = walk$2(node, self));
        }
        return true;
      };
      AstNode.prototype.walk = function (prev) {
        return walk$2(this, null, prev);
      };
      return AstNode;
    }();

    var extractBase64DataUris = function (html) {
      var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=]+)/gi;
      var chunks = [];
      var uris = {};
      var prefix = generate$1('img');
      var matches;
      var index = 0;
      var count = 0;
      while (matches = dataImageUri.exec(html)) {
        var uri = matches[0];
        var imageId = prefix + '_' + count++;
        uris[imageId] = uri;
        if (index &lt; matches.index) {
          chunks.push(html.substr(index, matches.index - index));
        }
        chunks.push(imageId);
        index = matches.index + uri.length;
      }
      var re = new RegExp(prefix + '_[0-9]+', 'g');
      if (index === 0) {
        return {
          prefix: prefix,
          uris: uris,
          html: html,
          re: re
        };
      } else {
        if (index &lt; html.length) {
          chunks.push(html.substr(index));
        }
        return {
          prefix: prefix,
          uris: uris,
          html: chunks.join(''),
          re: re
        };
      }
    };
    var restoreDataUris = function (html, result) {
      return html.replace(result.re, function (imageId) {
        return get$1(result.uris, imageId).getOr(imageId);
      });
    };
    var parseDataUri = function (uri) {
      var matches = /data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(uri);
      if (matches) {
        return Optional.some({
          type: matches[1],
          data: decodeURIComponent(matches[2])
        });
      } else {
        return Optional.none();
      }
    };

    var safeSvgDataUrlElements = [
      'img',
      'video'
    ];
    var isValidPrefixAttrName = function (name) {
      return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
    };
    var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
      var allowed = isNullable(allowSvgDataUrls) ? contains(safeSvgDataUrlElements, tagName) : allowSvgDataUrls;
      return !allowed;
    };
    var isInvalidUri = function (settings, uri, tagName) {
      if (settings.allow_html_data_urls) {
        return false;
      } else if (/^data:image\//i.test(uri)) {
        return blockSvgDataUris(settings.allow_svg_data_urls, tagName) &amp;&amp; /^data:image\/svg\+xml/i.test(uri);
      } else {
        return /^data:/i.test(uri);
      }
    };
    var findEndTagIndex = function (schema, html, startIndex) {
      var count = 1, index, matches;
      var shortEndedElements = schema.getShortEndedElements();
      var tokenRegExp = /&lt;([!?\/])?([A-Za-z0-9\-_:.]+)(\s(?:[^'"&gt;]+(?:"[^"]*"|'[^']*'))*[^"'&gt;]*(?:"[^"&gt;]*|'[^'&gt;]*)?|\s*|\/)&gt;/g;
      tokenRegExp.lastIndex = index = startIndex;
      while (matches = tokenRegExp.exec(html)) {
        index = tokenRegExp.lastIndex;
        if (matches[1] === '/') {
          count--;
        } else if (!matches[1]) {
          if (matches[2] in shortEndedElements) {
            continue;
          }
          count++;
        }
        if (count === 0) {
          break;
        }
      }
      return index;
    };
    var isConditionalComment = function (html, startIndex) {
      return /^\s*\[if [\w\W]+\]&gt;.*&lt;!\[endif\](--!?)?&gt;/.test(html.substr(startIndex));
    };
    var findCommentEndIndex = function (html, isBogus, startIndex) {
      if (startIndex === void 0) {
        startIndex = 0;
      }
      var lcHtml = html.toLowerCase();
      if (lcHtml.indexOf('[if ', startIndex) !== -1 &amp;&amp; isConditionalComment(lcHtml, startIndex)) {
        var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
        return lcHtml.indexOf('&gt;', endIfIndex);
      } else {
        if (isBogus) {
          var endIndex = lcHtml.indexOf('&gt;', startIndex);
          return endIndex !== -1 ? endIndex : lcHtml.length;
        } else {
          var endCommentRegexp = /--!?&gt;/g;
          endCommentRegexp.lastIndex = startIndex;
          var match = endCommentRegexp.exec(html);
          return match ? match.index + match[0].length : lcHtml.length;
        }
      }
    };
    var checkBogusAttribute = function (regExp, attrString) {
      var matches = regExp.exec(attrString);
      if (matches) {
        var name_1 = matches[1];
        var value = matches[2];
        return typeof name_1 === 'string' &amp;&amp; name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
      } else {
        return null;
      }
    };
    var SaxParser = function (settings, schema) {
      if (schema === void 0) {
        schema = Schema();
      }
      settings = settings || {};
      if (settings.fix_self_closing !== false) {
        settings.fix_self_closing = true;
      }
      var comment = settings.comment ? settings.comment : noop;
      var cdata = settings.cdata ? settings.cdata : noop;
      var text = settings.text ? settings.text : noop;
      var start = settings.start ? settings.start : noop;
      var end = settings.end ? settings.end : noop;
      var pi = settings.pi ? settings.pi : noop;
      var doctype = settings.doctype ? settings.doctype : noop;
      var parseInternal = function (base64Extract, format) {
        if (format === void 0) {
          format = 'html';
        }
        var html = base64Extract.html;
        var matches, index = 0, value, endRegExp;
        var stack = [];
        var attrList, i, textData, name;
        var isInternalElement, isShortEnded;
        var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
        var attributesRequired, attributesDefault, attributesForced;
        var anyAttributesRequired, attrValue, idCount = 0;
        var decode = Entities.decode;
        var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
        var scriptUriRegExp = /((java|vb)script|mhtml):/i;
        var parsingMode = format === 'html' ? 0 : 1;
        var processEndTag = function (name) {
          var pos, i;
          pos = stack.length;
          while (pos--) {
            if (stack[pos].name === name) {
              break;
            }
          }
          if (pos &gt;= 0) {
            for (i = stack.length - 1; i &gt;= pos; i--) {
              name = stack[i];
              if (name.valid) {
                end(name.name);
              }
            }
            stack.length = pos;
          }
        };
        var processText = function (value, raw) {
          return text(restoreDataUris(value, base64Extract), raw);
        };
        var processComment = function (value) {
          if (value === '') {
            return;
          }
          if (value.charAt(0) === '&gt;') {
            value = ' ' + value;
          }
          if (!settings.allow_conditional_comments &amp;&amp; value.substr(0, 3).toLowerCase() === '[if') {
            value = ' ' + value;
          }
          comment(restoreDataUris(value, base64Extract));
        };
        var processAttr = function (value) {
          return restoreDataUris(value, base64Extract);
        };
        var processMalformedComment = function (value, startIndex) {
          var startTag = value || '';
          var isBogus = !startsWith(startTag, '--');
          var endIndex = findCommentEndIndex(html, isBogus, startIndex);
          value = html.substr(startIndex, endIndex - startIndex);
          processComment(isBogus ? startTag + value : value);
          return endIndex + 1;
        };
        var parseAttribute = function (tagName, name, value, val2, val3) {
          var attrRule, i;
          var trimRegExp = /[\s\u0000-\u001F]+/g;
          name = name.toLowerCase();
          value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
          if (validate &amp;&amp; !isInternalElement &amp;&amp; isValidPrefixAttrName(name) === false) {
            attrRule = validAttributesMap[name];
            if (!attrRule &amp;&amp; validAttributePatterns) {
              i = validAttributePatterns.length;
              while (i--) {
                attrRule = validAttributePatterns[i];
                if (attrRule.pattern.test(name)) {
                  break;
                }
              }
              if (i === -1) {
                attrRule = null;
              }
            }
            if (!attrRule) {
              return;
            }
            if (attrRule.validValues &amp;&amp; !(value in attrRule.validValues)) {
              return;
            }
          }
          if (filteredUrlAttrs[name] &amp;&amp; !settings.allow_script_urls) {
            var uri = value.replace(trimRegExp, '');
            try {
              uri = decodeURIComponent(uri);
            } catch (ex) {
              uri = unescape(uri);
            }
            if (scriptUriRegExp.test(uri)) {
              return;
            }
            if (isInvalidUri(settings, uri, tagName)) {
              return;
            }
          }
          if (isInternalElement &amp;&amp; (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
            return;
          }
          attrList.map[name] = value;
          attrList.push({
            name: name,
            value: value
          });
        };
        var tokenRegExp = new RegExp('&lt;(?:' + '(?:!--([\\w\\W]*?)--!?&gt;)|' + '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]&gt;)|' + '(?:![Dd][Oo][Cc][Tt][Yy][Pp][Ee]([\\w\\W]*?)&gt;)|' + '(?:!(--)?)|' + '(?:\\?([^\\s\\/&lt;&gt;]+) ?([\\w\\W]*?)[?/]&gt;)|' + '(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)&gt;)|' + '(?:([A-Za-z][A-Za-z0-9\\-_:.]*)(\\s(?:[^\'"&gt;]+(?:"[^"]*"|\'[^\']*\'))*[^"\'&gt;]*(?:"[^"&gt;]*|\'[^\'&gt;]*)?|\\s*|\\/)&gt;)' + ')', 'g');
        var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^&gt;\s]+)))?/g;
        var shortEndedElements = schema.getShortEndedElements();
        var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
        var fillAttrsMap = schema.getBoolAttrs();
        var validate = settings.validate;
        var removeInternalElements = settings.remove_internals;
        var fixSelfClosing = settings.fix_self_closing;
        var specialElements = schema.getSpecialElements();
        var processHtml = html + '&gt;';
        while (matches = tokenRegExp.exec(processHtml)) {
          var matchText = matches[0];
          if (index &lt; matches.index) {
            processText(decode(html.substr(index, matches.index - index)));
          }
          if (value = matches[7]) {
            value = value.toLowerCase();
            if (value.charAt(0) === ':') {
              value = value.substr(1);
            }
            processEndTag(value);
          } else if (value = matches[8]) {
            if (matches.index + matchText.length &gt; html.length) {
              processText(decode(html.substr(matches.index)));
              index = matches.index + matchText.length;
              continue;
            }
            value = value.toLowerCase();
            if (value.charAt(0) === ':') {
              value = value.substr(1);
            }
            isShortEnded = value in shortEndedElements;
            if (fixSelfClosing &amp;&amp; selfClosing[value] &amp;&amp; stack.length &gt; 0 &amp;&amp; stack[stack.length - 1].name === value) {
              processEndTag(value);
            }
            var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
            if (bogusValue !== null) {
              if (bogusValue === 'all') {
                index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
                tokenRegExp.lastIndex = index;
                continue;
              }
              isValidElement = false;
            }
            if (!validate || (elementRule = schema.getElementRule(value))) {
              isValidElement = true;
              if (validate) {
                validAttributesMap = elementRule.attributes;
                validAttributePatterns = elementRule.attributePatterns;
              }
              if (attribsValue = matches[9]) {
                isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
                if (isInternalElement &amp;&amp; removeInternalElements) {
                  isValidElement = false;
                }
                attrList = [];
                attrList.map = {};
                attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
                  parseAttribute(value, name, val, val2, val3);
                  return '';
                });
              } else {
                attrList = [];
                attrList.map = {};
              }
              if (validate &amp;&amp; !isInternalElement) {
                attributesRequired = elementRule.attributesRequired;
                attributesDefault = elementRule.attributesDefault;
                attributesForced = elementRule.attributesForced;
                anyAttributesRequired = elementRule.removeEmptyAttrs;
                if (anyAttributesRequired &amp;&amp; !attrList.length) {
                  isValidElement = false;
                }
                if (attributesForced) {
                  i = attributesForced.length;
                  while (i--) {
                    attr = attributesForced[i];
                    name = attr.name;
                    attrValue = attr.value;
                    if (attrValue === '{$uid}') {
                      attrValue = 'mce_' + idCount++;
                    }
                    attrList.map[name] = attrValue;
                    attrList.push({
                      name: name,
                      value: attrValue
                    });
                  }
                }
                if (attributesDefault) {
                  i = attributesDefault.length;
                  while (i--) {
                    attr = attributesDefault[i];
                    name = attr.name;
                    if (!(name in attrList.map)) {
                      attrValue = attr.value;
                      if (attrValue === '{$uid}') {
                        attrValue = 'mce_' + idCount++;
                      }
                      attrList.map[name] = attrValue;
                      attrList.push({
                        name: name,
                        value: attrValue
                      });
                    }
                  }
                }
                if (attributesRequired) {
                  i = attributesRequired.length;
                  while (i--) {
                    if (attributesRequired[i] in attrList.map) {
                      break;
                    }
                  }
                  if (i === -1) {
                    isValidElement = false;
                  }
                }
                if (attr = attrList.map['data-mce-bogus']) {
                  if (attr === 'all') {
                    index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
                    tokenRegExp.lastIndex = index;
                    continue;
                  }
                  isValidElement = false;
                }
              }
              if (isValidElement) {
                start(value, attrList, isShortEnded);
              }
            } else {
              isValidElement = false;
            }
            if (endRegExp = specialElements[value]) {
              endRegExp.lastIndex = index = matches.index + matchText.length;
              if (matches = endRegExp.exec(html)) {
                if (isValidElement) {
                  textData = html.substr(index, matches.index - index);
                }
                index = matches.index + matches[0].length;
              } else {
                textData = html.substr(index);
                index = html.length;
              }
              if (isValidElement) {
                if (textData.length &gt; 0) {
                  processText(textData, true);
                }
                end(value);
              }
              tokenRegExp.lastIndex = index;
              continue;
            }
            if (!isShortEnded) {
              if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
                stack.push({
                  name: value,
                  valid: isValidElement
                });
              } else if (isValidElement) {
                end(value);
              }
            }
          } else if (value = matches[1]) {
            processComment(value);
          } else if (value = matches[2]) {
            var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length &gt; 0 &amp;&amp; schema.isValidChild(stack[stack.length - 1].name, '#cdata');
            if (isValidCdataSection) {
              cdata(value);
            } else {
              index = processMalformedComment('', matches.index + 2);
              tokenRegExp.lastIndex = index;
              continue;
            }
          } else if (value = matches[3]) {
            doctype(value);
          } else if ((value = matches[4]) || matchText === '&lt;!') {
            index = processMalformedComment(value, matches.index + matchText.length);
            tokenRegExp.lastIndex = index;
            continue;
          } else if (value = matches[5]) {
            if (parsingMode === 1) {
              pi(value, matches[6]);
            } else {
              index = processMalformedComment('?', matches.index + 2);
              tokenRegExp.lastIndex = index;
              continue;
            }
          }
          index = matches.index + matchText.length;
        }
        if (index &lt; html.length) {
          processText(decode(html.substr(index)));
        }
        for (i = stack.length - 1; i &gt;= 0; i--) {
          value = stack[i];
          if (value.valid) {
            end(value.name);
          }
        }
      };
      var parse = function (html, format) {
        if (format === void 0) {
          format = 'html';
        }
        parseInternal(extractBase64DataUris(html), format);
      };
      return { parse: parse };
    };
    SaxParser.findEndTag = findEndTagIndex;

    var trimHtml = function (tempAttrs, html) {
      var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
      return html.replace(trimContentRegExp, '');
    };
    var trimInternal = function (serializer, html) {
      var content = html;
      var bogusAllRegExp = /&lt;(\w+) [^&gt;]*data-mce-bogus="all"[^&gt;]*&gt;/g;
      var endTagIndex, index, matchLength, matches;
      var schema = serializer.schema;
      content = trimHtml(serializer.getTempAttrs(), content);
      var shortEndedElements = schema.getShortEndedElements();
      while (matches = bogusAllRegExp.exec(content)) {
        index = bogusAllRegExp.lastIndex;
        matchLength = matches[0].length;
        if (shortEndedElements[matches[1]]) {
          endTagIndex = index;
        } else {
          endTagIndex = SaxParser.findEndTag(schema, content, index);
        }
        content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
        bogusAllRegExp.lastIndex = index - matchLength;
      }
      return trim$2(content);
    };
    var trimExternal = trimInternal;

    var trimEmptyContents = function (editor, html) {
      var blockName = getForcedRootBlock(editor);
      var emptyRegExp = new RegExp('^(&lt;' + blockName + '[^&gt;]*&gt;(&amp;nbsp;|&amp;#160;|\\s|\xA0|&lt;br \\/&gt;|)&lt;\\/' + blockName + '&gt;[\r\n]*|&lt;br \\/&gt;[\r\n]*)$');
      return html.replace(emptyRegExp, '');
    };
    var getContentFromBody = function (editor, args, format, body) {
      var content;
      args.format = format;
      args.get = true;
      args.getInner = true;
      if (!args.no_events) {
        editor.fire('BeforeGetContent', args);
      }
      if (args.format === 'raw') {
        content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
      } else if (args.format === 'text') {
        content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
      } else if (args.format === 'tree') {
        content = editor.serializer.serialize(body, args);
      } else {
        content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
      }
      if (!contains([
          'text',
          'tree'
        ], args.format) &amp;&amp; !isWsPreserveElement(SugarElement.fromDom(body))) {
        args.content = Tools.trim(content);
      } else {
        args.content = content;
      }
      if (!args.no_events) {
        editor.fire('GetContent', args);
      }
      return args.content;
    };
    var getContentInternal = function (editor, args, format) {
      return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
        return getContentFromBody(editor, args, format, body);
      });
    };

    var each$7 = Tools.each;
    var ElementUtils = function (dom) {
      var compare = function (node1, node2) {
        if (node1.nodeName !== node2.nodeName) {
          return false;
        }
        var getAttribs = function (node) {
          var attribs = {};
          each$7(dom.getAttribs(node), function (attr) {
            var name = attr.nodeName.toLowerCase();
            if (name.indexOf('_') !== 0 &amp;&amp; name !== 'style' &amp;&amp; name.indexOf('data-') !== 0) {
              attribs[name] = dom.getAttrib(node, name);
            }
          });
          return attribs;
        };
        var compareObjects = function (obj1, obj2) {
          var value, name;
          for (name in obj1) {
            if (obj1.hasOwnProperty(name)) {
              value = obj2[name];
              if (typeof value === 'undefined') {
                return false;
              }
              if (obj1[name] !== value) {
                return false;
              }
              delete obj2[name];
            }
          }
          for (name in obj2) {
            if (obj2.hasOwnProperty(name)) {
              return false;
            }
          }
          return true;
        };
        if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
          return false;
        }
        if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
          return false;
        }
        return !isBookmarkNode$1(node1) &amp;&amp; !isBookmarkNode$1(node2);
      };
      return { compare: compare };
    };

    var makeMap$3 = Tools.makeMap;
    var Writer = function (settings) {
      var html = [];
      settings = settings || {};
      var indent = settings.indent;
      var indentBefore = makeMap$3(settings.indent_before || '');
      var indentAfter = makeMap$3(settings.indent_after || '');
      var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
      var htmlOutput = settings.element_format === 'html';
      return {
        start: function (name, attrs, empty) {
          var i, l, attr, value;
          if (indent &amp;&amp; indentBefore[name] &amp;&amp; html.length &gt; 0) {
            value = html[html.length - 1];
            if (value.length &gt; 0 &amp;&amp; value !== '\n') {
              html.push('\n');
            }
          }
          html.push('&lt;', name);
          if (attrs) {
            for (i = 0, l = attrs.length; i &lt; l; i++) {
              attr = attrs[i];
              html.push(' ', attr.name, '="', encode(attr.value, true), '"');
            }
          }
          if (!empty || htmlOutput) {
            html[html.length] = '&gt;';
          } else {
            html[html.length] = ' /&gt;';
          }
          if (empty &amp;&amp; indent &amp;&amp; indentAfter[name] &amp;&amp; html.length &gt; 0) {
            value = html[html.length - 1];
            if (value.length &gt; 0 &amp;&amp; value !== '\n') {
              html.push('\n');
            }
          }
        },
        end: function (name) {
          var value;
          html.push('&lt;/', name, '&gt;');
          if (indent &amp;&amp; indentAfter[name] &amp;&amp; html.length &gt; 0) {
            value = html[html.length - 1];
            if (value.length &gt; 0 &amp;&amp; value !== '\n') {
              html.push('\n');
            }
          }
        },
        text: function (text, raw) {
          if (text.length &gt; 0) {
            html[html.length] = raw ? text : encode(text);
          }
        },
        cdata: function (text) {
          html.push('&lt;![CDATA[', text, ']]&gt;');
        },
        comment: function (text) {
          html.push('&lt;!--', text, '--&gt;');
        },
        pi: function (name, text) {
          if (text) {
            html.push('&lt;?', name, ' ', encode(text), '?&gt;');
          } else {
            html.push('&lt;?', name, '?&gt;');
          }
          if (indent) {
            html.push('\n');
          }
        },
        doctype: function (text) {
          html.push('&lt;!DOCTYPE', text, '&gt;', indent ? '\n' : '');
        },
        reset: function () {
          html.length = 0;
        },
        getContent: function () {
          return html.join('').replace(/\n$/, '');
        }
      };
    };

    var HtmlSerializer = function (settings, schema) {
      if (schema === void 0) {
        schema = Schema();
      }
      var writer = Writer(settings);
      settings = settings || {};
      settings.validate = 'validate' in settings ? settings.validate : true;
      var serialize = function (node) {
        var validate = settings.validate;
        var handlers = {
          3: function (node) {
            writer.text(node.value, node.raw);
          },
          8: function (node) {
            writer.comment(node.value);
          },
          7: function (node) {
            writer.pi(node.name, node.value);
          },
          10: function (node) {
            writer.doctype(node.value);
          },
          4: function (node) {
            writer.cdata(node.value);
          },
          11: function (node) {
            if (node = node.firstChild) {
              do {
                walk(node);
              } while (node = node.next);
            }
          }
        };
        writer.reset();
        var walk = function (node) {
          var handler = handlers[node.type];
          var name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
          if (!handler) {
            name = node.name;
            isEmpty = node.shortEnded;
            attrs = node.attributes;
            if (validate &amp;&amp; attrs &amp;&amp; attrs.length &gt; 1) {
              sortedAttrs = [];
              sortedAttrs.map = {};
              elementRule = schema.getElementRule(node.name);
              if (elementRule) {
                for (i = 0, l = elementRule.attributesOrder.length; i &lt; l; i++) {
                  attrName = elementRule.attributesOrder[i];
                  if (attrName in attrs.map) {
                    attrValue = attrs.map[attrName];
                    sortedAttrs.map[attrName] = attrValue;
                    sortedAttrs.push({
                      name: attrName,
                      value: attrValue
                    });
                  }
                }
                for (i = 0, l = attrs.length; i &lt; l; i++) {
                  attrName = attrs[i].name;
                  if (!(attrName in sortedAttrs.map)) {
                    attrValue = attrs.map[attrName];
                    sortedAttrs.map[attrName] = attrValue;
                    sortedAttrs.push({
                      name: attrName,
                      value: attrValue
                    });
                  }
                }
                attrs = sortedAttrs;
              }
            }
            writer.start(node.name, attrs, isEmpty);
            if (!isEmpty) {
              if (node = node.firstChild) {
                do {
                  walk(node);
                } while (node = node.next);
              }
              writer.end(name);
            }
          } else {
            handler(node);
          }
        };
        if (node.type === 1 &amp;&amp; !settings.inner) {
          walk(node);
        } else {
          handlers[11](node);
        }
        return writer.getContent();
      };
      return { serialize: serialize };
    };

    var nonInheritableStyles = new Set();
    (function () {
      var nonInheritableStylesArr = [
        'margin',
        'margin-left',
        'margin-right',
        'margin-top',
        'margin-bottom',
        'padding',
        'padding-left',
        'padding-right',
        'padding-top',
        'padding-bottom',
        'border',
        'border-width',
        'border-style',
        'border-color',
        'background',
        'background-attachment',
        'background-clip',
        'background-color',
        'background-image',
        'background-origin',
        'background-position',
        'background-repeat',
        'background-size',
        'float',
        'position',
        'left',
        'right',
        'top',
        'bottom',
        'z-index',
        'display',
        'transform',
        'width',
        'max-width',
        'min-width',
        'height',
        'max-height',
        'min-height',
        'overflow',
        'overflow-x',
        'overflow-y',
        'text-overflow',
        'vertical-align',
        'transition',
        'transition-delay',
        'transition-duration',
        'transition-property',
        'transition-timing-function'
      ];
      each(nonInheritableStylesArr, function (style) {
        nonInheritableStyles.add(style);
      });
    }());
    var shorthandStyleProps = [
      'font',
      'text-decoration',
      'text-emphasis'
    ];
    var getStyleProps = function (dom, node) {
      return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
    };
    var isNonInheritableStyle = function (style) {
      return nonInheritableStyles.has(style);
    };
    var hasInheritableStyles = function (dom, node) {
      return forall(getStyleProps(dom, node), function (style) {
        return !isNonInheritableStyle(style);
      });
    };
    var getLonghandStyleProps = function (styles) {
      return filter(styles, function (style) {
        return exists(shorthandStyleProps, function (prop) {
          return startsWith(style, prop);
        });
      });
    };
    var hasStyleConflict = function (dom, node, parentNode) {
      var nodeStyleProps = getStyleProps(dom, node);
      var parentNodeStyleProps = getStyleProps(dom, parentNode);
      var valueMismatch = function (prop) {
        var nodeValue = dom.getStyle(node, prop);
        var parentValue = dom.getStyle(parentNode, prop);
        return isNotEmpty(nodeValue) &amp;&amp; isNotEmpty(parentValue) &amp;&amp; nodeValue !== parentValue;
      };
      return exists(nodeStyleProps, function (nodeStyleProp) {
        var propExists = function (props) {
          return exists(props, function (prop) {
            return prop === nodeStyleProp;
          });
        };
        if (!propExists(parentNodeStyleProps) &amp;&amp; propExists(shorthandStyleProps)) {
          var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
          return exists(longhandProps, valueMismatch);
        } else {
          return valueMismatch(nodeStyleProp);
        }
      });
    };

    var isChar = function (forward, predicate, pos) {
      return Optional.from(pos.container()).filter(isText$1).exists(function (text) {
        var delta = forward ? 0 : -1;
        return predicate(text.data.charAt(pos.offset() + delta));
      });
    };
    var isBeforeSpace = curry(isChar, true, isWhiteSpace$1);
    var isAfterSpace = curry(isChar, false, isWhiteSpace$1);
    var isEmptyText = function (pos) {
      var container = pos.container();
      return isText$1(container) &amp;&amp; (container.data.length === 0 || isZwsp$1(container.data) &amp;&amp; BookmarkManager.isBookmarkNode(container.parentNode));
    };
    var matchesElementPosition = function (before, predicate) {
      return function (pos) {
        return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
      };
    };
    var isImageBlock = function (node) {
      return isImg(node) &amp;&amp; get$5(SugarElement.fromDom(node), 'display') === 'block';
    };
    var isCefNode = function (node) {
      return isContentEditableFalse(node) &amp;&amp; !isBogusAll(node);
    };
    var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
    var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
    var isBeforeMedia = matchesElementPosition(true, isMedia);
    var isAfterMedia = matchesElementPosition(false, isMedia);
    var isBeforeTable = matchesElementPosition(true, isTable);
    var isAfterTable = matchesElementPosition(false, isTable);
    var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
    var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);

    var getLastChildren$1 = function (elm) {
      var children = [];
      var rawNode = elm.dom;
      while (rawNode) {
        children.push(SugarElement.fromDom(rawNode));
        rawNode = rawNode.lastChild;
      }
      return children;
    };
    var removeTrailingBr = function (elm) {
      var allBrs = descendants$1(elm, 'br');
      var brs = filter(getLastChildren$1(elm).slice(-1), isBr$1);
      if (allBrs.length === brs.length) {
        each(brs, remove);
      }
    };
    var fillWithPaddingBr = function (elm) {
      empty(elm);
      append(elm, SugarElement.fromHtml('&lt;br data-mce-bogus="1"&gt;'));
    };
    var trimBlockTrailingBr = function (elm) {
      lastChild(elm).each(function (lastChild) {
        prevSibling(lastChild).each(function (lastChildPrevSibling) {
          if (isBlock(elm) &amp;&amp; isBr$1(lastChild) &amp;&amp; isBlock(lastChildPrevSibling)) {
            remove(lastChild);
          }
        });
      });
    };

    var dropLast = function (xs) {
      return xs.slice(0, -1);
    };
    var parentsUntil$1 = function (start, root, predicate) {
      if (contains$2(root, start)) {
        return dropLast(parents(start, function (elm) {
          return predicate(elm) || eq$2(elm, root);
        }));
      } else {
        return [];
      }
    };
    var parents$1 = function (start, root) {
      return parentsUntil$1(start, root, never);
    };
    var parentsAndSelf = function (start, root) {
      return [start].concat(parents$1(start, root));
    };

    var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
      return navigateIgnore(forward, root, from, isEmptyText);
    };
    var getClosestBlock = function (root, pos) {
      return find(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
    };
    var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
      return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
        return getClosestBlock(root, pos).fold(function () {
          return isInSameBlock(newPos, pos, root.dom) === false;
        }, function (fromBlock) {
          return isInSameBlock(newPos, pos, root.dom) === false &amp;&amp; contains$2(fromBlock, SugarElement.fromDom(newPos.container()));
        });
      });
    };
    var isAtBlockBoundary$1 = function (forward, root, pos) {
      return getClosestBlock(root, pos).fold(function () {
        return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
          return isInSameBlock(newPos, pos, root.dom) === false;
        });
      }, function (parent) {
        return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
      });
    };
    var isAtStartOfBlock = curry(isAtBlockBoundary$1, false);
    var isAtEndOfBlock = curry(isAtBlockBoundary$1, true);
    var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
    var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);

    var isBr$5 = function (pos) {
      return getElementFromPosition(pos).exists(isBr$1);
    };
    var findBr = function (forward, root, pos) {
      var parentBlocks = filter(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
      var scope = head(parentBlocks).getOr(root);
      return fromPosition(forward, scope.dom, pos).filter(isBr$5);
    };
    var isBeforeBr = function (root, pos) {
      return getElementFromPosition(pos).exists(isBr$1) || findBr(true, root, pos).isSome();
    };
    var isAfterBr = function (root, pos) {
      return getElementFromPrevPosition(pos).exists(isBr$1) || findBr(false, root, pos).isSome();
    };
    var findPreviousBr = curry(findBr, false);
    var findNextBr = curry(findBr, true);

    var isInMiddleOfText = function (pos) {
      return CaretPosition.isTextPosition(pos) &amp;&amp; !pos.isAtStart() &amp;&amp; !pos.isAtEnd();
    };
    var getClosestBlock$1 = function (root, pos) {
      var parentBlocks = filter(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
      return head(parentBlocks).getOr(root);
    };
    var hasSpaceBefore = function (root, pos) {
      if (isInMiddleOfText(pos)) {
        return isAfterSpace(pos);
      } else {
        return isAfterSpace(pos) || prevPosition(getClosestBlock$1(root, pos).dom, pos).exists(isAfterSpace);
      }
    };
    var hasSpaceAfter = function (root, pos) {
      if (isInMiddleOfText(pos)) {
        return isBeforeSpace(pos);
      } else {
        return isBeforeSpace(pos) || nextPosition(getClosestBlock$1(root, pos).dom, pos).exists(isBeforeSpace);
      }
    };
    var isPreValue = function (value) {
      return contains([
        'pre',
        'pre-wrap'
      ], value);
    };
    var isInPre = function (pos) {
      return getElementFromPosition(pos).bind(function (elm) {
        return closest(elm, isElement);
      }).exists(function (elm) {
        return isPreValue(get$5(elm, 'white-space'));
      });
    };
    var isAtBeginningOfBody = function (root, pos) {
      return prevPosition(root.dom, pos).isNone();
    };
    var isAtEndOfBody = function (root, pos) {
      return nextPosition(root.dom, pos).isNone();
    };
    var isAtLineBoundary = function (root, pos) {
      return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr(root, pos);
    };
    var needsToHaveNbsp = function (root, pos) {
      if (isInPre(pos)) {
        return false;
      } else {
        return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
      }
    };
    var needsToBeNbspLeft = function (root, pos) {
      if (isInPre(pos)) {
        return false;
      } else {
        return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
      }
    };
    var leanRight = function (pos) {
      var container = pos.container();
      var offset = pos.offset();
      if (isText$1(container) &amp;&amp; offset &lt; container.data.length) {
        return CaretPosition(container, offset + 1);
      } else {
        return pos;
      }
    };
    var needsToBeNbspRight = function (root, pos) {
      if (isInPre(pos)) {
        return false;
      } else {
        return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr(root, pos) || hasSpaceAfter(root, pos);
      }
    };
    var needsToBeNbsp = function (root, pos) {
      return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
    };
    var isNbspAt = function (text, offset) {
      return isNbsp(text.charAt(offset));
    };
    var hasNbsp = function (pos) {
      var container = pos.container();
      return isText$1(container) &amp;&amp; contains$1(container.data, nbsp);
    };
    var normalizeNbspMiddle = function (text) {
      var chars = text.split('');
      return map(chars, function (chr, i) {
        if (isNbsp(chr) &amp;&amp; i &gt; 0 &amp;&amp; i &lt; chars.length - 1 &amp;&amp; isContent$1(chars[i - 1]) &amp;&amp; isContent$1(chars[i + 1])) {
          return ' ';
        } else {
          return chr;
        }
      }).join('');
    };
    var normalizeNbspAtStart = function (root, node) {
      var text = node.data;
      var firstPos = CaretPosition(node, 0);
      if (isNbspAt(text, 0) &amp;&amp; !needsToBeNbsp(root, firstPos)) {
        node.data = ' ' + text.slice(1);
        return true;
      } else {
        return false;
      }
    };
    var normalizeNbspInMiddleOfTextNode = function (node) {
      var text = node.data;
      var newText = normalizeNbspMiddle(text);
      if (newText !== text) {
        node.data = newText;
        return true;
      } else {
        return false;
      }
    };
    var normalizeNbspAtEnd = function (root, node) {
      var text = node.data;
      var lastPos = CaretPosition(node, text.length - 1);
      if (isNbspAt(text, text.length - 1) &amp;&amp; !needsToBeNbsp(root, lastPos)) {
        node.data = text.slice(0, -1) + ' ';
        return true;
      } else {
        return false;
      }
    };
    var normalizeNbsps = function (root, pos) {
      return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
        var container = pos.container();
        var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
        return normalized ? Optional.some(pos) : Optional.none();
      });
    };
    var normalizeNbspsInEditor = function (editor) {
      var root = SugarElement.fromDom(editor.getBody());
      if (editor.selection.isCollapsed()) {
        normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
          editor.selection.setRng(pos.toRange());
        });
      }
    };

    var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
      var result = foldl(content, function (acc, c) {
        if (isWhiteSpace$1(c) || isNbsp(c)) {
          if (acc.previousCharIsSpace || acc.str === '' &amp;&amp; isStartOfContent || acc.str.length === content.length - 1 &amp;&amp; isEndOfContent) {
            return {
              previousCharIsSpace: false,
              str: acc.str + nbsp
            };
          } else {
            return {
              previousCharIsSpace: true,
              str: acc.str + ' '
            };
          }
        } else {
          return {
            previousCharIsSpace: false,
            str: acc.str + c
          };
        }
      }, {
        previousCharIsSpace: false,
        str: ''
      });
      return result.str;
    };
    var normalize$1 = function (node, offset, count) {
      if (count === 0) {
        return;
      }
      var elm = SugarElement.fromDom(node);
      var root = ancestor(elm, isBlock).getOr(elm);
      var whitespace = node.data.slice(offset, offset + count);
      var isEndOfContent = offset + count &gt;= node.data.length &amp;&amp; needsToBeNbspRight(root, CaretPosition(node, node.data.length));
      var isStartOfContent = offset === 0 &amp;&amp; needsToBeNbspLeft(root, CaretPosition(node, 0));
      node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
    };
    var normalizeWhitespaceAfter = function (node, offset) {
      var content = node.data.slice(offset);
      var whitespaceCount = content.length - lTrim(content).length;
      return normalize$1(node, offset, whitespaceCount);
    };
    var normalizeWhitespaceBefore = function (node, offset) {
      var content = node.data.slice(0, offset);
      var whitespaceCount = content.length - rTrim(content).length;
      return normalize$1(node, offset - whitespaceCount, whitespaceCount);
    };
    var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
      if (mergeToPrev === void 0) {
        mergeToPrev = true;
      }
      var whitespaceOffset = rTrim(prevNode.data).length;
      var newNode = mergeToPrev ? prevNode : nextNode;
      var removeNode = mergeToPrev ? nextNode : prevNode;
      if (mergeToPrev) {
        newNode.appendData(removeNode.data);
      } else {
        newNode.insertData(0, removeNode.data);
      }
      remove(SugarElement.fromDom(removeNode));
      if (normalizeWhitespace) {
        normalizeWhitespaceAfter(newNode, whitespaceOffset);
      }
      return newNode;
    };

    var needsReposition = function (pos, elm) {
      var container = pos.container();
      var offset = pos.offset();
      return CaretPosition.isTextPosition(pos) === false &amp;&amp; container === elm.parentNode &amp;&amp; offset &gt; CaretPosition.before(elm).offset();
    };
    var reposition = function (elm, pos) {
      return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
    };
    var beforeOrStartOf = function (node) {
      return isText$1(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
    };
    var afterOrEndOf = function (node) {
      return isText$1(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
    };
    var getPreviousSiblingCaretPosition = function (elm) {
      if (isCaretCandidate(elm.previousSibling)) {
        return Optional.some(afterOrEndOf(elm.previousSibling));
      } else {
        return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
      }
    };
    var getNextSiblingCaretPosition = function (elm) {
      if (isCaretCandidate(elm.nextSibling)) {
        return Optional.some(beforeOrStartOf(elm.nextSibling));
      } else {
        return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
      }
    };
    var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
      var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
      return prevPosition(rootElement, startPosition).fold(function () {
        return nextPosition(rootElement, CaretPosition.after(elm));
      }, Optional.some);
    };
    var findCaretPositionForwardsFromElm = function (rootElement, elm) {
      return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
        return prevPosition(rootElement, CaretPosition.before(elm));
      }, Optional.some);
    };
    var findCaretPositionBackwards = function (rootElement, elm) {
      return getPreviousSiblingCaretPosition(elm).orThunk(function () {
        return getNextSiblingCaretPosition(elm);
      }).orThunk(function () {
        return findCaretPositionBackwardsFromElm(rootElement, elm);
      });
    };
    var findCaretPositionForward = function (rootElement, elm) {
      return getNextSiblingCaretPosition(elm).orThunk(function () {
        return getPreviousSiblingCaretPosition(elm);
      }).orThunk(function () {
        return findCaretPositionForwardsFromElm(rootElement, elm);
      });
    };
    var findCaretPosition$1 = function (forward, rootElement, elm) {
      return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
    };
    var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
      return findCaretPosition$1(forward, rootElement, elm).map(curry(reposition, elm));
    };
    var setSelection = function (editor, forward, pos) {
      pos.fold(function () {
        editor.focus();
      }, function (pos) {
        editor.selection.setRng(pos.toRange(), forward);
      });
    };
    var eqRawNode = function (rawNode) {
      return function (elm) {
        return elm.dom === rawNode;
      };
    };
    var isBlock$2 = function (editor, elm) {
      return elm &amp;&amp; has(editor.schema.getBlockElements(), name(elm));
    };
    var paddEmptyBlock = function (elm) {
      if (isEmpty(elm)) {
        var br = SugarElement.fromHtml('&lt;br data-mce-bogus="1"&gt;');
        empty(elm);
        append(elm, br);
        return Optional.some(CaretPosition.before(br.dom));
      } else {
        return Optional.none();
      }
    };
    var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
      var prevTextOpt = prevSibling(elm).filter(isText);
      var nextTextOpt = nextSibling(elm).filter(isText);
      remove(elm);
      return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
        var prevNode = prev.dom, nextNode = next.dom;
        var offset = prevNode.data.length;
        mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
        return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
      }).orThunk(function () {
        if (normalizeWhitespace) {
          prevTextOpt.each(function (elm) {
            return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
          });
          nextTextOpt.each(function (elm) {
            return normalizeWhitespaceAfter(elm.dom, 0);
          });
        }
        return afterDeletePosOpt;
      });
    };
    var isInlineElement = function (editor, element) {
      return has(editor.schema.getTextInlineElements(), name(element));
    };
    var deleteElement = function (editor, forward, elm, moveCaret) {
      if (moveCaret === void 0) {
        moveCaret = true;
      }
      var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
      var parentBlock = ancestor(elm, curry(isBlock$2, editor), eqRawNode(editor.getBody()));
      var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
      if (editor.dom.isEmpty(editor.getBody())) {
        editor.setContent('');
        editor.selection.setCursorLocation();
      } else {
        parentBlock.bind(paddEmptyBlock).fold(function () {
          if (moveCaret) {
            setSelection(editor, forward, normalizedAfterDeletePos);
          }
        }, function (paddPos) {
          if (moveCaret) {
            setSelection(editor, forward, Optional.some(paddPos));
          }
        });
      }
    };

    var tableCellRng = function (start, end) {
      return {
        start: start,
        end: end
      };
    };
    var tableSelection = function (rng, table, cells) {
      return {
        rng: rng,
        table: table,
        cells: cells
      };
    };
    var deleteAction = Adt.generate([
      { removeTable: ['element'] },
      { emptyCells: ['cells'] },
      {
        deleteCellSelection: [
          'rng',
          'cell'
        ]
      }
    ]);
    var isRootFromElement = function (root) {
      return function (cur) {
        return eq$2(root, cur);
      };
    };
    var getClosestCell = function (container, isRoot) {
      return closest$1(SugarElement.fromDom(container), 'td,th', isRoot);
    };
    var getClosestTable = function (cell, isRoot) {
      return ancestor$1(cell, 'table', isRoot);
    };
    var isExpandedCellRng = function (cellRng) {
      return !eq$2(cellRng.start, cellRng.end);
    };
    var getTableFromCellRng = function (cellRng, isRoot) {
      return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
        return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
          return someIf(eq$2(startParentTable, endParentTable), startParentTable);
        });
      });
    };
    var isSingleCellTable = function (cellRng, isRoot) {
      return !isExpandedCellRng(cellRng) &amp;&amp; getTableFromCellRng(cellRng, isRoot).exists(function (table) {
        var rows = table.dom.rows;
        return rows.length === 1 &amp;&amp; rows[0].cells.length === 1;
      });
    };
    var getTableCells = function (table) {
      return descendants$1(table, 'td,th');
    };
    var getCellRng = function (rng, isRoot) {
      var startCell = getClosestCell(rng.startContainer, isRoot);
      var endCell = getClosestCell(rng.endContainer, isRoot);
      return lift2(startCell, endCell, tableCellRng);
    };
    var getCellRangeFromStartTable = function (cellRng, isRoot) {
      return getClosestTable(cellRng.start, isRoot).bind(function (table) {
        return last(getTableCells(table)).map(function (endCell) {
          return tableCellRng(cellRng.start, endCell);
        });
      });
    };
    var partialSelection = function (isRoot, rng) {
      var startCell = getClosestCell(rng.startContainer, isRoot);
      var endCell = getClosestCell(rng.endContainer, isRoot);
      return rng.collapsed ? Optional.none() : lift2(startCell, endCell, tableCellRng).fold(function () {
        return startCell.fold(function () {
          return endCell.bind(function (endCell) {
            return getClosestTable(endCell, isRoot).bind(function (table) {
              return head(getTableCells(table)).map(function (startCell) {
                return tableCellRng(startCell, endCell);
              });
            });
          });
        }, function (startCell) {
          return getClosestTable(startCell, isRoot).bind(function (table) {
            return last(getTableCells(table)).map(function (endCell) {
              return tableCellRng(startCell, endCell);
            });
          });
        });
      }, function (cellRng) {
        return isWithinSameTable(isRoot, cellRng) ? Optional.none() : getCellRangeFromStartTable(cellRng, isRoot);
      });
    };
    var isWithinSameTable = function (isRoot, cellRng) {
      return getTableFromCellRng(cellRng, isRoot).isSome();
    };
    var getTableSelectionFromCellRng = function (cellRng, isRoot) {
      return getTableFromCellRng(cellRng, isRoot).map(function (table) {
        return tableSelection(cellRng, table, getTableCells(table));
      });
    };
    var getTableSelection = function (optCellRng, rng, isRoot) {
      return optCellRng.filter(function (cellRng) {
        return isExpandedCellRng(cellRng) &amp;&amp; isWithinSameTable(isRoot, cellRng);
      }).orThunk(function () {
        return partialSelection(isRoot, rng);
      }).bind(function (cRng) {
        return getTableSelectionFromCellRng(cRng, isRoot);
      });
    };
    var getCellIndex = function (cells, cell) {
      return findIndex(cells, function (x) {
        return eq$2(x, cell);
      });
    };
    var getSelectedCells = function (tableSelection) {
      return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
        return tableSelection.cells.slice(startIndex, endIndex + 1);
      });
    };
    var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
      return optCellRng.filter(function (cellRng) {
        return isSingleCellTable(cellRng, isRoot) &amp;&amp; hasAllContentsSelected(cellRng.start, rng);
      }).map(function (cellRng) {
        return cellRng.start;
      });
    };
    var getAction = function (tableSelection) {
      return getSelectedCells(tableSelection).map(function (selected) {
        var cells = tableSelection.cells;
        return selected.length === cells.length ? deleteAction.removeTable(tableSelection.table) : deleteAction.emptyCells(selected);
      });
    };
    var getActionFromRange = function (root, rng) {
      var isRoot = isRootFromElement(root);
      var optCellRng = getCellRng(rng, isRoot);
      return isSingleCellTableContentSelected(optCellRng, rng, isRoot).map(function (cell) {
        return deleteAction.deleteCellSelection(rng, cell);
      }).orThunk(function () {
        return getTableSelection(optCellRng, rng, isRoot).bind(getAction);
      });
    };

    var freefallRtl = function (root) {
      var child = isComment(root) ? prevSibling(root) : lastChild(root);
      return child.bind(freefallRtl).orThunk(function () {
        return Optional.some(root);
      });
    };
    var emptyCells = function (editor, cells) {
      each(cells, fillWithPaddingBr);
      editor.selection.setCursorLocation(cells[0].dom, 0);
      return true;
    };
    var deleteCellContents = function (editor, rng, cell) {
      rng.deleteContents();
      var lastNode = freefallRtl(cell).getOr(cell);
      var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
      if (isEmpty(lastBlock)) {
        fillWithPaddingBr(lastBlock);
        editor.selection.setCursorLocation(lastBlock.dom, 0);
      }
      if (!eq$2(cell, lastBlock)) {
        var additionalCleanupNodes = parent(lastBlock).is(cell) ? [] : siblings(lastBlock);
        each(additionalCleanupNodes.concat(children(cell)), function (node) {
          if (!eq$2(node, lastBlock) &amp;&amp; !contains$2(node, lastBlock)) {
            remove(node);
          }
        });
      }
      return true;
    };
    var deleteTableElement = function (editor, table) {
      deleteElement(editor, false, table);
      return true;
    };
    var deleteCellRange = function (editor, rootElm, rng) {
      return getActionFromRange(rootElm, rng).map(function (action) {
        return action.fold(curry(deleteTableElement, editor), curry(emptyCells, editor), curry(deleteCellContents, editor));
      });
    };
    var deleteCaptionRange = function (editor, caption) {
      return emptyElement(editor, caption);
    };
    var deleteTableRange = function (editor, rootElm, rng, startElm) {
      return getParentCaption(rootElm, startElm).fold(function () {
        return deleteCellRange(editor, rootElm, rng);
      }, function (caption) {
        return deleteCaptionRange(editor, caption);
      }).getOr(false);
    };
    var deleteRange = function (editor, startElm) {
      var rootNode = SugarElement.fromDom(editor.getBody());
      var rng = editor.selection.getRng();
      var selectedCells = getCellsFromEditor(editor);
      return selectedCells.length !== 0 ? emptyCells(editor, selectedCells) : deleteTableRange(editor, rootNode, rng, startElm);
    };
    var getParentCell = function (rootElm, elm) {
      return find(parentsAndSelf(elm, rootElm), isTableCell$1);
    };
    var getParentCaption = function (rootElm, elm) {
      return find(parentsAndSelf(elm, rootElm), function (elm) {
        return name(elm) === 'caption';
      });
    };
    var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
      return navigate(forward, editor.getBody(), from).bind(function (to) {
        return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
          return eq$2(toCell, fromCell) === false;
        });
      });
    };
    var emptyElement = function (editor, elm) {
      fillWithPaddingBr(elm);
      editor.selection.setCursorLocation(elm.dom, 0);
      return Optional.some(true);
    };
    var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
      return firstPositionIn(fromCaption.dom).bind(function (first) {
        return lastPositionIn(fromCaption.dom).map(function (last) {
          return forward ? from.isEqual(first) &amp;&amp; to.isEqual(last) : from.isEqual(last) &amp;&amp; to.isEqual(first);
        });
      }).getOr(true);
    };
    var emptyCaretCaption = function (editor, elm) {
      return emptyElement(editor, elm);
    };
    var validateCaretCaption = function (rootElm, fromCaption, to) {
      return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
        return eq$2(toCaption, fromCaption) === false;
      });
    };
    var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
      return navigate(forward, editor.getBody(), from).bind(function (to) {
        return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
      }).or(Optional.some(true));
    };
    var deleteCaretCells = function (editor, forward, rootElm, startElm) {
      var from = CaretPosition.fromRangeStart(editor.selection.getRng());
      return getParentCell(rootElm, startElm).bind(function (fromCell) {
        return isEmpty(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
      }).getOr(false);
    };
    var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
      var from = CaretPosition.fromRangeStart(editor.selection.getRng());
      return isEmpty(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
    };
    var isNearTable = function (forward, pos) {
      return forward ? isBeforeTable(pos) : isAfterTable(pos);
    };
    var isBeforeOrAfterTable = function (editor, forward) {
      var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
      return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
        return isNearTable(forward, pos);
      });
    };
    var deleteCaret = function (editor, forward, startElm) {
      var rootElm = SugarElement.fromDom(editor.getBody());
      return getParentCaption(rootElm, startElm).fold(function () {
        return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
      }, function (fromCaption) {
        return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
      });
    };
    var backspaceDelete = function (editor, forward) {
      var startElm = SugarElement.fromDom(editor.selection.getStart(true));
      var cells = getCellsFromEditor(editor);
      return editor.selection.isCollapsed() &amp;&amp; cells.length === 0 ? deleteCaret(editor, forward, startElm) : deleteRange(editor, startElm);
    };

    var createRange$1 = function (sc, so, ec, eo) {
      var rng = document.createRange();
      rng.setStart(sc, so);
      rng.setEnd(ec, eo);
      return rng;
    };
    var normalizeBlockSelectionRange = function (rng) {
      var startPos = CaretPosition.fromRangeStart(rng);
      var endPos = CaretPosition.fromRangeEnd(rng);
      var rootNode = rng.commonAncestorContainer;
      return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
        if (!isInSameBlock(startPos, endPos, rootNode) &amp;&amp; isInSameBlock(startPos, newEndPos, rootNode)) {
          return createRange$1(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
        } else {
          return rng;
        }
      }).getOr(rng);
    };
    var normalize$2 = function (rng) {
      return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
    };

    var hasOnlyOneChild = function (node) {
      return node.firstChild &amp;&amp; node.firstChild === node.lastChild;
    };
    var isPaddingNode = function (node) {
      return node.name === 'br' || node.value === nbsp;
    };
    var isPaddedEmptyBlock = function (schema, node) {
      var blockElements = schema.getBlockElements();
      return blockElements[node.name] &amp;&amp; hasOnlyOneChild(node) &amp;&amp; isPaddingNode(node.firstChild);
    };
    var isEmptyFragmentElement = function (schema, node) {
      var nonEmptyElements = schema.getNonEmptyElements();
      return node &amp;&amp; (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
    };
    var isListFragment = function (schema, fragment) {
      var firstChild = fragment.firstChild;
      var lastChild = fragment.lastChild;
      if (firstChild &amp;&amp; firstChild.name === 'meta') {
        firstChild = firstChild.next;
      }
      if (lastChild &amp;&amp; lastChild.attr('id') === 'mce_marker') {
        lastChild = lastChild.prev;
      }
      if (isEmptyFragmentElement(schema, lastChild)) {
        lastChild = lastChild.prev;
      }
      if (!firstChild || firstChild !== lastChild) {
        return false;
      }
      return firstChild.name === 'ul' || firstChild.name === 'ol';
    };
    var cleanupDomFragment = function (domFragment) {
      var firstChild = domFragment.firstChild;
      var lastChild = domFragment.lastChild;
      if (firstChild &amp;&amp; firstChild.nodeName === 'META') {
        firstChild.parentNode.removeChild(firstChild);
      }
      if (lastChild &amp;&amp; lastChild.id === 'mce_marker') {
        lastChild.parentNode.removeChild(lastChild);
      }
      return domFragment;
    };
    var toDomFragment = function (dom, serializer, fragment) {
      var html = serializer.serialize(fragment);
      var domFragment = dom.createFragment(html);
      return cleanupDomFragment(domFragment);
    };
    var listItems$1 = function (elm) {
      return Tools.grep(elm.childNodes, function (child) {
        return child.nodeName === 'LI';
      });
    };
    var isPadding = function (node) {
      return node.data === nbsp || isBr(node);
    };
    var isListItemPadded = function (node) {
      return node &amp;&amp; node.firstChild &amp;&amp; node.firstChild === node.lastChild &amp;&amp; isPadding(node.firstChild);
    };
    var isEmptyOrPadded = function (elm) {
      return !elm.firstChild || isListItemPadded(elm);
    };
    var trimListItems = function (elms) {
      return elms.length &gt; 0 &amp;&amp; isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
    };
    var getParentLi = function (dom, node) {
      var parentBlock = dom.getParent(node, dom.isBlock);
      return parentBlock &amp;&amp; parentBlock.nodeName === 'LI' ? parentBlock : null;
    };
    var isParentBlockLi = function (dom, node) {
      return !!getParentLi(dom, node);
    };
    var getSplit = function (parentNode, rng) {
      var beforeRng = rng.cloneRange();
      var afterRng = rng.cloneRange();
      beforeRng.setStartBefore(parentNode);
      afterRng.setEndAfter(parentNode);
      return [
        beforeRng.cloneContents(),
        afterRng.cloneContents()
      ];
    };
    var findFirstIn = function (node, rootNode) {
      var caretPos = CaretPosition.before(node);
      var caretWalker = CaretWalker(rootNode);
      var newCaretPos = caretWalker.next(caretPos);
      return newCaretPos ? newCaretPos.toRange() : null;
    };
    var findLastOf = function (node, rootNode) {
      var caretPos = CaretPosition.after(node);
      var caretWalker = CaretWalker(rootNode);
      var newCaretPos = caretWalker.prev(caretPos);
      return newCaretPos ? newCaretPos.toRange() : null;
    };
    var insertMiddle = function (target, elms, rootNode, rng) {
      var parts = getSplit(target, rng);
      var parentElm = target.parentNode;
      parentElm.insertBefore(parts[0], target);
      Tools.each(elms, function (li) {
        parentElm.insertBefore(li, target);
      });
      parentElm.insertBefore(parts[1], target);
      parentElm.removeChild(target);
      return findLastOf(elms[elms.length - 1], rootNode);
    };
    var insertBefore = function (target, elms, rootNode) {
      var parentElm = target.parentNode;
      Tools.each(elms, function (elm) {
        parentElm.insertBefore(elm, target);
      });
      return findFirstIn(target, rootNode);
    };
    var insertAfter = function (target, elms, rootNode, dom) {
      dom.insertAfter(elms.reverse(), target);
      return findLastOf(elms[0], rootNode);
    };
    var insertAtCaret = function (serializer, dom, rng, fragment) {
      var domFragment = toDomFragment(dom, serializer, fragment);
      var liTarget = getParentLi(dom, rng.startContainer);
      var liElms = trimListItems(listItems$1(domFragment.firstChild));
      var BEGINNING = 1, END = 2;
      var rootNode = dom.getRoot();
      var isAt = function (location) {
        var caretPos = CaretPosition.fromRangeStart(rng);
        var caretWalker = CaretWalker(dom.getRoot());
        var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
        return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
      };
      if (isAt(BEGINNING)) {
        return insertBefore(liTarget, liElms, rootNode);
      } else if (isAt(END)) {
        return insertAfter(liTarget, liElms, rootNode, dom);
      }
      return insertMiddle(liTarget, liElms, rootNode, rng);
    };

    var trimOrPadLeftRight = function (dom, rng, html) {
      var root = SugarElement.fromDom(dom.getRoot());
      if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
        html = html.replace(/^ /, '&amp;nbsp;');
      } else {
        html = html.replace(/^&amp;nbsp;/, ' ');
      }
      if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
        html = html.replace(/(&amp;nbsp;| )(&lt;br( \/)&gt;)?$/, '&amp;nbsp;');
      } else {
        html = html.replace(/&amp;nbsp;(&lt;br( \/)?&gt;)?$/, ' ');
      }
      return html;
    };

    var isTableCell$4 = isTableCell;
    var isTableCellContentSelected = function (dom, rng, cell) {
      if (cell !== null) {
        var endCell = dom.getParent(rng.endContainer, isTableCell$4);
        return cell === endCell &amp;&amp; hasAllContentsSelected(SugarElement.fromDom(cell), rng);
      } else {
        return false;
      }
    };
    var validInsertion = function (editor, value, parentNode) {
      if (parentNode.getAttribute('data-mce-bogus') === 'all') {
        parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
      } else {
        var node = parentNode.firstChild;
        var node2 = parentNode.lastChild;
        if (!node || node === node2 &amp;&amp; node.nodeName === 'BR') {
          editor.dom.setHTML(parentNode, value);
        } else {
          editor.selection.setContent(value);
        }
      }
    };
    var trimBrsFromTableCell = function (dom, elm) {
      Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
    };
    var reduceInlineTextElements = function (editor, merge) {
      var textInlineElements = editor.schema.getTextInlineElements();
      var dom = editor.dom;
      if (merge) {
        var root_1 = editor.getBody();
        var elementUtils_1 = ElementUtils(dom);
        Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
          var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
          if (isInline &amp;&amp; hasInheritableStyles(dom, node)) {
            for (var parentNode = node.parentNode; isNonNullable(parentNode) &amp;&amp; parentNode !== root_1; parentNode = parentNode.parentNode) {
              var styleConflict = hasStyleConflict(dom, node, parentNode);
              if (styleConflict) {
                break;
              }
              if (elementUtils_1.compare(parentNode, node)) {
                dom.remove(node, true);
                break;
              }
            }
          }
        });
      }
    };
    var markFragmentElements = function (fragment) {
      var node = fragment;
      while (node = node.walk()) {
        if (node.type === 1) {
          node.attr('data-mce-fragment', '1');
        }
      }
    };
    var unmarkFragmentElements = function (elm) {
      Tools.each(elm.getElementsByTagName('*'), function (elm) {
        elm.removeAttribute('data-mce-fragment');
      });
    };
    var isPartOfFragment = function (node) {
      return !!node.getAttribute('data-mce-fragment');
    };
    var canHaveChildren = function (editor, node) {
      return node &amp;&amp; !editor.schema.getShortEndedElements()[node.nodeName];
    };
    var moveSelectionToMarker = function (editor, marker) {
      var nextRng;
      var dom = editor.dom, selection = editor.selection;
      var node2;
      var getContentEditableFalseParent = function (node) {
        var root = editor.getBody();
        for (; node &amp;&amp; node !== root; node = node.parentNode) {
          if (dom.getContentEditable(node) === 'false') {
            return node;
          }
        }
        return null;
      };
      if (!marker) {
        return;
      }
      selection.scrollIntoView(marker);
      var parentEditableFalseElm = getContentEditableFalseParent(marker);
      if (parentEditableFalseElm) {
        dom.remove(marker);
        selection.select(parentEditableFalseElm);
        return;
      }
      var rng = dom.createRng();
      var node = marker.previousSibling;
      if (node &amp;&amp; node.nodeType === 3) {
        rng.setStart(node, node.nodeValue.length);
        if (!Env.ie) {
          node2 = marker.nextSibling;
          if (node2 &amp;&amp; node2.nodeType === 3) {
            node.appendData(node2.data);
            node2.parentNode.removeChild(node2);
          }
        }
      } else {
        rng.setStartBefore(marker);
        rng.setEndBefore(marker);
      }
      var findNextCaretRng = function (rng) {
        var caretPos = CaretPosition.fromRangeStart(rng);
        var caretWalker = CaretWalker(editor.getBody());
        caretPos = caretWalker.next(caretPos);
        if (caretPos) {
          return caretPos.toRange();
        }
      };
      var parentBlock = dom.getParent(marker, dom.isBlock);
      dom.remove(marker);
      if (parentBlock &amp;&amp; dom.isEmpty(parentBlock)) {
        editor.$(parentBlock).empty();
        rng.setStart(parentBlock, 0);
        rng.setEnd(parentBlock, 0);
        if (!isTableCell$4(parentBlock) &amp;&amp; !isPartOfFragment(parentBlock) &amp;&amp; (nextRng = findNextCaretRng(rng))) {
          rng = nextRng;
          dom.remove(parentBlock);
        } else {
          dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
        }
      }
      selection.setRng(rng);
    };
    var deleteSelectedContent = function (editor) {
      var dom = editor.dom;
      var rng = normalize$2(editor.selection.getRng());
      editor.selection.setRng(rng);
      var startCell = dom.getParent(rng.startContainer, isTableCell$4);
      if (isTableCellContentSelected(dom, rng, startCell)) {
        deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
      } else {
        editor.getDoc().execCommand('Delete', false, null);
      }
    };
    var insertHtmlAtCaret = function (editor, value, details) {
      var parentNode, rootNode, args;
      var marker, rng, node;
      var selection = editor.selection, dom = editor.dom;
      if (/^ | $/.test(value)) {
        value = trimOrPadLeftRight(dom, selection.getRng(), value);
      }
      var parser = editor.parser;
      var merge = details.merge;
      var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
      var bookmarkHtml = '&lt;span id="mce_marker" data-mce-type="bookmark"&gt;&amp;#xFEFF;&lt;/span&gt;';
      args = {
        content: value,
        format: 'html',
        selection: true,
        paste: details.paste
      };
      args = editor.fire('BeforeSetContent', args);
      if (args.isDefaultPrevented()) {
        editor.fire('SetContent', {
          content: args.content,
          format: 'html',
          selection: true,
          paste: details.paste
        });
        return;
      }
      value = args.content;
      if (value.indexOf('{$caret}') === -1) {
        value += '{$caret}';
      }
      value = value.replace(/\{\$caret\}/, bookmarkHtml);
      rng = selection.getRng();
      var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
      var body = editor.getBody();
      if (caretElement === body &amp;&amp; selection.isCollapsed()) {
        if (dom.isBlock(body.firstChild) &amp;&amp; canHaveChildren(editor, body.firstChild) &amp;&amp; dom.isEmpty(body.firstChild)) {
          rng = dom.createRng();
          rng.setStart(body.firstChild, 0);
          rng.setEnd(body.firstChild, 0);
          selection.setRng(rng);
        }
      }
      if (!selection.isCollapsed()) {
        deleteSelectedContent(editor);
      }
      parentNode = selection.getNode();
      var parserArgs = {
        context: parentNode.nodeName.toLowerCase(),
        data: details.data,
        insert: true
      };
      var fragment = parser.parse(value, parserArgs);
      if (details.paste === true &amp;&amp; isListFragment(editor.schema, fragment) &amp;&amp; isParentBlockLi(dom, parentNode)) {
        rng = insertAtCaret(serializer, dom, selection.getRng(), fragment);
        selection.setRng(rng);
        editor.fire('SetContent', args);
        return;
      }
      markFragmentElements(fragment);
      node = fragment.lastChild;
      if (node.attr('id') === 'mce_marker') {
        marker = node;
        for (node = node.prev; node; node = node.walk(true)) {
          if (node.type === 3 || !dom.isBlock(node.name)) {
            if (editor.schema.isValidChild(node.parent.name, 'span')) {
              node.parent.insert(marker, node, node.name === 'br');
            }
            break;
          }
        }
      }
      editor._selectionOverrides.showBlockCaretContainer(parentNode);
      if (!parserArgs.invalid) {
        value = serializer.serialize(fragment);
        validInsertion(editor, value, parentNode);
      } else {
        editor.selection.setContent(bookmarkHtml);
        parentNode = selection.getNode();
        rootNode = editor.getBody();
        if (parentNode.nodeType === 9) {
          parentNode = node = rootNode;
        } else {
          node = parentNode;
        }
        while (node !== rootNode) {
          parentNode = node;
          node = node.parentNode;
        }
        value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
        value = serializer.serialize(parser.parse(value.replace(/&lt;span (id="mce_marker"|id=mce_marker).+?&lt;\/span&gt;/i, function () {
          return serializer.serialize(fragment);
        })));
        if (parentNode === rootNode) {
          dom.setHTML(rootNode, value);
        } else {
          dom.setOuterHTML(parentNode, value);
        }
      }
      reduceInlineTextElements(editor, merge);
      moveSelectionToMarker(editor, dom.get('mce_marker'));
      unmarkFragmentElements(editor.getBody());
      trimBrsFromTableCell(dom, selection.getStart());
      editor.fire('SetContent', args);
      editor.addVisual();
    };

    var traverse = function (node, fn) {
      fn(node);
      if (node.firstChild) {
        traverse(node.firstChild, fn);
      }
      if (node.next) {
        traverse(node.next, fn);
      }
    };
    var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
      var nodeMatches = {};
      var attrMatches = {};
      var matches = [];
      if (node.firstChild) {
        traverse(node.firstChild, function (node) {
          each(nodeFilters, function (filter) {
            if (filter.name === node.name) {
              if (nodeMatches[filter.name]) {
                nodeMatches[filter.name].nodes.push(node);
              } else {
                nodeMatches[filter.name] = {
                  filter: filter,
                  nodes: [node]
                };
              }
            }
          });
          each(attributeFilters, function (filter) {
            if (typeof node.attr(filter.name) === 'string') {
              if (attrMatches[filter.name]) {
                attrMatches[filter.name].nodes.push(node);
              } else {
                attrMatches[filter.name] = {
                  filter: filter,
                  nodes: [node]
                };
              }
            }
          });
        });
      }
      for (var name_1 in nodeMatches) {
        if (nodeMatches.hasOwnProperty(name_1)) {
          matches.push(nodeMatches[name_1]);
        }
      }
      for (var name_2 in attrMatches) {
        if (attrMatches.hasOwnProperty(name_2)) {
          matches.push(attrMatches[name_2]);
        }
      }
      return matches;
    };
    var filter$3 = function (nodeFilters, attributeFilters, node) {
      var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
      each(matches, function (match) {
        each(match.filter.callbacks, function (callback) {
          callback(match.nodes, match.filter.name, {});
        });
      });
    };

    var defaultFormat = 'html';
    var isTreeNode = function (content) {
      return content instanceof AstNode;
    };
    var moveSelection = function (editor) {
      if (hasFocus$1(editor)) {
        firstPositionIn(editor.getBody()).each(function (pos) {
          var node = pos.getNode();
          var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos;
          editor.selection.setRng(caretPos.toRange());
        });
      }
    };
    var setEditorHtml = function (editor, html) {
      editor.dom.setHTML(editor.getBody(), html);
      moveSelection(editor);
    };
    var setContentString = function (editor, body, content, args) {
      var forcedRootBlockName, padd;
      if (content.length === 0 || /^\s+$/.test(content)) {
        padd = '&lt;br data-mce-bogus="1"&gt;';
        if (body.nodeName === 'TABLE') {
          content = '&lt;tr&gt;&lt;td&gt;' + padd + '&lt;/td&gt;&lt;/tr&gt;';
        } else if (/^(UL|OL)$/.test(body.nodeName)) {
          content = '&lt;li&gt;' + padd + '&lt;/li&gt;';
        }
        forcedRootBlockName = getForcedRootBlock(editor);
        if (forcedRootBlockName &amp;&amp; editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
          content = padd;
          content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
        } else if (!content) {
          content = '&lt;br data-mce-bogus="1"&gt;';
        }
        setEditorHtml(editor, content);
        editor.fire('SetContent', args);
      } else {
        if (args.format !== 'raw') {
          content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
            isRootContent: true,
            insert: true
          }));
        }
        args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
        setEditorHtml(editor, args.content);
        if (!args.no_events) {
          editor.fire('SetContent', args);
        }
      }
      return args.content;
    };
    var setContentTree = function (editor, body, content, args) {
      filter$3(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
      var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
      args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
      setEditorHtml(editor, args.content);
      if (!args.no_events) {
        editor.fire('SetContent', args);
      }
      return content;
    };
    var setContentInternal = function (editor, content, args) {
      args.format = args.format ? args.format : defaultFormat;
      args.set = true;
      args.content = isTreeNode(content) ? '' : content;
      if (!args.no_events) {
        editor.fire('BeforeSetContent', args);
      }
      if (!isTreeNode(content)) {
        content = args.content;
      }
      return Optional.from(editor.getBody()).fold(constant(content), function (body) {
        return isTreeNode(content) ? setContentTree(editor, body, content, args) : setContentString(editor, body, content, args);
      });
    };

    var sibling$2 = function (scope, predicate) {
      return sibling(scope, predicate).isSome();
    };

    var ensureIsRoot = function (isRoot) {
      return isFunction(isRoot) ? isRoot : never;
    };
    var ancestor$3 = function (scope, transform, isRoot) {
      var element = scope.dom;
      var stop = ensureIsRoot(isRoot);
      while (element.parentNode) {
        element = element.parentNode;
        var el = SugarElement.fromDom(element);
        var transformed = transform(el);
        if (transformed.isSome()) {
          return transformed;
        } else if (stop(el)) {
          break;
        }
      }
      return Optional.none();
    };
    var closest$2 = function (scope, transform, isRoot) {
      var current = transform(scope);
      var stop = ensureIsRoot(isRoot);
      return current.orThunk(function () {
        return stop(scope) ? Optional.none() : ancestor$3(scope, transform, stop);
      });
    };

    var isEq$2 = isEq;
    var matchesUnInheritedFormatSelector = function (ed, node, name) {
      var formatList = ed.formatter.get(name);
      if (formatList) {
        for (var i = 0; i &lt; formatList.length; i++) {
          if (formatList[i].inherit === false &amp;&amp; ed.dom.is(node, formatList[i].selector)) {
            return true;
          }
        }
      }
      return false;
    };
    var matchParents = function (editor, node, name, vars) {
      var root = editor.dom.getRoot();
      if (node === root) {
        return false;
      }
      node = editor.dom.getParent(node, function (node) {
        if (matchesUnInheritedFormatSelector(editor, node, name)) {
          return true;
        }
        return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
      });
      return matchNode(editor, node, name, vars);
    };
    var matchName = function (dom, node, format) {
      if (isEq$2(node, format.inline)) {
        return true;
      }
      if (isEq$2(node, format.block)) {
        return true;
      }
      if (format.selector) {
        return node.nodeType === 1 &amp;&amp; dom.is(node, format.selector);
      }
    };
    var matchItems = function (dom, node, format, itemName, similar, vars) {
      var key, value;
      var items = format[itemName];
      var i;
      if (format.onmatch) {
        return format.onmatch(node, format, itemName);
      }
      if (items) {
        if (typeof items.length === 'undefined') {
          for (key in items) {
            if (items.hasOwnProperty(key)) {
              if (itemName === 'attributes') {
                value = dom.getAttrib(node, key);
              } else {
                value = getStyle(dom, node, key);
              }
              if (similar &amp;&amp; !value &amp;&amp; !format.exact) {
                return;
              }
              if ((!similar || format.exact) &amp;&amp; !isEq$2(value, normalizeStyleValue(dom, replaceVars(items[key], vars), key))) {
                return;
              }
            }
          }
        } else {
          for (i = 0; i &lt; items.length; i++) {
            if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
              return format;
            }
          }
        }
      }
      return format;
    };
    var matchNode = function (ed, node, name, vars, similar) {
      var formatList = ed.formatter.get(name);
      var format, i, x, classes;
      var dom = ed.dom;
      if (formatList &amp;&amp; node) {
        for (i = 0; i &lt; formatList.length; i++) {
          format = formatList[i];
          if (matchName(ed.dom, node, format) &amp;&amp; matchItems(dom, node, format, 'attributes', similar, vars) &amp;&amp; matchItems(dom, node, format, 'styles', similar, vars)) {
            if (classes = format.classes) {
              for (x = 0; x &lt; classes.length; x++) {
                if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
                  return;
                }
              }
            }
            return format;
          }
        }
      }
    };
    var match = function (editor, name, vars, node) {
      if (node) {
        return matchParents(editor, node, name, vars);
      }
      node = editor.selection.getNode();
      if (matchParents(editor, node, name, vars)) {
        return true;
      }
      var startNode = editor.selection.getStart();
      if (startNode !== node) {
        if (matchParents(editor, startNode, name, vars)) {
          return true;
        }
      }
      return false;
    };
    var matchAll = function (editor, names, vars) {
      var matchedFormatNames = [];
      var checkedMap = {};
      var startElement = editor.selection.getStart();
      editor.dom.getParent(startElement, function (node) {
        for (var i = 0; i &lt; names.length; i++) {
          var name_1 = names[i];
          if (!checkedMap[name_1] &amp;&amp; matchNode(editor, node, name_1, vars)) {
            checkedMap[name_1] = true;
            matchedFormatNames.push(name_1);
          }
        }
      }, editor.dom.getRoot());
      return matchedFormatNames;
    };
    var closest$3 = function (editor, names) {
      var isRoot = function (elm) {
        return eq$2(elm, SugarElement.fromDom(editor.getBody()));
      };
      var match = function (elm, name) {
        return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
      };
      return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
        return closest$2(SugarElement.fromDom(rawElm), function (elm) {
          return findMap(names, function (name) {
            return match(elm, name);
          });
        }, isRoot);
      }).getOrNull();
    };
    var canApply = function (editor, name) {
      var formatList = editor.formatter.get(name);
      var startNode, parents, i, x, selector;
      var dom = editor.dom;
      if (formatList) {
        startNode = editor.selection.getStart();
        parents = getParents$1(dom, startNode);
        for (x = formatList.length - 1; x &gt;= 0; x--) {
          selector = formatList[x].selector;
          if (!selector || formatList[x].defaultBlock) {
            return true;
          }
          for (i = parents.length - 1; i &gt;= 0; i--) {
            if (dom.is(parents[i], selector)) {
              return true;
            }
          }
        }
      }
      return false;
    };
    var matchAllOnNode = function (editor, node, formatNames) {
      return foldl(formatNames, function (acc, name) {
        var matchSimilar = isVariableFormatName(editor, name);
        if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
          return acc.concat([name]);
        } else {
          return acc;
        }
      }, []);
    };

    var ZWSP$1 = ZWSP, CARET_ID$1 = '_mce_caret';
    var importNode = function (ownerDocument, node) {
      return ownerDocument.importNode(node, true);
    };
    var getEmptyCaretContainers = function (node) {
      var nodes = [];
      while (node) {
        if (node.nodeType === 3 &amp;&amp; node.nodeValue !== ZWSP$1 || node.childNodes.length &gt; 1) {
          return [];
        }
        if (node.nodeType === 1) {
          nodes.push(node);
        }
        node = node.firstChild;
      }
      return nodes;
    };
    var isCaretContainerEmpty = function (node) {
      return getEmptyCaretContainers(node).length &gt; 0;
    };
    var findFirstTextNode = function (node) {
      if (node) {
        var walker = new DomTreeWalker(node, node);
        for (node = walker.current(); node; node = walker.next()) {
          if (isText$1(node)) {
            return node;
          }
        }
      }
      return null;
    };
    var createCaretContainer = function (fill) {
      var caretContainer = SugarElement.fromTag('span');
      setAll(caretContainer, {
        'id': CARET_ID$1,
        'data-mce-bogus': '1',
        'data-mce-type': 'format-caret'
      });
      if (fill) {
        append(caretContainer, SugarElement.fromText(ZWSP$1));
      }
      return caretContainer;
    };
    var trimZwspFromCaretContainer = function (caretContainerNode) {
      var textNode = findFirstTextNode(caretContainerNode);
      if (textNode &amp;&amp; textNode.nodeValue.charAt(0) === ZWSP$1) {
        textNode.deleteData(0, 1);
      }
      return textNode;
    };
    var removeCaretContainerNode = function (editor, node, moveCaret) {
      if (moveCaret === void 0) {
        moveCaret = true;
      }
      var dom = editor.dom, selection = editor.selection;
      if (isCaretContainerEmpty(node)) {
        deleteElement(editor, false, SugarElement.fromDom(node), moveCaret);
      } else {
        var rng = selection.getRng();
        var block = dom.getParent(node, dom.isBlock);
        var startContainer = rng.startContainer;
        var startOffset = rng.startOffset;
        var endContainer = rng.endContainer;
        var endOffset = rng.endOffset;
        var textNode = trimZwspFromCaretContainer(node);
        dom.remove(node, true);
        if (startContainer === textNode &amp;&amp; startOffset &gt; 0) {
          rng.setStart(textNode, startOffset - 1);
        }
        if (endContainer === textNode &amp;&amp; endOffset &gt; 0) {
          rng.setEnd(textNode, endOffset - 1);
        }
        if (block &amp;&amp; dom.isEmpty(block)) {
          fillWithPaddingBr(SugarElement.fromDom(block));
        }
        selection.setRng(rng);
      }
    };
    var removeCaretContainer = function (editor, node, moveCaret) {
      if (moveCaret === void 0) {
        moveCaret = true;
      }
      var dom = editor.dom, selection = editor.selection;
      if (!node) {
        node = getParentCaretContainer(editor.getBody(), selection.getStart());
        if (!node) {
          while (node = dom.get(CARET_ID$1)) {
            removeCaretContainerNode(editor, node, false);
          }
        }
      } else {
        removeCaretContainerNode(editor, node, moveCaret);
      }
    };
    var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
      var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
      if (block &amp;&amp; dom.isEmpty(block)) {
        formatNode.parentNode.replaceChild(caretContainer, formatNode);
      } else {
        removeTrailingBr(SugarElement.fromDom(formatNode));
        if (dom.isEmpty(formatNode)) {
          formatNode.parentNode.replaceChild(caretContainer, formatNode);
        } else {
          dom.insertAfter(caretContainer, formatNode);
        }
      }
    };
    var appendNode = function (parentNode, node) {
      parentNode.appendChild(node);
      return node;
    };
    var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
      var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
        return appendNode(parentNode, formatNode.cloneNode(false));
      }, caretContainer);
      return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP$1));
    };
    var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
      var formatter = editor.formatter;
      var dom = editor.dom;
      var validFormats = filter(keys(formatter.get()), function (formatName) {
        return formatName !== name &amp;&amp; !contains$1(formatName, 'removeformat');
      });
      var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
      var uniqueFormats = filter(matchedFormats, function (fmtName) {
        return !areSimilarFormats(editor, fmtName, name);
      });
      if (uniqueFormats.length &gt; 0) {
        var clonedFormatNode = formatNode.cloneNode(false);
        dom.add(caretContainer, clonedFormatNode);
        formatter.remove(name, vars, clonedFormatNode, similar);
        dom.remove(clonedFormatNode);
        return Optional.some(clonedFormatNode);
      } else {
        return Optional.none();
      }
    };
    var applyCaretFormat = function (editor, name, vars) {
      var caretContainer, textNode;
      var selection = editor.selection;
      var selectionRng = selection.getRng();
      var offset = selectionRng.startOffset;
      var container = selectionRng.startContainer;
      var text = container.nodeValue;
      caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
      if (caretContainer) {
        textNode = findFirstTextNode(caretContainer);
      }
      var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
      if (text &amp;&amp; offset &gt; 0 &amp;&amp; offset &lt; text.length &amp;&amp; wordcharRegex.test(text.charAt(offset)) &amp;&amp; wordcharRegex.test(text.charAt(offset - 1))) {
        var bookmark = selection.getBookmark();
        selectionRng.collapse(true);
        var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
        rng = split$1(rng);
        editor.formatter.apply(name, vars, rng);
        selection.moveToBookmark(bookmark);
      } else {
        if (!caretContainer || textNode.nodeValue !== ZWSP$1) {
          caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
          textNode = caretContainer.firstChild;
          selectionRng.insertNode(caretContainer);
          offset = 1;
          editor.formatter.apply(name, vars, caretContainer);
        } else {
          editor.formatter.apply(name, vars, caretContainer);
        }
        selection.setCursorLocation(textNode, offset);
      }
    };
    var removeCaretFormat = function (editor, name, vars, similar) {
      var dom = editor.dom;
      var selection = editor.selection;
      var hasContentAfter, node, formatNode;
      var parents = [];
      var rng = selection.getRng();
      var container = rng.startContainer;
      var offset = rng.startOffset;
      node = container;
      if (container.nodeType === 3) {
        if (offset !== container.nodeValue.length) {
          hasContentAfter = true;
        }
        node = node.parentNode;
      }
      while (node) {
        if (matchNode(editor, node, name, vars, similar)) {
          formatNode = node;
          break;
        }
        if (node.nextSibling) {
          hasContentAfter = true;
        }
        parents.push(node);
        node = node.parentNode;
      }
      if (!formatNode) {
        return;
      }
      if (hasContentAfter) {
        var bookmark = selection.getBookmark();
        rng.collapse(true);
        var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
        expandedRng = split$1(expandedRng);
        editor.formatter.remove(name, vars, expandedRng, similar);
        selection.moveToBookmark(bookmark);
      } else {
        var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
        var newCaretContainer = createCaretContainer(false).dom;
        insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
        var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
        var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
        removeCaretContainerNode(editor, caretContainer, false);
        selection.setCursorLocation(caretTextNode, 1);
        if (dom.isEmpty(formatNode)) {
          dom.remove(formatNode);
        }
      }
    };
    var disableCaretContainer = function (editor, keyCode) {
      var selection = editor.selection, body = editor.getBody();
      removeCaretContainer(editor, null, false);
      if ((keyCode === 8 || keyCode === 46) &amp;&amp; selection.isCollapsed() &amp;&amp; selection.getStart().innerHTML === ZWSP$1) {
        removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
      }
      if (keyCode === 37 || keyCode === 39) {
        removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
      }
    };
    var setup$3 = function (editor) {
      editor.on('mouseup keydown', function (e) {
        disableCaretContainer(editor, e.keyCode);
      });
    };
    var replaceWithCaretFormat = function (targetNode, formatNodes) {
      var caretContainer = createCaretContainer(false);
      var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
      before(SugarElement.fromDom(targetNode), caretContainer);
      remove(SugarElement.fromDom(targetNode));
      return CaretPosition(innerMost, 0);
    };
    var isFormatElement = function (editor, element) {
      var inlineElements = editor.schema.getTextInlineElements();
      return inlineElements.hasOwnProperty(name(element)) &amp;&amp; !isCaretNode(element.dom) &amp;&amp; !isBogus(element.dom);
    };
    var isEmptyCaretFormatElement = function (element) {
      return isCaretNode(element.dom) &amp;&amp; isCaretContainerEmpty(element.dom);
    };

    var postProcessHooks = {};
    var filter$4 = filter$2;
    var each$8 = each$2;
    var addPostProcessHook = function (name, hook) {
      var hooks = postProcessHooks[name];
      if (!hooks) {
        postProcessHooks[name] = [];
      }
      postProcessHooks[name].push(hook);
    };
    var postProcess = function (name, editor) {
      each$8(postProcessHooks[name], function (hook) {
        hook(editor);
      });
    };
    addPostProcessHook('pre', function (editor) {
      var rng = editor.selection.getRng();
      var blocks;
      var hasPreSibling = function (pre) {
        return isPre(pre.previousSibling) &amp;&amp; indexOf$1(blocks, pre.previousSibling) !== -1;
      };
      var joinPre = function (pre1, pre2) {
        DomQuery(pre2).remove();
        DomQuery(pre1).append('&lt;br&gt;&lt;br&gt;').append(pre2.childNodes);
      };
      var isPre = matchNodeNames(['pre']);
      if (!rng.collapsed) {
        blocks = editor.selection.getSelectedBlocks();
        each$8(filter$4(filter$4(blocks, isPre), hasPreSibling), function (pre) {
          joinPre(pre.previousSibling, pre);
        });
      }
    });

    var each$9 = Tools.each;
    var isElementNode = function (node) {
      return isElement$1(node) &amp;&amp; !isBookmarkNode$1(node) &amp;&amp; !isCaretNode(node) &amp;&amp; !isBogus(node);
    };
    var findElementSibling = function (node, siblingName) {
      var sibling;
      for (sibling = node; sibling; sibling = sibling[siblingName]) {
        if (isText$1(sibling) &amp;&amp; sibling.nodeValue.length !== 0) {
          return node;
        }
        if (isElement$1(sibling) &amp;&amp; !isBookmarkNode$1(sibling)) {
          return sibling;
        }
      }
      return node;
    };
    var mergeSiblingsNodes = function (dom, prev, next) {
      var sibling, tmpSibling;
      var elementUtils = ElementUtils(dom);
      if (prev &amp;&amp; next) {
        prev = findElementSibling(prev, 'previousSibling');
        next = findElementSibling(next, 'nextSibling');
        if (elementUtils.compare(prev, next)) {
          for (sibling = prev.nextSibling; sibling &amp;&amp; sibling !== next;) {
            tmpSibling = sibling;
            sibling = sibling.nextSibling;
            prev.appendChild(tmpSibling);
          }
          dom.remove(next);
          Tools.each(Tools.grep(next.childNodes), function (node) {
            prev.appendChild(node);
          });
          return prev;
        }
      }
      return next;
    };
    var mergeSiblings = function (dom, format, vars, node) {
      if (node &amp;&amp; format.merge_siblings !== false) {
        var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
        mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
      }
    };
    var clearChildStyles = function (dom, format, node) {
      if (format.clear_child_styles) {
        var selector = format.links ? '*:not(a)' : '*';
        each$9(dom.select(selector, node), function (node) {
          if (isElementNode(node)) {
            each$9(format.styles, function (value, name) {
              dom.setStyle(node, name, '');
            });
          }
        });
      }
    };
    var processChildElements = function (node, filter, process) {
      each$9(node.childNodes, function (node) {
        if (isElementNode(node)) {
          if (filter(node)) {
            process(node);
          }
          if (node.hasChildNodes()) {
            processChildElements(node, filter, process);
          }
        }
      });
    };
    var unwrapEmptySpan = function (dom, node) {
      if (node.nodeName === 'SPAN' &amp;&amp; dom.getAttribs(node).length === 0) {
        dom.remove(node, true);
      }
    };
    var hasStyle = function (dom, name) {
      return function (node) {
        return !!(node &amp;&amp; getStyle(dom, node, name));
      };
    };
    var applyStyle = function (dom, name, value) {
      return function (node) {
        dom.setStyle(node, name, value);
        if (node.getAttribute('style') === '') {
          node.removeAttribute('style');
        }
        unwrapEmptySpan(dom, node);
      };
    };

    var removeResult = Adt.generate([
      { keep: [] },
      { rename: ['name'] },
      { removed: [] }
    ]);
    var MCE_ATTR_RE = /^(src|href|style)$/;
    var each$a = Tools.each;
    var isEq$3 = isEq;
    var isTableCellOrRow = function (node) {
      return /^(TR|TH|TD)$/.test(node.nodeName);
    };
    var isChildOfInlineParent = function (dom, node, parent) {
      return dom.isChildOf(node, parent) &amp;&amp; node !== parent &amp;&amp; !dom.isBlock(parent);
    };
    var getContainer = function (ed, rng, start) {
      var container, offset;
      container = rng[start ? 'startContainer' : 'endContainer'];
      offset = rng[start ? 'startOffset' : 'endOffset'];
      if (isElement$1(container)) {
        var lastIdx = container.childNodes.length - 1;
        if (!start &amp;&amp; offset) {
          offset--;
        }
        container = container.childNodes[offset &gt; lastIdx ? lastIdx : offset];
      }
      if (isText$1(container) &amp;&amp; start &amp;&amp; offset &gt;= container.nodeValue.length) {
        container = new DomTreeWalker(container, ed.getBody()).next() || container;
      }
      if (isText$1(container) &amp;&amp; !start &amp;&amp; offset === 0) {
        container = new DomTreeWalker(container, ed.getBody()).prev() || container;
      }
      return container;
    };
    var normalizeTableSelection = function (node, start) {
      var prop = start ? 'firstChild' : 'lastChild';
      if (isTableCellOrRow(node) &amp;&amp; node[prop]) {
        var childNode = node[prop];
        if (node.nodeName === 'TR') {
          return childNode[prop] || childNode;
        } else {
          return childNode;
        }
      }
      return node;
    };
    var wrap$2 = function (dom, node, name, attrs) {
      var wrapper = dom.create(name, attrs);
      node.parentNode.insertBefore(wrapper, node);
      wrapper.appendChild(node);
      return wrapper;
    };
    var wrapWithSiblings = function (dom, node, next, name, attrs) {
      var start = SugarElement.fromDom(node);
      var wrapper = SugarElement.fromDom(dom.create(name, attrs));
      var siblings = next ? nextSiblings(start) : prevSiblings(start);
      append$1(wrapper, siblings);
      if (next) {
        before(start, wrapper);
        prepend(wrapper, start);
      } else {
        after(start, wrapper);
        append(wrapper, start);
      }
      return wrapper.dom;
    };
    var matchName$1 = function (dom, node, format) {
      if (isEq$3(node, format.inline)) {
        return true;
      }
      if (isEq$3(node, format.block)) {
        return true;
      }
      if (format.selector) {
        return isElement$1(node) &amp;&amp; dom.is(node, format.selector);
      }
    };
    var isColorFormatAndAnchor = function (node, format) {
      return format.links &amp;&amp; node.nodeName === 'A';
    };
    var find$3 = function (dom, node, next, inc) {
      node = getNonWhiteSpaceSibling(node, next, inc);
      return !node || (node.nodeName === 'BR' || dom.isBlock(node));
    };
    var removeNode$1 = function (ed, node, format) {
      var parentNode = node.parentNode;
      var rootBlockElm;
      var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
      if (format.block) {
        if (!forcedRootBlock) {
          if (dom.isBlock(node) &amp;&amp; !dom.isBlock(parentNode)) {
            if (!find$3(dom, node, false) &amp;&amp; !find$3(dom, node.firstChild, true, true)) {
              node.insertBefore(dom.create('br'), node.firstChild);
            }
            if (!find$3(dom, node, true) &amp;&amp; !find$3(dom, node.lastChild, false, true)) {
              node.appendChild(dom.create('br'));
            }
          }
        } else {
          if (parentNode === dom.getRoot()) {
            if (!format.list_block || !isEq$3(node, format.list_block)) {
              each(from$1(node.childNodes), function (node) {
                if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
                  if (!rootBlockElm) {
                    rootBlockElm = wrap$2(dom, node, forcedRootBlock);
                    dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
                  } else {
                    rootBlockElm.appendChild(node);
                  }
                } else {
                  rootBlockElm = 0;
                }
              });
            }
          }
        }
      }
      if (format.selector &amp;&amp; format.inline &amp;&amp; !isEq$3(format.inline, node)) {
        return;
      }
      dom.remove(node, true);
    };
    var removeFormatInternal = function (ed, format, vars, node, compareNode) {
      var stylesModified;
      var dom = ed.dom;
      if (!matchName$1(dom, node, format) &amp;&amp; !isColorFormatAndAnchor(node, format)) {
        return removeResult.keep();
      }
      var elm = node;
      if (format.inline &amp;&amp; format.remove === 'all' &amp;&amp; isArray(format.preserve_attributes)) {
        var attrsToPreserve = filter(dom.getAttribs(elm), function (attr) {
          return contains(format.preserve_attributes, attr.name.toLowerCase());
        });
        dom.removeAllAttribs(elm);
        each(attrsToPreserve, function (attr) {
          return dom.setAttrib(elm, attr.name, attr.value);
        });
        if (attrsToPreserve.length &gt; 0) {
          return removeResult.rename('span');
        }
      }
      if (format.remove !== 'all') {
        each$a(format.styles, function (value, name) {
          value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
          if (isNumber(name)) {
            name = value;
            compareNode = null;
          }
          if (format.remove_similar || (!compareNode || isEq$3(getStyle(dom, compareNode, name), value))) {
            dom.setStyle(elm, name, '');
          }
          stylesModified = true;
        });
        if (stylesModified &amp;&amp; dom.getAttrib(elm, 'style') === '') {
          elm.removeAttribute('style');
          elm.removeAttribute('data-mce-style');
        }
        each$a(format.attributes, function (value, name) {
          var valueOut;
          value = replaceVars(value, vars);
          if (isNumber(name)) {
            name = value;
            compareNode = null;
          }
          if (format.remove_similar || (!compareNode || isEq$3(dom.getAttrib(compareNode, name), value))) {
            if (name === 'class') {
              value = dom.getAttrib(elm, name);
              if (value) {
                valueOut = '';
                each(value.split(/\s+/), function (cls) {
                  if (/mce\-\w+/.test(cls)) {
                    valueOut += (valueOut ? ' ' : '') + cls;
                  }
                });
                if (valueOut) {
                  dom.setAttrib(elm, name, valueOut);
                  return;
                }
              }
            }
            if (MCE_ATTR_RE.test(name)) {
              elm.removeAttribute('data-mce-' + name);
            }
            if (name === 'style' &amp;&amp; matchNodeNames(['li'])(elm) &amp;&amp; dom.getStyle(elm, 'list-style-type') === 'none') {
              elm.removeAttribute(name);
              dom.setStyle(elm, 'list-style-type', 'none');
              return;
            }
            if (name === 'class') {
              elm.removeAttribute('className');
            }
            elm.removeAttribute(name);
          }
        });
        each$a(format.classes, function (value) {
          value = replaceVars(value, vars);
          if (!compareNode || dom.hasClass(compareNode, value)) {
            dom.removeClass(elm, value);
          }
        });
        var attrs = dom.getAttribs(elm);
        for (var i = 0; i &lt; attrs.length; i++) {
          var attrName = attrs[i].nodeName;
          if (attrName.indexOf('_') !== 0 &amp;&amp; attrName.indexOf('data-') !== 0) {
            return removeResult.keep();
          }
        }
      }
      if (format.remove !== 'none') {
        removeNode$1(ed, elm, format);
        return removeResult.removed();
      }
      return removeResult.keep();
    };
    var removeFormat = function (ed, format, vars, node, compareNode) {
      return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
        ed.dom.rename(node, newName);
        return true;
      }, always);
    };
    var findFormatRoot = function (editor, container, name, vars, similar) {
      var formatRoot;
      each(getParents$1(editor.dom, container.parentNode).reverse(), function (parent) {
        if (!formatRoot &amp;&amp; parent.id !== '_start' &amp;&amp; parent.id !== '_end') {
          var format = matchNode(editor, parent, name, vars, similar);
          if (format &amp;&amp; format.split !== false) {
            formatRoot = parent;
          }
        }
      });
      return formatRoot;
    };
    var removeFormatFromClone = function (editor, format, vars, clone) {
      return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
        var fragment = editor.dom.createFragment();
        fragment.appendChild(clone);
        return editor.dom.rename(clone, newName);
      }, constant(null));
    };
    var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
      var clone, lastClone, firstClone;
      var dom = editor.dom;
      if (formatRoot) {
        var formatRootParent = formatRoot.parentNode;
        for (var parent_1 = container.parentNode; parent_1 &amp;&amp; parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
          clone = dom.clone(parent_1, false);
          for (var i = 0; i &lt; formatList.length; i++) {
            clone = removeFormatFromClone(editor, formatList[i], vars, clone);
            if (clone === null) {
              break;
            }
          }
          if (clone) {
            if (lastClone) {
              clone.appendChild(lastClone);
            }
            if (!firstClone) {
              firstClone = clone;
            }
            lastClone = clone;
          }
        }
        if (split &amp;&amp; (!format.mixed || !dom.isBlock(formatRoot))) {
          container = dom.split(formatRoot, container);
        }
        if (lastClone) {
          target.parentNode.insertBefore(lastClone, target);
          firstClone.appendChild(target);
          if (format.inline) {
            mergeSiblings(dom, format, vars, lastClone);
          }
        }
      }
      return container;
    };
    var remove$6 = function (ed, name, vars, node, similar) {
      var formatList = ed.formatter.get(name);
      var format = formatList[0];
      var contentEditable = true;
      var dom = ed.dom;
      var selection = ed.selection;
      var splitToFormatRoot = function (container) {
        var formatRoot = findFormatRoot(ed, container, name, vars, similar);
        return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
      };
      var isRemoveBookmarkNode = function (node) {
        return isBookmarkNode$1(node) &amp;&amp; isElement$1(node) &amp;&amp; (node.id === '_start' || node.id === '_end');
      };
      var process = function (node) {
        var lastContentEditable, hasContentEditableState;
        var parentNode = node.parentNode;
        if (isText$1(node) &amp;&amp; hasBlockChildren(dom, parentNode)) {
          removeFormat(ed, format, vars, parentNode, parentNode);
        }
        if (isElement$1(node) &amp;&amp; dom.getContentEditable(node)) {
          lastContentEditable = contentEditable;
          contentEditable = dom.getContentEditable(node) === 'true';
          hasContentEditableState = true;
        }
        var children = from$1(node.childNodes);
        if (contentEditable &amp;&amp; !hasContentEditableState) {
          for (var i = 0; i &lt; formatList.length; i++) {
            if (removeFormat(ed, formatList[i], vars, node, node)) {
              break;
            }
          }
        }
        if (format.deep) {
          if (children.length) {
            for (var i = 0; i &lt; children.length; i++) {
              process(children[i]);
            }
            if (hasContentEditableState) {
              contentEditable = lastContentEditable;
            }
          }
        }
      };
      var unwrap = function (start) {
        var node = dom.get(start ? '_start' : '_end');
        var out = node[start ? 'firstChild' : 'lastChild'];
        if (isRemoveBookmarkNode(out)) {
          out = out[start ? 'firstChild' : 'lastChild'];
        }
        if (isText$1(out) &amp;&amp; out.data.length === 0) {
          out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
        }
        dom.remove(node, true);
        return out;
      };
      var removeRngStyle = function (rng) {
        var startContainer, endContainer;
        var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
        if (format.split) {
          expandedRng = split$1(expandedRng);
          startContainer = getContainer(ed, expandedRng, true);
          endContainer = getContainer(ed, expandedRng);
          if (startContainer !== endContainer) {
            startContainer = normalizeTableSelection(startContainer, true);
            endContainer = normalizeTableSelection(endContainer, false);
            if (isChildOfInlineParent(dom, startContainer, endContainer)) {
              var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
              splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
                'id': '_start',
                'data-mce-type': 'bookmark'
              }));
              unwrap(true);
              return;
            }
            if (isChildOfInlineParent(dom, endContainer, startContainer)) {
              var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
              splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
                'id': '_end',
                'data-mce-type': 'bookmark'
              }));
              unwrap(false);
              return;
            }
            startContainer = wrap$2(dom, startContainer, 'span', {
              'id': '_start',
              'data-mce-type': 'bookmark'
            });
            endContainer = wrap$2(dom, endContainer, 'span', {
              'id': '_end',
              'data-mce-type': 'bookmark'
            });
            var newRng = dom.createRng();
            newRng.setStartAfter(startContainer);
            newRng.setEndBefore(endContainer);
            walk$1(dom, newRng, function (nodes) {
              each(nodes, function (n) {
                if (!isBookmarkNode$1(n) &amp;&amp; !isBookmarkNode$1(n.parentNode)) {
                  splitToFormatRoot(n);
                }
              });
            });
            splitToFormatRoot(startContainer);
            splitToFormatRoot(endContainer);
            startContainer = unwrap(true);
            endContainer = unwrap();
          } else {
            startContainer = endContainer = splitToFormatRoot(startContainer);
          }
          expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
          expandedRng.startOffset = dom.nodeIndex(startContainer);
          expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
          expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
        }
        walk$1(dom, expandedRng, function (nodes) {
          each(nodes, function (node) {
            process(node);
            var textDecorations = [
              'underline',
              'line-through',
              'overline'
            ];
            each(textDecorations, function (decoration) {
              if (isElement$1(node) &amp;&amp; ed.dom.getStyle(node, 'text-decoration') === decoration &amp;&amp; node.parentNode &amp;&amp; getTextDecoration(dom, node.parentNode) === decoration) {
                removeFormat(ed, {
                  deep: false,
                  exact: true,
                  inline: 'span',
                  styles: { textDecoration: decoration }
                }, null, node);
              }
            });
          });
        });
      };
      if (node) {
        if (isNode(node)) {
          var rng = dom.createRng();
          rng.setStartBefore(node);
          rng.setEndAfter(node);
          removeRngStyle(rng);
        } else {
          removeRngStyle(node);
        }
        return;
      }
      if (dom.getContentEditable(selection.getNode()) === 'false') {
        node = selection.getNode();
        for (var i = 0; i &lt; formatList.length; i++) {
          if (formatList[i].ceFalseOverride) {
            if (removeFormat(ed, formatList[i], vars, node, node)) {
              break;
            }
          }
        }
        return;
      }
      if (!selection.isCollapsed() || !format.inline || getCellsFromEditor(ed).length) {
        preserve(selection, true, function () {
          runOnRanges(ed, removeRngStyle);
        });
        if (format.inline &amp;&amp; match(ed, name, vars, selection.getStart())) {
          moveStart(dom, selection, selection.getRng());
        }
        ed.nodeChanged();
      } else {
        removeCaretFormat(ed, name, vars, similar);
      }
    };

    var each$b = Tools.each;
    var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
      var processTextDecorationsAndColor = function (n) {
        if (n.nodeType === 1 &amp;&amp; n.parentNode &amp;&amp; n.parentNode.nodeType === 1) {
          var textDecoration = getTextDecoration(dom, n.parentNode);
          if (dom.getStyle(n, 'color') &amp;&amp; textDecoration) {
            dom.setStyle(n, 'text-decoration', textDecoration);
          } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
            dom.setStyle(n, 'text-decoration', null);
          }
        }
      };
      if (format.styles &amp;&amp; (format.styles.color || format.styles.textDecoration)) {
        Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
        processTextDecorationsAndColor(node);
      }
    };
    var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
      if (format.styles &amp;&amp; format.styles.backgroundColor) {
        processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
      }
    };
    var mergeSubSup = function (dom, format, vars, node) {
      if (format.inline === 'sub' || format.inline === 'sup') {
        processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
        dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
      }
    };
    var mergeWithChildren = function (editor, formatList, vars, node) {
      each$b(formatList, function (format) {
        each$b(editor.dom.select(format.inline, node), function (child) {
          if (!isElementNode(child)) {
            return;
          }
          removeFormat(editor, format, vars, child, format.exact ? child : null);
        });
        clearChildStyles(editor.dom, format, node);
      });
    };
    var mergeWithParents = function (editor, format, name, vars, node) {
      if (matchNode(editor, node.parentNode, name, vars)) {
        if (removeFormat(editor, format, vars, node)) {
          return;
        }
      }
      if (format.merge_with_parents) {
        editor.dom.getParent(node.parentNode, function (parent) {
          if (matchNode(editor, parent, name, vars)) {
            removeFormat(editor, format, vars, node);
            return true;
          }
        });
      }
    };

    var each$c = Tools.each;
    var hasFormatProperty = function (format, prop) {
      return hasNonNullableKey(format, prop);
    };
    var isElementNode$1 = function (node) {
      return node &amp;&amp; node.nodeType === 1 &amp;&amp; !isBookmarkNode$1(node) &amp;&amp; !isCaretNode(node) &amp;&amp; !isBogus(node);
    };
    var canFormatBR = function (editor, format, node, parentName) {
      if (canFormatEmptyLines(editor) &amp;&amp; isInlineFormat(format)) {
        var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
          td: {},
          th: {},
          li: {},
          dt: {},
          dd: {},
          figcaption: {},
          caption: {},
          details: {},
          summary: {}
        });
        var hasCaretNodeSibling = sibling$2(SugarElement.fromDom(node), function (sibling) {
          return isCaretNode(sibling.dom);
        });
        return hasNonNullableKey(validBRParentElements, parentName) &amp;&amp; isEmpty(SugarElement.fromDom(node.parentNode), false) &amp;&amp; !hasCaretNodeSibling;
      } else {
        return false;
      }
    };
    var applyFormat = function (ed, name, vars, node) {
      var formatList = ed.formatter.get(name);
      var format = formatList[0];
      var isCollapsed = !node &amp;&amp; ed.selection.isCollapsed();
      var dom = ed.dom;
      var selection = ed.selection;
      var setElementFormat = function (elm, fmt) {
        fmt = fmt || format;
        if (elm) {
          if (fmt.onformat) {
            fmt.onformat(elm, fmt, vars, node);
          }
          each$c(fmt.styles, function (value, name) {
            dom.setStyle(elm, name, replaceVars(value, vars));
          });
          if (fmt.styles) {
            var styleVal = dom.getAttrib(elm, 'style');
            if (styleVal) {
              dom.setAttrib(elm, 'data-mce-style', styleVal);
            }
          }
          each$c(fmt.attributes, function (value, name) {
            dom.setAttrib(elm, name, replaceVars(value, vars));
          });
          each$c(fmt.classes, function (value) {
            value = replaceVars(value, vars);
            if (!dom.hasClass(elm, value)) {
              dom.addClass(elm, value);
            }
          });
        }
      };
      var applyNodeStyle = function (formatList, node) {
        var found = false;
        if (!isSelectorFormat(format)) {
          return false;
        }
        each$c(formatList, function (format) {
          if ('collapsed' in format &amp;&amp; format.collapsed !== isCollapsed) {
            return;
          }
          if (dom.is(node, format.selector) &amp;&amp; !isCaretNode(node)) {
            setElementFormat(node, format);
            found = true;
            return false;
          }
        });
        return found;
      };
      var applyRngStyle = function (dom, rng, bookmark, nodeSpecific) {
        var newWrappers = [];
        var contentEditable = true;
        var wrapName = format.inline || format.block;
        var wrapElm = dom.create(wrapName);
        setElementFormat(wrapElm);
        walk$1(dom, rng, function (nodes) {
          var currentWrapElm;
          var process = function (node) {
            var hasContentEditableState = false;
            var lastContentEditable = contentEditable;
            var nodeName = node.nodeName.toLowerCase();
            var parentName = node.parentNode.nodeName.toLowerCase();
            if (isElement$1(node) &amp;&amp; dom.getContentEditable(node)) {
              lastContentEditable = contentEditable;
              contentEditable = dom.getContentEditable(node) === 'true';
              hasContentEditableState = true;
            }
            if (isBr(node) &amp;&amp; !canFormatBR(ed, format, node, parentName)) {
              currentWrapElm = null;
              if (isBlockFormat(format)) {
                dom.remove(node);
              }
              return;
            }
            if (format.wrapper &amp;&amp; matchNode(ed, node, name, vars)) {
              currentWrapElm = null;
              return;
            }
            if (contentEditable &amp;&amp; !hasContentEditableState &amp;&amp; isBlockFormat(format) &amp;&amp; !format.wrapper &amp;&amp; isTextBlock$1(ed, nodeName) &amp;&amp; isValid(ed, parentName, wrapName)) {
              var elm = dom.rename(node, wrapName);
              setElementFormat(elm);
              newWrappers.push(elm);
              currentWrapElm = null;
              return;
            }
            if (isSelectorFormat(format)) {
              var found = applyNodeStyle(formatList, node);
              if (isText$1(node) &amp;&amp; hasBlockChildren(dom, node.parentNode)) {
                applyNodeStyle(formatList, node.parentNode);
              }
              if (!hasFormatProperty(format, 'inline') || found) {
                currentWrapElm = null;
                return;
              }
            }
            if (contentEditable &amp;&amp; !hasContentEditableState &amp;&amp; isValid(ed, wrapName, nodeName) &amp;&amp; isValid(ed, parentName, wrapName) &amp;&amp; !(!nodeSpecific &amp;&amp; node.nodeType === 3 &amp;&amp; node.nodeValue.length === 1 &amp;&amp; node.nodeValue.charCodeAt(0) === 65279) &amp;&amp; !isCaretNode(node) &amp;&amp; (!hasFormatProperty(format, 'inline') || !dom.isBlock(node))) {
              if (!currentWrapElm) {
                currentWrapElm = dom.clone(wrapElm, false);
                node.parentNode.insertBefore(currentWrapElm, node);
                newWrappers.push(currentWrapElm);
              }
              currentWrapElm.appendChild(node);
            } else {
              currentWrapElm = null;
              each$c(Tools.grep(node.childNodes), process);
              if (hasContentEditableState) {
                contentEditable = lastContentEditable;
              }
              currentWrapElm = null;
            }
          };
          each$c(nodes, process);
        });
        if (format.links === true) {
          each$c(newWrappers, function (node) {
            var process = function (node) {
              if (node.nodeName === 'A') {
                setElementFormat(node, format);
              }
              each$c(Tools.grep(node.childNodes), process);
            };
            process(node);
          });
        }
        each$c(newWrappers, function (node) {
          var getChildCount = function (node) {
            var count = 0;
            each$c(node.childNodes, function (node) {
              if (!isEmptyTextNode(node) &amp;&amp; !isBookmarkNode$1(node)) {
                count++;
              }
            });
            return count;
          };
          var getChildElementNode = function (root) {
            var child = false;
            each$c(root.childNodes, function (node) {
              if (isElementNode$1(node)) {
                child = node;
                return false;
              }
            });
            return child;
          };
          var mergeStyles = function (node) {
            var clone;
            var child = getChildElementNode(node);
            if (child &amp;&amp; !isBookmarkNode$1(child) &amp;&amp; matchName(dom, child, format)) {
              clone = dom.clone(child, false);
              setElementFormat(clone);
              dom.replace(clone, node, true);
              dom.remove(child, true);
            }
            return clone || node;
          };
          var childCount = getChildCount(node);
          if ((newWrappers.length &gt; 1 || !dom.isBlock(node)) &amp;&amp; childCount === 0) {
            dom.remove(node, true);
            return;
          }
          if (isInlineFormat(format) || format.wrapper) {
            if (!format.exact &amp;&amp; childCount === 1) {
              node = mergeStyles(node);
            }
            mergeWithChildren(ed, formatList, vars, node);
            mergeWithParents(ed, format, name, vars, node);
            mergeBackgroundColorAndFontSize(dom, format, vars, node);
            mergeTextDecorationsAndColor(dom, format, vars, node);
            mergeSubSup(dom, format, vars, node);
            mergeSiblings(dom, format, vars, node);
          }
        });
      };
      if (dom.getContentEditable(selection.getNode()) === 'false') {
        node = selection.getNode();
        for (var i = 0, l = formatList.length; i &lt; l; i++) {
          var formatItem = formatList[i];
          if (formatItem.ceFalseOverride &amp;&amp; isSelectorFormat(formatItem) &amp;&amp; dom.is(node, formatItem.selector)) {
            setElementFormat(node, formatItem);
            return;
          }
        }
        return;
      }
      if (format) {
        if (node) {
          if (isNode(node)) {
            if (!applyNodeStyle(formatList, node)) {
              var rng = dom.createRng();
              rng.setStartBefore(node);
              rng.setEndAfter(node);
              applyRngStyle(dom, expandRng(ed, rng, formatList), null, true);
            }
          } else {
            applyRngStyle(dom, node, null, true);
          }
        } else {
          if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
            var curSelNode = selection.getNode();
            var firstFormat = formatList[0];
            if (!ed.settings.forced_root_block &amp;&amp; firstFormat.defaultBlock &amp;&amp; !dom.getParent(curSelNode, dom.isBlock)) {
              applyFormat(ed, firstFormat.defaultBlock);
            }
            selection.setRng(normalize$2(selection.getRng()));
            preserve(selection, true, function (bookmark) {
              runOnRanges(ed, function (selectionRng, fake) {
                var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
                applyRngStyle(dom, expandedRng);
              });
            });
            moveStart(dom, selection, selection.getRng());
            ed.nodeChanged();
          } else {
            applyCaretFormat(ed, name, vars);
          }
        }
        postProcess(name, ed);
      }
    };

    var setup$4 = function (registeredFormatListeners, editor) {
      var currentFormats = Cell({});
      registeredFormatListeners.set({});
      editor.on('NodeChange', function (e) {
        updateAndFireChangeCallbacks(editor, e.element, currentFormats, registeredFormatListeners.get());
      });
    };
    var updateAndFireChangeCallbacks = function (editor, elm, currentFormats, formatChangeData) {
      var formatsList = keys(currentFormats.get());
      var newFormats = {};
      var matchedFormats = {};
      var parents = filter(getParents$1(editor.dom, elm), function (node) {
        return node.nodeType === 1 &amp;&amp; !node.getAttribute('data-mce-bogus');
      });
      each$1(formatChangeData, function (data, format) {
        Tools.each(parents, function (node) {
          if (editor.formatter.matchNode(node, format, {}, data.similar)) {
            if (formatsList.indexOf(format) === -1) {
              each(data.callbacks, function (callback) {
                callback(true, {
                  node: node,
                  format: format,
                  parents: parents
                });
              });
              newFormats[format] = data.callbacks;
            }
            matchedFormats[format] = data.callbacks;
            return false;
          }
          if (matchesUnInheritedFormatSelector(editor, node, format)) {
            return false;
          }
        });
      });
      var remainingFormats = filterRemainingFormats(currentFormats.get(), matchedFormats, elm, parents);
      currentFormats.set(__assign(__assign({}, newFormats), remainingFormats));
    };
    var filterRemainingFormats = function (currentFormats, matchedFormats, elm, parents) {
      return bifilter(currentFormats, function (callbacks, format) {
        if (!has(matchedFormats, format)) {
          each(callbacks, function (callback) {
            callback(false, {
              node: elm,
              format: format,
              parents: parents
            });
          });
          return false;
        } else {
          return true;
        }
      }).t;
    };
    var addListeners = function (registeredFormatListeners, formats, callback, similar) {
      var formatChangeItems = registeredFormatListeners.get();
      each(formats.split(','), function (format) {
        if (!formatChangeItems[format]) {
          formatChangeItems[format] = {
            similar: similar,
            callbacks: []
          };
        }
        formatChangeItems[format].callbacks.push(callback);
      });
      registeredFormatListeners.set(formatChangeItems);
    };
    var removeListeners = function (registeredFormatListeners, formats, callback) {
      var formatChangeItems = registeredFormatListeners.get();
      each(formats.split(','), function (format) {
        formatChangeItems[format].callbacks = filter(formatChangeItems[format].callbacks, function (c) {
          return c !== callback;
        });
        if (formatChangeItems[format].callbacks.length === 0) {
          delete formatChangeItems[format];
        }
      });
      registeredFormatListeners.set(formatChangeItems);
    };
    var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar) {
      if (registeredFormatListeners.get() === null) {
        setup$4(registeredFormatListeners, editor);
      }
      addListeners(registeredFormatListeners, formats, callback, similar);
      return {
        unbind: function () {
          return removeListeners(registeredFormatListeners, formats, callback);
        }
      };
    };

    var toggle = function (editor, name, vars, node) {
      var fmt = editor.formatter.get(name);
      if (match(editor, name, vars, node) &amp;&amp; (!('toggle' in fmt[0]) || fmt[0].toggle)) {
        remove$6(editor, name, vars, node);
      } else {
        applyFormat(editor, name, vars, node);
      }
    };

    var fromElements = function (elements, scope) {
      var doc = scope || document;
      var fragment = doc.createDocumentFragment();
      each(elements, function (element) {
        fragment.appendChild(element.dom);
      });
      return SugarElement.fromDom(fragment);
    };

    var tableModel = function (element, width, rows) {
      return {
        element: element,
        width: width,
        rows: rows
      };
    };
    var tableRow = function (element, cells) {
      return {
        element: element,
        cells: cells
      };
    };
    var cellPosition = function (x, y) {
      return {
        x: x,
        y: y
      };
    };
    var getSpan = function (td, key) {
      var value = parseInt(get$4(td, key), 10);
      return isNaN(value) ? 1 : value;
    };
    var fillout = function (table, x, y, tr, td) {
      var rowspan = getSpan(td, 'rowspan');
      var colspan = getSpan(td, 'colspan');
      var rows = table.rows;
      for (var y2 = y; y2 &lt; y + rowspan; y2++) {
        if (!rows[y2]) {
          rows[y2] = tableRow(deep(tr), []);
        }
        for (var x2 = x; x2 &lt; x + colspan; x2++) {
          var cells = rows[y2].cells;
          cells[x2] = y2 === y &amp;&amp; x2 === x ? td : shallow(td);
        }
      }
    };
    var cellExists = function (table, x, y) {
      var rows = table.rows;
      var cells = rows[y] ? rows[y].cells : [];
      return !!cells[x];
    };
    var skipCellsX = function (table, x, y) {
      while (cellExists(table, x, y)) {
        x++;
      }
      return x;
    };
    var getWidth = function (rows) {
      return foldl(rows, function (acc, row) {
        return row.cells.length &gt; acc ? row.cells.length : acc;
      }, 0);
    };
    var findElementPos = function (table, element) {
      var rows = table.rows;
      for (var y = 0; y &lt; rows.length; y++) {
        var cells = rows[y].cells;
        for (var x = 0; x &lt; cells.length; x++) {
          if (eq$2(cells[x], element)) {
            return Optional.some(cellPosition(x, y));
          }
        }
      }
      return Optional.none();
    };
    var extractRows = function (table, sx, sy, ex, ey) {
      var newRows = [];
      var rows = table.rows;
      for (var y = sy; y &lt;= ey; y++) {
        var cells = rows[y].cells;
        var slice = sx &lt; ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
        newRows.push(tableRow(rows[y].element, slice));
      }
      return newRows;
    };
    var subTable = function (table, startPos, endPos) {
      var sx = startPos.x, sy = startPos.y;
      var ex = endPos.x, ey = endPos.y;
      var newRows = sy &lt; ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
      return tableModel(table.element, getWidth(newRows), newRows);
    };
    var createDomTable = function (table, rows) {
      var tableElement = shallow(table.element);
      var tableBody = SugarElement.fromTag('tbody');
      append$1(tableBody, rows);
      append(tableElement, tableBody);
      return tableElement;
    };
    var modelRowsToDomRows = function (table) {
      return map(table.rows, function (row) {
        var cells = map(row.cells, function (cell) {
          var td = deep(cell);
          remove$1(td, 'colspan');
          remove$1(td, 'rowspan');
          return td;
        });
        var tr = shallow(row.element);
        append$1(tr, cells);
        return tr;
      });
    };
    var fromDom$1 = function (tableElm) {
      var table = tableModel(shallow(tableElm), 0, []);
      each(descendants$1(tableElm, 'tr'), function (tr, y) {
        each(descendants$1(tr, 'td,th'), function (td, x) {
          fillout(table, skipCellsX(table, x, y), y, tr, td);
        });
      });
      return tableModel(table.element, getWidth(table.rows), table.rows);
    };
    var toDom = function (table) {
      return createDomTable(table, modelRowsToDomRows(table));
    };
    var subsection = function (table, startElement, endElement) {
      return findElementPos(table, startElement).bind(function (startPos) {
        return findElementPos(table, endElement).map(function (endPos) {
          return subTable(table, startPos, endPos);
        });
      });
    };

    var findParentListContainer = function (parents) {
      return find(parents, function (elm) {
        return name(elm) === 'ul' || name(elm) === 'ol';
      });
    };
    var getFullySelectedListWrappers = function (parents, rng) {
      return find(parents, function (elm) {
        return name(elm) === 'li' &amp;&amp; hasAllContentsSelected(elm, rng);
      }).fold(constant([]), function (_li) {
        return findParentListContainer(parents).map(function (listCont) {
          var listElm = SugarElement.fromTag(name(listCont));
          var listStyles = filter$1(getAllRaw(listCont), function (_style, name) {
            return startsWith(name, 'list-style');
          });
          setAll$1(listElm, listStyles);
          return [
            SugarElement.fromTag('li'),
            listElm
          ];
        }).getOr([]);
      });
    };
    var wrap$3 = function (innerElm, elms) {
      var wrapped = foldl(elms, function (acc, elm) {
        append(elm, acc);
        return elm;
      }, innerElm);
      return elms.length &gt; 0 ? fromElements([wrapped]) : wrapped;
    };
    var directListWrappers = function (commonAnchorContainer) {
      if (isListItem(commonAnchorContainer)) {
        return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
          return [
            commonAnchorContainer,
            listElm
          ];
        });
      } else {
        return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
      }
    };
    var getWrapElements = function (rootNode, rng) {
      var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
      var parents = parentsAndSelf(commonAnchorContainer, rootNode);
      var wrapElements = filter(parents, function (elm) {
        return isInline(elm) || isHeading(elm);
      });
      var listWrappers = getFullySelectedListWrappers(parents, rng);
      var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
      return map(allWrappers, shallow);
    };
    var emptyFragment = function () {
      return fromElements([]);
    };
    var getFragmentFromRange = function (rootNode, rng) {
      return wrap$3(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
    };
    var getParentTable = function (rootElm, cell) {
      return ancestor$1(cell, 'table', curry(eq$2, rootElm));
    };
    var getTableFragment = function (rootNode, selectedTableCells) {
      return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
        var firstCell = selectedTableCells[0];
        var lastCell = selectedTableCells[selectedTableCells.length - 1];
        var fullTableModel = fromDom$1(tableElm);
        return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
          return fromElements([toDom(sectionedTableModel)]);
        });
      }).getOrThunk(emptyFragment);
    };
    var getSelectionFragment = function (rootNode, ranges) {
      return ranges.length &gt; 0 &amp;&amp; ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
    };
    var read$1 = function (rootNode, ranges) {
      var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
      return selectedCells.length &gt; 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
    };

    var trimLeadingCollapsibleText = function (text) {
      return text.replace(/^[ \f\n\r\t\v]+/, '');
    };
    var isCollapsibleWhitespace = function (text, index) {
      return index &gt;= 0 &amp;&amp; index &lt; text.length &amp;&amp; isWhiteSpace$1(text.charAt(index));
    };
    var getInnerText = function (bin, shouldTrim) {
      var text = trim$2(bin.innerText);
      return shouldTrim ? trimLeadingCollapsibleText(text) : text;
    };
    var getContextNodeName = function (parentBlockOpt) {
      return parentBlockOpt.map(function (block) {
        return block.nodeName;
      }).getOr('div').toLowerCase();
    };
    var getTextContent = function (editor) {
      return Optional.from(editor.selection.getRng()).map(function (rng) {
        var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
        var body = editor.getBody();
        var contextNodeName = getContextNodeName(parentBlockOpt);
        var shouldTrimSpaces = Env.browser.isIE() &amp;&amp; contextNodeName !== 'pre';
        var bin = editor.dom.add(body, contextNodeName, {
          'data-mce-bogus': 'all',
          'style': 'overflow: hidden; opacity: 0;'
        }, rng.cloneContents());
        var text = getInnerText(bin, shouldTrimSpaces);
        var nonRenderedText = trim$2(bin.textContent);
        editor.dom.remove(bin);
        if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
          var parentBlock = parentBlockOpt.getOr(body);
          var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
          var textIndex = parentBlockText.indexOf(text);
          if (textIndex === -1) {
            return text;
          } else {
            var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
            var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
            return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
          }
        } else {
          return text;
        }
      }).getOr('');
    };
    var getSerializedContent = function (editor, args) {
      var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
      var sel = editor.selection.getSel();
      var ranges = processRanges(editor, getRanges(sel));
      var fragment = args.contextual ? read$1(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
      if (fragment) {
        tmpElm.appendChild(fragment);
      }
      return editor.selection.serializer.serialize(tmpElm, args);
    };
    var getSelectedContentInternal = function (editor, format, args) {
      if (args === void 0) {
        args = {};
      }
      args.get = true;
      args.format = format;
      args.selection = true;
      args = editor.fire('BeforeGetContent', args);
      if (args.isDefaultPrevented()) {
        editor.fire('GetContent', args);
        return args.content;
      }
      if (args.format === 'text') {
        return getTextContent(editor);
      } else {
        args.getInner = true;
        var content = getSerializedContent(editor, args);
        if (args.format === 'tree') {
          return content;
        } else {
          args.content = editor.selection.isCollapsed() ? '' : content;
          editor.fire('GetContent', args);
          return args.content;
        }
      }
    };

    var KEEP = 0, INSERT = 1, DELETE = 2;
    var diff = function (left, right) {
      var size = left.length + right.length + 2;
      var vDown = new Array(size);
      var vUp = new Array(size);
      var snake = function (start, end, diag) {
        return {
          start: start,
          end: end,
          diag: diag
        };
      };
      var buildScript = function (start1, end1, start2, end2, script) {
        var middle = getMiddleSnake(start1, end1, start2, end2);
        if (middle === null || middle.start === end1 &amp;&amp; middle.diag === end1 - end2 || middle.end === start1 &amp;&amp; middle.diag === start1 - start2) {
          var i = start1;
          var j = start2;
          while (i &lt; end1 || j &lt; end2) {
            if (i &lt; end1 &amp;&amp; j &lt; end2 &amp;&amp; left[i] === right[j]) {
              script.push([
                KEEP,
                left[i]
              ]);
              ++i;
              ++j;
            } else {
              if (end1 - start1 &gt; end2 - start2) {
                script.push([
                  DELETE,
                  left[i]
                ]);
                ++i;
              } else {
                script.push([
                  INSERT,
                  right[j]
                ]);
                ++j;
              }
            }
          }
        } else {
          buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
          for (var i2 = middle.start; i2 &lt; middle.end; ++i2) {
            script.push([
              KEEP,
              left[i2]
            ]);
          }
          buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
        }
      };
      var buildSnake = function (start, diag, end1, end2) {
        var end = start;
        while (end - diag &lt; end2 &amp;&amp; end &lt; end1 &amp;&amp; left[end] === right[end - diag]) {
          ++end;
        }
        return snake(start, end, diag);
      };
      var getMiddleSnake = function (start1, end1, start2, end2) {
        var m = end1 - start1;
        var n = end2 - start2;
        if (m === 0 || n === 0) {
          return null;
        }
        var delta = m - n;
        var sum = n + m;
        var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
        vDown[1 + offset] = start1;
        vUp[1 + offset] = end1 + 1;
        var d, k, i, x, y;
        for (d = 0; d &lt;= offset; ++d) {
          for (k = -d; k &lt;= d; k += 2) {
            i = k + offset;
            if (k === -d || k !== d &amp;&amp; vDown[i - 1] &lt; vDown[i + 1]) {
              vDown[i] = vDown[i + 1];
            } else {
              vDown[i] = vDown[i - 1] + 1;
            }
            x = vDown[i];
            y = x - start1 + start2 - k;
            while (x &lt; end1 &amp;&amp; y &lt; end2 &amp;&amp; left[x] === right[y]) {
              vDown[i] = ++x;
              ++y;
            }
            if (delta % 2 !== 0 &amp;&amp; delta - d &lt;= k &amp;&amp; k &lt;= delta + d) {
              if (vUp[i - delta] &lt;= vDown[i]) {
                return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
              }
            }
          }
          for (k = delta - d; k &lt;= delta + d; k += 2) {
            i = k + offset - delta;
            if (k === delta - d || k !== delta + d &amp;&amp; vUp[i + 1] &lt;= vUp[i - 1]) {
              vUp[i] = vUp[i + 1] - 1;
            } else {
              vUp[i] = vUp[i - 1];
            }
            x = vUp[i] - 1;
            y = x - start1 + start2 - k;
            while (x &gt;= start1 &amp;&amp; y &gt;= start2 &amp;&amp; left[x] === right[y]) {
              vUp[i] = x--;
              y--;
            }
            if (delta % 2 === 0 &amp;&amp; -d &lt;= k &amp;&amp; k &lt;= d) {
              if (vUp[i] &lt;= vDown[i + delta]) {
                return buildSnake(vUp[i], k + start1 - start2, end1, end2);
              }
            }
          }
        }
      };
      var script = [];
      buildScript(0, left.length, 0, right.length, script);
      return script;
    };

    var getOuterHtml = function (elm) {
      if (isElement$1(elm)) {
        return elm.outerHTML;
      } else if (isText$1(elm)) {
        return Entities.encodeRaw(elm.data, false);
      } else if (isComment$1(elm)) {
        return '&lt;!--' + elm.data + '--&gt;';
      }
      return '';
    };
    var createFragment$1 = function (html) {
      var node;
      var container = document.createElement('div');
      var frag = document.createDocumentFragment();
      if (html) {
        container.innerHTML = html;
      }
      while (node = container.firstChild) {
        frag.appendChild(node);
      }
      return frag;
    };
    var insertAt = function (elm, html, index) {
      var fragment = createFragment$1(html);
      if (elm.hasChildNodes() &amp;&amp; index &lt; elm.childNodes.length) {
        var target = elm.childNodes[index];
        target.parentNode.insertBefore(fragment, target);
      } else {
        elm.appendChild(fragment);
      }
    };
    var removeAt = function (elm, index) {
      if (elm.hasChildNodes() &amp;&amp; index &lt; elm.childNodes.length) {
        var target = elm.childNodes[index];
        target.parentNode.removeChild(target);
      }
    };
    var applyDiff = function (diff, elm) {
      var index = 0;
      each(diff, function (action) {
        if (action[0] === KEEP) {
          index++;
        } else if (action[0] === INSERT) {
          insertAt(elm, action[1], index);
          index++;
        } else if (action[0] === DELETE) {
          removeAt(elm, index);
        }
      });
    };
    var read$2 = function (elm) {
      return filter(map(from$1(elm.childNodes), getOuterHtml), function (item) {
        return item.length &gt; 0;
      });
    };
    var write = function (fragments, elm) {
      var currentFragments = map(from$1(elm.childNodes), getOuterHtml);
      applyDiff(diff(currentFragments, fragments), elm);
      return elm;
    };

    var undoLevelDocument = Cell(Optional.none());
    var lazyTempDocument = function () {
      return undoLevelDocument.get().getOrThunk(function () {
        var doc = document.implementation.createHTMLDocument('undo');
        undoLevelDocument.set(Optional.some(doc));
        return doc;
      });
    };
    var hasIframes = function (html) {
      return html.indexOf('&lt;/iframe&gt;') !== -1;
    };
    var createFragmentedLevel = function (fragments) {
      return {
        type: 'fragmented',
        fragments: fragments,
        content: '',
        bookmark: null,
        beforeBookmark: null
      };
    };
    var createCompleteLevel = function (content) {
      return {
        type: 'complete',
        fragments: null,
        content: content,
        bookmark: null,
        beforeBookmark: null
      };
    };
    var createFromEditor = function (editor) {
      var fragments = read$2(editor.getBody());
      var trimmedFragments = bind(fragments, function (html) {
        var trimmed = trimInternal(editor.serializer, html);
        return trimmed.length &gt; 0 ? [trimmed] : [];
      });
      var content = trimmedFragments.join('');
      return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
    };
    var applyToEditor = function (editor, level, before) {
      if (level.type === 'fragmented') {
        write(level.fragments, editor.getBody());
      } else {
        editor.setContent(level.content, { format: 'raw' });
      }
      editor.selection.moveToBookmark(before ? level.beforeBookmark : level.bookmark);
    };
    var getLevelContent = function (level) {
      return level.type === 'fragmented' ? level.fragments.join('') : level.content;
    };
    var getCleanLevelContent = function (level) {
      var elm = SugarElement.fromTag('body', lazyTempDocument());
      set$1(elm, getLevelContent(level));
      each(descendants$1(elm, '*[data-mce-bogus]'), unwrap);
      return get$7(elm);
    };
    var hasEqualContent = function (level1, level2) {
      return getLevelContent(level1) === getLevelContent(level2);
    };
    var hasEqualCleanedContent = function (level1, level2) {
      return getCleanLevelContent(level1) === getCleanLevelContent(level2);
    };
    var isEq$4 = function (level1, level2) {
      if (!level1 || !level2) {
        return false;
      } else if (hasEqualContent(level1, level2)) {
        return true;
      } else {
        return hasEqualCleanedContent(level1, level2);
      }
    };

    var isUnlocked = function (locks) {
      return locks.get() === 0;
    };

    var setTyping = function (undoManager, typing, locks) {
      if (isUnlocked(locks)) {
        undoManager.typing = typing;
      }
    };
    var endTyping = function (undoManager, locks) {
      if (undoManager.typing) {
        setTyping(undoManager, false, locks);
        undoManager.add();
      }
    };
    var endTypingLevelIgnoreLocks = function (undoManager) {
      if (undoManager.typing) {
        undoManager.typing = false;
        undoManager.add();
      }
    };

    var beforeChange = function (editor, locks, beforeBookmark) {
      if (isUnlocked(locks)) {
        beforeBookmark.set(Optional.some(getUndoBookmark(editor.selection)));
      }
    };
    var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
      var currentLevel = createFromEditor(editor);
      level = level || {};
      level = Tools.extend(level, currentLevel);
      if (isUnlocked(locks) === false || editor.removed) {
        return null;
      }
      var lastLevel = undoManager.data[index.get()];
      if (editor.fire('BeforeAddUndo', {
          level: level,
          lastLevel: lastLevel,
          originalEvent: event
        }).isDefaultPrevented()) {
        return null;
      }
      if (lastLevel &amp;&amp; isEq$4(lastLevel, level)) {
        return null;
      }
      if (undoManager.data[index.get()]) {
        beforeBookmark.get().each(function (bm) {
          undoManager.data[index.get()].beforeBookmark = bm;
        });
      }
      var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
      if (customUndoRedoLevels) {
        if (undoManager.data.length &gt; customUndoRedoLevels) {
          for (var i = 0; i &lt; undoManager.data.length - 1; i++) {
            undoManager.data[i] = undoManager.data[i + 1];
          }
          undoManager.data.length--;
          index.set(undoManager.data.length);
        }
      }
      level.bookmark = getUndoBookmark(editor.selection);
      if (index.get() &lt; undoManager.data.length - 1) {
        undoManager.data.length = index.get() + 1;
      }
      undoManager.data.push(level);
      index.set(undoManager.data.length - 1);
      var args = {
        level: level,
        lastLevel: lastLevel,
        originalEvent: event
      };
      if (index.get() &gt; 0) {
        editor.setDirty(true);
        editor.fire('AddUndo', args);
        editor.fire('change', args);
      } else {
        editor.fire('AddUndo', args);
      }
      return level;
    };
    var clear = function (editor, undoManager, index) {
      undoManager.data = [];
      index.set(0);
      undoManager.typing = false;
      editor.fire('ClearUndos');
    };
    var extra = function (editor, undoManager, index, callback1, callback2) {
      if (undoManager.transact(callback1)) {
        var bookmark = undoManager.data[index.get()].bookmark;
        var lastLevel = undoManager.data[index.get() - 1];
        applyToEditor(editor, lastLevel, true);
        if (undoManager.transact(callback2)) {
          undoManager.data[index.get() - 1].beforeBookmark = bookmark;
        }
      }
    };
    var redo = function (editor, index, data) {
      var level;
      if (index.get() &lt; data.length - 1) {
        index.set(index.get() + 1);
        level = data[index.get()];
        applyToEditor(editor, level, false);
        editor.setDirty(true);
        editor.fire('Redo', { level: level });
      }
      return level;
    };
    var undo = function (editor, undoManager, locks, index) {
      var level;
      if (undoManager.typing) {
        undoManager.add();
        undoManager.typing = false;
        setTyping(undoManager, false, locks);
      }
      if (index.get() &gt; 0) {
        index.set(index.get() - 1);
        level = undoManager.data[index.get()];
        applyToEditor(editor, level, true);
        editor.setDirty(true);
        editor.fire('Undo', { level: level });
      }
      return level;
    };
    var reset = function (undoManager) {
      undoManager.clear();
      undoManager.add();
    };
    var hasUndo = function (editor, undoManager, index) {
      return index.get() &gt; 0 || undoManager.typing &amp;&amp; undoManager.data[0] &amp;&amp; !isEq$4(createFromEditor(editor), undoManager.data[0]);
    };
    var hasRedo = function (undoManager, index) {
      return index.get() &lt; undoManager.data.length - 1 &amp;&amp; !undoManager.typing;
    };
    var transact = function (undoManager, locks, callback) {
      endTyping(undoManager, locks);
      undoManager.beforeChange();
      undoManager.ignore(callback);
      return undoManager.add();
    };
    var ignore = function (locks, callback) {
      try {
        locks.set(locks.get() + 1);
        callback();
      } finally {
        locks.set(locks.get() - 1);
      }
    };

    var addVisualInternal = function (editor, elm) {
      var dom = editor.dom;
      var scope = isNonNullable(elm) ? elm : editor.getBody();
      if (isUndefined(editor.hasVisual)) {
        editor.hasVisual = isVisualAidsEnabled(editor);
      }
      each(dom.select('table,a', scope), function (matchedElm) {
        switch (matchedElm.nodeName) {
        case 'TABLE':
          var cls = getVisualAidsTableClass(editor);
          var value = dom.getAttrib(matchedElm, 'border');
          if ((!value || value === '0') &amp;&amp; editor.hasVisual) {
            dom.addClass(matchedElm, cls);
          } else {
            dom.removeClass(matchedElm, cls);
          }
          break;
        case 'A':
          if (!dom.getAttrib(matchedElm, 'href')) {
            var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
            var cls_1 = getVisualAidsAnchorClass(editor);
            if (value_1 &amp;&amp; editor.hasVisual) {
              dom.addClass(matchedElm, cls_1);
            } else {
              dom.removeClass(matchedElm, cls_1);
            }
          }
          break;
        }
      });
      editor.fire('VisualAid', {
        element: elm,
        hasVisual: editor.hasVisual
      });
    };

    var makePlainAdaptor = function (editor) {
      return {
        undoManager: {
          beforeChange: function (locks, beforeBookmark) {
            return beforeChange(editor, locks, beforeBookmark);
          },
          addUndoLevel: function (undoManager, index, locks, beforeBookmark, level, event) {
            return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
          },
          undo: function (undoManager, locks, index) {
            return undo(editor, undoManager, locks, index);
          },
          redo: function (index, data) {
            return redo(editor, index, data);
          },
          clear: function (undoManager, index) {
            return clear(editor, undoManager, index);
          },
          reset: function (undoManager) {
            return reset(undoManager);
          },
          hasUndo: function (undoManager, index) {
            return hasUndo(editor, undoManager, index);
          },
          hasRedo: function (undoManager, index) {
            return hasRedo(undoManager, index);
          },
          transact: function (undoManager, locks, callback) {
            return transact(undoManager, locks, callback);
          },
          ignore: function (locks, callback) {
            return ignore(locks, callback);
          },
          extra: function (undoManager, index, callback1, callback2) {
            return extra(editor, undoManager, index, callback1, callback2);
          }
        },
        formatter: {
          match: function (name, vars, node) {
            return match(editor, name, vars, node);
          },
          matchAll: function (names, vars) {
            return matchAll(editor, names, vars);
          },
          matchNode: function (node, name, vars, similar) {
            return matchNode(editor, node, name, vars, similar);
          },
          canApply: function (name) {
            return canApply(editor, name);
          },
          closest: function (names) {
            return closest$3(editor, names);
          },
          apply: function (name, vars, node) {
            return applyFormat(editor, name, vars, node);
          },
          remove: function (name, vars, node, similar) {
            return remove$6(editor, name, vars, node, similar);
          },
          toggle: function (name, vars, node) {
            return toggle(editor, name, vars, node);
          },
          formatChanged: function (registeredFormatListeners, formats, callback, similar) {
            return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar);
          }
        },
        editor: {
          getContent: function (args, format) {
            return getContentInternal(editor, args, format);
          },
          setContent: function (content, args) {
            return setContentInternal(editor, content, args);
          },
          insertContent: function (value, details) {
            return insertHtmlAtCaret(editor, value, details);
          },
          addVisual: function (elm) {
            return addVisualInternal(editor, elm);
          }
        },
        selection: {
          getContent: function (format, args) {
            return getSelectedContentInternal(editor, format, args);
          }
        },
        raw: {
          getModel: function () {
            return Optional.none();
          }
        }
      };
    };
    var makeRtcAdaptor = function (rtcEditor) {
      var defaultVars = function (vars) {
        return isObject(vars) ? vars : {};
      };
      var unsupported = die('Unimplemented feature for rtc');
      var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
      var ignore = noop;
      return {
        undoManager: {
          beforeChange: ignore,
          addUndoLevel: unsupported,
          undo: function () {
            return undoManager.undo();
          },
          redo: function () {
            return undoManager.redo();
          },
          clear: function () {
            return undoManager.clear();
          },
          reset: function () {
            return undoManager.reset();
          },
          hasUndo: function () {
            return undoManager.hasUndo();
          },
          hasRedo: function () {
            return undoManager.hasRedo();
          },
          transact: function (_undoManager, _locks, fn) {
            return undoManager.transact(fn);
          },
          ignore: function (_locks, callback) {
            return undoManager.ignore(callback);
          },
          extra: function (_undoManager, _index, callback1, callback2) {
            return undoManager.extra(callback1, callback2);
          }
        },
        formatter: {
          match: function (name, vars, _node) {
            return formatter.match(name, defaultVars(vars));
          },
          matchAll: unsupported,
          matchNode: unsupported,
          canApply: function (name) {
            return formatter.canApply(name);
          },
          closest: function (names) {
            return formatter.closest(names);
          },
          apply: function (name, vars, _node) {
            return formatter.apply(name, defaultVars(vars));
          },
          remove: function (name, vars, _node, _similar) {
            return formatter.remove(name, defaultVars(vars));
          },
          toggle: function (name, vars, _node) {
            return formatter.toggle(name, defaultVars(vars));
          },
          formatChanged: function (_rfl, formats, callback, similar) {
            return formatter.formatChanged(formats, callback, similar);
          }
        },
        editor: {
          getContent: function (args, _format) {
            return editor.getContent(args);
          },
          setContent: function (content, args) {
            return editor.setContent(content, args);
          },
          insertContent: function (content, _details) {
            return editor.insertContent(content);
          },
          addVisual: ignore
        },
        selection: {
          getContent: function (_format, args) {
            return selection.getContent(args);
          }
        },
        raw: {
          getModel: function () {
            return Optional.some(raw.getRawModel());
          }
        }
      };
    };
    var makeNoopAdaptor = function () {
      var nul = constant(null);
      var empty = constant('');
      return {
        undoManager: {
          beforeChange: noop,
          addUndoLevel: nul,
          undo: nul,
          redo: nul,
          clear: noop,
          reset: noop,
          hasUndo: never,
          hasRedo: never,
          transact: nul,
          ignore: noop,
          extra: noop
        },
        formatter: {
          match: never,
          matchAll: constant([]),
          matchNode: never,
          canApply: never,
          closest: empty,
          apply: noop,
          remove: noop,
          toggle: noop,
          formatChanged: constant({ unbind: noop })
        },
        editor: {
          getContent: empty,
          setContent: empty,
          insertContent: noop,
          addVisual: noop
        },
        selection: { getContent: empty },
        raw: { getModel: constant(Optional.none()) }
      };
    };
    var isRtc = function (editor) {
      return has(editor.plugins, 'rtc');
    };
    var getRtcSetup = function (editor) {
      return get$1(editor.plugins, 'rtc').bind(function (rtcPlugin) {
        return Optional.from(rtcPlugin.setup);
      });
    };
    var setup$5 = function (editor) {
      var editorCast = editor;
      return getRtcSetup(editor).fold(function () {
        editorCast.rtcInstance = makePlainAdaptor(editor);
        return Optional.none();
      }, function (setup) {
        return Optional.some(setup().then(function (rtcEditor) {
          editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
          return rtcEditor.rtc.isRemote;
        }, function (err) {
          editorCast.rtcInstance = makeNoopAdaptor();
          return promiseObj.reject(err);
        }));
      });
    };
    var getRtcInstanceWithFallback = function (editor) {
      return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
    };
    var getRtcInstanceWithError = function (editor) {
      var rtcInstance = editor.rtcInstance;
      if (!rtcInstance) {
        throw new Error('Failed to get RTC instance not yet initialized.');
      } else {
        return rtcInstance;
      }
    };
    var beforeChange$1 = function (editor, locks, beforeBookmark) {
      getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
    };
    var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
      return getRtcInstanceWithError(editor).undoManager.addUndoLevel(undoManager, index, locks, beforeBookmark, level, event);
    };
    var undo$1 = function (editor, undoManager, locks, index) {
      return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
    };
    var redo$1 = function (editor, index, data) {
      return getRtcInstanceWithError(editor).undoManager.redo(index, data);
    };
    var clear$1 = function (editor, undoManager, index) {
      getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
    };
    var reset$1 = function (editor, undoManager) {
      getRtcInstanceWithError(editor).undoManager.reset(undoManager);
    };
    var hasUndo$1 = function (editor, undoManager, index) {
      return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
    };
    var hasRedo$1 = function (editor, undoManager, index) {
      return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
    };
    var transact$1 = function (editor, undoManager, locks, callback) {
      return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
    };
    var ignore$1 = function (editor, locks, callback) {
      getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
    };
    var extra$1 = function (editor, undoManager, index, callback1, callback2) {
      getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
    };
    var matchFormat = function (editor, name, vars, node) {
      return getRtcInstanceWithError(editor).formatter.match(name, vars, node);
    };
    var matchAllFormats = function (editor, names, vars) {
      return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
    };
    var matchNodeFormat = function (editor, node, name, vars, similar) {
      return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
    };
    var canApplyFormat = function (editor, name) {
      return getRtcInstanceWithError(editor).formatter.canApply(name);
    };
    var closestFormat = function (editor, names) {
      return getRtcInstanceWithError(editor).formatter.closest(names);
    };
    var applyFormat$1 = function (editor, name, vars, node) {
      getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
    };
    var removeFormat$1 = function (editor, name, vars, node, similar) {
      getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
    };
    var toggleFormat = function (editor, name, vars, node) {
      getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
    };
    var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar) {
      if (similar === void 0) {
        similar = false;
      }
      return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar);
    };
    var getContent = function (editor, args, format) {
      return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
    };
    var setContent = function (editor, content, args) {
      return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
    };
    var insertContent = function (editor, value, details) {
      return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
    };
    var getSelectedContent = function (editor, format, args) {
      return getRtcInstanceWithError(editor).selection.getContent(format, args);
    };
    var addVisual = function (editor, elm) {
      return getRtcInstanceWithError(editor).editor.addVisual(elm);
    };

    var getContent$1 = function (editor, args) {
      if (args === void 0) {
        args = {};
      }
      var format = args.format ? args.format : 'html';
      return getSelectedContent(editor, format, args);
    };

    var removeEmpty = function (text) {
      if (text.dom.length === 0) {
        remove(text);
        return Optional.none();
      } else {
        return Optional.some(text);
      }
    };
    var walkPastBookmark = function (node, start) {
      return node.filter(function (elm) {
        return BookmarkManager.isBookmarkNode(elm.dom);
      }).bind(start ? nextSibling : prevSibling);
    };
    var merge = function (outer, inner, rng, start) {
      var outerElm = outer.dom;
      var innerElm = inner.dom;
      var oldLength = start ? outerElm.length : innerElm.length;
      if (start) {
        mergeTextNodes(outerElm, innerElm, false, !start);
        rng.setStart(innerElm, oldLength);
      } else {
        mergeTextNodes(innerElm, outerElm, false, !start);
        rng.setEnd(innerElm, oldLength);
      }
    };
    var normalizeTextIfRequired = function (inner, start) {
      parent(inner).each(function (root) {
        var text = inner.dom;
        if (start &amp;&amp; needsToBeNbspLeft(root, CaretPosition(text, 0))) {
          normalizeWhitespaceAfter(text, 0);
        } else if (!start &amp;&amp; needsToBeNbspRight(root, CaretPosition(text, text.length))) {
          normalizeWhitespaceBefore(text, text.length);
        }
      });
    };
    var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
      outerNode.bind(function (outer) {
        var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
        normalizer(outer.dom, start ? outer.dom.length : 0);
        return innerNode.filter(isText).map(function (inner) {
          return merge(outer, inner, rng, start);
        });
      }).orThunk(function () {
        var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText);
        return innerTextNode.map(function (inner) {
          return normalizeTextIfRequired(inner, start);
        });
      });
    };
    var rngSetContent = function (rng, fragment) {
      var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
      var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
      rng.deleteContents();
      rng.insertNode(fragment);
      var prevText = firstChild.bind(prevSibling).filter(isText).bind(removeEmpty);
      var nextText = lastChild.bind(nextSibling).filter(isText).bind(removeEmpty);
      mergeAndNormalizeText(prevText, firstChild, rng, true);
      mergeAndNormalizeText(nextText, lastChild, rng, false);
      rng.collapse(false);
    };
    var setupArgs = function (args, content) {
      return __assign(__assign({ format: 'html' }, args), {
        set: true,
        selection: true,
        content: content
      });
    };
    var cleanContent = function (editor, args) {
      if (args.format !== 'raw') {
        var rng = editor.selection.getRng();
        var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
        var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
        var node = editor.parser.parse(args.content, __assign(__assign({
          isRootContent: true,
          forced_root_block: false
        }, contextArgs), args));
        return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
      } else {
        return args.content;
      }
    };
    var setContent$1 = function (editor, content, args) {
      if (args === void 0) {
        args = {};
      }
      var contentArgs = setupArgs(args, content);
      if (!contentArgs.no_events) {
        contentArgs = editor.fire('BeforeSetContent', contentArgs);
        if (contentArgs.isDefaultPrevented()) {
          editor.fire('SetContent', contentArgs);
          return;
        }
      }
      args.content = cleanContent(editor, contentArgs);
      var rng = editor.selection.getRng();
      rngSetContent(rng, rng.createContextualFragment(args.content));
      editor.selection.setRng(rng);
      scrollRangeIntoView(editor, rng);
      if (!contentArgs.no_events) {
        editor.fire('SetContent', contentArgs);
      }
    };

    var deleteFromCallbackMap = function (callbackMap, selector, callback) {
      if (callbackMap &amp;&amp; callbackMap.hasOwnProperty(selector)) {
        var newCallbacks = filter(callbackMap[selector], function (cb) {
          return cb !== callback;
        });
        if (newCallbacks.length === 0) {
          delete callbackMap[selector];
        } else {
          callbackMap[selector] = newCallbacks;
        }
      }
    };
    function SelectorChanged (dom, editor) {
      var selectorChangedData;
      var currentSelectors;
      return {
        selectorChangedWithUnbind: function (selector, callback) {
          if (!selectorChangedData) {
            selectorChangedData = {};
            currentSelectors = {};
            editor.on('NodeChange', function (e) {
              var node = e.element, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
              Tools.each(selectorChangedData, function (callbacks, selector) {
                Tools.each(parents, function (node) {
                  if (dom.is(node, selector)) {
                    if (!currentSelectors[selector]) {
                      Tools.each(callbacks, function (callback) {
                        callback(true, {
                          node: node,
                          selector: selector,
                          parents: parents
                        });
                      });
                      currentSelectors[selector] = callbacks;
                    }
                    matchedSelectors[selector] = callbacks;
                    return false;
                  }
                });
              });
              Tools.each(currentSelectors, function (callbacks, selector) {
                if (!matchedSelectors[selector]) {
                  delete currentSelectors[selector];
                  Tools.each(callbacks, function (callback) {
                    callback(false, {
                      node: node,
                      selector: selector,
                      parents: parents
                    });
                  });
                }
              });
            });
          }
          if (!selectorChangedData[selector]) {
            selectorChangedData[selector] = [];
          }
          selectorChangedData[selector].push(callback);
          return {
            unbind: function () {
              deleteFromCallbackMap(selectorChangedData, selector, callback);
              deleteFromCallbackMap(currentSelectors, selector, callback);
            }
          };
        }
      };
    }

    var isNativeIeSelection = function (rng) {
      return !!rng.select;
    };
    var isAttachedToDom = function (node) {
      return !!(node &amp;&amp; node.ownerDocument) &amp;&amp; contains$2(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
    };
    var isValidRange = function (rng) {
      if (!rng) {
        return false;
      } else if (isNativeIeSelection(rng)) {
        return true;
      } else {
        return isAttachedToDom(rng.startContainer) &amp;&amp; isAttachedToDom(rng.endContainer);
      }
    };
    var EditorSelection = function (dom, win, serializer, editor) {
      var selectedRange;
      var explicitRange;
      var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
      var setCursorLocation = function (node, offset) {
        var rng = dom.createRng();
        if (isNonNullable(node) &amp;&amp; isNonNullable(offset)) {
          rng.setStart(node, offset);
          rng.setEnd(node, offset);
          setRng(rng);
          collapse(false);
        } else {
          moveEndPoint$1(dom, rng, editor.getBody(), true);
          setRng(rng);
        }
      };
      var getContent = function (args) {
        return getContent$1(editor, args);
      };
      var setContent = function (content, args) {
        return setContent$1(editor, content, args);
      };
      var getStart = function (real) {
        return getStart$2(editor.getBody(), getRng$1(), real);
      };
      var getEnd$1 = function (real) {
        return getEnd(editor.getBody(), getRng$1(), real);
      };
      var getBookmark = function (type, normalized) {
        return bookmarkManager.getBookmark(type, normalized);
      };
      var moveToBookmark = function (bookmark) {
        return bookmarkManager.moveToBookmark(bookmark);
      };
      var select = function (node, content) {
        select$1(dom, node, content).each(setRng);
        return node;
      };
      var isCollapsed = function () {
        var rng = getRng$1(), sel = getSel();
        if (!rng || rng.item) {
          return false;
        }
        if (rng.compareEndPoints) {
          return rng.compareEndPoints('StartToEnd', rng) === 0;
        }
        return !sel || rng.collapsed;
      };
      var collapse = function (toStart) {
        var rng = getRng$1();
        rng.collapse(!!toStart);
        setRng(rng);
      };
      var getSel = function () {
        return win.getSelection ? win.getSelection() : win.document.selection;
      };
      var getRng$1 = function () {
        var selection, rng, elm;
        var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
          try {
            return sourceRange.compareBoundaryPoints(how, destinationRange);
          } catch (ex) {
            return -1;
          }
        };
        var doc = win.document;
        if (editor.bookmark !== undefined &amp;&amp; hasFocus$1(editor) === false) {
          var bookmark = getRng(editor);
          if (bookmark.isSome()) {
            return bookmark.map(function (r) {
              return processRanges(editor, [r])[0];
            }).getOr(doc.createRange());
          }
        }
        try {
          if ((selection = getSel()) &amp;&amp; !isRestrictedNode(selection.anchorNode)) {
            if (selection.rangeCount &gt; 0) {
              rng = selection.getRangeAt(0);
            } else {
              rng = selection.createRange ? selection.createRange() : doc.createRange();
            }
            rng = processRanges(editor, [rng])[0];
          }
        } catch (ex) {
        }
        if (!rng) {
          rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
        }
        if (rng.setStart &amp;&amp; rng.startContainer.nodeType === 9 &amp;&amp; rng.collapsed) {
          elm = dom.getRoot();
          rng.setStart(elm, 0);
          rng.setEnd(elm, 0);
        }
        if (selectedRange &amp;&amp; explicitRange) {
          if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 &amp;&amp; tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
            rng = explicitRange;
          } else {
            selectedRange = null;
            explicitRange = null;
          }
        }
        return rng;
      };
      var setRng = function (rng, forward) {
        var node;
        if (!isValidRange(rng)) {
          return;
        }
        var ieRange = isNativeIeSelection(rng) ? rng : null;
        if (ieRange) {
          explicitRange = null;
          try {
            ieRange.select();
          } catch (ex) {
          }
          return;
        }
        var sel = getSel();
        var evt = editor.fire('SetSelectionRange', {
          range: rng,
          forward: forward
        });
        rng = evt.range;
        if (sel) {
          explicitRange = rng;
          try {
            sel.removeAllRanges();
            sel.addRange(rng);
          } catch (ex) {
          }
          if (forward === false &amp;&amp; sel.extend) {
            sel.collapse(rng.endContainer, rng.endOffset);
            sel.extend(rng.startContainer, rng.startOffset);
          }
          selectedRange = sel.rangeCount &gt; 0 ? sel.getRangeAt(0) : null;
        }
        if (!rng.collapsed &amp;&amp; rng.startContainer === rng.endContainer &amp;&amp; sel.setBaseAndExtent &amp;&amp; !Env.ie) {
          if (rng.endOffset - rng.startOffset &lt; 2) {
            if (rng.startContainer.hasChildNodes()) {
              node = rng.startContainer.childNodes[rng.startOffset];
              if (node &amp;&amp; node.tagName === 'IMG') {
                sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
                if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
                  sel.setBaseAndExtent(node, 0, node, 1);
                }
              }
            }
          }
        }
        editor.fire('AfterSetSelectionRange', {
          range: rng,
          forward: forward
        });
      };
      var setNode = function (elm) {
        setContent(dom.getOuterHTML(elm));
        return elm;
      };
      var getNode = function () {
        return getNode$1(editor.getBody(), getRng$1());
      };
      var getSelectedBlocks$1 = function (startElm, endElm) {
        return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
      };
      var isForward = function () {
        var sel = getSel();
        var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
        var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
        if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
          return true;
        }
        var anchorRange = dom.createRng();
        anchorRange.setStart(anchorNode, sel.anchorOffset);
        anchorRange.collapse(true);
        var focusRange = dom.createRng();
        focusRange.setStart(focusNode, sel.focusOffset);
        focusRange.collapse(true);
        return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) &lt;= 0;
      };
      var normalize$1 = function () {
        var rng = getRng$1();
        var sel = getSel();
        if (!hasMultipleRanges(sel) &amp;&amp; hasAnyRanges(editor)) {
          var normRng = normalize(dom, rng);
          normRng.each(function (normRng) {
            setRng(normRng, isForward());
          });
          return normRng.getOr(rng);
        }
        return rng;
      };
      var selectorChanged = function (selector, callback) {
        selectorChangedWithUnbind(selector, callback);
        return exports;
      };
      var getScrollContainer = function () {
        var scrollContainer;
        var node = dom.getRoot();
        while (node &amp;&amp; node.nodeName !== 'BODY') {
          if (node.scrollHeight &gt; node.clientHeight) {
            scrollContainer = node;
            break;
          }
          node = node.parentNode;
        }
        return scrollContainer;
      };
      var scrollIntoView = function (elm, alignToTop) {
        return scrollElementIntoView(editor, elm, alignToTop);
      };
      var placeCaretAt = function (clientX, clientY) {
        return setRng(fromPoint$1(clientX, clientY, editor.getDoc()));
      };
      var getBoundingClientRect = function () {
        var rng = getRng$1();
        return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
      };
      var destroy = function () {
        win = selectedRange = explicitRange = null;
        controlSelection.destroy();
      };
      var exports = {
        bookmarkManager: null,
        controlSelection: null,
        dom: dom,
        win: win,
        serializer: serializer,
        editor: editor,
        collapse: collapse,
        setCursorLocation: setCursorLocation,
        getContent: getContent,
        setContent: setContent,
        getBookmark: getBookmark,
        moveToBookmark: moveToBookmark,
        select: select,
        isCollapsed: isCollapsed,
        isForward: isForward,
        setNode: setNode,
        getNode: getNode,
        getSel: getSel,
        setRng: setRng,
        getRng: getRng$1,
        getStart: getStart,
        getEnd: getEnd$1,
        getSelectedBlocks: getSelectedBlocks$1,
        normalize: normalize$1,
        selectorChanged: selectorChanged,
        selectorChangedWithUnbind: selectorChangedWithUnbind,
        getScrollContainer: getScrollContainer,
        scrollIntoView: scrollIntoView,
        placeCaretAt: placeCaretAt,
        getBoundingClientRect: getBoundingClientRect,
        destroy: destroy
      };
      var bookmarkManager = BookmarkManager(exports);
      var controlSelection = ControlSelection(exports, editor);
      exports.bookmarkManager = bookmarkManager;
      exports.controlSelection = controlSelection;
      return exports;
    };

    var removeAttrs = function (node, names) {
      each(names, function (name) {
        node.attr(name, null);
      });
    };
    var addFontToSpansFilter = function (domParser, styles, fontSizes) {
      domParser.addNodeFilter('font', function (nodes) {
        each(nodes, function (node) {
          var props = styles.parse(node.attr('style'));
          var color = node.attr('color');
          var face = node.attr('face');
          var size = node.attr('size');
          if (color) {
            props.color = color;
          }
          if (face) {
            props['font-family'] = face;
          }
          if (size) {
            props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
          }
          node.name = 'span';
          node.attr('style', styles.serialize(props));
          removeAttrs(node, [
            'color',
            'face',
            'size'
          ]);
        });
      });
    };
    var addStrikeToSpanFilter = function (domParser, styles) {
      domParser.addNodeFilter('strike', function (nodes) {
        each(nodes, function (node) {
          var props = styles.parse(node.attr('style'));
          props['text-decoration'] = 'line-through';
          node.name = 'span';
          node.attr('style', styles.serialize(props));
        });
      });
    };
    var addFilters = function (domParser, settings) {
      var styles = Styles();
      if (settings.convert_fonts_to_spans) {
        addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
      }
      addStrikeToSpanFilter(domParser, styles);
    };
    var register$1 = function (domParser, settings) {
      if (settings.inline_styles) {
        addFilters(domParser, settings);
      }
    };

    var blobUriToBlob = function (url) {
      return new promiseObj(function (resolve, reject) {
        var rejectWithError = function () {
          reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
        };
        try {
          var xhr_1 = new XMLHttpRequest();
          xhr_1.open('GET', url, true);
          xhr_1.responseType = 'blob';
          xhr_1.onload = function () {
            if (xhr_1.status === 200) {
              resolve(xhr_1.response);
            } else {
              rejectWithError();
            }
          };
          xhr_1.onerror = rejectWithError;
          xhr_1.send();
        } catch (ex) {
          rejectWithError();
        }
      });
    };
    var parseDataUri$1 = function (uri) {
      var type;
      var uriParts = decodeURIComponent(uri).split(',');
      var matches = /data:([^;]+)/.exec(uriParts[0]);
      if (matches) {
        type = matches[1];
      }
      return {
        type: type,
        data: uriParts[1]
      };
    };
    var buildBlob = function (type, data) {
      var str;
      try {
        str = atob(data);
      } catch (e) {
        return Optional.none();
      }
      var arr = new Uint8Array(str.length);
      for (var i = 0; i &lt; arr.length; i++) {
        arr[i] = str.charCodeAt(i);
      }
      return Optional.some(new Blob([arr], { type: type }));
    };
    var dataUriToBlob = function (uri) {
      return new promiseObj(function (resolve) {
        var _a = parseDataUri$1(uri), type = _a.type, data = _a.data;
        buildBlob(type, data).fold(function () {
          return resolve(new Blob([]));
        }, resolve);
      });
    };
    var uriToBlob = function (url) {
      if (url.indexOf('blob:') === 0) {
        return blobUriToBlob(url);
      }
      if (url.indexOf('data:') === 0) {
        return dataUriToBlob(url);
      }
      return null;
    };
    var blobToDataUri = function (blob) {
      return new promiseObj(function (resolve) {
        var reader = new FileReader();
        reader.onloadend = function () {
          resolve(reader.result);
        };
        reader.readAsDataURL(blob);
      });
    };

    var count = 0;
    var uniqueId = function (prefix) {
      return (prefix || 'blobid') + count++;
    };
    var imageToBlobInfo = function (blobCache, img, resolve, reject) {
      var base64, blobInfo;
      if (img.src.indexOf('blob:') === 0) {
        blobInfo = blobCache.getByUri(img.src);
        if (blobInfo) {
          resolve({
            image: img,
            blobInfo: blobInfo
          });
        } else {
          uriToBlob(img.src).then(function (blob) {
            blobToDataUri(blob).then(function (dataUri) {
              base64 = parseDataUri$1(dataUri).data;
              blobInfo = blobCache.create(uniqueId(), blob, base64);
              blobCache.add(blobInfo);
              resolve({
                image: img,
                blobInfo: blobInfo
              });
            });
          }, function (err) {
            reject(err);
          });
        }
        return;
      }
      var _a = parseDataUri$1(img.src), data = _a.data, type = _a.type;
      base64 = data;
      blobInfo = blobCache.getByData(base64, type);
      if (blobInfo) {
        resolve({
          image: img,
          blobInfo: blobInfo
        });
      } else {
        uriToBlob(img.src).then(function (blob) {
          blobInfo = blobCache.create(uniqueId(), blob, base64);
          blobCache.add(blobInfo);
          resolve({
            image: img,
            blobInfo: blobInfo
          });
        }, function (err) {
          reject(err);
        });
      }
    };
    var getAllImages = function (elm) {
      return elm ? from$1(elm.getElementsByTagName('img')) : [];
    };
    var ImageScanner = function (uploadStatus, blobCache) {
      var cachedPromises = {};
      var findAll = function (elm, predicate) {
        if (!predicate) {
          predicate = always;
        }
        var images = filter(getAllImages(elm), function (img) {
          var src = img.src;
          if (!Env.fileApi) {
            return false;
          }
          if (img.hasAttribute('data-mce-bogus')) {
            return false;
          }
          if (img.hasAttribute('data-mce-placeholder')) {
            return false;
          }
          if (!src || src === Env.transparentSrc) {
            return false;
          }
          if (src.indexOf('blob:') === 0) {
            return !uploadStatus.isUploaded(src) &amp;&amp; predicate(img);
          }
          if (src.indexOf('data:') === 0) {
            return predicate(img);
          }
          return false;
        });
        var promises = map(images, function (img) {
          if (cachedPromises[img.src] !== undefined) {
            return new promiseObj(function (resolve) {
              cachedPromises[img.src].then(function (imageInfo) {
                if (typeof imageInfo === 'string') {
                  return imageInfo;
                }
                resolve({
                  image: img,
                  blobInfo: imageInfo.blobInfo
                });
              });
            });
          }
          var newPromise = new promiseObj(function (resolve, reject) {
            imageToBlobInfo(blobCache, img, resolve, reject);
          }).then(function (result) {
            delete cachedPromises[result.image.src];
            return result;
          }).catch(function (error) {
            delete cachedPromises[img.src];
            return error;
          });
          cachedPromises[img.src] = newPromise;
          return newPromise;
        });
        return promiseObj.all(promises);
      };
      return { findAll: findAll };
    };

    var paddEmptyNode = function (settings, args, blockElements, node) {
      var brPreferred = settings.padd_empty_with_br || args.insert;
      if (brPreferred &amp;&amp; blockElements[node.name]) {
        node.empty().append(new AstNode('br', 1)).shortEnded = true;
      } else {
        node.empty().append(new AstNode('#text', 3)).value = nbsp;
      }
    };
    var isPaddedWithNbsp = function (node) {
      return hasOnlyChild(node, '#text') &amp;&amp; node.firstChild.value === nbsp;
    };
    var hasOnlyChild = function (node, name) {
      return node &amp;&amp; node.firstChild &amp;&amp; node.firstChild === node.lastChild &amp;&amp; node.firstChild.name === name;
    };
    var isPadded = function (schema, node) {
      var rule = schema.getElementRule(node.name);
      return rule &amp;&amp; rule.paddEmpty;
    };
    var isEmpty$2 = function (schema, nonEmptyElements, whitespaceElements, node) {
      return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
        return isPadded(schema, node);
      });
    };
    var isLineBreakNode = function (node, blockElements) {
      return node &amp;&amp; (blockElements[node.name] || node.name === 'br');
    };

    var isBogusImage = function (img) {
      return img.attr('data-mce-bogus');
    };
    var isInternalImageSource = function (img) {
      return img.attr('src') === Env.transparentSrc || img.attr('data-mce-placeholder');
    };
    var isValidDataImg = function (img, settings) {
      if (settings.images_dataimg_filter) {
        var imgElem_1 = new Image();
        imgElem_1.src = img.attr('src');
        each$1(img.attributes.map, function (value, key) {
          imgElem_1.setAttribute(key, value);
        });
        return settings.images_dataimg_filter(imgElem_1);
      } else {
        return true;
      }
    };
    var registerBase64ImageFilter = function (parser, settings) {
      var blobCache = settings.blob_cache;
      var processImage = function (img) {
        var inputSrc = img.attr('src');
        if (isInternalImageSource(img) || isBogusImage(img)) {
          return;
        }
        parseDataUri(inputSrc).filter(function () {
          return isValidDataImg(img, settings);
        }).bind(function (_a) {
          var type = _a.type, data = _a.data;
          return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
            return buildBlob(type, data).map(function (blob) {
              var blobInfo = blobCache.create(uniqueId(), blob, data);
              blobCache.add(blobInfo);
              return blobInfo;
            });
          });
        }).each(function (blobInfo) {
          img.attr('src', blobInfo.blobUri());
        });
      };
      if (blobCache) {
        parser.addAttributeFilter('src', function (nodes) {
          return each(nodes, processImage);
        });
      }
    };
    var register$2 = function (parser, settings) {
      var schema = parser.schema;
      if (settings.remove_trailing_brs) {
        parser.addNodeFilter('br', function (nodes, _, args) {
          var i;
          var l = nodes.length;
          var node;
          var blockElements = Tools.extend({}, schema.getBlockElements());
          var nonEmptyElements = schema.getNonEmptyElements();
          var parent, lastParent, prev, prevName;
          var whiteSpaceElements = schema.getWhiteSpaceElements();
          var elementRule, textNode;
          blockElements.body = 1;
          for (i = 0; i &lt; l; i++) {
            node = nodes[i];
            parent = node.parent;
            if (blockElements[node.parent.name] &amp;&amp; node === parent.lastChild) {
              prev = node.prev;
              while (prev) {
                prevName = prev.name;
                if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
                  if (prevName === 'br') {
                    node = null;
                  }
                  break;
                }
                prev = prev.prev;
              }
              if (node) {
                node.remove();
                if (isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, parent)) {
                  elementRule = schema.getElementRule(parent.name);
                  if (elementRule) {
                    if (elementRule.removeEmpty) {
                      parent.remove();
                    } else if (elementRule.paddEmpty) {
                      paddEmptyNode(settings, args, blockElements, parent);
                    }
                  }
                }
              }
            } else {
              lastParent = node;
              while (parent &amp;&amp; parent.firstChild === lastParent &amp;&amp; parent.lastChild === lastParent) {
                lastParent = parent;
                if (blockElements[parent.name]) {
                  break;
                }
                parent = parent.parent;
              }
              if (lastParent === parent &amp;&amp; settings.padd_empty_with_br !== true) {
                textNode = new AstNode('#text', 3);
                textNode.value = nbsp;
                node.replace(textNode);
              }
            }
          }
        });
      }
      parser.addAttributeFilter('href', function (nodes) {
        var i = nodes.length;
        var appendRel = function (rel) {
          var parts = rel.split(' ').filter(function (p) {
            return p.length &gt; 0;
          });
          return parts.concat(['noopener']).sort().join(' ');
        };
        var addNoOpener = function (rel) {
          var newRel = rel ? Tools.trim(rel) : '';
          if (!/\b(noopener)\b/g.test(newRel)) {
            return appendRel(newRel);
          } else {
            return newRel;
          }
        };
        if (!settings.allow_unsafe_link_target) {
          while (i--) {
            var node = nodes[i];
            if (node.name === 'a' &amp;&amp; node.attr('target') === '_blank') {
              node.attr('rel', addNoOpener(node.attr('rel')));
            }
          }
        }
      });
      if (!settings.allow_html_in_named_anchor) {
        parser.addAttributeFilter('id,name', function (nodes) {
          var i = nodes.length, sibling, prevSibling, parent, node;
          while (i--) {
            node = nodes[i];
            if (node.name === 'a' &amp;&amp; node.firstChild &amp;&amp; !node.attr('href')) {
              parent = node.parent;
              sibling = node.lastChild;
              do {
                prevSibling = sibling.prev;
                parent.insert(sibling, node);
                sibling = prevSibling;
              } while (sibling);
            }
          }
        });
      }
      if (settings.fix_list_elements) {
        parser.addNodeFilter('ul,ol', function (nodes) {
          var i = nodes.length, node, parentNode;
          while (i--) {
            node = nodes[i];
            parentNode = node.parent;
            if (parentNode.name === 'ul' || parentNode.name === 'ol') {
              if (node.prev &amp;&amp; node.prev.name === 'li') {
                node.prev.append(node);
              } else {
                var li = new AstNode('li', 1);
                li.attr('style', 'list-style-type: none');
                node.wrap(li);
              }
            }
          }
        });
      }
      if (settings.validate &amp;&amp; schema.getValidClasses()) {
        parser.addAttributeFilter('class', function (nodes) {
          var i = nodes.length, node, classList, ci, className, classValue;
          var validClasses = schema.getValidClasses();
          var validClassesMap, valid;
          while (i--) {
            node = nodes[i];
            classList = node.attr('class').split(' ');
            classValue = '';
            for (ci = 0; ci &lt; classList.length; ci++) {
              className = classList[ci];
              valid = false;
              validClassesMap = validClasses['*'];
              if (validClassesMap &amp;&amp; validClassesMap[className]) {
                valid = true;
              }
              validClassesMap = validClasses[node.name];
              if (!valid &amp;&amp; validClassesMap &amp;&amp; validClassesMap[className]) {
                valid = true;
              }
              if (valid) {
                if (classValue) {
                  classValue += ' ';
                }
                classValue += className;
              }
            }
            if (!classValue.length) {
              classValue = null;
            }
            node.attr('class', classValue);
          }
        });
      }
      registerBase64ImageFilter(parser, settings);
    };

    var makeMap$4 = Tools.makeMap, each$d = Tools.each, explode$2 = Tools.explode, extend$2 = Tools.extend;
    var DomParser = function (settings, schema) {
      if (schema === void 0) {
        schema = Schema();
      }
      var nodeFilters = {};
      var attributeFilters = [];
      var matchedNodes = {};
      var matchedAttributes = {};
      settings = settings || {};
      settings.validate = 'validate' in settings ? settings.validate : true;
      settings.root_name = settings.root_name || 'body';
      var fixInvalidChildren = function (nodes) {
        var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i;
        var sibling, nextNode;
        var nonSplitableElements = makeMap$4('tr,td,th,tbody,thead,tfoot,table');
        var nonEmptyElements = schema.getNonEmptyElements();
        var whitespaceElements = schema.getWhiteSpaceElements();
        var textBlockElements = schema.getTextBlockElements();
        var specialElements = schema.getSpecialElements();
        for (ni = 0; ni &lt; nodes.length; ni++) {
          node = nodes[ni];
          if (!node.parent || node.fixed) {
            continue;
          }
          if (textBlockElements[node.name] &amp;&amp; node.parent.name === 'li') {
            sibling = node.next;
            while (sibling) {
              if (textBlockElements[sibling.name]) {
                sibling.name = 'li';
                sibling.fixed = true;
                node.parent.insert(sibling, node.parent);
              } else {
                break;
              }
              sibling = sibling.next;
            }
            node.unwrap(node);
            continue;
          }
          parents = [node];
          for (parent = node.parent; parent &amp;&amp; !schema.isValidChild(parent.name, node.name) &amp;&amp; !nonSplitableElements[parent.name]; parent = parent.parent) {
            parents.push(parent);
          }
          if (parent &amp;&amp; parents.length &gt; 1) {
            parents.reverse();
            newParent = currentNode = filterNode(parents[0].clone());
            for (i = 0; i &lt; parents.length - 1; i++) {
              if (schema.isValidChild(currentNode.name, parents[i].name)) {
                tempNode = filterNode(parents[i].clone());
                currentNode.append(tempNode);
              } else {
                tempNode = currentNode;
              }
              for (childNode = parents[i].firstChild; childNode &amp;&amp; childNode !== parents[i + 1];) {
                nextNode = childNode.next;
                tempNode.append(childNode);
                childNode = nextNode;
              }
              currentNode = tempNode;
            }
            if (!isEmpty$2(schema, nonEmptyElements, whitespaceElements, newParent)) {
              parent.insert(newParent, parents[0], true);
              parent.insert(node, newParent);
            } else {
              parent.insert(node, parents[0], true);
            }
            parent = parents[0];
            if (isEmpty$2(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
              parent.empty().remove();
            }
          } else if (node.parent) {
            if (node.name === 'li') {
              sibling = node.prev;
              if (sibling &amp;&amp; (sibling.name === 'ul' || sibling.name === 'ol')) {
                sibling.append(node);
                continue;
              }
              sibling = node.next;
              if (sibling &amp;&amp; (sibling.name === 'ul' || sibling.name === 'ol')) {
                sibling.insert(node, sibling.firstChild, true);
                continue;
              }
              node.wrap(filterNode(new AstNode('ul', 1)));
              continue;
            }
            if (schema.isValidChild(node.parent.name, 'div') &amp;&amp; schema.isValidChild('div', node.name)) {
              node.wrap(filterNode(new AstNode('div', 1)));
            } else {
              if (specialElements[node.name]) {
                node.empty().remove();
              } else {
                node.unwrap();
              }
            }
          }
        }
      };
      var filterNode = function (node) {
        var i, name, list;
        name = node.name;
        if (name in nodeFilters) {
          list = matchedNodes[name];
          if (list) {
            list.push(node);
          } else {
            matchedNodes[name] = [node];
          }
        }
        i = attributeFilters.length;
        while (i--) {
          name = attributeFilters[i].name;
          if (name in node.attributes.map) {
            list = matchedAttributes[name];
            if (list) {
              list.push(node);
            } else {
              matchedAttributes[name] = [node];
            }
          }
        }
        return node;
      };
      var addNodeFilter = function (name, callback) {
        each$d(explode$2(name), function (name) {
          var list = nodeFilters[name];
          if (!list) {
            nodeFilters[name] = list = [];
          }
          list.push(callback);
        });
      };
      var getNodeFilters = function () {
        var out = [];
        for (var name_1 in nodeFilters) {
          if (nodeFilters.hasOwnProperty(name_1)) {
            out.push({
              name: name_1,
              callbacks: nodeFilters[name_1]
            });
          }
        }
        return out;
      };
      var addAttributeFilter = function (name, callback) {
        each$d(explode$2(name), function (name) {
          var i;
          for (i = 0; i &lt; attributeFilters.length; i++) {
            if (attributeFilters[i].name === name) {
              attributeFilters[i].callbacks.push(callback);
              return;
            }
          }
          attributeFilters.push({
            name: name,
            callbacks: [callback]
          });
        });
      };
      var getAttributeFilters = function () {
        return [].concat(attributeFilters);
      };
      var parse = function (html, args) {
        var nodes, i, l, fi, fl, list, name;
        var invalidChildren = [];
        var isInWhiteSpacePreservedElement;
        var node;
        var getRootBlockName = function (name) {
          if (name === false) {
            return '';
          } else if (name === true) {
            return 'p';
          } else {
            return name;
          }
        };
        args = args || {};
        matchedNodes = {};
        matchedAttributes = {};
        var blockElements = extend$2(makeMap$4('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
        var nonEmptyElements = schema.getNonEmptyElements();
        var children = schema.children;
        var validate = settings.validate;
        var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
        var rootBlockName = getRootBlockName(forcedRootBlockName);
        var whiteSpaceElements = schema.getWhiteSpaceElements();
        var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
        var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
        var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
        var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
        isInWhiteSpacePreservedElement = whiteSpaceElements.hasOwnProperty(args.context) || whiteSpaceElements.hasOwnProperty(settings.root_name);
        var addRootBlocks = function () {
          var node = rootNode.firstChild, next, rootBlockNode;
          var trim = function (rootBlockNode) {
            if (rootBlockNode) {
              node = rootBlockNode.firstChild;
              if (node &amp;&amp; node.type === 3) {
                node.value = node.value.replace(startWhiteSpaceRegExp, '');
              }
              node = rootBlockNode.lastChild;
              if (node &amp;&amp; node.type === 3) {
                node.value = node.value.replace(endWhiteSpaceRegExp, '');
              }
            }
          };
          if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
            return;
          }
          while (node) {
            next = node.next;
            if (node.type === 3 || node.type === 1 &amp;&amp; node.name !== 'p' &amp;&amp; !blockElements[node.name] &amp;&amp; !node.attr('data-mce-type')) {
              if (!rootBlockNode) {
                rootBlockNode = createNode(rootBlockName, 1);
                rootBlockNode.attr(settings.forced_root_block_attrs);
                rootNode.insert(rootBlockNode, node);
                rootBlockNode.append(node);
              } else {
                rootBlockNode.append(node);
              }
            } else {
              trim(rootBlockNode);
              rootBlockNode = null;
            }
            node = next;
          }
          trim(rootBlockNode);
        };
        var createNode = function (name, type) {
          var node = new AstNode(name, type);
          var list;
          if (name in nodeFilters) {
            list = matchedNodes[name];
            if (list) {
              list.push(node);
            } else {
              matchedNodes[name] = [node];
            }
          }
          return node;
        };
        var removeWhitespaceBefore = function (node) {
          var textNode, textNodeNext, textVal, sibling;
          var blockElements = schema.getBlockElements();
          for (textNode = node.prev; textNode &amp;&amp; textNode.type === 3;) {
            textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
            if (textVal.length &gt; 0) {
              textNode.value = textVal;
              return;
            }
            textNodeNext = textNode.next;
            if (textNodeNext) {
              if (textNodeNext.type === 3 &amp;&amp; textNodeNext.value.length) {
                textNode = textNode.prev;
                continue;
              }
              if (!blockElements[textNodeNext.name] &amp;&amp; textNodeNext.name !== 'script' &amp;&amp; textNodeNext.name !== 'style') {
                textNode = textNode.prev;
                continue;
              }
            }
            sibling = textNode.prev;
            textNode.remove();
            textNode = sibling;
          }
        };
        var cloneAndExcludeBlocks = function (input) {
          var name;
          var output = {};
          for (name in input) {
            if (name !== 'li' &amp;&amp; name !== 'p') {
              output[name] = input[name];
            }
          }
          return output;
        };
        var parser = SaxParser({
          validate: validate,
          allow_html_data_urls: settings.allow_html_data_urls,
          allow_svg_data_urls: settings.allow_svg_data_urls,
          allow_script_urls: settings.allow_script_urls,
          allow_conditional_comments: settings.allow_conditional_comments,
          preserve_cdata: settings.preserve_cdata,
          self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
          cdata: function (text) {
            node.append(createNode('#cdata', 4)).value = text;
          },
          text: function (text, raw) {
            var textNode;
            if (!isInWhiteSpacePreservedElement) {
              text = text.replace(allWhiteSpaceRegExp, ' ');
              if (isLineBreakNode(node.lastChild, blockElements)) {
                text = text.replace(startWhiteSpaceRegExp, '');
              }
            }
            if (text.length !== 0) {
              textNode = createNode('#text', 3);
              textNode.raw = !!raw;
              node.append(textNode).value = text;
            }
          },
          comment: function (text) {
            node.append(createNode('#comment', 8)).value = text;
          },
          pi: function (name, text) {
            node.append(createNode(name, 7)).value = text;
            removeWhitespaceBefore(node);
          },
          doctype: function (text) {
            var newNode = node.append(createNode('#doctype', 10));
            newNode.value = text;
            removeWhitespaceBefore(node);
          },
          start: function (name, attrs, empty) {
            var newNode, attrFiltersLen, attrName, parent;
            var elementRule = validate ? schema.getElementRule(name) : {};
            if (elementRule) {
              newNode = createNode(elementRule.outputName || name, 1);
              newNode.attributes = attrs;
              newNode.shortEnded = empty;
              node.append(newNode);
              parent = children[node.name];
              if (parent &amp;&amp; children[newNode.name] &amp;&amp; !parent[newNode.name]) {
                invalidChildren.push(newNode);
              }
              attrFiltersLen = attributeFilters.length;
              while (attrFiltersLen--) {
                attrName = attributeFilters[attrFiltersLen].name;
                if (attrName in attrs.map) {
                  list = matchedAttributes[attrName];
                  if (list) {
                    list.push(newNode);
                  } else {
                    matchedAttributes[attrName] = [newNode];
                  }
                }
              }
              if (blockElements[name]) {
                removeWhitespaceBefore(newNode);
              }
              if (!empty) {
                node = newNode;
              }
              if (!isInWhiteSpacePreservedElement &amp;&amp; whiteSpaceElements[name]) {
                isInWhiteSpacePreservedElement = true;
              }
            }
          },
          end: function (name) {
            var textNode, text, sibling, tempNode;
            var elementRule = validate ? schema.getElementRule(name) : {};
            if (elementRule) {
              if (blockElements[name]) {
                if (!isInWhiteSpacePreservedElement) {
                  textNode = node.firstChild;
                  if (textNode &amp;&amp; textNode.type === 3) {
                    text = textNode.value.replace(startWhiteSpaceRegExp, '');
                    if (text.length &gt; 0) {
                      textNode.value = text;
                      textNode = textNode.next;
                    } else {
                      sibling = textNode.next;
                      textNode.remove();
                      textNode = sibling;
                      while (textNode &amp;&amp; textNode.type === 3) {
                        text = textNode.value;
                        sibling = textNode.next;
                        if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                          textNode.remove();
                          textNode = sibling;
                        }
                        textNode = sibling;
                      }
                    }
                  }
                  textNode = node.lastChild;
                  if (textNode &amp;&amp; textNode.type === 3) {
                    text = textNode.value.replace(endWhiteSpaceRegExp, '');
                    if (text.length &gt; 0) {
                      textNode.value = text;
                      textNode = textNode.prev;
                    } else {
                      sibling = textNode.prev;
                      textNode.remove();
                      textNode = sibling;
                      while (textNode &amp;&amp; textNode.type === 3) {
                        text = textNode.value;
                        sibling = textNode.prev;
                        if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                          textNode.remove();
                          textNode = sibling;
                        }
                        textNode = sibling;
                      }
                    }
                  }
                }
              }
              if (isInWhiteSpacePreservedElement &amp;&amp; whiteSpaceElements[name]) {
                isInWhiteSpacePreservedElement = false;
              }
              if (elementRule.removeEmpty &amp;&amp; isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node)) {
                tempNode = node.parent;
                if (blockElements[node.name]) {
                  node.empty().remove();
                } else {
                  node.unwrap();
                }
                node = tempNode;
                return;
              }
              if (elementRule.paddEmpty &amp;&amp; (isPaddedWithNbsp(node) || isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node))) {
                paddEmptyNode(settings, args, blockElements, node);
              }
              node = node.parent;
            }
          }
        }, schema);
        var rootNode = node = new AstNode(args.context || settings.root_name, 11);
        parser.parse(html, args.format);
        if (validate &amp;&amp; invalidChildren.length) {
          if (!args.context) {
            fixInvalidChildren(invalidChildren);
          } else {
            args.invalid = true;
          }
        }
        if (rootBlockName &amp;&amp; (rootNode.name === 'body' || args.isRootContent)) {
          addRootBlocks();
        }
        if (!args.invalid) {
          for (name in matchedNodes) {
            if (!matchedNodes.hasOwnProperty(name)) {
              continue;
            }
            list = nodeFilters[name];
            nodes = matchedNodes[name];
            fi = nodes.length;
            while (fi--) {
              if (!nodes[fi].parent) {
                nodes.splice(fi, 1);
              }
            }
            for (i = 0, l = list.length; i &lt; l; i++) {
              list[i](nodes, name, args);
            }
          }
          for (i = 0, l = attributeFilters.length; i &lt; l; i++) {
            list = attributeFilters[i];
            if (list.name in matchedAttributes) {
              nodes = matchedAttributes[list.name];
              fi = nodes.length;
              while (fi--) {
                if (!nodes[fi].parent) {
                  nodes.splice(fi, 1);
                }
              }
              for (fi = 0, fl = list.callbacks.length; fi &lt; fl; fi++) {
                list.callbacks[fi](nodes, list.name, args);
              }
            }
          }
        }
        return rootNode;
      };
      var exports = {
        schema: schema,
        addAttributeFilter: addAttributeFilter,
        getAttributeFilters: getAttributeFilters,
        addNodeFilter: addNodeFilter,
        getNodeFilters: getNodeFilters,
        filterNode: filterNode,
        parse: parse
      };
      register$2(exports, settings);
      register$1(exports, settings);
      return exports;
    };

    var register$3 = function (htmlParser, settings, dom) {
      htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i];
          node.attr('tabindex', node.attr('data-mce-tabindex'));
          node.attr(name, null);
        }
      });
      htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
        var i = nodes.length, node, value;
        var internalName = 'data-mce-' + name;
        var urlConverter = settings.url_converter;
        var urlConverterScope = settings.url_converter_scope;
        while (i--) {
          node = nodes[i];
          value = node.attr(internalName);
          if (value !== undefined) {
            node.attr(name, value.length &gt; 0 ? value : null);
            node.attr(internalName, null);
          } else {
            value = node.attr(name);
            if (name === 'style') {
              value = dom.serializeStyle(dom.parseStyle(value), node.name);
            } else if (urlConverter) {
              value = urlConverter.call(urlConverterScope, value, name, node.name);
            }
            node.attr(name, value.length &gt; 0 ? value : null);
          }
        }
      });
      htmlParser.addAttributeFilter('class', function (nodes) {
        var i = nodes.length, node, value;
        while (i--) {
          node = nodes[i];
          value = node.attr('class');
          if (value) {
            value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
            node.attr('class', value.length &gt; 0 ? value : null);
          }
        }
      });
      htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i];
          if (node.attr('data-mce-type') === 'bookmark' &amp;&amp; !args.cleanup) {
            var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
              return !isZwsp$1(firstChild.value);
            });
            if (hasChildren) {
              node.unwrap();
            } else {
              node.remove();
            }
          }
        }
      });
      htmlParser.addNodeFilter('noscript', function (nodes) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i].firstChild;
          if (node) {
            node.value = Entities.decode(node.value);
          }
        }
      });
      htmlParser.addNodeFilter('script,style', function (nodes, name) {
        var i = nodes.length, node, value, type;
        var trim = function (value) {
          return value.replace(/(&lt;!--\[CDATA\[|\]\]--&gt;)/g, '\n').replace(/^[\r\n]*|[\r\n]*$/g, '').replace(/^\s*((&lt;!--)?(\s*\/\/)?\s*&lt;!\[CDATA\[|(&lt;!--\s*)?\/\*\s*&lt;!\[CDATA\[\s*\*\/|(\/\/)?\s*&lt;!--|\/\*\s*&lt;!--\s*\*\/)\s*[\r\n]*/gi, '').replace(/\s*(\/\*\s*\]\]&gt;\s*\*\/(--&gt;)?|\s*\/\/\s*\]\]&gt;(--&gt;)?|\/\/\s*(--&gt;)?|\]\]&gt;|\/\*\s*--&gt;\s*\*\/|\s*--&gt;\s*)\s*$/g, '');
        };
        while (i--) {
          node = nodes[i];
          value = node.firstChild ? node.firstChild.value : '';
          if (name === 'script') {
            type = node.attr('type');
            if (type) {
              node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
            }
            if (settings.element_format === 'xhtml' &amp;&amp; value.length &gt; 0) {
              node.firstChild.value = '// &lt;![CDATA[\n' + trim(value) + '\n// ]]&gt;';
            }
          } else {
            if (settings.element_format === 'xhtml' &amp;&amp; value.length &gt; 0) {
              node.firstChild.value = '&lt;!--\n' + trim(value) + '\n--&gt;';
            }
          }
        }
      });
      htmlParser.addNodeFilter('#comment', function (nodes) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i];
          if (settings.preserve_cdata &amp;&amp; node.value.indexOf('[CDATA[') === 0) {
            node.name = '#cdata';
            node.type = 4;
            node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
          } else if (node.value.indexOf('mce:protected ') === 0) {
            node.name = '#text';
            node.type = 3;
            node.raw = true;
            node.value = unescape(node.value).substr(14);
          }
        }
      });
      htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
        var i = nodes.length, node;
        while (i--) {
          node = nodes[i];
          if (node.type === 7) {
            node.remove();
          } else if (node.type === 1) {
            if (name === 'input' &amp;&amp; !node.attr('type')) {
              node.attr('type', 'text');
            }
          }
        }
      });
      htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
        each(nodes, function (node) {
          if (node.attr('data-mce-type') === 'format-caret') {
            if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
              node.remove();
            } else {
              node.unwrap();
            }
          }
        });
      });
      htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,' + 'data-mce-selected,data-mce-expando,' + 'data-mce-type,data-mce-resize,data-mce-placeholder', function (nodes, name) {
        var i = nodes.length;
        while (i--) {
          nodes[i].attr(name, null);
        }
      });
    };
    var trimTrailingBr = function (rootNode) {
      var isBr = function (node) {
        return node &amp;&amp; node.name === 'br';
      };
      var brNode1 = rootNode.lastChild;
      if (isBr(brNode1)) {
        var brNode2 = brNode1.prev;
        if (isBr(brNode2)) {
          brNode1.remove();
          brNode2.remove();
        }
      }
    };

    var preProcess = function (editor, node, args) {
      var doc, oldDoc;
      var dom = editor.dom;
      node = node.cloneNode(true);
      var impl = document.implementation;
      if (impl.createHTMLDocument) {
        doc = impl.createHTMLDocument('');
        Tools.each(node.nodeName === 'BODY' ? node.childNodes : [node], function (node) {
          doc.body.appendChild(doc.importNode(node, true));
        });
        if (node.nodeName !== 'BODY') {
          node = doc.body.firstChild;
        } else {
          node = doc.body;
        }
        oldDoc = dom.doc;
        dom.doc = doc;
      }
      firePreProcess(editor, __assign(__assign({}, args), { node: node }));
      if (oldDoc) {
        dom.doc = oldDoc;
      }
      return node;
    };
    var shouldFireEvent = function (editor, args) {
      return editor &amp;&amp; editor.hasEventListeners('PreProcess') &amp;&amp; !args.no_events;
    };
    var process = function (editor, node, args) {
      return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
    };

    var addTempAttr = function (htmlParser, tempAttrs, name) {
      if (Tools.inArray(tempAttrs, name) === -1) {
        htmlParser.addAttributeFilter(name, function (nodes, name) {
          var i = nodes.length;
          while (i--) {
            nodes[i].attr(name, null);
          }
        });
        tempAttrs.push(name);
      }
    };
    var postProcess$1 = function (editor, args, content) {
      if (!args.no_events &amp;&amp; editor) {
        var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
        return outArgs.content;
      } else {
        return content;
      }
    };
    var getHtmlFromNode = function (dom, node, args) {
      var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
      return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
    };
    var parseHtml = function (htmlParser, html, args) {
      var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
      var rootNode = htmlParser.parse(html, parserArgs);
      trimTrailingBr(rootNode);
      return rootNode;
    };
    var serializeNode = function (settings, schema, node) {
      var htmlSerializer = HtmlSerializer(settings, schema);
      return htmlSerializer.serialize(node);
    };
    var toHtml = function (editor, settings, schema, rootNode, args) {
      var content = serializeNode(settings, schema, rootNode);
      return postProcess$1(editor, args, content);
    };
    var DomSerializerImpl = function (settings, editor) {
      var tempAttrs = ['data-mce-selected'];
      var dom = editor &amp;&amp; editor.dom ? editor.dom : DOMUtils.DOM;
      var schema = editor &amp;&amp; editor.schema ? editor.schema : Schema(settings);
      settings.entity_encoding = settings.entity_encoding || 'named';
      settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
      var htmlParser = DomParser(settings, schema);
      register$3(htmlParser, settings, dom);
      var serialize = function (node, parserArgs) {
        if (parserArgs === void 0) {
          parserArgs = {};
        }
        var args = __assign({ format: 'html' }, parserArgs);
        var targetNode = process(editor, node, args);
        var html = getHtmlFromNode(dom, targetNode, args);
        var rootNode = parseHtml(htmlParser, html, args);
        return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
      };
      return {
        schema: schema,
        addNodeFilter: htmlParser.addNodeFilter,
        addAttributeFilter: htmlParser.addAttributeFilter,
        serialize: serialize,
        addRules: function (rules) {
          schema.addValidElements(rules);
        },
        setRules: function (rules) {
          schema.setValidElements(rules);
        },
        addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
        getTempAttrs: constant(tempAttrs),
        getNodeFilters: htmlParser.getNodeFilters,
        getAttributeFilters: htmlParser.getAttributeFilters
      };
    };

    var DomSerializer = function (settings, editor) {
      var domSerializer = DomSerializerImpl(settings, editor);
      return {
        schema: domSerializer.schema,
        addNodeFilter: domSerializer.addNodeFilter,
        addAttributeFilter: domSerializer.addAttributeFilter,
        serialize: domSerializer.serialize,
        addRules: domSerializer.addRules,
        setRules: domSerializer.setRules,
        addTempAttr: domSerializer.addTempAttr,
        getTempAttrs: domSerializer.getTempAttrs,
        getNodeFilters: domSerializer.getNodeFilters,
        getAttributeFilters: domSerializer.getAttributeFilters
      };
    };

    var defaultFormat$1 = 'html';
    var getContent$2 = function (editor, args) {
      if (args === void 0) {
        args = {};
      }
      var format = args.format ? args.format : defaultFormat$1;
      return getContent(editor, args, format);
    };

    var setContent$2 = function (editor, content, args) {
      if (args === void 0) {
        args = {};
      }
      return setContent(editor, content, args);
    };

    var DOM$3 = DOMUtils.DOM;
    var restoreOriginalStyles = function (editor) {
      DOM$3.setStyle(editor.id, 'display', editor.orgDisplay);
    };
    var safeDestroy = function (x) {
      return Optional.from(x).each(function (x) {
        return x.destroy();
      });
    };
    var clearDomReferences = function (editor) {
      editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
      editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
      editor.iframeElement = editor.targetElm = null;
      if (editor.selection) {
        editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
      }
    };
    var restoreForm = function (editor) {
      var form = editor.formElement;
      if (form) {
        if (form._mceOldSubmit) {
          form.submit = form._mceOldSubmit;
          form._mceOldSubmit = null;
        }
        DOM$3.unbind(form, 'submit reset', editor.formEventDelegate);
      }
    };
    var remove$7 = function (editor) {
      if (!editor.removed) {
        var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
        var body = editor.getBody();
        var element = editor.getElement();
        if (body) {
          editor.save({ is_removing: true });
        }
        editor.removed = true;
        editor.unbindAllNativeEvents();
        if (editor.hasHiddenInput &amp;&amp; element) {
          DOM$3.remove(element.nextSibling);
        }
        fireRemove(editor);
        editor.editorManager.remove(editor);
        if (!editor.inline &amp;&amp; body) {
          restoreOriginalStyles(editor);
        }
        fireDetach(editor);
        DOM$3.remove(editor.getContainer());
        safeDestroy(_selectionOverrides);
        safeDestroy(editorUpload);
        editor.destroy();
      }
    };
    var destroy = function (editor, automatic) {
      var selection = editor.selection, dom = editor.dom;
      if (editor.destroyed) {
        return;
      }
      if (!automatic &amp;&amp; !editor.removed) {
        editor.remove();
        return;
      }
      if (!automatic) {
        editor.editorManager.off('beforeunload', editor._beforeUnload);
        if (editor.theme &amp;&amp; editor.theme.destroy) {
          editor.theme.destroy();
        }
        safeDestroy(selection);
        safeDestroy(dom);
      }
      restoreForm(editor);
      clearDomReferences(editor);
      editor.destroyed = true;
    };

    var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
    var deep$1 = function (old, nu) {
      var bothObjects = isObject(old) &amp;&amp; isObject(nu);
      return bothObjects ? deepMerge(old, nu) : nu;
    };
    var baseMerge = function (merger) {
      return function () {
        var objects = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          objects[_i] = arguments[_i];
        }
        if (objects.length === 0) {
          throw new Error('Can\'t merge zero objects');
        }
        var ret = {};
        for (var j = 0; j &lt; objects.length; j++) {
          var curObject = objects[j];
          for (var key in curObject) {
            if (hasOwnProperty$2.call(curObject, key)) {
              ret[key] = merger(ret[key], curObject[key]);
            }
          }
        }
        return ret;
      };
    };
    var deepMerge = baseMerge(deep$1);

    var sectionResult = function (sections, settings) {
      return {
        sections: constant(sections),
        settings: constant(settings)
      };
    };
    var deviceDetection = detect$3().deviceType;
    var isTouch = deviceDetection.isTouch();
    var isPhone = deviceDetection.isPhone();
    var isTablet = deviceDetection.isTablet();
    var legacyMobilePlugins = [
      'lists',
      'autolink',
      'autosave'
    ];
    var defaultTouchSettings = {
      table_grid: false,
      object_resizing: false,
      resize: false
    };
    var normalizePlugins = function (plugins) {
      var pluginNames = isArray(plugins) ? plugins.join(' ') : plugins;
      var trimmedPlugins = map(isString(pluginNames) ? pluginNames.split(' ') : [], trim);
      return filter(trimmedPlugins, function (item) {
        return item.length &gt; 0;
      });
    };
    var filterLegacyMobilePlugins = function (plugins) {
      return filter(plugins, curry(contains, legacyMobilePlugins));
    };
    var extractSections = function (keys, settings) {
      var result = bifilter(settings, function (value, key) {
        return contains(keys, key);
      });
      return sectionResult(result.t, result.f);
    };
    var getSection = function (sectionResult, name, defaults) {
      if (defaults === void 0) {
        defaults = {};
      }
      var sections = sectionResult.sections();
      var sectionSettings = sections.hasOwnProperty(name) ? sections[name] : {};
      return Tools.extend({}, defaults, sectionSettings);
    };
    var hasSection = function (sectionResult, name) {
      return sectionResult.sections().hasOwnProperty(name);
    };
    var isSectionTheme = function (sectionResult, name, theme) {
      var section = sectionResult.sections();
      return hasSection(sectionResult, name) &amp;&amp; section[name].theme === theme;
    };
    var getSectionConfig = function (sectionResult, name) {
      return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
    };
    var getToolbarMode = function (settings, defaultVal) {
      return get$1(settings, 'toolbar_mode').orThunk(function () {
        return get$1(settings, 'toolbar_drawer').map(function (val) {
          return val === false ? 'wrap' : val;
        });
      }).getOr(defaultVal);
    };
    var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
      var baseDefaults = {
        id: id,
        theme: 'silver',
        toolbar_mode: getToolbarMode(settings, 'floating'),
        plugins: '',
        document_base_url: documentBaseUrl,
        add_form_submit_trigger: true,
        submit_patch: true,
        add_unload_trigger: true,
        convert_urls: true,
        relative_urls: true,
        remove_script_host: true,
        object_resizing: true,
        doctype: '&lt;!DOCTYPE html&gt;',
        visual: true,
        font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
        forced_root_block: 'p',
        hidden_input: true,
        inline_styles: true,
        convert_fonts_to_spans: true,
        indent: true,
        indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
        indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
        entity_encoding: 'named',
        url_converter: editor.convertURL,
        url_converter_scope: editor
      };
      return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
    };
    var getDefaultMobileSettings = function (mobileSettings, isPhone) {
      var defaultMobileSettings = {
        resize: false,
        toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
        toolbar_sticky: false
      };
      var defaultPhoneSettings = { menubar: false };
      return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
    };
    var getExternalPlugins$1 = function (overrideSettings, settings) {
      var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
      if (overrideSettings &amp;&amp; overrideSettings.external_plugins) {
        return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
      } else {
        return userDefinedExternalPlugins;
      }
    };
    var combinePlugins = function (forcedPlugins, plugins) {
      return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
    };
    var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
      if (isMobileDevice &amp;&amp; isSectionTheme(sectionResult, 'mobile', 'mobile')) {
        return filterLegacyMobilePlugins(mobilePlugins);
      } else if (isMobileDevice &amp;&amp; hasSection(sectionResult, 'mobile')) {
        return mobilePlugins;
      } else {
        return desktopPlugins;
      }
    };
    var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
      var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
      var desktopPlugins = normalizePlugins(settings.plugins);
      var mobileConfig = getSectionConfig(sectionResult, 'mobile');
      var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
      var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
      var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
      if (Env.browser.isIE() &amp;&amp; contains(combinedPlugins, 'rtc')) {
        throw new Error('RTC plugin is not supported on IE 11.');
      }
      return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
    };
    var isOnMobile = function (isMobileDevice, sectionResult) {
      return isMobileDevice &amp;&amp; hasSection(sectionResult, 'mobile');
    };
    var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
      var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
      var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
      var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
        validate: true,
        external_plugins: getExternalPlugins$1(defaultOverrideSettings, sectionResult.settings())
      });
      return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
    };
    var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
      var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
      return combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
    };
    var getFiltered = function (predicate, editor, name) {
      return Optional.from(editor.settings[name]).filter(predicate);
    };
    var getParamObject = function (value) {
      var output = {};
      if (typeof value === 'string') {
        each(value.indexOf('=') &gt; 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
          var arr = val.split('=');
          if (arr.length &gt; 1) {
            output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
          } else {
            output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
          }
        });
      } else {
        output = value;
      }
      return output;
    };
    var isArrayOf = function (p) {
      return function (a) {
        return isArray(a) &amp;&amp; forall(a, p);
      };
    };
    var getParam = function (editor, name, defaultVal, type) {
      var value = name in editor.settings ? editor.settings[name] : defaultVal;
      if (type === 'hash') {
        return getParamObject(value);
      } else if (type === 'string') {
        return getFiltered(isString, editor, name).getOr(defaultVal);
      } else if (type === 'number') {
        return getFiltered(isNumber, editor, name).getOr(defaultVal);
      } else if (type === 'boolean') {
        return getFiltered(isBoolean, editor, name).getOr(defaultVal);
      } else if (type === 'object') {
        return getFiltered(isObject, editor, name).getOr(defaultVal);
      } else if (type === 'array') {
        return getFiltered(isArray, editor, name).getOr(defaultVal);
      } else if (type === 'string[]') {
        return getFiltered(isArrayOf(isString), editor, name).getOr(defaultVal);
      } else if (type === 'function') {
        return getFiltered(isFunction, editor, name).getOr(defaultVal);
      } else {
        return value;
      }
    };

    var CreateIconManager = function () {
      var lookup = {};
      var add = function (id, iconPack) {
        lookup[id] = iconPack;
      };
      var get = function (id) {
        if (lookup[id]) {
          return lookup[id];
        }
        return { icons: {} };
      };
      var has$1 = function (id) {
        return has(lookup, id);
      };
      return {
        add: add,
        get: get,
        has: has$1
      };
    };
    var IconManager = CreateIconManager();

    var getProp = function (propName, elm) {
      var rawElm = elm.dom;
      return rawElm[propName];
    };
    var getComputedSizeProp = function (propName, elm) {
      return parseInt(get$5(elm, propName), 10);
    };
    var getClientWidth = curry(getProp, 'clientWidth');
    var getClientHeight = curry(getProp, 'clientHeight');
    var getMarginTop = curry(getComputedSizeProp, 'margin-top');
    var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
    var getBoundingClientRect$1 = function (elm) {
      return elm.dom.getBoundingClientRect();
    };
    var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
      var clientWidth = getClientWidth(bodyElm);
      var clientHeight = getClientHeight(bodyElm);
      return clientX &gt;= 0 &amp;&amp; clientY &gt;= 0 &amp;&amp; clientX &lt;= clientWidth &amp;&amp; clientY &lt;= clientHeight;
    };
    var transpose = function (inline, elm, clientX, clientY) {
      var clientRect = getBoundingClientRect$1(elm);
      var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
      var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
      var x = clientX - deltaX;
      var y = clientY - deltaY;
      return {
        x: x,
        y: y
      };
    };
    var isXYInContentArea = function (editor, clientX, clientY) {
      var bodyElm = SugarElement.fromDom(editor.getBody());
      var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
      var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
      return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
    };
    var fromDomSafe = function (node) {
      return Optional.from(node).map(SugarElement.fromDom);
    };
    var isEditorAttachedToDom = function (editor) {
      var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
      return fromDomSafe(rawContainer).map(inBody).getOr(false);
    };

    var NotificationManagerImpl = function () {
      var unimplemented = function () {
        throw new Error('Theme did not provide a NotificationManager implementation.');
      };
      return {
        open: unimplemented,
        close: unimplemented,
        reposition: unimplemented,
        getArgs: unimplemented
      };
    };

    var NotificationManager = function (editor) {
      var notifications = [];
      var getImplementation = function () {
        var theme = editor.theme;
        return theme &amp;&amp; theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
      };
      var getTopNotification = function () {
        return Optional.from(notifications[0]);
      };
      var isEqual = function (a, b) {
        return a.type === b.type &amp;&amp; a.text === b.text &amp;&amp; !a.progressBar &amp;&amp; !a.timeout &amp;&amp; !b.progressBar &amp;&amp; !b.timeout;
      };
      var reposition = function () {
        if (notifications.length &gt; 0) {
          getImplementation().reposition(notifications);
        }
      };
      var addNotification = function (notification) {
        notifications.push(notification);
      };
      var closeNotification = function (notification) {
        findIndex(notifications, function (otherNotification) {
          return otherNotification === notification;
        }).each(function (index) {
          notifications.splice(index, 1);
        });
      };
      var open = function (spec, fireEvent) {
        if (fireEvent === void 0) {
          fireEvent = true;
        }
        if (editor.removed || !isEditorAttachedToDom(editor)) {
          return;
        }
        if (fireEvent) {
          editor.fire('BeforeOpenNotification', { notification: spec });
        }
        return find(notifications, function (notification) {
          return isEqual(getImplementation().getArgs(notification), spec);
        }).getOrThunk(function () {
          editor.editorManager.setActive(editor);
          var notification = getImplementation().open(spec, function () {
            closeNotification(notification);
            reposition();
            getTopNotification().fold(function () {
              return editor.focus();
            }, function (top) {
              return focus(SugarElement.fromDom(top.getEl()));
            });
          });
          addNotification(notification);
          reposition();
          editor.fire('OpenNotification', { notification: __assign({}, notification) });
          return notification;
        });
      };
      var close = function () {
        getTopNotification().each(function (notification) {
          getImplementation().close(notification);
          closeNotification(notification);
          reposition();
        });
      };
      var getNotifications = function () {
        return notifications;
      };
      var registerEvents = function (editor) {
        editor.on('SkinLoaded', function () {
          var serviceMessage = getServiceMessage(editor);
          if (serviceMessage) {
            open({
              text: serviceMessage,
              type: 'warning',
              timeout: 0
            }, false);
          }
        });
        editor.on('ResizeEditor ResizeWindow NodeChange', function () {
          Delay.requestAnimationFrame(reposition);
        });
        editor.on('remove', function () {
          each(notifications.slice(), function (notification) {
            getImplementation().close(notification);
          });
        });
      };
      registerEvents(editor);
      return {
        open: open,
        close: close,
        getNotifications: getNotifications
      };
    };

    var PluginManager = AddOnManager.PluginManager;

    var ThemeManager = AddOnManager.ThemeManager;

    function WindowManagerImpl () {
      var unimplemented = function () {
        throw new Error('Theme did not provide a WindowManager implementation.');
      };
      return {
        open: unimplemented,
        openUrl: unimplemented,
        alert: unimplemented,
        confirm: unimplemented,
        close: unimplemented,
        getParams: unimplemented,
        setParams: unimplemented
      };
    }

    var WindowManager = function (editor) {
      var dialogs = [];
      var getImplementation = function () {
        var theme = editor.theme;
        return theme &amp;&amp; theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
      };
      var funcBind = function (scope, f) {
        return function () {
          var args = [];
          for (var _i = 0; _i &lt; arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          return f ? f.apply(scope, args) : undefined;
        };
      };
      var fireOpenEvent = function (dialog) {
        editor.fire('OpenWindow', { dialog: dialog });
      };
      var fireCloseEvent = function (dialog) {
        editor.fire('CloseWindow', { dialog: dialog });
      };
      var addDialog = function (dialog) {
        dialogs.push(dialog);
        fireOpenEvent(dialog);
      };
      var closeDialog = function (dialog) {
        fireCloseEvent(dialog);
        dialogs = filter(dialogs, function (otherDialog) {
          return otherDialog !== dialog;
        });
        if (dialogs.length === 0) {
          editor.focus();
        }
      };
      var getTopDialog = function () {
        return Optional.from(dialogs[dialogs.length - 1]);
      };
      var storeSelectionAndOpenDialog = function (openDialog) {
        editor.editorManager.setActive(editor);
        store(editor);
        var dialog = openDialog();
        addDialog(dialog);
        return dialog;
      };
      var open = function (args, params) {
        return storeSelectionAndOpenDialog(function () {
          return getImplementation().open(args, params, closeDialog);
        });
      };
      var openUrl = function (args) {
        return storeSelectionAndOpenDialog(function () {
          return getImplementation().openUrl(args, closeDialog);
        });
      };
      var alert = function (message, callback, scope) {
        var windowManagerImpl = getImplementation();
        windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
      };
      var confirm = function (message, callback, scope) {
        var windowManagerImpl = getImplementation();
        windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
      };
      var close = function () {
        getTopDialog().each(function (dialog) {
          getImplementation().close(dialog);
          closeDialog(dialog);
        });
      };
      editor.on('remove', function () {
        each(dialogs, function (dialog) {
          getImplementation().close(dialog);
        });
      });
      return {
        open: open,
        openUrl: openUrl,
        alert: alert,
        confirm: confirm,
        close: close
      };
    };

    var displayNotification = function (editor, message) {
      editor.notificationManager.open({
        type: 'error',
        text: message
      });
    };
    var displayError = function (editor, message) {
      if (editor._skinLoaded) {
        displayNotification(editor, message);
      } else {
        editor.on('SkinLoaded', function () {
          displayNotification(editor, message);
        });
      }
    };
    var uploadError = function (editor, message) {
      displayError(editor, I18n.translate([
        'Failed to upload image: {0}',
        message
      ]));
    };
    var logError = function (editor, errorType, msg) {
      fireError(editor, errorType, { message: msg });
      console.error(msg);
    };
    var createLoadError = function (type, url, name) {
      return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
    };
    var pluginLoadError = function (editor, url, name) {
      logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
    };
    var iconsLoadError = function (editor, url, name) {
      logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
    };
    var languageLoadError = function (editor, url, name) {
      logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
    };
    var pluginInitError = function (editor, name, err) {
      var message = I18n.translate([
        'Failed to initialize plugin: {0}',
        name
      ]);
      fireError(editor, 'PluginLoadError', { message: message });
      initError(message, err);
      displayError(editor, message);
    };
    var initError = function (message) {
      var x = [];
      for (var _i = 1; _i &lt; arguments.length; _i++) {
        x[_i - 1] = arguments[_i];
      }
      var console = window.console;
      if (console) {
        if (console.error) {
          console.error.apply(console, __spreadArrays([message], x));
        } else {
          console.log.apply(console, __spreadArrays([message], x));
        }
      }
    };

    var isContentCssSkinName = function (url) {
      return /^[a-z0-9\-]+$/i.test(url);
    };
    var getContentCssUrls = function (editor) {
      return transformToUrls(editor, getContentCss(editor));
    };
    var getFontCssUrls = function (editor) {
      return transformToUrls(editor, getFontCss(editor));
    };
    var transformToUrls = function (editor, cssLinks) {
      var skinUrl = editor.editorManager.baseURL + '/skins/content';
      var suffix = editor.editorManager.suffix;
      var contentCssFile = 'content' + suffix + '.css';
      var inline = editor.inline === true;
      return map(cssLinks, function (url) {
        if (isContentCssSkinName(url) &amp;&amp; !inline) {
          return skinUrl + '/' + url + '/' + contentCssFile;
        } else {
          return editor.documentBaseURI.toAbsolute(url);
        }
      });
    };
    var appendContentCssFromSettings = function (editor) {
      editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
    };

    var UploadStatus = function () {
      var PENDING = 1, UPLOADED = 2;
      var blobUriStatuses = {};
      var createStatus = function (status, resultUri) {
        return {
          status: status,
          resultUri: resultUri
        };
      };
      var hasBlobUri = function (blobUri) {
        return blobUri in blobUriStatuses;
      };
      var getResultUri = function (blobUri) {
        var result = blobUriStatuses[blobUri];
        return result ? result.resultUri : null;
      };
      var isPending = function (blobUri) {
        return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
      };
      var isUploaded = function (blobUri) {
        return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
      };
      var markPending = function (blobUri) {
        blobUriStatuses[blobUri] = createStatus(PENDING, null);
      };
      var markUploaded = function (blobUri, resultUri) {
        blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
      };
      var removeFailed = function (blobUri) {
        delete blobUriStatuses[blobUri];
      };
      var destroy = function () {
        blobUriStatuses = {};
      };
      return {
        hasBlobUri: hasBlobUri,
        getResultUri: getResultUri,
        isPending: isPending,
        isUploaded: isUploaded,
        markPending: markPending,
        markUploaded: markUploaded,
        removeFailed: removeFailed,
        destroy: destroy
      };
    };

    var count$1 = 0;
    var seed = function () {
      var rnd = function () {
        return Math.round(Math.random() * 4294967295).toString(36);
      };
      var now = new Date().getTime();
      return 's' + now.toString(36) + rnd() + rnd() + rnd();
    };
    var uuid = function (prefix) {
      return prefix + count$1++ + seed();
    };

    var BlobCache = function () {
      var cache = [];
      var mimeToExt = function (mime) {
        var mimes = {
          'image/jpeg': 'jpg',
          'image/jpg': 'jpg',
          'image/gif': 'gif',
          'image/png': 'png',
          'image/apng': 'apng',
          'image/avif': 'avif',
          'image/svg+xml': 'svg',
          'image/webp': 'webp',
          'image/bmp': 'bmp',
          'image/tiff': 'tiff'
        };
        return mimes[mime.toLowerCase()] || 'dat';
      };
      var create = function (o, blob, base64, name, filename) {
        if (isString(o)) {
          var id = o;
          return toBlobInfo({
            id: id,
            name: name,
            filename: filename,
            blob: blob,
            base64: base64
          });
        } else if (isObject(o)) {
          return toBlobInfo(o);
        } else {
          throw new Error('Unknown input type');
        }
      };
      var toBlobInfo = function (o) {
        if (!o.blob || !o.base64) {
          throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
        }
        var id = o.id || uuid('blobid');
        var name = o.name || id;
        var blob = o.blob;
        return {
          id: constant(id),
          name: constant(name),
          filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
          blob: constant(blob),
          base64: constant(o.base64),
          blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
          uri: constant(o.uri)
        };
      };
      var add = function (blobInfo) {
        if (!get(blobInfo.id())) {
          cache.push(blobInfo);
        }
      };
      var findFirst = function (predicate) {
        return find(cache, predicate).getOrUndefined();
      };
      var get = function (id) {
        return findFirst(function (cachedBlobInfo) {
          return cachedBlobInfo.id() === id;
        });
      };
      var getByUri = function (blobUri) {
        return findFirst(function (blobInfo) {
          return blobInfo.blobUri() === blobUri;
        });
      };
      var getByData = function (base64, type) {
        return findFirst(function (blobInfo) {
          return blobInfo.base64() === base64 &amp;&amp; blobInfo.blob().type === type;
        });
      };
      var removeByUri = function (blobUri) {
        cache = filter(cache, function (blobInfo) {
          if (blobInfo.blobUri() === blobUri) {
            URL.revokeObjectURL(blobInfo.blobUri());
            return false;
          }
          return true;
        });
      };
      var destroy = function () {
        each(cache, function (cachedBlobInfo) {
          URL.revokeObjectURL(cachedBlobInfo.blobUri());
        });
        cache = [];
      };
      return {
        create: create,
        add: add,
        get: get,
        getByUri: getByUri,
        getByData: getByData,
        findFirst: findFirst,
        removeByUri: removeByUri,
        destroy: destroy
      };
    };

    var Uploader = function (uploadStatus, settings) {
      var pendingPromises = {};
      var pathJoin = function (path1, path2) {
        if (path1) {
          return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
        }
        return path2;
      };
      var defaultHandler = function (blobInfo, success, failure, progress) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', settings.url);
        xhr.withCredentials = settings.credentials;
        xhr.upload.onprogress = function (e) {
          progress(e.loaded / e.total * 100);
        };
        xhr.onerror = function () {
          failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
        };
        xhr.onload = function () {
          if (xhr.status &lt; 200 || xhr.status &gt;= 300) {
            failure('HTTP Error: ' + xhr.status);
            return;
          }
          var json = JSON.parse(xhr.responseText);
          if (!json || typeof json.location !== 'string') {
            failure('Invalid JSON: ' + xhr.responseText);
            return;
          }
          success(pathJoin(settings.basePath, json.location));
        };
        var formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
      };
      var noUpload = function () {
        return new promiseObj(function (resolve) {
          resolve([]);
        });
      };
      var handlerSuccess = function (blobInfo, url) {
        return {
          url: url,
          blobInfo: blobInfo,
          status: true
        };
      };
      var handlerFailure = function (blobInfo, message, options) {
        return {
          url: '',
          blobInfo: blobInfo,
          status: false,
          error: {
            message: message,
            options: options
          }
        };
      };
      var resolvePending = function (blobUri, result) {
        Tools.each(pendingPromises[blobUri], function (resolve) {
          resolve(result);
        });
        delete pendingPromises[blobUri];
      };
      var uploadBlobInfo = function (blobInfo, handler, openNotification) {
        uploadStatus.markPending(blobInfo.blobUri());
        return new promiseObj(function (resolve) {
          var notification, progress;
          try {
            var closeNotification_1 = function () {
              if (notification) {
                notification.close();
                progress = noop;
              }
            };
            var success = function (url) {
              closeNotification_1();
              uploadStatus.markUploaded(blobInfo.blobUri(), url);
              resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
              resolve(handlerSuccess(blobInfo, url));
            };
            var failure = function (error, options) {
              var failureOptions = options ? options : {};
              closeNotification_1();
              uploadStatus.removeFailed(blobInfo.blobUri());
              resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
              resolve(handlerFailure(blobInfo, error, failureOptions));
            };
            progress = function (percent) {
              if (percent &lt; 0 || percent &gt; 100) {
                return;
              }
              Optional.from(notification).orThunk(function () {
                return Optional.from(openNotification).map(apply);
              }).each(function (n) {
                notification = n;
                n.progressBar.value(percent);
              });
            };
            handler(blobInfo, success, failure, progress);
          } catch (ex) {
            resolve(handlerFailure(blobInfo, ex.message, {}));
          }
        });
      };
      var isDefaultHandler = function (handler) {
        return handler === defaultHandler;
      };
      var pendingUploadBlobInfo = function (blobInfo) {
        var blobUri = blobInfo.blobUri();
        return new promiseObj(function (resolve) {
          pendingPromises[blobUri] = pendingPromises[blobUri] || [];
          pendingPromises[blobUri].push(resolve);
        });
      };
      var uploadBlobs = function (blobInfos, openNotification) {
        blobInfos = Tools.grep(blobInfos, function (blobInfo) {
          return !uploadStatus.isUploaded(blobInfo.blobUri());
        });
        return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
          return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
        }));
      };
      var upload = function (blobInfos, openNotification) {
        return !settings.url &amp;&amp; isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
      };
      if (isFunction(settings.handler) === false) {
        settings.handler = defaultHandler;
      }
      return { upload: upload };
    };

    var openNotification = function (editor) {
      return function () {
        return editor.notificationManager.open({
          text: editor.translate('Image uploading...'),
          type: 'info',
          timeout: -1,
          progressBar: true
        });
      };
    };
    var createUploader = function (editor, uploadStatus) {
      return Uploader(uploadStatus, {
        url: getImageUploadUrl(editor),
        basePath: getImageUploadBasePath(editor),
        credentials: getImagesUploadCredentials(editor),
        handler: getImagesUploadHandler(editor)
      });
    };
    var ImageUploader = function (editor) {
      var uploadStatus = UploadStatus();
      var uploader = createUploader(editor, uploadStatus);
      return {
        upload: function (blobInfos, showNotification) {
          if (showNotification === void 0) {
            showNotification = true;
          }
          return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
        }
      };
    };

    var UploadChangeHandler = function (editor) {
      var lastChangedLevel = Cell(null);
      editor.on('change AddUndo', function (e) {
        lastChangedLevel.set(__assign({}, e.level));
      });
      var fireIfChanged = function () {
        var data = editor.undoManager.data;
        last(data).filter(function (level) {
          return !isEq$4(lastChangedLevel.get(), level);
        }).each(function (level) {
          editor.setDirty(true);
          editor.fire('change', {
            level: level,
            lastLevel: get(data, data.length - 2).getOrNull()
          });
        });
      };
      return { fireIfChanged: fireIfChanged };
    };
    var EditorUpload = function (editor) {
      var blobCache = BlobCache();
      var uploader, imageScanner;
      var uploadStatus = UploadStatus();
      var urlFilters = [];
      var changeHandler = UploadChangeHandler(editor);
      var aliveGuard = function (callback) {
        return function (result) {
          if (editor.selection) {
            return callback(result);
          }
          return [];
        };
      };
      var cacheInvalidator = function (url) {
        return url + (url.indexOf('?') === -1 ? '?' : '&amp;') + new Date().getTime();
      };
      var replaceString = function (content, search, replace) {
        var index = 0;
        do {
          index = content.indexOf(search, index);
          if (index !== -1) {
            content = content.substring(0, index) + replace + content.substr(index + search.length);
            index += replace.length - search.length + 1;
          }
        } while (index !== -1);
        return content;
      };
      var replaceImageUrl = function (content, targetUrl, replacementUrl) {
        var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
        content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
        content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
        return content;
      };
      var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
        each(editor.undoManager.data, function (level) {
          if (level.type === 'fragmented') {
            level.fragments = map(level.fragments, function (fragment) {
              return replaceImageUrl(fragment, targetUrl, replacementUrl);
            });
          } else {
            level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
          }
        });
      };
      var replaceImageUriInView = function (image, resultUri) {
        var src = editor.convertURL(resultUri, 'src');
        replaceUrlInUndoStack(image.src, resultUri);
        editor.$(image).attr({
          'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
          'data-mce-src': src
        });
      };
      var uploadImages = function (callback) {
        if (!uploader) {
          uploader = createUploader(editor, uploadStatus);
        }
        return scanForImages().then(aliveGuard(function (imageInfos) {
          var blobInfos = map(imageInfos, function (imageInfo) {
            return imageInfo.blobInfo;
          });
          return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
            var imagesToRemove = [];
            var filteredResult = map(result, function (uploadInfo, index) {
              var blobInfo = imageInfos[index].blobInfo;
              var image = imageInfos[index].image;
              if (uploadInfo.status &amp;&amp; shouldReplaceBlobUris(editor)) {
                blobCache.removeByUri(image.src);
                replaceImageUriInView(image, uploadInfo.url);
              } else if (uploadInfo.error) {
                if (uploadInfo.error.options.remove) {
                  replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
                  imagesToRemove.push(image);
                }
                uploadError(editor, uploadInfo.error.message);
              }
              return {
                element: image,
                status: uploadInfo.status,
                uploadUri: uploadInfo.url,
                blobInfo: blobInfo
              };
            });
            if (filteredResult.length &gt; 0) {
              changeHandler.fireIfChanged();
            }
            if (imagesToRemove.length &gt; 0) {
              if (isRtc(editor)) {
                console.error('Removing images on failed uploads is currently unsupported for RTC');
              } else {
                editor.undoManager.transact(function () {
                  each(imagesToRemove, function (element) {
                    editor.dom.remove(element);
                    blobCache.removeByUri(element.src);
                  });
                });
              }
            }
            if (callback) {
              callback(filteredResult);
            }
            return filteredResult;
          }));
        }));
      };
      var uploadImagesAuto = function (callback) {
        if (isAutomaticUploadsEnabled(editor)) {
          return uploadImages(callback);
        }
      };
      var isValidDataUriImage = function (imgElm) {
        if (forall(urlFilters, function (filter) {
            return filter(imgElm);
          }) === false) {
          return false;
        }
        if (imgElm.getAttribute('src').indexOf('data:') === 0) {
          var dataImgFilter = getImagesDataImgFilter(editor);
          return dataImgFilter(imgElm);
        }
        return true;
      };
      var addFilter = function (filter) {
        urlFilters.push(filter);
      };
      var scanForImages = function () {
        if (!imageScanner) {
          imageScanner = ImageScanner(uploadStatus, blobCache);
        }
        return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
          result = filter(result, function (resultItem) {
            if (typeof resultItem === 'string') {
              displayError(editor, resultItem);
              return false;
            }
            return true;
          });
          each(result, function (resultItem) {
            replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
            resultItem.image.src = resultItem.blobInfo.blobUri();
            resultItem.image.removeAttribute('data-mce-src');
          });
          return result;
        }));
      };
      var destroy = function () {
        blobCache.destroy();
        uploadStatus.destroy();
        imageScanner = uploader = null;
      };
      var replaceBlobUris = function (content) {
        return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
          var resultUri = uploadStatus.getResultUri(blobUri);
          if (resultUri) {
            return 'src="' + resultUri + '"';
          }
          var blobInfo = blobCache.getByUri(blobUri);
          if (!blobInfo) {
            blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
              return result || editor.editorUpload &amp;&amp; editor.editorUpload.blobCache.getByUri(blobUri);
            }, null);
          }
          if (blobInfo) {
            var blob = blobInfo.blob();
            return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
          }
          return match;
        });
      };
      editor.on('SetContent', function () {
        if (isAutomaticUploadsEnabled(editor)) {
          uploadImagesAuto();
        } else {
          scanForImages();
        }
      });
      editor.on('RawSaveContent', function (e) {
        e.content = replaceBlobUris(e.content);
      });
      editor.on('GetContent', function (e) {
        if (e.source_view || e.format === 'raw' || e.format === 'tree') {
          return;
        }
        e.content = replaceBlobUris(e.content);
      });
      editor.on('PostRender', function () {
        editor.parser.addNodeFilter('img', function (images) {
          each(images, function (img) {
            var src = img.attr('src');
            if (blobCache.getByUri(src)) {
              return;
            }
            var resultUri = uploadStatus.getResultUri(src);
            if (resultUri) {
              img.attr('src', resultUri);
            }
          });
        });
      });
      return {
        blobCache: blobCache,
        addFilter: addFilter,
        uploadImages: uploadImages,
        uploadImagesAuto: uploadImagesAuto,
        scanForImages: scanForImages,
        destroy: destroy
      };
    };

    var get$a = function (dom) {
      var formats = {
        valigntop: [{
            selector: 'td,th',
            styles: { verticalAlign: 'top' }
          }],
        valignmiddle: [{
            selector: 'td,th',
            styles: { verticalAlign: 'middle' }
          }],
        valignbottom: [{
            selector: 'td,th',
            styles: { verticalAlign: 'bottom' }
          }],
        alignleft: [
          {
            selector: 'figure.image',
            collapsed: false,
            classes: 'align-left',
            ceFalseOverride: true,
            preview: 'font-family font-size'
          },
          {
            selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
            styles: { textAlign: 'left' },
            inherit: false,
            preview: false,
            defaultBlock: 'div'
          },
          {
            selector: 'img,table,audio,video',
            collapsed: false,
            styles: { float: 'left' },
            preview: 'font-family font-size'
          }
        ],
        aligncenter: [
          {
            selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
            styles: { textAlign: 'center' },
            inherit: false,
            preview: 'font-family font-size',
            defaultBlock: 'div'
          },
          {
            selector: 'figure.image',
            collapsed: false,
            classes: 'align-center',
            ceFalseOverride: true,
            preview: 'font-family font-size'
          },
          {
            selector: 'img,audio,video',
            collapsed: false,
            styles: {
              display: 'block',
              marginLeft: 'auto',
              marginRight: 'auto'
            },
            preview: false
          },
          {
            selector: 'table',
            collapsed: false,
            styles: {
              marginLeft: 'auto',
              marginRight: 'auto'
            },
            preview: 'font-family font-size'
          }
        ],
        alignright: [
          {
            selector: 'figure.image',
            collapsed: false,
            classes: 'align-right',
            ceFalseOverride: true,
            preview: 'font-family font-size'
          },
          {
            selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
            styles: { textAlign: 'right' },
            inherit: false,
            preview: 'font-family font-size',
            defaultBlock: 'div'
          },
          {
            selector: 'img,table,audio,video',
            collapsed: false,
            styles: { float: 'right' },
            preview: 'font-family font-size'
          }
        ],
        alignjustify: [{
            selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
            styles: { textAlign: 'justify' },
            inherit: false,
            defaultBlock: 'div',
            preview: 'font-family font-size'
          }],
        bold: [
          {
            inline: 'strong',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          },
          {
            inline: 'span',
            styles: { fontWeight: 'bold' }
          },
          {
            inline: 'b',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          }
        ],
        italic: [
          {
            inline: 'em',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          },
          {
            inline: 'span',
            styles: { fontStyle: 'italic' }
          },
          {
            inline: 'i',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          }
        ],
        underline: [
          {
            inline: 'span',
            styles: { textDecoration: 'underline' },
            exact: true
          },
          {
            inline: 'u',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          }
        ],
        strikethrough: [
          {
            inline: 'span',
            styles: { textDecoration: 'line-through' },
            exact: true
          },
          {
            inline: 'strike',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          },
          {
            inline: 's',
            remove: 'all',
            preserve_attributes: [
              'class',
              'style'
            ]
          }
        ],
        forecolor: {
          inline: 'span',
          styles: { color: '%value' },
          links: true,
          remove_similar: true,
          clear_child_styles: true
        },
        hilitecolor: {
          inline: 'span',
          styles: { backgroundColor: '%value' },
          links: true,
          remove_similar: true,
          clear_child_styles: true
        },
        fontname: {
          inline: 'span',
          toggle: false,
          styles: { fontFamily: '%value' },
          clear_child_styles: true
        },
        fontsize: {
          inline: 'span',
          toggle: false,
          styles: { fontSize: '%value' },
          clear_child_styles: true
        },
        lineheight: {
          selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
          defaultBlock: 'p',
          styles: { lineHeight: '%value' }
        },
        fontsize_class: {
          inline: 'span',
          attributes: { class: '%value' }
        },
        blockquote: {
          block: 'blockquote',
          wrapper: true,
          remove: 'all'
        },
        subscript: { inline: 'sub' },
        superscript: { inline: 'sup' },
        code: { inline: 'code' },
        link: {
          inline: 'a',
          selector: 'a',
          remove: 'all',
          split: true,
          deep: true,
          onmatch: function (node, _fmt, _itemName) {
            return isElement$1(node) &amp;&amp; node.hasAttribute('href');
          },
          onformat: function (elm, _fmt, vars) {
            Tools.each(vars, function (value, key) {
              dom.setAttrib(elm, key, value);
            });
          }
        },
        removeformat: [
          {
            selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
            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
          }
        ]
      };
      Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
        formats[name] = {
          block: name,
          remove: 'all'
        };
      });
      return formats;
    };

    var FormatRegistry = function (editor) {
      var formats = {};
      var get = function (name) {
        return name ? formats[name] : formats;
      };
      var has$1 = function (name) {
        return has(formats, name);
      };
      var register = function (name, format) {
        if (name) {
          if (typeof name !== 'string') {
            Tools.each(name, function (format, name) {
              register(name, format);
            });
          } else {
            if (!isArray(format)) {
              format = [format];
            }
            Tools.each(format, function (format) {
              if (typeof format.deep === 'undefined') {
                format.deep = !format.selector;
              }
              if (typeof format.split === 'undefined') {
                format.split = !format.selector || format.inline;
              }
              if (typeof format.remove === 'undefined' &amp;&amp; format.selector &amp;&amp; !format.inline) {
                format.remove = 'none';
              }
              if (format.selector &amp;&amp; format.inline) {
                format.mixed = true;
                format.block_expand = true;
              }
              if (typeof format.classes === 'string') {
                format.classes = format.classes.split(/\s+/);
              }
            });
            formats[name] = format;
          }
        }
      };
      var unregister = function (name) {
        if (name &amp;&amp; formats[name]) {
          delete formats[name];
        }
        return formats;
      };
      register(get$a(editor.dom));
      register(getFormats(editor));
      return {
        get: get,
        has: has$1,
        register: register,
        unregister: unregister
      };
    };

    var each$e = Tools.each;
    var dom = DOMUtils.DOM;
    var parsedSelectorToHtml = function (ancestry, editor) {
      var elm, item, fragment;
      var schema = editor &amp;&amp; editor.schema || Schema({});
      var decorate = function (elm, item) {
        if (item.classes.length) {
          dom.addClass(elm, item.classes.join(' '));
        }
        dom.setAttribs(elm, item.attrs);
      };
      var createElement = function (sItem) {
        item = typeof sItem === 'string' ? {
          name: sItem,
          classes: [],
          attrs: {}
        } : sItem;
        var elm = dom.create(item.name);
        decorate(elm, item);
        return elm;
      };
      var getRequiredParent = function (elm, candidate) {
        var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
        var elmRule = schema.getElementRule(name);
        var parentsRequired = elmRule &amp;&amp; elmRule.parentsRequired;
        if (parentsRequired &amp;&amp; parentsRequired.length) {
          return candidate &amp;&amp; Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
        } else {
          return false;
        }
      };
      var wrapInHtml = function (elm, ancestry, siblings) {
        var parent, parentCandidate;
        var ancestor = ancestry.length &gt; 0 &amp;&amp; ancestry[0];
        var ancestorName = ancestor &amp;&amp; ancestor.name;
        var parentRequired = getRequiredParent(elm, ancestorName);
        if (parentRequired) {
          if (ancestorName === parentRequired) {
            parentCandidate = ancestry[0];
            ancestry = ancestry.slice(1);
          } else {
            parentCandidate = parentRequired;
          }
        } else if (ancestor) {
          parentCandidate = ancestry[0];
          ancestry = ancestry.slice(1);
        } else if (!siblings) {
          return elm;
        }
        if (parentCandidate) {
          parent = createElement(parentCandidate);
          parent.appendChild(elm);
        }
        if (siblings) {
          if (!parent) {
            parent = dom.create('div');
            parent.appendChild(elm);
          }
          Tools.each(siblings, function (sibling) {
            var siblingElm = createElement(sibling);
            parent.insertBefore(siblingElm, elm);
          });
        }
        return wrapInHtml(parent, ancestry, parentCandidate &amp;&amp; parentCandidate.siblings);
      };
      if (ancestry &amp;&amp; ancestry.length) {
        item = ancestry[0];
        elm = createElement(item);
        fragment = dom.create('div');
        fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
        return fragment;
      } else {
        return '';
      }
    };
    var parseSelectorItem = function (item) {
      var tagName;
      var obj = {
        classes: [],
        attrs: {}
      };
      item = obj.selector = Tools.trim(item);
      if (item !== '*') {
        tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
          switch ($1) {
          case '#':
            obj.attrs.id = $2;
            break;
          case '.':
            obj.classes.push($2);
            break;
          case ':':
            if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
              obj.attrs[$2] = $2;
            }
            break;
          }
          if ($3 === '[') {
            var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
            if (m) {
              obj.attrs[m[1]] = m[2];
            }
          }
          return '';
        });
      }
      obj.name = tagName || 'div';
      return obj;
    };
    var parseSelector = function (selector) {
      if (!selector || typeof selector !== 'string') {
        return [];
      }
      selector = selector.split(/\s*,\s*/)[0];
      selector = selector.replace(/\s*(~\+|~|\+|&gt;)\s*/g, '$1');
      return Tools.map(selector.split(/(?:&gt;|\s+(?![^\[\]]+\]))/), function (item) {
        var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
        var obj = siblings.pop();
        if (siblings.length) {
          obj.siblings = siblings;
        }
        return obj;
      }).reverse();
    };
    var getCssText = function (editor, format) {
      var name, previewFrag;
      var previewCss = '', parentFontSize;
      var previewStyles = getPreviewStyles(editor);
      if (previewStyles === '') {
        return '';
      }
      var removeVars = function (val) {
        return val.replace(/%(\w+)/g, '');
      };
      if (typeof format === 'string') {
        format = editor.formatter.get(format);
        if (!format) {
          return;
        }
        format = format[0];
      }
      if ('preview' in format) {
        var previewOpt = get$1(format, 'preview');
        if (previewOpt.is(false)) {
          return '';
        } else {
          previewStyles = previewOpt.getOr(previewStyles);
        }
      }
      name = format.block || format.inline || 'span';
      var items = parseSelector(format.selector);
      if (items.length) {
        if (!items[0].name) {
          items[0].name = name;
        }
        name = format.selector;
        previewFrag = parsedSelectorToHtml(items, editor);
      } else {
        previewFrag = parsedSelectorToHtml([name], editor);
      }
      var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
      each$e(format.styles, function (value, name) {
        var newValue = removeVars(value);
        if (newValue) {
          dom.setStyle(previewElm, name, newValue);
        }
      });
      each$e(format.attributes, function (value, name) {
        var newValue = removeVars(value);
        if (newValue) {
          dom.setAttrib(previewElm, name, newValue);
        }
      });
      each$e(format.classes, function (value) {
        var newValue = removeVars(value);
        if (!dom.hasClass(previewElm, newValue)) {
          dom.addClass(previewElm, newValue);
        }
      });
      editor.fire('PreviewFormats');
      dom.setStyles(previewFrag, {
        position: 'absolute',
        left: -65535
      });
      editor.getBody().appendChild(previewFrag);
      parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
      parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
      each$e(previewStyles.split(' '), function (name) {
        var value = dom.getStyle(previewElm, name, true);
        if (name === 'background-color' &amp;&amp; /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
          value = dom.getStyle(editor.getBody(), name, true);
          if (dom.toHex(value).toLowerCase() === '#ffffff') {
            return;
          }
        }
        if (name === 'color') {
          if (dom.toHex(value).toLowerCase() === '#000000') {
            return;
          }
        }
        if (name === 'font-size') {
          if (/em|%$/.test(value)) {
            if (parentFontSize === 0) {
              return;
            }
            var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
            value = numValue * parentFontSize + 'px';
          }
        }
        if (name === 'border' &amp;&amp; value) {
          previewCss += 'padding:0 2px;';
        }
        previewCss += name + ':' + value + ';';
      });
      editor.fire('AfterPreviewFormats');
      dom.remove(previewFrag);
      return previewCss;
    };

    var setup$6 = function (editor) {
      editor.addShortcut('meta+b', '', 'Bold');
      editor.addShortcut('meta+i', '', 'Italic');
      editor.addShortcut('meta+u', '', 'Underline');
      for (var i = 1; i &lt;= 6; i++) {
        editor.addShortcut('access+' + i, '', [
          'FormatBlock',
          false,
          'h' + i
        ]);
      }
      editor.addShortcut('access+7', '', [
        'FormatBlock',
        false,
        'p'
      ]);
      editor.addShortcut('access+8', '', [
        'FormatBlock',
        false,
        'div'
      ]);
      editor.addShortcut('access+9', '', [
        'FormatBlock',
        false,
        'address'
      ]);
    };

    var Formatter = function (editor) {
      var formats = FormatRegistry(editor);
      var formatChangeState = Cell(null);
      setup$6(editor);
      setup$3(editor);
      return {
        get: formats.get,
        has: formats.has,
        register: formats.register,
        unregister: formats.unregister,
        apply: function (name, vars, node) {
          applyFormat$1(editor, name, vars, node);
        },
        remove: function (name, vars, node, similar) {
          removeFormat$1(editor, name, vars, node, similar);
        },
        toggle: function (name, vars, node) {
          toggleFormat(editor, name, vars, node);
        },
        match: function (name, vars, node) {
          return matchFormat(editor, name, vars, node);
        },
        closest: function (names) {
          return closestFormat(editor, names);
        },
        matchAll: function (names, vars) {
          return matchAllFormats(editor, names, vars);
        },
        matchNode: function (node, names, vars, similar) {
          return matchNodeFormat(editor, node, names, vars, similar);
        },
        canApply: function (name) {
          return canApplyFormat(editor, name);
        },
        formatChanged: function (formats, callback, similar) {
          return formatChanged(editor, formatChangeState, formats, callback, similar);
        },
        getCssText: curry(getCssText, editor)
      };
    };

    var registerEvents$1 = function (editor, undoManager, locks) {
      var isFirstTypedCharacter = Cell(false);
      var addNonTypingUndoLevel = function (e) {
        setTyping(undoManager, false, locks);
        undoManager.add({}, e);
      };
      editor.on('init', function () {
        undoManager.add();
      });
      editor.on('BeforeExecCommand', function (e) {
        var cmd = e.command.toLowerCase();
        if (cmd !== 'undo' &amp;&amp; cmd !== 'redo' &amp;&amp; cmd !== 'mcerepaint') {
          endTyping(undoManager, locks);
          undoManager.beforeChange();
        }
      });
      editor.on('ExecCommand', function (e) {
        var cmd = e.command.toLowerCase();
        if (cmd !== 'undo' &amp;&amp; cmd !== 'redo' &amp;&amp; cmd !== 'mcerepaint') {
          addNonTypingUndoLevel(e);
        }
      });
      editor.on('ObjectResizeStart cut', function () {
        undoManager.beforeChange();
      });
      editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
      editor.on('dragend', addNonTypingUndoLevel);
      editor.on('keyup', function (e) {
        var keyCode = e.keyCode;
        if (e.isDefaultPrevented()) {
          return;
        }
        if (keyCode &gt;= 33 &amp;&amp; keyCode &lt;= 36 || keyCode &gt;= 37 &amp;&amp; keyCode &lt;= 40 || keyCode === 45 || e.ctrlKey) {
          addNonTypingUndoLevel();
          editor.nodeChanged();
        }
        if (keyCode === 46 || keyCode === 8) {
          editor.nodeChanged();
        }
        if (isFirstTypedCharacter.get() &amp;&amp; undoManager.typing &amp;&amp; isEq$4(createFromEditor(editor), undoManager.data[0]) === false) {
          if (editor.isDirty() === false) {
            editor.setDirty(true);
            editor.fire('change', {
              level: undoManager.data[0],
              lastLevel: null
            });
          }
          editor.fire('TypingUndo');
          isFirstTypedCharacter.set(false);
          editor.nodeChanged();
        }
      });
      editor.on('keydown', function (e) {
        var keyCode = e.keyCode;
        if (e.isDefaultPrevented()) {
          return;
        }
        if (keyCode &gt;= 33 &amp;&amp; keyCode &lt;= 36 || keyCode &gt;= 37 &amp;&amp; keyCode &lt;= 40 || keyCode === 45) {
          if (undoManager.typing) {
            addNonTypingUndoLevel(e);
          }
          return;
        }
        var modKey = e.ctrlKey &amp;&amp; !e.altKey || e.metaKey;
        if ((keyCode &lt; 16 || keyCode &gt; 20) &amp;&amp; keyCode !== 224 &amp;&amp; keyCode !== 91 &amp;&amp; !undoManager.typing &amp;&amp; !modKey) {
          undoManager.beforeChange();
          setTyping(undoManager, true, locks);
          undoManager.add({}, e);
          isFirstTypedCharacter.set(true);
        }
      });
      editor.on('mousedown', function (e) {
        if (undoManager.typing) {
          addNonTypingUndoLevel(e);
        }
      });
      var isInsertReplacementText = function (event) {
        return event.inputType === 'insertReplacementText';
      };
      var isInsertTextDataNull = function (event) {
        return event.inputType === 'insertText' &amp;&amp; event.data === null;
      };
      var isInsertFromPasteOrDrop = function (event) {
        return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
      };
      editor.on('input', function (e) {
        if (e.inputType &amp;&amp; (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
          addNonTypingUndoLevel(e);
        }
      });
      editor.on('AddUndo Undo Redo ClearUndos', function (e) {
        if (!e.isDefaultPrevented()) {
          editor.nodeChanged();
        }
      });
    };
    var addKeyboardShortcuts = function (editor) {
      editor.addShortcut('meta+z', '', 'Undo');
      editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
    };

    var UndoManager = function (editor) {
      var beforeBookmark = Cell(Optional.none());
      var locks = Cell(0);
      var index = Cell(0);
      var undoManager = {
        data: [],
        typing: false,
        beforeChange: function () {
          beforeChange$1(editor, locks, beforeBookmark);
        },
        add: function (level, event) {
          return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
        },
        undo: function () {
          return undo$1(editor, undoManager, locks, index);
        },
        redo: function () {
          return redo$1(editor, index, undoManager.data);
        },
        clear: function () {
          clear$1(editor, undoManager, index);
        },
        reset: function () {
          reset$1(editor, undoManager);
        },
        hasUndo: function () {
          return hasUndo$1(editor, undoManager, index);
        },
        hasRedo: function () {
          return hasRedo$1(editor, undoManager, index);
        },
        transact: function (callback) {
          return transact$1(editor, undoManager, locks, callback);
        },
        ignore: function (callback) {
          ignore$1(editor, locks, callback);
        },
        extra: function (callback1, callback2) {
          extra$1(editor, undoManager, index, callback1, callback2);
        }
      };
      if (!isRtc(editor)) {
        registerEvents$1(editor, undoManager, locks);
      }
      addKeyboardShortcuts(editor);
      return undoManager;
    };

    var nonTypingKeycodes = [
      9,
      27,
      VK.HOME,
      VK.END,
      19,
      20,
      44,
      144,
      145,
      33,
      34,
      45,
      16,
      17,
      18,
      91,
      92,
      93,
      VK.DOWN,
      VK.UP,
      VK.LEFT,
      VK.RIGHT
    ].concat(Env.browser.isFirefox() ? [224] : []);
    var placeholderAttr = 'data-mce-placeholder';
    var isKeyboardEvent = function (e) {
      return e.type === 'keydown' || e.type === 'keyup';
    };
    var isDeleteEvent = function (e) {
      var keyCode = e.keyCode;
      return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
    };
    var isNonTypingKeyboardEvent = function (e) {
      if (isKeyboardEvent(e)) {
        var keyCode = e.keyCode;
        return !isDeleteEvent(e) &amp;&amp; (VK.metaKeyPressed(e) || e.altKey || keyCode &gt;= 112 &amp;&amp; keyCode &lt;= 123 || contains(nonTypingKeycodes, keyCode));
      } else {
        return false;
      }
    };
    var isTypingKeyboardEvent = function (e) {
      return isKeyboardEvent(e) &amp;&amp; !(isDeleteEvent(e) || e.type === 'keyup' &amp;&amp; e.keyCode === 229);
    };
    var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
      if (isEmpty(SugarElement.fromDom(rootElm), false)) {
        var isForcedRootBlockFalse = forcedRootBlock === '';
        var firstElement = rootElm.firstElementChild;
        if (!firstElement) {
          return true;
        } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
          return false;
        } else {
          return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
        }
      } else {
        return false;
      }
    };
    var setup$7 = function (editor) {
      var dom = editor.dom;
      var rootBlock = getForcedRootBlock(editor);
      var placeholder = getPlaceholder(editor);
      var updatePlaceholder = function (e, initial) {
        if (isNonTypingKeyboardEvent(e)) {
          return;
        }
        var body = editor.getBody();
        var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
        var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
        if (isPlaceholderShown !== showPlaceholder || initial) {
          dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
          dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
          firePlaceholderToggle(editor, showPlaceholder);
          editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
          editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
        }
      };
      if (placeholder) {
        editor.on('init', function (e) {
          updatePlaceholder(e, true);
          editor.on('change SetContent ExecCommand', updatePlaceholder);
          editor.on('paste', function (e) {
            return Delay.setEditorTimeout(editor, function () {
              return updatePlaceholder(e);
            });
          });
        });
      }
    };

    var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
    var hasStrongRtl = function (text) {
      return strongRtl.test(text);
    };

    var isInlineTarget = function (editor, elm) {
      return is$1(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
    };
    var isRtl$1 = function (element) {
      return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
    };
    var findInlineParents = function (isInlineTarget, rootNode, pos) {
      return filter(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
    };
    var findRootInline = function (isInlineTarget, rootNode, pos) {
      var parents = findInlineParents(isInlineTarget, rootNode, pos);
      return Optional.from(parents[parents.length - 1]);
    };
    var hasSameParentBlock = function (rootNode, node1, node2) {
      var block1 = getParentBlock(node1, rootNode);
      var block2 = getParentBlock(node2, rootNode);
      return block1 &amp;&amp; block1 === block2;
    };
    var isAtZwsp = function (pos) {
      return isBeforeInline(pos) || isAfterInline(pos);
    };
    var normalizePosition = function (forward, pos) {
      if (!pos) {
        return pos;
      }
      var container = pos.container(), offset = pos.offset();
      if (forward) {
        if (isCaretContainerInline(container)) {
          if (isText$1(container.nextSibling)) {
            return CaretPosition(container.nextSibling, 0);
          } else {
            return CaretPosition.after(container);
          }
        } else {
          return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
        }
      } else {
        if (isCaretContainerInline(container)) {
          if (isText$1(container.previousSibling)) {
            return CaretPosition(container.previousSibling, container.previousSibling.data.length);
          } else {
            return CaretPosition.before(container);
          }
        } else {
          return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
        }
      }
    };
    var normalizeForwards = curry(normalizePosition, true);
    var normalizeBackwards = curry(normalizePosition, false);

    var isBeforeRoot = function (rootNode) {
      return function (elm) {
        return eq$2(rootNode, SugarElement.fromDom(elm.dom.parentNode));
      };
    };
    var getParentBlock$1 = function (rootNode, elm) {
      return contains$2(rootNode, elm) ? closest(elm, function (element) {
        return isTextBlock(element) || isListItem(element);
      }, isBeforeRoot(rootNode)) : Optional.none();
    };
    var placeCaretInEmptyBody = function (editor) {
      var body = editor.getBody();
      var node = body.firstChild &amp;&amp; editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
      editor.selection.setCursorLocation(node, 0);
    };
    var paddEmptyBody = function (editor) {
      if (editor.dom.isEmpty(editor.getBody())) {
        editor.setContent('');
        placeCaretInEmptyBody(editor);
      }
    };
    var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
      return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
        var normalizedFirstPos = normalizePosition(true, firstPos);
        var normalizedLastPos = normalizePosition(false, lastPos);
        var normalizedFromPos = normalizePosition(false, fromPos);
        if (forward) {
          return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
            return nextPos.isEqual(normalizedLastPos) &amp;&amp; fromPos.isEqual(normalizedFirstPos);
          });
        } else {
          return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
            return prevPos.isEqual(normalizedFirstPos) &amp;&amp; fromPos.isEqual(normalizedLastPos);
          });
        }
      }).getOr(true);
    };

    var blockPosition = function (block, position) {
      return {
        block: block,
        position: position
      };
    };
    var blockBoundary = function (from, to) {
      return {
        from: from,
        to: to
      };
    };
    var getBlockPosition = function (rootNode, pos) {
      var rootElm = SugarElement.fromDom(rootNode);
      var containerElm = SugarElement.fromDom(pos.container());
      return getParentBlock$1(rootElm, containerElm).map(function (block) {
        return blockPosition(block, pos);
      });
    };
    var isDifferentBlocks = function (blockBoundary) {
      return eq$2(blockBoundary.from.block, blockBoundary.to.block) === false;
    };
    var hasSameParent = function (blockBoundary) {
      return parent(blockBoundary.from.block).bind(function (parent1) {
        return parent(blockBoundary.to.block).filter(function (parent2) {
          return eq$2(parent1, parent2);
        });
      }).isSome();
    };
    var isEditable = function (blockBoundary) {
      return isContentEditableFalse(blockBoundary.from.block.dom) === false &amp;&amp; isContentEditableFalse(blockBoundary.to.block.dom) === false;
    };
    var skipLastBr = function (rootNode, forward, blockPosition) {
      if (isBr(blockPosition.position.getNode()) &amp;&amp; isEmpty(blockPosition.block) === false) {
        return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
          if (lastPositionInBlock.isEqual(blockPosition.position)) {
            return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
              return getBlockPosition(rootNode, to);
            });
          } else {
            return Optional.some(blockPosition);
          }
        }).getOr(blockPosition);
      } else {
        return blockPosition;
      }
    };
    var readFromRange = function (rootNode, forward, rng) {
      var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
      var toBlockPos = fromBlockPos.bind(function (blockPos) {
        return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
          return getBlockPosition(rootNode, to).map(function (blockPos) {
            return skipLastBr(rootNode, forward, blockPos);
          });
        });
      });
      return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
        return isDifferentBlocks(blockBoundary) &amp;&amp; hasSameParent(blockBoundary) &amp;&amp; isEditable(blockBoundary);
      });
    };
    var read$3 = function (rootNode, forward, rng) {
      return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
    };

    var getChildrenUntilBlockBoundary = function (block) {
      var children$1 = children(block);
      return findIndex(children$1, isBlock).fold(function () {
        return children$1;
      }, function (index) {
        return children$1.slice(0, index);
      });
    };
    var extractChildren = function (block) {
      var children = getChildrenUntilBlockBoundary(block);
      each(children, remove);
      return children;
    };
    var removeEmptyRoot = function (rootNode, block) {
      var parents = parentsAndSelf(block, rootNode);
      return find(parents.reverse(), function (element) {
        return isEmpty(element);
      }).each(remove);
    };
    var isEmptyBefore = function (el) {
      return filter(prevSiblings(el), function (el) {
        return !isEmpty(el);
      }).length === 0;
    };
    var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
      if (isEmpty(toBlock)) {
        fillWithPaddingBr(toBlock);
        return firstPositionIn(toBlock.dom);
      }
      if (isEmptyBefore(insertionPoint) &amp;&amp; isEmpty(fromBlock)) {
        before(insertionPoint, SugarElement.fromTag('br'));
      }
      var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
      each(extractChildren(fromBlock), function (child) {
        before(insertionPoint, child);
      });
      removeEmptyRoot(rootNode, fromBlock);
      return position;
    };
    var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
      if (isEmpty(toBlock)) {
        remove(toBlock);
        if (isEmpty(fromBlock)) {
          fillWithPaddingBr(fromBlock);
        }
        return firstPositionIn(fromBlock.dom);
      }
      var position = lastPositionIn(toBlock.dom);
      each(extractChildren(fromBlock), function (child) {
        append(toBlock, child);
      });
      removeEmptyRoot(rootNode, fromBlock);
      return position;
    };
    var findInsertionPoint = function (toBlock, block) {
      var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
      return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
    };
    var getInsertionPoint = function (fromBlock, toBlock) {
      return contains$2(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
    };
    var trimBr = function (first, block) {
      positionIn(first, block.dom).map(function (position) {
        return position.getNode();
      }).map(SugarElement.fromDom).filter(isBr$1).each(remove);
    };
    var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
      trimBr(true, fromBlock);
      trimBr(false, toBlock);
      return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
    };
    var mergeBlocks = function (rootNode, forward, block1, block2) {
      return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
    };

    var backspaceDelete$1 = function (editor, forward) {
      var rootNode = SugarElement.fromDom(editor.getBody());
      var position = read$3(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
        return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
      });
      position.each(function (pos) {
        editor.selection.setRng(pos.toRange());
      });
      return position.isSome();
    };

    var deleteRangeMergeBlocks = function (rootNode, selection) {
      var rng = selection.getRng();
      return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
        if (eq$2(block1, block2) === false) {
          rng.deleteContents();
          mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
            selection.setRng(pos.toRange());
          });
          return true;
        } else {
          return false;
        }
      }).getOr(false);
    };
    var isRawNodeInTable = function (root, rawNode) {
      var node = SugarElement.fromDom(rawNode);
      var isRoot = curry(eq$2, root);
      return ancestor(node, isTableCell$1, isRoot).isSome();
    };
    var isSelectionInTable = function (root, rng) {
      return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
    };
    var isEverythingSelected = function (root, rng) {
      var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
      var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
      return !isSelectionInTable(root, rng) &amp;&amp; noPrevious &amp;&amp; noNext;
    };
    var emptyEditor = function (editor) {
      editor.setContent('');
      editor.selection.setCursorLocation();
      return true;
    };
    var deleteRange$1 = function (editor) {
      var rootNode = SugarElement.fromDom(editor.getBody());
      var rng = editor.selection.getRng();
      return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
    };
    var backspaceDelete$2 = function (editor, _forward) {
      return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
    };

    var isContentEditableTrue$2 = isContentEditableTrue;
    var isContentEditableFalse$7 = isContentEditableFalse;
    var showCaret = function (direction, editor, node, before, scrollIntoView) {
      return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
    };
    var getNodeRange = function (node) {
      var rng = node.ownerDocument.createRange();
      rng.selectNode(node);
      return rng;
    };
    var selectNode = function (editor, node) {
      var e = editor.fire('BeforeObjectSelected', { target: node });
      if (e.isDefaultPrevented()) {
        return Optional.none();
      }
      return Optional.some(getNodeRange(node));
    };
    var renderCaretAtRange = function (editor, range, scrollIntoView) {
      var normalizedRange = normalizeRange(1, editor.getBody(), range);
      var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
      var caretPositionNode = caretPosition.getNode();
      if (isInlineFakeCaretTarget(caretPositionNode)) {
        return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
      }
      var caretPositionBeforeNode = caretPosition.getNode(true);
      if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
        return showCaret(1, editor, caretPositionBeforeNode, false, false);
      }
      var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
        return isContentEditableFalse$7(node) || isContentEditableTrue$2(node);
      });
      if (isInlineFakeCaretTarget(ceRoot)) {
        return showCaret(1, editor, ceRoot, false, scrollIntoView);
      }
      return Optional.none();
    };
    var renderRangeCaret = function (editor, range, scrollIntoView) {
      return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
    };

    var isBeforeBoundary = function (pos) {
      return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
    };
    var isAfterBoundary = function (pos) {
      return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
    };
    var trimEmptyTextNode$1 = function (dom, node) {
      if (isText$1(node) &amp;&amp; node.data.length === 0) {
        dom.remove(node);
      }
    };
    var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
      showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
        if (range.collapsed) {
          var deleteRange = range.cloneRange();
          if (forward) {
            deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
          } else {
            deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
          }
          deleteRange.deleteContents();
        } else {
          range.deleteContents();
        }
        editor.selection.setRng(caretRange);
      });
      trimEmptyTextNode$1(editor.dom, node);
      return true;
    };
    var deleteBoundaryText = function (editor, forward) {
      var range = editor.selection.getRng();
      if (!isText$1(range.commonAncestorContainer)) {
        return false;
      }
      var direction = forward ? HDirection.Forwards : HDirection.Backwards;
      var caretWalker = CaretWalker(editor.getBody());
      var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
      var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
      var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
      var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
      if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
        return false;
      } else if (isBeforeFn(nextCaretPosition)) {
        return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
      }
      var peekCaretPosition = getNextPosFn(nextCaretPosition);
      if (peekCaretPosition &amp;&amp; isBeforeFn(peekCaretPosition)) {
        if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
          return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
        }
      }
      return false;
    };
    var backspaceDelete$3 = function (editor, forward) {
      return deleteBoundaryText(editor, forward);
    };

    var isCompoundElement = function (node) {
      return isTableCell$1(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
    };
    var DeleteAction = Adt.generate([
      { remove: ['element'] },
      { moveToElement: ['element'] },
      { moveToPosition: ['position'] }
    ]);
    var isAtContentEditableBlockCaret = function (forward, from) {
      var elm = from.getNode(forward === false);
      var caretLocation = forward ? 'after' : 'before';
      return isElement$1(elm) &amp;&amp; elm.getAttribute('data-mce-caret') === caretLocation;
    };
    var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
      var inSameBlock = function (elm) {
        return isInline(SugarElement.fromDom(elm)) &amp;&amp; !isInSameBlock(from, to, root);
      };
      return getRelativeCefElm(!forward, from).fold(function () {
        return getRelativeCefElm(forward, to).fold(never, inSameBlock);
      }, inSameBlock);
    };
    var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
      var toCefElm = to.getNode(forward === false);
      return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
        return isEmpty(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
      }).orThunk(function () {
        return Optional.some(DeleteAction.moveToElement(toCefElm));
      });
    };
    var findCefPosition = function (root, forward, from) {
      return fromPosition(forward, root, from).bind(function (to) {
        if (isCompoundElement(to.getNode())) {
          return Optional.none();
        } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
          return Optional.none();
        } else if (forward &amp;&amp; isContentEditableFalse(to.getNode())) {
          return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
        } else if (forward === false &amp;&amp; isContentEditableFalse(to.getNode(true))) {
          return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
        } else if (forward &amp;&amp; isAfterContentEditableFalse(from)) {
          return Optional.some(DeleteAction.moveToPosition(to));
        } else if (forward === false &amp;&amp; isBeforeContentEditableFalse(from)) {
          return Optional.some(DeleteAction.moveToPosition(to));
        } else {
          return Optional.none();
        }
      });
    };
    var getContentEditableBlockAction = function (forward, elm) {
      if (forward &amp;&amp; isContentEditableFalse(elm.nextSibling)) {
        return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
      } else if (forward === false &amp;&amp; isContentEditableFalse(elm.previousSibling)) {
        return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
      } else {
        return Optional.none();
      }
    };
    var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
      return deleteAction.fold(function (elm) {
        return Optional.some(DeleteAction.remove(elm));
      }, function (elm) {
        return Optional.some(DeleteAction.moveToElement(elm));
      }, function (to) {
        if (isInSameBlock(from, to, root)) {
          return Optional.none();
        } else {
          return Optional.some(DeleteAction.moveToPosition(to));
        }
      });
    };
    var getContentEditableAction = function (root, forward, from) {
      if (isAtContentEditableBlockCaret(forward, from)) {
        return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
          return findCefPosition(root, forward, from);
        }, Optional.some);
      } else {
        return findCefPosition(root, forward, from).bind(function (deleteAction) {
          return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
        });
      }
    };
    var read$4 = function (root, forward, rng) {
      var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
      var from = CaretPosition.fromRangeStart(normalizedRange);
      var rootElement = SugarElement.fromDom(root);
      if (forward === false &amp;&amp; isAfterContentEditableFalse(from)) {
        return Optional.some(DeleteAction.remove(from.getNode(true)));
      } else if (forward &amp;&amp; isBeforeContentEditableFalse(from)) {
        return Optional.some(DeleteAction.remove(from.getNode()));
      } else if (forward === false &amp;&amp; isBeforeContentEditableFalse(from) &amp;&amp; isAfterBr(rootElement, from)) {
        return findPreviousBr(rootElement, from).map(function (br) {
          return DeleteAction.remove(br.getNode());
        });
      } else if (forward &amp;&amp; isAfterContentEditableFalse(from) &amp;&amp; isBeforeBr(rootElement, from)) {
        return findNextBr(rootElement, from).map(function (br) {
          return DeleteAction.remove(br.getNode());
        });
      } else {
        return getContentEditableAction(root, forward, from);
      }
    };

    var deleteElement$1 = function (editor, forward) {
      return function (element) {
        editor._selectionOverrides.hideFakeCaret();
        deleteElement(editor, forward, SugarElement.fromDom(element));
        return true;
      };
    };
    var moveToElement = function (editor, forward) {
      return function (element) {
        var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
        editor.selection.setRng(pos.toRange());
        return true;
      };
    };
    var moveToPosition = function (editor) {
      return function (pos) {
        editor.selection.setRng(pos.toRange());
        return true;
      };
    };
    var getAncestorCe = function (editor, node) {
      return Optional.from(getContentEditableRoot(editor.getBody(), node));
    };
    var backspaceDeleteCaret = function (editor, forward) {
      var selectedNode = editor.selection.getNode();
      return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse).fold(function () {
        return read$4(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
          return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
        });
      }, always);
    };
    var deleteOffscreenSelection = function (rootElement) {
      each(descendants$1(rootElement, '.mce-offscreen-selection'), remove);
    };
    var backspaceDeleteRange = function (editor, forward) {
      var selectedNode = editor.selection.getNode();
      if (isContentEditableFalse(selectedNode)) {
        var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse);
        return hasCefAncestor.fold(function () {
          deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
          deleteElement(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
          paddEmptyBody(editor);
          return true;
        }, always);
      }
      return false;
    };
    var paddEmptyElement = function (editor) {
      var dom = editor.dom, selection = editor.selection;
      var ceRoot = getContentEditableRoot(editor.getBody(), selection.getNode());
      if (isContentEditableTrue(ceRoot) &amp;&amp; dom.isBlock(ceRoot) &amp;&amp; dom.isEmpty(ceRoot)) {
        var br = dom.create('br', { 'data-mce-bogus': '1' });
        dom.setHTML(ceRoot, '');
        ceRoot.appendChild(br);
        selection.setRng(CaretPosition.before(br).toRange());
      }
      return true;
    };
    var backspaceDelete$4 = function (editor, forward) {
      if (editor.selection.isCollapsed()) {
        return backspaceDeleteCaret(editor, forward);
      } else {
        return backspaceDeleteRange(editor, forward);
      }
    };

    var deleteCaret$1 = function (editor, forward) {
      var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
      return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
        return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
      }).bind(function (pos) {
        return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
      }).exists(function (elm) {
        editor.selection.select(elm);
        return true;
      });
    };
    var backspaceDelete$5 = function (editor, forward) {
      return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
    };

    var isText$8 = isText$1;
    var startsWithCaretContainer$1 = function (node) {
      return isText$8(node) &amp;&amp; node.data[0] === ZWSP;
    };
    var endsWithCaretContainer$1 = function (node) {
      return isText$8(node) &amp;&amp; node.data[node.data.length - 1] === ZWSP;
    };
    var createZwsp = function (node) {
      return node.ownerDocument.createTextNode(ZWSP);
    };
    var insertBefore$1 = function (node) {
      if (isText$8(node.previousSibling)) {
        if (endsWithCaretContainer$1(node.previousSibling)) {
          return node.previousSibling;
        } else {
          node.previousSibling.appendData(ZWSP);
          return node.previousSibling;
        }
      } else if (isText$8(node)) {
        if (startsWithCaretContainer$1(node)) {
          return node;
        } else {
          node.insertData(0, ZWSP);
          return node;
        }
      } else {
        var newNode = createZwsp(node);
        node.parentNode.insertBefore(newNode, node);
        return newNode;
      }
    };
    var insertAfter$1 = function (node) {
      if (isText$8(node.nextSibling)) {
        if (startsWithCaretContainer$1(node.nextSibling)) {
          return node.nextSibling;
        } else {
          node.nextSibling.insertData(0, ZWSP);
          return node.nextSibling;
        }
      } else if (isText$8(node)) {
        if (endsWithCaretContainer$1(node)) {
          return node;
        } else {
          node.appendData(ZWSP);
          return node;
        }
      } else {
        var newNode = createZwsp(node);
        if (node.nextSibling) {
          node.parentNode.insertBefore(newNode, node.nextSibling);
        } else {
          node.parentNode.appendChild(newNode);
        }
        return newNode;
      }
    };
    var insertInline$1 = function (before, node) {
      return before ? insertBefore$1(node) : insertAfter$1(node);
    };
    var insertInlineBefore = curry(insertInline$1, true);
    var insertInlineAfter = curry(insertInline$1, false);

    var insertInlinePos = function (pos, before) {
      if (isText$1(pos.container())) {
        return insertInline$1(before, pos.container());
      } else {
        return insertInline$1(before, pos.getNode());
      }
    };
    var isPosCaretContainer = function (pos, caret) {
      var caretNode = caret.get();
      return caretNode &amp;&amp; pos.container() === caretNode &amp;&amp; isCaretContainerInline(caretNode);
    };
    var renderCaret = function (caret, location) {
      return location.fold(function (element) {
        remove$5(caret.get());
        var text = insertInlineBefore(element);
        caret.set(text);
        return Optional.some(CaretPosition(text, text.length - 1));
      }, function (element) {
        return firstPositionIn(element).map(function (pos) {
          if (!isPosCaretContainer(pos, caret)) {
            remove$5(caret.get());
            var text = insertInlinePos(pos, true);
            caret.set(text);
            return CaretPosition(text, 1);
          } else {
            return CaretPosition(caret.get(), 1);
          }
        });
      }, function (element) {
        return lastPositionIn(element).map(function (pos) {
          if (!isPosCaretContainer(pos, caret)) {
            remove$5(caret.get());
            var text = insertInlinePos(pos, false);
            caret.set(text);
            return CaretPosition(text, text.length - 1);
          } else {
            return CaretPosition(caret.get(), caret.get().length - 1);
          }
        });
      }, function (element) {
        remove$5(caret.get());
        var text = insertInlineAfter(element);
        caret.set(text);
        return Optional.some(CaretPosition(text, 1));
      });
    };

    var evaluateUntil = function (fns, args) {
      for (var i = 0; i &lt; fns.length; i++) {
        var result = fns[i].apply(null, args);
        if (result.isSome()) {
          return result;
        }
      }
      return Optional.none();
    };

    var Location = Adt.generate([
      { before: ['element'] },
      { start: ['element'] },
      { end: ['element'] },
      { after: ['element'] }
    ]);
    var rescope = function (rootNode, node) {
      var parentBlock = getParentBlock(node, rootNode);
      return parentBlock ? parentBlock : rootNode;
    };
    var before$4 = function (isInlineTarget, rootNode, pos) {
      var nPos = normalizeForwards(pos);
      var scope = rescope(rootNode, nPos.container());
      return findRootInline(isInlineTarget, scope, nPos).fold(function () {
        return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
          return Location.before(inline);
        });
      }, Optional.none);
    };
    var isNotInsideFormatCaretContainer = function (rootNode, elm) {
      return getParentCaretContainer(rootNode, elm) === null;
    };
    var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
      return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
    };
    var start = function (isInlineTarget, rootNode, pos) {
      var nPos = normalizeBackwards(pos);
      return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
        var prevPos = prevPosition(inline, nPos);
        return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
      });
    };
    var end = function (isInlineTarget, rootNode, pos) {
      var nPos = normalizeForwards(pos);
      return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
        var nextPos = nextPosition(inline, nPos);
        return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
      });
    };
    var after$3 = function (isInlineTarget, rootNode, pos) {
      var nPos = normalizeBackwards(pos);
      var scope = rescope(rootNode, nPos.container());
      return findRootInline(isInlineTarget, scope, nPos).fold(function () {
        return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
          return Location.after(inline);
        });
      }, Optional.none);
    };
    var isValidLocation = function (location) {
      return isRtl$1(getElement(location)) === false;
    };
    var readLocation = function (isInlineTarget, rootNode, pos) {
      var location = evaluateUntil([
        before$4,
        start,
        end,
        after$3
      ], [
        isInlineTarget,
        rootNode,
        pos
      ]);
      return location.filter(isValidLocation);
    };
    var getElement = function (location) {
      return location.fold(identity, identity, identity, identity);
    };
    var getName = function (location) {
      return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
    };
    var outside = function (location) {
      return location.fold(Location.before, Location.before, Location.after, Location.after);
    };
    var inside = function (location) {
      return location.fold(Location.start, Location.start, Location.end, Location.end);
    };
    var isEq$5 = function (location1, location2) {
      return getName(location1) === getName(location2) &amp;&amp; getElement(location1) === getElement(location2);
    };
    var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
      return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
        if (fromInline !== toInline &amp;&amp; hasSameParentBlock(rootNode, fromInline, toInline)) {
          return Location.after(forward ? fromInline : toInline);
        } else {
          return location;
        }
      }).getOr(location);
    };
    var skipNoMovement = function (fromLocation, toLocation) {
      return fromLocation.fold(always, function (fromLocation) {
        return !isEq$5(fromLocation, toLocation);
      });
    };
    var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
      var from = normalizePosition(forward, pos);
      var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
      var location = to.fold(function () {
        return fromLocation.map(outside);
      }, function (to) {
        return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
      });
      return location.filter(isValidLocation);
    };
    var findLocationSimple = function (forward, location) {
      if (forward) {
        return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
      } else {
        return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
      }
    };
    var findLocation = function (forward, isInlineTarget, rootNode, pos) {
      var from = normalizePosition(forward, pos);
      var fromLocation = readLocation(isInlineTarget, rootNode, from);
      return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
        return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
      });
    };
    var prevLocation = curry(findLocation, false);
    var nextLocation = curry(findLocation, true);

    var hasSelectionModifyApi = function (editor) {
      return isFunction(editor.selection.getSel().modify);
    };
    var moveRel = function (forward, selection, pos) {
      var delta = forward ? 1 : -1;
      selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
      selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
      return true;
    };
    var moveByWord = function (forward, editor) {
      var rng = editor.selection.getRng();
      var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
      if (!hasSelectionModifyApi(editor)) {
        return false;
      } else if (forward &amp;&amp; isBeforeInline(pos)) {
        return moveRel(true, editor.selection, pos);
      } else if (!forward &amp;&amp; isAfterInline(pos)) {
        return moveRel(false, editor.selection, pos);
      } else {
        return false;
      }
    };

    var BreakType;
    (function (BreakType) {
      BreakType[BreakType['Br'] = 0] = 'Br';
      BreakType[BreakType['Block'] = 1] = 'Block';
      BreakType[BreakType['Wrap'] = 2] = 'Wrap';
      BreakType[BreakType['Eol'] = 3] = 'Eol';
    }(BreakType || (BreakType = {})));
    var flip = function (direction, positions) {
      return direction === HDirection.Backwards ? reverse(positions) : positions;
    };
    var walk$3 = function (direction, caretWalker, pos) {
      return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
    };
    var getBreakType = function (scope, direction, currentPos, nextPos) {
      if (isBr(nextPos.getNode(direction === HDirection.Forwards))) {
        return BreakType.Br;
      } else if (isInSameBlock(currentPos, nextPos) === false) {
        return BreakType.Block;
      } else {
        return BreakType.Wrap;
      }
    };
    var getPositionsUntil = function (predicate, direction, scope, start) {
      var caretWalker = CaretWalker(scope);
      var currentPos = start, nextPos;
      var positions = [];
      while (currentPos) {
        nextPos = walk$3(direction, caretWalker, currentPos);
        if (!nextPos) {
          break;
        }
        if (isBr(nextPos.getNode(false))) {
          if (direction === HDirection.Forwards) {
            return {
              positions: flip(direction, positions).concat([nextPos]),
              breakType: BreakType.Br,
              breakAt: Optional.some(nextPos)
            };
          } else {
            return {
              positions: flip(direction, positions),
              breakType: BreakType.Br,
              breakAt: Optional.some(nextPos)
            };
          }
        }
        if (!nextPos.isVisible()) {
          currentPos = nextPos;
          continue;
        }
        if (predicate(currentPos, nextPos)) {
          var breakType = getBreakType(scope, direction, currentPos, nextPos);
          return {
            positions: flip(direction, positions),
            breakType: breakType,
            breakAt: Optional.some(nextPos)
          };
        }
        positions.push(nextPos);
        currentPos = nextPos;
      }
      return {
        positions: flip(direction, positions),
        breakType: BreakType.Eol,
        breakAt: Optional.none()
      };
    };
    var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
      return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
        var positions = getPositionsUntilBreak(scope, pos).positions;
        return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
      }).getOr([]);
    };
    var findClosestHorizontalPositionFromPoint = function (positions, x) {
      return foldl(positions, function (acc, newPos) {
        return acc.fold(function () {
          return Optional.some(newPos);
        }, function (lastPos) {
          return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
            var lastDist = Math.abs(x - lastRect.left);
            var newDist = Math.abs(x - newRect.left);
            return newDist &lt;= lastDist ? newPos : lastPos;
          }).or(acc);
        });
      }, Optional.none());
    };
    var findClosestHorizontalPosition = function (positions, pos) {
      return head(pos.getClientRects()).bind(function (targetRect) {
        return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
      });
    };
    var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
    var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
    var isAtFirstLine = function (scope, pos) {
      return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
    };
    var isAtLastLine = function (scope, pos) {
      return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
    };
    var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
    var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
    var getFirstLinePositions = function (scope) {
      return firstPositionIn(scope).map(function (pos) {
        return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
      }).getOr([]);
    };
    var getLastLinePositions = function (scope) {
      return lastPositionIn(scope).map(function (pos) {
        return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
      }).getOr([]);
    };

    var getNodeClientRects = function (node) {
      var toArrayWithNode = function (clientRects) {
        return map(clientRects, function (clientRect) {
          clientRect = clone$2(clientRect);
          clientRect.node = node;
          return clientRect;
        });
      };
      if (isElement$1(node)) {
        return toArrayWithNode(node.getClientRects());
      }
      if (isText$1(node)) {
        var rng = node.ownerDocument.createRange();
        rng.setStart(node, 0);
        rng.setEnd(node, node.data.length);
        return toArrayWithNode(rng.getClientRects());
      }
    };
    var getClientRects = function (nodes) {
      return bind(nodes, getNodeClientRects);
    };

    var VDirection;
    (function (VDirection) {
      VDirection[VDirection['Up'] = -1] = 'Up';
      VDirection[VDirection['Down'] = 1] = 'Down';
    }(VDirection || (VDirection = {})));
    var findUntil$1 = function (direction, root, predicateFn, node) {
      while (node = findNode(node, direction, isEditableCaretCandidate, root)) {
        if (predicateFn(node)) {
          return;
        }
      }
    };
    var walkUntil = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
      var line = 0;
      var result = [];
      var add = function (node) {
        var i, clientRect, clientRects;
        clientRects = getClientRects([node]);
        if (direction === -1) {
          clientRects = clientRects.reverse();
        }
        for (i = 0; i &lt; clientRects.length; i++) {
          clientRect = clientRects[i];
          if (isBeflowFn(clientRect, targetClientRect)) {
            continue;
          }
          if (result.length &gt; 0 &amp;&amp; isAboveFn(clientRect, last$1(result))) {
            line++;
          }
          clientRect.line = line;
          if (predicateFn(clientRect)) {
            return true;
          }
          result.push(clientRect);
        }
      };
      var targetClientRect = last$1(caretPosition.getClientRects());
      if (!targetClientRect) {
        return result;
      }
      var node = caretPosition.getNode();
      add(node);
      findUntil$1(direction, root, add, node);
      return result;
    };
    var aboveLineNumber = function (lineNumber, clientRect) {
      return clientRect.line &gt; lineNumber;
    };
    var isLineNumber = function (lineNumber, clientRect) {
      return clientRect.line === lineNumber;
    };
    var upUntil = curry(walkUntil, VDirection.Up, isAbove, isBelow);
    var downUntil = curry(walkUntil, VDirection.Down, isBelow, isAbove);
    var positionsUntil = function (direction, root, predicateFn, node) {
      var caretWalker = CaretWalker(root);
      var walkFn, isBelowFn, isAboveFn, caretPosition;
      var result = [];
      var line = 0, clientRect;
      var getClientRect = function (caretPosition) {
        if (direction === 1) {
          return last$1(caretPosition.getClientRects());
        }
        return last$1(caretPosition.getClientRects());
      };
      if (direction === 1) {
        walkFn = caretWalker.next;
        isBelowFn = isBelow;
        isAboveFn = isAbove;
        caretPosition = CaretPosition.after(node);
      } else {
        walkFn = caretWalker.prev;
        isBelowFn = isAbove;
        isAboveFn = isBelow;
        caretPosition = CaretPosition.before(node);
      }
      var targetClientRect = getClientRect(caretPosition);
      do {
        if (!caretPosition.isVisible()) {
          continue;
        }
        clientRect = getClientRect(caretPosition);
        if (isAboveFn(clientRect, targetClientRect)) {
          continue;
        }
        if (result.length &gt; 0 &amp;&amp; isBelowFn(clientRect, last$1(result))) {
          line++;
        }
        clientRect = clone$2(clientRect);
        clientRect.position = caretPosition;
        clientRect.line = line;
        if (predicateFn(clientRect)) {
          return result;
        }
        result.push(clientRect);
      } while (caretPosition = walkFn(caretPosition));
      return result;
    };
    var isAboveLine = function (lineNumber) {
      return function (clientRect) {
        return aboveLineNumber(lineNumber, clientRect);
      };
    };
    var isLine = function (lineNumber) {
      return function (clientRect) {
        return isLineNumber(lineNumber, clientRect);
      };
    };

    var isContentEditableFalse$8 = isContentEditableFalse;
    var findNode$1 = findNode;
    var distanceToRectLeft = function (clientRect, clientX) {
      return Math.abs(clientRect.left - clientX);
    };
    var distanceToRectRight = function (clientRect, clientX) {
      return Math.abs(clientRect.right - clientX);
    };
    var isInsideX = function (clientX, clientRect) {
      return clientX &gt;= clientRect.left &amp;&amp; clientX &lt;= clientRect.right;
    };
    var isInsideY = function (clientY, clientRect) {
      return clientY &gt;= clientRect.top &amp;&amp; clientY &lt;= clientRect.bottom;
    };
    var findClosestClientRect = function (clientRects, clientX) {
      return reduce(clientRects, function (oldClientRect, clientRect) {
        var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
        var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
        if (isInsideX(clientX, clientRect)) {
          return clientRect;
        }
        if (isInsideX(clientX, oldClientRect)) {
          return oldClientRect;
        }
        if (newDistance === oldDistance &amp;&amp; isContentEditableFalse$8(clientRect.node)) {
          return clientRect;
        }
        if (newDistance &lt; oldDistance) {
          return clientRect;
        }
        return oldClientRect;
      });
    };
    var walkUntil$1 = function (direction, root, predicateFn, startNode, includeChildren) {
      var node = findNode$1(startNode, direction, isEditableCaretCandidate, root, !includeChildren);
      do {
        if (!node || predicateFn(node)) {
          return;
        }
      } while (node = findNode$1(node, direction, isEditableCaretCandidate, root));
    };
    var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
      if (includeChildren === void 0) {
        includeChildren = true;
      }
      var clientRects = [];
      var collect = function (checkPosFn, node) {
        var lineRects = filter(getClientRects([node]), function (clientRect) {
          return !checkPosFn(clientRect, targetNodeRect);
        });
        clientRects = clientRects.concat(lineRects);
        return lineRects.length === 0;
      };
      clientRects.push(targetNodeRect);
      walkUntil$1(VDirection.Up, root, curry(collect, isAbove), targetNodeRect.node, includeChildren);
      walkUntil$1(VDirection.Down, root, curry(collect, isBelow), targetNodeRect.node, includeChildren);
      return clientRects;
    };
    var getFakeCaretTargets = function (root) {
      return filter(from$1(root.getElementsByTagName('*')), isFakeCaretTarget);
    };
    var caretInfo = function (clientRect, clientX) {
      return {
        node: clientRect.node,
        before: distanceToRectLeft(clientRect, clientX) &lt; distanceToRectRight(clientRect, clientX)
      };
    };
    var closestFakeCaret = function (root, clientX, clientY) {
      var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
      var targetNodeRects = filter(fakeTargetNodeRects, curry(isInsideY, clientY));
      var closestNodeRect = findClosestClientRect(targetNodeRects, clientX);
      if (closestNodeRect) {
        var includeChildren = !isTable(closestNodeRect.node) &amp;&amp; !isMedia(closestNodeRect.node);
        closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX);
        if (closestNodeRect &amp;&amp; isFakeCaretTarget(closestNodeRect.node)) {
          return caretInfo(closestNodeRect, clientX);
        }
      }
      return null;
    };

    var moveToRange = function (editor, rng) {
      editor.selection.setRng(rng);
      scrollRangeIntoView(editor, editor.selection.getRng());
    };
    var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
      return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
    };
    var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
      var forwards = direction === HDirection.Forwards;
      var caretWalker = CaretWalker(editor.getBody());
      var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
      var isBeforeFn = forwards ? isBefore : isAfter;
      if (!range.collapsed) {
        var node = getSelectedNode(range);
        if (isElement(node)) {
          return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
        }
      }
      var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
      if (isBeforeFn(caretPosition)) {
        return selectNode(editor, caretPosition.getNode(!forwards));
      }
      var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
      var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
      if (!nextCaretPosition) {
        return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
      }
      if (isBeforeFn(nextCaretPosition)) {
        return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
      }
      var peekCaretPosition = getNextPosFn(nextCaretPosition);
      if (peekCaretPosition &amp;&amp; isBeforeFn(peekCaretPosition)) {
        if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
          return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
        }
      }
      if (rangeIsInContainerBlock) {
        return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
      }
      return Optional.none();
    };
    var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
      var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
      var caretClientRect = last$1(caretPosition.getClientRects());
      var forwards = direction === VDirection.Down;
      if (!caretClientRect) {
        return Optional.none();
      }
      var walkerFn = forwards ? downUntil : upUntil;
      var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
      var nextLinePositions = filter(linePositions, isLine(1));
      var clientX = caretClientRect.left;
      var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
      if (nextLineRect &amp;&amp; isElement(nextLineRect.node)) {
        var dist1 = Math.abs(clientX - nextLineRect.left);
        var dist2 = Math.abs(clientX - nextLineRect.right);
        return showCaret(direction, editor, nextLineRect.node, dist1 &lt; dist2, false);
      }
      var currentNode;
      if (isBefore(caretPosition)) {
        currentNode = caretPosition.getNode();
      } else if (isAfter(caretPosition)) {
        currentNode = caretPosition.getNode(true);
      } else {
        currentNode = getSelectedNode(range);
      }
      if (currentNode) {
        var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
        var closestNextLineRect = findClosestClientRect(filter(caretPositions, isLine(1)), clientX);
        if (closestNextLineRect) {
          return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
        }
        closestNextLineRect = last$1(filter(caretPositions, isLine(0)));
        if (closestNextLineRect) {
          return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
        }
      }
      if (nextLinePositions.length === 0) {
        return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
          return renderRangeCaret(editor, pos.toRange(), false);
        });
      }
      return Optional.none();
    };
    var getLineEndPoint = function (editor, forward) {
      var rng = editor.selection.getRng();
      var body = editor.getBody();
      if (forward) {
        var from = CaretPosition.fromRangeEnd(rng);
        var result = getPositionsUntilNextLine(body, from);
        return last(result.positions);
      } else {
        var from = CaretPosition.fromRangeStart(rng);
        var result = getPositionsUntilPreviousLine(body, from);
        return head(result.positions);
      }
    };
    var moveToLineEndPoint = function (editor, forward, isElementPosition) {
      return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
        editor.selection.setRng(pos.toRange());
        return true;
      });
    };

    var setCaretPosition = function (editor, pos) {
      var rng = editor.dom.createRng();
      rng.setStart(pos.container(), pos.offset());
      rng.setEnd(pos.container(), pos.offset());
      editor.selection.setRng(rng);
    };
    var setSelected = function (state, elm) {
      if (state) {
        elm.setAttribute('data-mce-selected', 'inline-boundary');
      } else {
        elm.removeAttribute('data-mce-selected');
      }
    };
    var renderCaretLocation = function (editor, caret, location) {
      return renderCaret(caret, location).map(function (pos) {
        setCaretPosition(editor, pos);
        return location;
      });
    };
    var findLocation$1 = function (editor, caret, forward) {
      var rootNode = editor.getBody();
      var from = CaretPosition.fromRangeStart(editor.selection.getRng());
      var isInlineTarget$1 = curry(isInlineTarget, editor);
      var location = findLocation(forward, isInlineTarget$1, rootNode, from);
      return location.bind(function (location) {
        return renderCaretLocation(editor, caret, location);
      });
    };
    var toggleInlines = function (isInlineTarget, dom, elms) {
      var inlineBoundaries = map(descendants$1(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
        return e.dom;
      });
      var selectedInlines = filter(inlineBoundaries, isInlineTarget);
      var targetInlines = filter(elms, isInlineTarget);
      each(difference(selectedInlines, targetInlines), curry(setSelected, false));
      each(difference(targetInlines, selectedInlines), curry(setSelected, true));
    };
    var safeRemoveCaretContainer = function (editor, caret) {
      if (editor.selection.isCollapsed() &amp;&amp; editor.composing !== true &amp;&amp; caret.get()) {
        var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
        if (CaretPosition.isTextPosition(pos) &amp;&amp; isAtZwsp(pos) === false) {
          setCaretPosition(editor, removeAndReposition(caret.get(), pos));
          caret.set(null);
        }
      }
    };
    var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
      if (editor.selection.isCollapsed()) {
        var inlines = filter(elms, isInlineTarget);
        each(inlines, function (_inline) {
          var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
          readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
            return renderCaretLocation(editor, caret, location);
          });
        });
      }
    };
    var move = function (editor, caret, forward) {
      return isInlineBoundariesEnabled(editor) ? findLocation$1(editor, caret, forward).isSome() : false;
    };
    var moveWord = function (forward, editor, _caret) {
      return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
    };
    var setupSelectedState = function (editor) {
      var caret = Cell(null);
      var isInlineTarget$1 = curry(isInlineTarget, editor);
      editor.on('NodeChange', function (e) {
        if (isInlineBoundariesEnabled(editor) &amp;&amp; !(Env.browser.isIE() &amp;&amp; e.initial)) {
          toggleInlines(isInlineTarget$1, editor.dom, e.parents);
          safeRemoveCaretContainer(editor, caret);
          renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
        }
      });
      return caret;
    };
    var moveNextWord = curry(moveWord, true);
    var movePrevWord = curry(moveWord, false);
    var moveToLineEndPoint$1 = function (editor, forward, caret) {
      if (isInlineBoundariesEnabled(editor)) {
        var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
          var rng = editor.selection.getRng();
          return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
        });
        return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
          var outsideLoc = outside(loc);
          return renderCaret(caret, outsideLoc).exists(function (pos) {
            setCaretPosition(editor, pos);
            return true;
          });
        });
      } else {
        return false;
      }
    };

    var rangeFromPositions = function (from, to) {
      var range = document.createRange();
      range.setStart(from.container(), from.offset());
      range.setEnd(to.container(), to.offset());
      return range;
    };
    var hasOnlyTwoOrLessPositionsLeft = function (elm) {
      return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
        var normalizedFirstPos = normalizePosition(true, firstPos);
        var normalizedLastPos = normalizePosition(false, lastPos);
        return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
          return pos.isEqual(normalizedLastPos);
        });
      }).getOr(true);
    };
    var setCaretLocation = function (editor, caret) {
      return function (location) {
        return renderCaret(caret, location).exists(function (pos) {
          setCaretPosition(editor, pos);
          return true;
        });
      };
    };
    var deleteFromTo = function (editor, caret, from, to) {
      var rootNode = editor.getBody();
      var isInlineTarget$1 = curry(isInlineTarget, editor);
      editor.undoManager.ignore(function () {
        editor.selection.setRng(rangeFromPositions(from, to));
        editor.execCommand('Delete');
        readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
      });
      editor.nodeChanged();
    };
    var rescope$1 = function (rootNode, node) {
      var parentBlock = getParentBlock(node, rootNode);
      return parentBlock ? parentBlock : rootNode;
    };
    var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
      var rootNode = rescope$1(editor.getBody(), from.container());
      var isInlineTarget$1 = curry(isInlineTarget, editor);
      var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
      return fromLocation.bind(function (location) {
        if (forward) {
          return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
        } else {
          return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
        }
      }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
        var toPosition = navigate(forward, rootNode, from);
        var toLocation = toPosition.bind(function (pos) {
          return readLocation(isInlineTarget$1, rootNode, pos);
        });
        return lift2(fromLocation, toLocation, function () {
          return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
            if (hasOnlyTwoOrLessPositionsLeft(elm)) {
              deleteElement(editor, forward, SugarElement.fromDom(elm));
              return true;
            } else {
              return false;
            }
          });
        }).orThunk(function () {
          return toLocation.bind(function (_) {
            return toPosition.map(function (to) {
              if (forward) {
                deleteFromTo(editor, caret, from, to);
              } else {
                deleteFromTo(editor, caret, to, from);
              }
              return true;
            });
          });
        }).getOr(false);
      });
    };
    var backspaceDelete$6 = function (editor, caret, forward) {
      if (editor.selection.isCollapsed() &amp;&amp; isInlineBoundariesEnabled(editor)) {
        var from = CaretPosition.fromRangeStart(editor.selection.getRng());
        return backspaceDeleteCollapsed(editor, caret, forward, from);
      }
      return false;
    };

    var getParentInlines = function (rootElm, startElm) {
      var parents = parentsAndSelf(startElm, rootElm);
      return findIndex(parents, isBlock).fold(constant(parents), function (index) {
        return parents.slice(0, index);
      });
    };
    var hasOnlyOneChild$1 = function (elm) {
      return children(elm).length === 1;
    };
    var deleteLastPosition = function (forward, editor, target, parentInlines) {
      var isFormatElement$1 = curry(isFormatElement, editor);
      var formatNodes = map(filter(parentInlines, isFormatElement$1), function (elm) {
        return elm.dom;
      });
      if (formatNodes.length === 0) {
        deleteElement(editor, forward, target);
      } else {
        var pos = replaceWithCaretFormat(target.dom, formatNodes);
        editor.selection.setRng(pos.toRange());
      }
    };
    var deleteCaret$2 = function (editor, forward) {
      var rootElm = SugarElement.fromDom(editor.getBody());
      var startElm = SugarElement.fromDom(editor.selection.getStart());
      var parentInlines = filter(getParentInlines(rootElm, startElm), hasOnlyOneChild$1);
      return last(parentInlines).exists(function (target) {
        var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
        if (willDeleteLastPositionInElement(forward, fromPos, target.dom) &amp;&amp; !isEmptyCaretFormatElement(target)) {
          deleteLastPosition(forward, editor, target, parentInlines);
          return true;
        } else {
          return false;
        }
      });
    };
    var backspaceDelete$7 = function (editor, forward) {
      return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
    };

    var deleteElement$2 = function (editor, forward, element) {
      editor._selectionOverrides.hideFakeCaret();
      deleteElement(editor, forward, SugarElement.fromDom(element));
      return true;
    };
    var deleteCaret$3 = function (editor, forward) {
      var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
      var direction = forward ? HDirection.Forwards : HDirection.Backwards;
      var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
      if (isNearMedia(fromPos)) {
        return deleteElement$2(editor, forward, fromPos.getNode(!forward));
      } else {
        return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
          return isNearMedia(pos) &amp;&amp; isMoveInsideSameBlock(fromPos, pos);
        }).exists(function (pos) {
          return deleteElement$2(editor, forward, pos.getNode(!forward));
        });
      }
    };
    var deleteRange$2 = function (editor, forward) {
      var selectedNode = editor.selection.getNode();
      return isMedia(selectedNode) ? deleteElement$2(editor, forward, selectedNode) : false;
    };
    var backspaceDelete$8 = function (editor, forward) {
      return editor.selection.isCollapsed() ? deleteCaret$3(editor, forward) : deleteRange$2(editor, forward);
    };

    var isEditable$1 = function (target) {
      return closest(target, function (elm) {
        return isContentEditableTrue(elm.dom) || isContentEditableFalse(elm.dom);
      }).exists(function (elm) {
        return isContentEditableTrue(elm.dom);
      });
    };
    var parseIndentValue = function (value) {
      var number = parseInt(value, 10);
      return isNaN(number) ? 0 : number;
    };
    var getIndentStyleName = function (useMargin, element) {
      var indentStyleName = useMargin || isTable$1(element) ? 'margin' : 'padding';
      var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
      return indentStyleName + suffix;
    };
    var indentElement = function (dom, command, useMargin, value, unit, element) {
      var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
      if (command === 'outdent') {
        var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
        dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
      } else {
        var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
        dom.setStyle(element, indentStyleName, styleValue);
      }
    };
    var validateBlocks = function (editor, blocks) {
      return forall(blocks, function (block) {
        var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
        var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
        var contentEditable = editor.dom.getContentEditable(block.dom);
        return contentEditable !== 'false' &amp;&amp; intentValue &gt; 0;
      });
    };
    var canOutdent = function (editor) {
      var blocks = getBlocksToIndent(editor);
      return !editor.mode.isReadOnly() &amp;&amp; (blocks.length &gt; 1 || validateBlocks(editor, blocks));
    };
    var isListComponent = function (el) {
      return isList(el) || isListItem(el);
    };
    var parentIsListComponent = function (el) {
      return parent(el).map(isListComponent).getOr(false);
    };
    var getBlocksToIndent = function (editor) {
      return filter(map(editor.selection.getSelectedBlocks(), SugarElement.fromDom), function (el) {
        return !isListComponent(el) &amp;&amp; !parentIsListComponent(el) &amp;&amp; isEditable$1(el);
      });
    };
    var handle = function (editor, command) {
      var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
      var indentation = getIndentation(editor);
      var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
      var indentValue = parseInt(indentation, 10);
      var useMargin = shouldIndentUseMargin(editor);
      var forcedRootBlock = getForcedRootBlock(editor);
      if (!editor.queryCommandState('InsertUnorderedList') &amp;&amp; !editor.queryCommandState('InsertOrderedList')) {
        if (forcedRootBlock === '' &amp;&amp; !dom.getParent(selection.getNode(), dom.isBlock)) {
          formatter.apply('div');
        }
      }
      each(getBlocksToIndent(editor), function (block) {
        indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
      });
    };

    var backspaceDelete$9 = function (editor, _forward) {
      if (editor.selection.isCollapsed() &amp;&amp; canOutdent(editor)) {
        var dom = editor.dom;
        var rng = editor.selection.getRng();
        var pos = CaretPosition.fromRangeStart(rng);
        var block = dom.getParent(rng.startContainer, dom.isBlock);
        if (block !== null &amp;&amp; isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
          handle(editor, 'outdent');
          return true;
        }
      }
      return false;
    };

    var nativeCommand = function (editor, command) {
      editor.getDoc().execCommand(command, false, null);
    };
    var deleteCommand = function (editor, caret) {
      if (backspaceDelete$9(editor)) {
        return;
      } else if (backspaceDelete$4(editor, false)) {
        return;
      } else if (backspaceDelete$3(editor, false)) {
        return;
      } else if (backspaceDelete$6(editor, caret, false)) {
        return;
      } else if (backspaceDelete$1(editor, false)) {
        return;
      } else if (backspaceDelete(editor)) {
        return;
      } else if (backspaceDelete$5(editor, false)) {
        return;
      } else if (backspaceDelete$8(editor, false)) {
        return;
      } else if (backspaceDelete$2(editor)) {
        return;
      } else if (backspaceDelete$7(editor, false)) {
        return;
      } else {
        nativeCommand(editor, 'Delete');
        paddEmptyBody(editor);
      }
    };
    var forwardDeleteCommand = function (editor, caret) {
      if (backspaceDelete$4(editor, true)) {
        return;
      } else if (backspaceDelete$3(editor, true)) {
        return;
      } else if (backspaceDelete$6(editor, caret, true)) {
        return;
      } else if (backspaceDelete$1(editor, true)) {
        return;
      } else if (backspaceDelete(editor)) {
        return;
      } else if (backspaceDelete$5(editor, true)) {
        return;
      } else if (backspaceDelete$8(editor, true)) {
        return;
      } else if (backspaceDelete$2(editor)) {
        return;
      } else if (backspaceDelete$7(editor, true)) {
        return;
      } else {
        nativeCommand(editor, 'ForwardDelete');
      }
    };
    var setup$8 = function (editor, caret) {
      editor.addCommand('delete', function () {
        deleteCommand(editor, caret);
      });
      editor.addCommand('forwardDelete', function () {
        forwardDeleteCommand(editor, caret);
      });
    };

    var SIGNIFICANT_MOVE = 5;
    var LONGPRESS_DELAY = 400;
    var getTouch = function (event) {
      if (event.touches === undefined || event.touches.length !== 1) {
        return Optional.none();
      }
      return Optional.some(event.touches[0]);
    };
    var isFarEnough = function (touch, data) {
      var distX = Math.abs(touch.clientX - data.x);
      var distY = Math.abs(touch.clientY - data.y);
      return distX &gt; SIGNIFICANT_MOVE || distY &gt; SIGNIFICANT_MOVE;
    };
    var setup$9 = function (editor) {
      var startData = Cell(Optional.none());
      var longpressFired = Cell(false);
      var debounceLongpress = last$2(function (e) {
        editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
        longpressFired.set(true);
      }, LONGPRESS_DELAY);
      editor.on('touchstart', function (e) {
        getTouch(e).each(function (touch) {
          debounceLongpress.cancel();
          var data = {
            x: touch.clientX,
            y: touch.clientY,
            target: e.target
          };
          debounceLongpress.throttle(e);
          longpressFired.set(false);
          startData.set(Optional.some(data));
        });
      }, true);
      editor.on('touchmove', function (e) {
        debounceLongpress.cancel();
        getTouch(e).each(function (touch) {
          startData.get().each(function (data) {
            if (isFarEnough(touch, data)) {
              startData.set(Optional.none());
              longpressFired.set(false);
              editor.fire('longpresscancel');
            }
          });
        });
      }, true);
      editor.on('touchend touchcancel', function (e) {
        debounceLongpress.cancel();
        if (e.type === 'touchcancel') {
          return;
        }
        startData.get().filter(function (data) {
          return data.target.isEqualNode(e.target);
        }).each(function () {
          if (longpressFired.get()) {
            e.preventDefault();
          } else {
            editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
          }
        });
      }, true);
    };

    var isBlockElement = function (blockElements, node) {
      return blockElements.hasOwnProperty(node.nodeName);
    };
    var isValidTarget = function (blockElements, node) {
      if (isText$1(node)) {
        return true;
      } else if (isElement$1(node)) {
        return !isBlockElement(blockElements, node) &amp;&amp; !isBookmarkNode$1(node);
      } else {
        return false;
      }
    };
    var hasBlockParent = function (blockElements, root, node) {
      return exists(parents$1(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
        return isBlockElement(blockElements, elm.dom);
      });
    };
    var shouldRemoveTextNode = function (blockElements, node) {
      if (isText$1(node)) {
        if (node.nodeValue.length === 0) {
          return true;
        } else if (/^\s+$/.test(node.nodeValue) &amp;&amp; (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
          return true;
        }
      }
      return false;
    };
    var addRootBlocks = function (editor) {
      var dom = editor.dom, selection = editor.selection;
      var schema = editor.schema, blockElements = schema.getBlockElements();
      var node = selection.getStart();
      var rootNode = editor.getBody();
      var rootBlockNode, tempNode, wrapped;
      var forcedRootBlock = getForcedRootBlock(editor);
      if (!node || !isElement$1(node) || !forcedRootBlock) {
        return;
      }
      var rootNodeName = rootNode.nodeName.toLowerCase();
      if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
        return;
      }
      var rng = selection.getRng();
      var startContainer = rng.startContainer;
      var startOffset = rng.startOffset;
      var endContainer = rng.endContainer;
      var endOffset = rng.endOffset;
      var restoreSelection = hasFocus$1(editor);
      node = rootNode.firstChild;
      while (node) {
        if (isValidTarget(blockElements, node)) {
          if (shouldRemoveTextNode(blockElements, node)) {
            tempNode = node;
            node = node.nextSibling;
            dom.remove(tempNode);
            continue;
          }
          if (!rootBlockNode) {
            rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
            node.parentNode.insertBefore(rootBlockNode, node);
            wrapped = true;
          }
          tempNode = node;
          node = node.nextSibling;
          rootBlockNode.appendChild(tempNode);
        } else {
          rootBlockNode = null;
          node = node.nextSibling;
        }
      }
      if (wrapped &amp;&amp; restoreSelection) {
        rng.setStart(startContainer, startOffset);
        rng.setEnd(endContainer, endOffset);
        selection.setRng(rng);
        editor.nodeChanged();
      }
    };
    var setup$a = function (editor) {
      if (getForcedRootBlock(editor)) {
        editor.on('NodeChange', curry(addRootBlocks, editor));
      }
    };

    var findBlockCaretContainer = function (editor) {
      return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').fold(constant(null), function (elm) {
        return elm.dom;
      });
    };
    var removeIeControlRect = function (editor) {
      editor.selection.setRng(editor.selection.getRng());
    };
    var showBlockCaretContainer = function (editor, blockCaretContainer) {
      if (blockCaretContainer.hasAttribute('data-mce-caret')) {
        showCaretContainerBlock(blockCaretContainer);
        removeIeControlRect(editor);
        editor.selection.scrollIntoView(blockCaretContainer);
      }
    };
    var handleBlockContainer = function (editor, e) {
      var blockCaretContainer = findBlockCaretContainer(editor);
      if (!blockCaretContainer) {
        return;
      }
      if (e.type === 'compositionstart') {
        e.preventDefault();
        e.stopPropagation();
        showBlockCaretContainer(editor, blockCaretContainer);
        return;
      }
      if (hasContent(blockCaretContainer)) {
        showBlockCaretContainer(editor, blockCaretContainer);
        editor.undoManager.add();
      }
    };
    var setup$b = function (editor) {
      editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
    };

    var isContentEditableFalse$9 = isContentEditableFalse;
    var moveToCeFalseHorizontally = function (direction, editor, range) {
      return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$9);
    };
    var moveToCeFalseVertically = function (direction, editor, range) {
      var isBefore = function (caretPosition) {
        return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
      };
      var isAfter = function (caretPosition) {
        return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
      };
      return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$9);
    };
    var createTextBlock = function (editor) {
      var textBlock = editor.dom.create(getForcedRootBlock(editor));
      if (!Env.ie || Env.ie &gt;= 11) {
        textBlock.innerHTML = '&lt;br data-mce-bogus="1"&gt;';
      }
      return textBlock;
    };
    var exitPreBlock = function (editor, direction, range) {
      var caretWalker = CaretWalker(editor.getBody());
      var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
      if (range.collapsed &amp;&amp; hasForcedRootBlock(editor)) {
        var pre = editor.dom.getParent(range.startContainer, 'PRE');
        if (!pre) {
          return;
        }
        var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
        if (!caretPos) {
          var newBlock = createTextBlock(editor);
          if (direction === 1) {
            editor.$(pre).after(newBlock);
          } else {
            editor.$(pre).before(newBlock);
          }
          editor.selection.select(newBlock, true);
          editor.selection.collapse();
        }
      }
    };
    var getHorizontalRange = function (editor, forward) {
      var direction = forward ? HDirection.Forwards : HDirection.Backwards;
      var range = editor.selection.getRng();
      return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
        exitPreBlock(editor, direction, range);
        return Optional.none();
      });
    };
    var getVerticalRange = function (editor, down) {
      var direction = down ? 1 : -1;
      var range = editor.selection.getRng();
      return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
        exitPreBlock(editor, direction, range);
        return Optional.none();
      });
    };
    var moveH = function (editor, forward) {
      return getHorizontalRange(editor, forward).exists(function (newRange) {
        moveToRange(editor, newRange);
        return true;
      });
    };
    var moveV = function (editor, down) {
      return getVerticalRange(editor, down).exists(function (newRange) {
        moveToRange(editor, newRange);
        return true;
      });
    };
    var moveToLineEndPoint$2 = function (editor, forward) {
      var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
      return moveToLineEndPoint(editor, forward, isCefPosition);
    };

    var isTarget = function (node) {
      return contains(['figcaption'], name(node));
    };
    var rangeBefore = function (target) {
      var rng = document.createRange();
      rng.setStartBefore(target.dom);
      rng.setEndBefore(target.dom);
      return rng;
    };
    var insertElement = function (root, elm, forward) {
      if (forward) {
        append(root, elm);
      } else {
        prepend(root, elm);
      }
    };
    var insertBr = function (root, forward) {
      var br = SugarElement.fromTag('br');
      insertElement(root, br, forward);
      return rangeBefore(br);
    };
    var insertBlock$1 = function (root, forward, blockName, attrs) {
      var block = SugarElement.fromTag(blockName);
      var br = SugarElement.fromTag('br');
      setAll(block, attrs);
      append(block, br);
      insertElement(root, block, forward);
      return rangeBefore(br);
    };
    var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
      if (rootBlockName === '') {
        return insertBr(root, forward);
      } else {
        return insertBlock$1(root, forward, rootBlockName, attrs);
      }
    };
    var getClosestTargetBlock = function (pos, root) {
      var isRoot = curry(eq$2, root);
      return closest(SugarElement.fromDom(pos.container()), isBlock, isRoot).filter(isTarget);
    };
    var isAtFirstOrLastLine = function (root, forward, pos) {
      return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
    };
    var moveCaretToNewEmptyLine = function (editor, forward) {
      var root = SugarElement.fromDom(editor.getBody());
      var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
      var rootBlock = getForcedRootBlock(editor);
      var rootBlockAttrs = getForcedRootBlockAttrs(editor);
      return getClosestTargetBlock(pos, root).exists(function () {
        if (isAtFirstOrLastLine(root, forward, pos)) {
          var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
          editor.selection.setRng(rng);
          return true;
        } else {
          return false;
        }
      });
    };
    var moveV$1 = function (editor, forward) {
      if (editor.selection.isCollapsed()) {
        return moveCaretToNewEmptyLine(editor, forward);
      } else {
        return false;
      }
    };

    var defaultPatterns = function (patterns) {
      return map(patterns, function (pattern) {
        return __assign({
          shiftKey: false,
          altKey: false,
          ctrlKey: false,
          metaKey: false,
          keyCode: 0,
          action: noop
        }, pattern);
      });
    };
    var matchesEvent = function (pattern, evt) {
      return evt.keyCode === pattern.keyCode &amp;&amp; evt.shiftKey === pattern.shiftKey &amp;&amp; evt.altKey === pattern.altKey &amp;&amp; evt.ctrlKey === pattern.ctrlKey &amp;&amp; evt.metaKey === pattern.metaKey;
    };
    var match$1 = function (patterns, evt) {
      return bind(defaultPatterns(patterns), function (pattern) {
        return matchesEvent(pattern, evt) ? [pattern] : [];
      });
    };
    var action = function (f) {
      var x = [];
      for (var _i = 1; _i &lt; arguments.length; _i++) {
        x[_i - 1] = arguments[_i];
      }
      return function () {
        return f.apply(null, x);
      };
    };
    var execute = function (patterns, evt) {
      return find(match$1(patterns, evt), function (pattern) {
        return pattern.action();
      });
    };

    var moveH$1 = function (editor, forward) {
      var direction = forward ? HDirection.Forwards : HDirection.Backwards;
      var range = editor.selection.getRng();
      return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia).exists(function (newRange) {
        moveToRange(editor, newRange);
        return true;
      });
    };
    var moveV$2 = function (editor, down) {
      var direction = down ? 1 : -1;
      var range = editor.selection.getRng();
      return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia).exists(function (newRange) {
        moveToRange(editor, newRange);
        return true;
      });
    };
    var moveToLineEndPoint$3 = function (editor, forward) {
      var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
      return moveToLineEndPoint(editor, forward, isNearMedia);
    };

    var deflate = function (rect, delta) {
      return {
        left: rect.left - delta,
        top: rect.top - delta,
        right: rect.right + delta * 2,
        bottom: rect.bottom + delta * 2,
        width: rect.width + delta,
        height: rect.height + delta
      };
    };
    var getCorners = function (getYAxisValue, tds) {
      return bind(tds, function (td) {
        var rect = deflate(clone$2(td.getBoundingClientRect()), -1);
        return [
          {
            x: rect.left,
            y: getYAxisValue(rect),
            cell: td
          },
          {
            x: rect.right,
            y: getYAxisValue(rect),
            cell: td
          }
        ];
      });
    };
    var findClosestCorner = function (corners, x, y) {
      return foldl(corners, function (acc, newCorner) {
        return acc.fold(function () {
          return Optional.some(newCorner);
        }, function (oldCorner) {
          var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
          var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
          return Optional.some(newDist &lt; oldDist ? newCorner : oldCorner);
        });
      }, Optional.none());
    };
    var getClosestCell$1 = function (getYAxisValue, isTargetCorner, table, x, y) {
      var cells = descendants$1(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
        return e.dom;
      });
      var corners = filter(getCorners(getYAxisValue, cells), function (corner) {
        return isTargetCorner(corner, y);
      });
      return findClosestCorner(corners, x, y).map(function (corner) {
        return corner.cell;
      });
    };
    var getBottomValue = function (rect) {
      return rect.bottom;
    };
    var getTopValue = function (rect) {
      return rect.top;
    };
    var isAbove$1 = function (corner, y) {
      return corner.y &lt; y;
    };
    var isBelow$1 = function (corner, y) {
      return corner.y &gt; y;
    };
    var getClosestCellAbove = curry(getClosestCell$1, getBottomValue, isAbove$1);
    var getClosestCellBelow = curry(getClosestCell$1, getTopValue, isBelow$1);
    var findClosestPositionInAboveCell = function (table, pos) {
      return head(pos.getClientRects()).bind(function (rect) {
        return getClosestCellAbove(table, rect.left, rect.top);
      }).bind(function (cell) {
        return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
      });
    };
    var findClosestPositionInBelowCell = function (table, pos) {
      return last(pos.getClientRects()).bind(function (rect) {
        return getClosestCellBelow(table, rect.left, rect.top);
      }).bind(function (cell) {
        return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
      });
    };

    var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
      return lineInfo.breakAt.exists(function (breakPos) {
        return getPositionsUntil(scope, breakPos).breakAt.isSome();
      });
    };
    var startsWithWrapBreak = function (lineInfo) {
      return lineInfo.breakType === BreakType.Wrap &amp;&amp; lineInfo.positions.length === 0;
    };
    var startsWithBrBreak = function (lineInfo) {
      return lineInfo.breakType === BreakType.Br &amp;&amp; lineInfo.positions.length === 1;
    };
    var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
      var lineInfo = getPositionsUntil(scope, pos);
      if (startsWithWrapBreak(lineInfo) || !isBr(pos.getNode()) &amp;&amp; startsWithBrBreak(lineInfo)) {
        return !hasNextBreak(getPositionsUntil, scope, lineInfo);
      } else {
        return lineInfo.breakAt.isNone();
      }
    };
    var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
    var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
    var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
      var caretPos = CaretPosition.fromRangeStart(rng);
      return positionIn(!forward, table).exists(function (pos) {
        return pos.isEqual(caretPos);
      });
    };
    var navigateHorizontally = function (editor, forward, table, _td) {
      var rng = editor.selection.getRng();
      var direction = forward ? 1 : -1;
      if (isFakeCaretTableBrowser() &amp;&amp; isCaretAtStartOrEndOfTable(forward, rng, table)) {
        showCaret(direction, editor, table, !forward, false).each(function (newRng) {
          moveToRange(editor, newRng);
        });
        return true;
      }
      return false;
    };
    var getClosestAbovePosition = function (root, table, start) {
      return findClosestPositionInAboveCell(table, start).orThunk(function () {
        return head(start.getClientRects()).bind(function (rect) {
          return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
        });
      }).getOr(CaretPosition.before(table));
    };
    var getClosestBelowPosition = function (root, table, start) {
      return findClosestPositionInBelowCell(table, start).orThunk(function () {
        return head(start.getClientRects()).bind(function (rect) {
          return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
        });
      }).getOr(CaretPosition.after(table));
    };
    var getTable = function (previous, pos) {
      var node = pos.getNode(previous);
      return isElement$1(node) &amp;&amp; node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
    };
    var renderBlock = function (down, editor, table, pos) {
      var forcedRootBlock = getForcedRootBlock(editor);
      if (forcedRootBlock) {
        editor.undoManager.transact(function () {
          var element = SugarElement.fromTag(forcedRootBlock);
          setAll(element, getForcedRootBlockAttrs(editor));
          append(element, SugarElement.fromTag('br'));
          if (down) {
            after(SugarElement.fromDom(table), element);
          } else {
            before(SugarElement.fromDom(table), element);
          }
          var rng = editor.dom.createRng();
          rng.setStart(element.dom, 0);
          rng.setEnd(element.dom, 0);
          moveToRange(editor, rng);
        });
      } else {
        moveToRange(editor, pos.toRange());
      }
    };
    var moveCaret = function (editor, down, pos) {
      var table = down ? getTable(true, pos) : getTable(false, pos);
      var last = down === false;
      table.fold(function () {
        return moveToRange(editor, pos.toRange());
      }, function (table) {
        return positionIn(last, editor.getBody()).filter(function (lastPos) {
          return lastPos.isEqual(pos);
        }).fold(function () {
          return moveToRange(editor, pos.toRange());
        }, function (_) {
          return renderBlock(down, editor, table, pos);
        });
      });
    };
    var navigateVertically = function (editor, down, table, td) {
      var rng = editor.selection.getRng();
      var pos = CaretPosition.fromRangeStart(rng);
      var root = editor.getBody();
      if (!down &amp;&amp; isAtFirstTableCellLine(td, pos)) {
        var newPos = getClosestAbovePosition(root, table, pos);
        moveCaret(editor, down, newPos);
        return true;
      } else if (down &amp;&amp; isAtLastTableCellLine(td, pos)) {
        var newPos = getClosestBelowPosition(root, table, pos);
        moveCaret(editor, down, newPos);
        return true;
      } else {
        return false;
      }
    };
    var move$1 = function (editor, forward, mover) {
      return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
        return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
          return mover(editor, forward, table, td);
        });
      }).getOr(false);
    };
    var moveH$2 = function (editor, forward) {
      return move$1(editor, forward, navigateHorizontally);
    };
    var moveV$3 = function (editor, forward) {
      return move$1(editor, forward, navigateVertically);
    };

    var executeKeydownOverride = function (editor, caret, evt) {
      var os = detect$3().os;
      execute([
        {
          keyCode: VK.RIGHT,
          action: action(moveH, editor, true)
        },
        {
          keyCode: VK.LEFT,
          action: action(moveH, editor, false)
        },
        {
          keyCode: VK.UP,
          action: action(moveV, editor, false)
        },
        {
          keyCode: VK.DOWN,
          action: action(moveV, editor, true)
        },
        {
          keyCode: VK.RIGHT,
          action: action(moveH$2, editor, true)
        },
        {
          keyCode: VK.LEFT,
          action: action(moveH$2, editor, false)
        },
        {
          keyCode: VK.UP,
          action: action(moveV$3, editor, false)
        },
        {
          keyCode: VK.DOWN,
          action: action(moveV$3, editor, true)
        },
        {
          keyCode: VK.RIGHT,
          action: action(moveH$1, editor, true)
        },
        {
          keyCode: VK.LEFT,
          action: action(moveH$1, editor, false)
        },
        {
          keyCode: VK.UP,
          action: action(moveV$2, editor, false)
        },
        {
          keyCode: VK.DOWN,
          action: action(moveV$2, editor, true)
        },
        {
          keyCode: VK.RIGHT,
          action: action(move, editor, caret, true)
        },
        {
          keyCode: VK.LEFT,
          action: action(move, editor, caret, false)
        },
        {
          keyCode: VK.RIGHT,
          ctrlKey: !os.isOSX(),
          altKey: os.isOSX(),
          action: action(moveNextWord, editor, caret)
        },
        {
          keyCode: VK.LEFT,
          ctrlKey: !os.isOSX(),
          altKey: os.isOSX(),
          action: action(movePrevWord, editor, caret)
        },
        {
          keyCode: VK.UP,
          action: action(moveV$1, editor, false)
        },
        {
          keyCode: VK.DOWN,
          action: action(moveV$1, editor, true)
        }
      ], evt).each(function (_) {
        evt.preventDefault();
      });
    };
    var setup$c = function (editor, caret) {
      editor.on('keydown', function (evt) {
        if (evt.isDefaultPrevented() === false) {
          executeKeydownOverride(editor, caret, evt);
        }
      });
    };

    var executeKeydownOverride$1 = function (editor, caret, evt) {
      execute([
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$9, editor, false)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$4, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$4, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$3, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$3, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$6, editor, caret, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$6, editor, caret, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$5, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$5, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$8, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$8, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$2, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$2, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$1, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$1, editor, true)
        },
        {
          keyCode: VK.BACKSPACE,
          action: action(backspaceDelete$7, editor, false)
        },
        {
          keyCode: VK.DELETE,
          action: action(backspaceDelete$7, editor, true)
        }
      ], evt).each(function (_) {
        evt.preventDefault();
      });
    };
    var executeKeyupOverride = function (editor, evt) {
      execute([
        {
          keyCode: VK.BACKSPACE,
          action: action(paddEmptyElement, editor)
        },
        {
          keyCode: VK.DELETE,
          action: action(paddEmptyElement, editor)
        }
      ], evt);
    };
    var setup$d = function (editor, caret) {
      editor.on('keydown', function (evt) {
        if (evt.isDefaultPrevented() === false) {
          executeKeydownOverride$1(editor, caret, evt);
        }
      });
      editor.on('keyup', function (evt) {
        if (evt.isDefaultPrevented() === false) {
          executeKeyupOverride(editor, evt);
        }
      });
    };

    var firstNonWhiteSpaceNodeSibling = function (node) {
      while (node) {
        if (node.nodeType === 1 || node.nodeType === 3 &amp;&amp; node.data &amp;&amp; /[\r\n\s]/.test(node.data)) {
          return node;
        }
        node = node.nextSibling;
      }
    };
    var moveToCaretPosition = function (editor, root) {
      var node, lastNode = root;
      var dom = editor.dom;
      var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
      if (!root) {
        return;
      }
      if (/^(LI|DT|DD)$/.test(root.nodeName)) {
        var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
        if (firstChild &amp;&amp; /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
          root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
        }
      }
      var rng = dom.createRng();
      root.normalize();
      if (root.hasChildNodes()) {
        var walker = new DomTreeWalker(root, root);
        while (node = walker.current()) {
          if (isText$1(node)) {
            rng.setStart(node, 0);
            rng.setEnd(node, 0);
            break;
          }
          if (moveCaretBeforeOnEnterElementsMap[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 (isBr(root)) {
          if (root.nextSibling &amp;&amp; dom.isBlock(root.nextSibling)) {
            rng.setStartBefore(root);
            rng.setEndBefore(root);
          } else {
            rng.setStartAfter(root);
            rng.setEndAfter(root);
          }
        } else {
          rng.setStart(root, 0);
          rng.setEnd(root, 0);
        }
      }
      editor.selection.setRng(rng);
      scrollRangeIntoView(editor, rng);
    };
    var getEditableRoot = function (dom, node) {
      var root = dom.getRoot();
      var parent, editableRoot;
      parent = node;
      while (parent !== root &amp;&amp; dom.getContentEditable(parent) !== 'false') {
        if (dom.getContentEditable(parent) === 'true') {
          editableRoot = parent;
        }
        parent = parent.parentNode;
      }
      return parent !== root ? editableRoot : root;
    };
    var getParentBlock$2 = function (editor) {
      return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
    };
    var getParentBlockName = function (editor) {
      return getParentBlock$2(editor).fold(constant(''), function (parentBlock) {
        return parentBlock.nodeName.toUpperCase();
      });
    };
    var isListItemParentBlock = function (editor) {
      return getParentBlock$2(editor).filter(function (elm) {
        return isListItem(SugarElement.fromDom(elm));
      }).isSome();
    };

    var hasFirstChild = function (elm, name) {
      return elm.firstChild &amp;&amp; elm.firstChild.nodeName === name;
    };
    var isFirstChild = function (elm) {
      var _a;
      return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
    };
    var hasParent$1 = function (elm, parentName) {
      return elm &amp;&amp; elm.parentNode &amp;&amp; elm.parentNode.nodeName === parentName;
    };
    var isListBlock = function (elm) {
      return elm &amp;&amp; /^(OL|UL|LI)$/.test(elm.nodeName);
    };
    var isNestedList = function (elm) {
      return isListBlock(elm) &amp;&amp; isListBlock(elm.parentNode);
    };
    var getContainerBlock = function (containerBlock) {
      var containerBlockParent = containerBlock.parentNode;
      if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
        return containerBlockParent;
      }
      return containerBlock;
    };
    var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
      var node = containerBlock[first ? 'firstChild' : 'lastChild'];
      while (node) {
        if (isElement$1(node)) {
          break;
        }
        node = node[first ? 'nextSibling' : 'previousSibling'];
      }
      return node === parentBlock;
    };
    var insert = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
      var dom = editor.dom;
      var rng = editor.selection.getRng();
      if (containerBlock === editor.getBody()) {
        return;
      }
      if (isNestedList(containerBlock)) {
        newBlockName = 'LI';
      }
      var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
      if (isFirstOrLastLi(containerBlock, parentBlock, true) &amp;&amp; isFirstOrLastLi(containerBlock, parentBlock, false)) {
        if (hasParent$1(containerBlock, 'LI')) {
          var containerBlockParent = getContainerBlock(containerBlock);
          dom.insertAfter(newBlock, containerBlockParent);
          if (isFirstChild(containerBlock)) {
            dom.remove(containerBlockParent);
          } else {
            dom.remove(containerBlock);
          }
        } else {
          dom.replace(newBlock, containerBlock);
        }
      } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
        if (hasParent$1(containerBlock, 'LI')) {
          dom.insertAfter(newBlock, getContainerBlock(containerBlock));
          newBlock.appendChild(dom.doc.createTextNode(' '));
          newBlock.appendChild(containerBlock);
        } else {
          containerBlock.parentNode.insertBefore(newBlock, containerBlock);
        }
        dom.remove(parentBlock);
      } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
        dom.insertAfter(newBlock, getContainerBlock(containerBlock));
        dom.remove(parentBlock);
      } else {
        containerBlock = getContainerBlock(containerBlock);
        var tmpRng = rng.cloneRange();
        tmpRng.setStartAfter(parentBlock);
        tmpRng.setEndAfter(containerBlock);
        var fragment = tmpRng.extractContents();
        if (newBlockName === 'LI' &amp;&amp; hasFirstChild(fragment, 'LI')) {
          newBlock = fragment.firstChild;
          dom.insertAfter(fragment, containerBlock);
        } else {
          dom.insertAfter(fragment, containerBlock);
          dom.insertAfter(newBlock, containerBlock);
        }
        dom.remove(parentBlock);
      }
      moveToCaretPosition(editor, newBlock);
    };

    var trimZwsp = function (fragment) {
      each(descendants(SugarElement.fromDom(fragment), isText), function (text) {
        var rawNode = text.dom;
        rawNode.nodeValue = trim$2(rawNode.nodeValue);
      });
    };
    var isEmptyAnchor = function (dom, elm) {
      return elm &amp;&amp; elm.nodeName === 'A' &amp;&amp; dom.isEmpty(elm);
    };
    var isTableCell$5 = function (node) {
      return node &amp;&amp; /^(TD|TH|CAPTION)$/.test(node.nodeName);
    };
    var emptyBlock = function (elm) {
      elm.innerHTML = '&lt;br data-mce-bogus="1"&gt;';
    };
    var containerAndSiblingName = function (container, nodeName) {
      return container.nodeName === nodeName || container.previousSibling &amp;&amp; container.previousSibling.nodeName === nodeName;
    };
    var canSplitBlock = function (dom, node) {
      return node &amp;&amp; dom.isBlock(node) &amp;&amp; !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) &amp;&amp; !/^(fixed|absolute)/i.test(node.style.position) &amp;&amp; dom.getContentEditable(node) !== 'true';
    };
    var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
      var node = block;
      var firstChilds = [];
      var i;
      if (!node) {
        return;
      }
      while (node = node.firstChild) {
        if (dom.isBlock(node)) {
          return;
        }
        if (isElement$1(node) &amp;&amp; !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
          firstChilds.push(node);
        }
      }
      i = firstChilds.length;
      while (i--) {
        node = firstChilds[i];
        if (!node.hasChildNodes() || node.firstChild === node.lastChild &amp;&amp; node.firstChild.nodeValue === '') {
          dom.remove(node);
        } else {
          if (isEmptyAnchor(dom, node)) {
            dom.remove(node);
          }
        }
      }
    };
    var normalizeZwspOffset = function (start, container, offset) {
      if (isText$1(container) === false) {
        return offset;
      } else if (start) {
        return offset === 1 &amp;&amp; container.data.charAt(offset - 1) === ZWSP ? 0 : offset;
      } else {
        return offset === container.data.length - 1 &amp;&amp; container.data.charAt(offset) === ZWSP ? container.data.length : offset;
      }
    };
    var includeZwspInRange = function (rng) {
      var newRng = rng.cloneRange();
      newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
      newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
      return newRng;
    };
    var trimLeadingLineBreaks = function (node) {
      do {
        if (isText$1(node)) {
          node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
        }
        node = node.firstChild;
      } while (node);
    };
    var getEditableRoot$1 = function (dom, node) {
      var root = dom.getRoot();
      var parent, editableRoot;
      parent = node;
      while (parent !== root &amp;&amp; dom.getContentEditable(parent) !== 'false') {
        if (dom.getContentEditable(parent) === 'true') {
          editableRoot = parent;
        }
        parent = parent.parentNode;
      }
      return parent !== root ? editableRoot : root;
    };
    var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
      var dom = editor.dom;
      Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
        var currentStyles = getAllRaw(SugarElement.fromDom(node));
        var newStyles = __assign(__assign({}, currentStyles), attrStyles);
        dom.setStyles(node, newStyles);
      });
      var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
        return attrClasses.split(/\s+/);
      });
      var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
        return filter(currentClasses.split(/\s+/), function (clazz) {
          return clazz !== '';
        });
      });
      lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
        var filteredClasses = filter(currentClasses, function (clazz) {
          return !contains(attrClasses, clazz);
        });
        var newClasses = __spreadArrays(attrClasses, filteredClasses);
        dom.setAttrib(node, 'class', newClasses.join(' '));
      });
      var appliedAttrs = [
        'style',
        'class'
      ];
      var remainingAttrs = filter$1(forcedRootBlockAttrs, function (_, attrs) {
        return !contains(appliedAttrs, attrs);
      });
      dom.setAttribs(node, remainingAttrs);
    };
    var setForcedBlockAttrs = function (editor, node) {
      var forcedRootBlockName = getForcedRootBlock(editor);
      if (forcedRootBlockName &amp;&amp; forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
        var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
        applyAttributes(editor, node, forcedRootBlockAttrs);
      }
    };
    var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
      var newBlock, parentBlock, startNode, node, next, rootBlockName;
      var blockName = newBlockName || 'P';
      var dom = editor.dom, editableRoot = getEditableRoot$1(dom, container);
      parentBlock = dom.getParent(container, dom.isBlock);
      if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
        parentBlock = parentBlock || editableRoot;
        if (parentBlock === editor.getBody() || isTableCell$5(parentBlock)) {
          rootBlockName = parentBlock.nodeName.toLowerCase();
        } else {
          rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
        }
        if (!parentBlock.hasChildNodes()) {
          newBlock = dom.create(blockName);
          setForcedBlockAttrs(editor, newBlock);
          parentBlock.appendChild(newBlock);
          rng.setStart(newBlock, 0);
          rng.setEnd(newBlock, 0);
          return newBlock;
        }
        node = container;
        while (node.parentNode !== parentBlock) {
          node = node.parentNode;
        }
        while (node &amp;&amp; !dom.isBlock(node)) {
          startNode = node;
          node = node.previousSibling;
        }
        if (startNode &amp;&amp; editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
          newBlock = dom.create(blockName);
          setForcedBlockAttrs(editor, newBlock);
          startNode.parentNode.insertBefore(newBlock, startNode);
          node = startNode;
          while (node &amp;&amp; !dom.isBlock(node)) {
            next = node.nextSibling;
            newBlock.appendChild(node);
            node = next;
          }
          rng.setStart(container, offset);
          rng.setEnd(container, offset);
        }
      }
      return container;
    };
    var addBrToBlockIfNeeded = function (dom, block) {
      block.normalize();
      var lastChild = block.lastChild;
      if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
        dom.add(block, 'br');
      }
    };
    var insert$1 = function (editor, evt) {
      var tmpRng, container, offset, parentBlock;
      var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
      var dom = editor.dom;
      var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
      var rng = editor.selection.getRng();
      var createNewBlock = function (name) {
        var node = container, block, clonedNode, caretNode;
        var textInlineElements = schema.getTextInlineElements();
        if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
          block = dom.create(name || newBlockName);
        } else {
          block = parentBlock.cloneNode(false);
        }
        caretNode = block;
        if (shouldKeepStyles(editor) === false) {
          dom.setAttrib(block, 'style', null);
          dom.setAttrib(block, 'class', null);
        } else {
          do {
            if (textInlineElements[node.nodeName]) {
              if (isCaretNode(node) || isBookmarkNode$1(node)) {
                continue;
              }
              clonedNode = node.cloneNode(false);
              dom.setAttrib(clonedNode, 'id', '');
              if (block.hasChildNodes()) {
                clonedNode.appendChild(block.firstChild);
                block.appendChild(clonedNode);
              } else {
                caretNode = clonedNode;
                block.appendChild(clonedNode);
              }
            }
          } while ((node = node.parentNode) &amp;&amp; node !== editableRoot);
        }
        setForcedBlockAttrs(editor, block);
        emptyBlock(caretNode);
        return block;
      };
      var isCaretAtStartOrEndOfBlock = function (start) {
        var node, name;
        var normalizedOffset = normalizeZwspOffset(start, container, offset);
        if (isText$1(container) &amp;&amp; (start ? normalizedOffset &gt; 0 : normalizedOffset &lt; container.nodeValue.length)) {
          return false;
        }
        if (container.parentNode === parentBlock &amp;&amp; isAfterLastNodeInContainer &amp;&amp; !start) {
          return true;
        }
        if (start &amp;&amp; isElement$1(container) &amp;&amp; container === parentBlock.firstChild) {
          return true;
        }
        if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
          return isAfterLastNodeInContainer &amp;&amp; !start || !isAfterLastNodeInContainer &amp;&amp; start;
        }
        var walker = new DomTreeWalker(container, parentBlock);
        if (isText$1(container)) {
          if (start &amp;&amp; normalizedOffset === 0) {
            walker.prev();
          } else if (!start &amp;&amp; normalizedOffset === container.nodeValue.length) {
            walker.next();
          }
        }
        while (node = walker.current()) {
          if (isElement$1(node)) {
            if (!node.getAttribute('data-mce-bogus')) {
              name = node.nodeName.toLowerCase();
              if (nonEmptyElementsMap[name] &amp;&amp; name !== 'br') {
                return false;
              }
            }
          } else if (isText$1(node) &amp;&amp; !isWhitespaceText(node.nodeValue)) {
            return false;
          }
          if (start) {
            walker.prev();
          } else {
            walker.next();
          }
        }
        return true;
      };
      var insertNewBlockAfter = function () {
        if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) &amp;&amp; containerBlockName !== 'HGROUP') {
          newBlock = createNewBlock(newBlockName);
        } else {
          newBlock = createNewBlock();
        }
        if (shouldEndContainerOnEmptyBlock(editor) &amp;&amp; canSplitBlock(dom, containerBlock) &amp;&amp; dom.isEmpty(parentBlock)) {
          newBlock = dom.split(containerBlock, parentBlock);
        } else {
          dom.insertAfter(newBlock, parentBlock);
        }
        moveToCaretPosition(editor, newBlock);
      };
      normalize(dom, rng).each(function (normRng) {
        rng.setStart(normRng.startContainer, normRng.startOffset);
        rng.setEnd(normRng.endContainer, normRng.endOffset);
      });
      container = rng.startContainer;
      offset = rng.startOffset;
      newBlockName = getForcedRootBlock(editor);
      var shiftKey = !!(evt &amp;&amp; evt.shiftKey);
      var ctrlKey = !!(evt &amp;&amp; evt.ctrlKey);
      if (isElement$1(container) &amp;&amp; container.hasChildNodes()) {
        isAfterLastNodeInContainer = offset &gt; container.childNodes.length - 1;
        container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
        if (isAfterLastNodeInContainer &amp;&amp; isText$1(container)) {
          offset = container.nodeValue.length;
        } else {
          offset = 0;
        }
      }
      var editableRoot = getEditableRoot$1(dom, container);
      if (!editableRoot) {
        return;
      }
      if (newBlockName &amp;&amp; !shiftKey || !newBlockName &amp;&amp; shiftKey) {
        container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
      }
      parentBlock = dom.getParent(container, dom.isBlock);
      containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
      parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
      var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
      if (containerBlockName === 'LI' &amp;&amp; !ctrlKey) {
        parentBlock = containerBlock;
        containerBlock = containerBlock.parentNode;
        parentBlockName = containerBlockName;
      }
      if (/^(LI|DT|DD)$/.test(parentBlockName)) {
        if (dom.isEmpty(parentBlock)) {
          insert(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
          return;
        }
      }
      if (newBlockName &amp;&amp; parentBlock === editor.getBody()) {
        return;
      }
      newBlockName = newBlockName || 'P';
      if (isCaretContainerBlock(parentBlock)) {
        newBlock = showCaretContainerBlock(parentBlock);
        if (dom.isEmpty(parentBlock)) {
          emptyBlock(parentBlock);
        }
        setForcedBlockAttrs(editor, newBlock);
        moveToCaretPosition(editor, newBlock);
      } else if (isCaretAtStartOrEndOfBlock()) {
        insertNewBlockAfter();
      } else if (isCaretAtStartOrEndOfBlock(true)) {
        newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
        moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
      } else {
        tmpRng = includeZwspInRange(rng).cloneRange();
        tmpRng.setEndAfter(parentBlock);
        fragment = tmpRng.extractContents();
        trimZwsp(fragment);
        trimLeadingLineBreaks(fragment);
        newBlock = fragment.firstChild;
        dom.insertAfter(fragment, parentBlock);
        trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
        addBrToBlockIfNeeded(dom, parentBlock);
        if (dom.isEmpty(parentBlock)) {
          emptyBlock(parentBlock);
        }
        newBlock.normalize();
        if (dom.isEmpty(newBlock)) {
          dom.remove(newBlock);
          insertNewBlockAfter();
        } else {
          setForcedBlockAttrs(editor, newBlock);
          moveToCaretPosition(editor, newBlock);
        }
      }
      dom.setAttrib(newBlock, 'id', '');
      editor.fire('NewBlock', { newBlock: newBlock });
    };

    var hasRightSideContent = function (schema, container, parentBlock) {
      var walker = new DomTreeWalker(container, parentBlock);
      var node;
      var nonEmptyElementsMap = schema.getNonEmptyElements();
      while (node = walker.next()) {
        if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length &gt; 0) {
          return true;
        }
      }
    };
    var moveSelectionToBr = function (editor, brElm, extraBr) {
      var rng = editor.dom.createRng();
      if (!extraBr) {
        rng.setStartAfter(brElm);
        rng.setEndAfter(brElm);
      } else {
        rng.setStartBefore(brElm);
        rng.setEndBefore(brElm);
      }
      editor.selection.setRng(rng);
      scrollRangeIntoView(editor, rng);
    };
    var insertBrAtCaret = function (editor, evt) {
      var selection = editor.selection;
      var dom = editor.dom;
      var rng = selection.getRng();
      var brElm;
      var extraBr;
      normalize(dom, rng).each(function (normRng) {
        rng.setStart(normRng.startContainer, normRng.startOffset);
        rng.setEnd(normRng.endContainer, normRng.endOffset);
      });
      var offset = rng.startOffset;
      var container = rng.startContainer;
      if (container.nodeType === 1 &amp;&amp; container.hasChildNodes()) {
        var isAfterLastNodeInContainer = offset &gt; container.childNodes.length - 1;
        container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
        if (isAfterLastNodeInContainer &amp;&amp; container.nodeType === 3) {
          offset = container.nodeValue.length;
        } else {
          offset = 0;
        }
      }
      var parentBlock = dom.getParent(container, dom.isBlock);
      var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
      var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
      var isControlKey = !!(evt &amp;&amp; evt.ctrlKey);
      if (containerBlockName === 'LI' &amp;&amp; !isControlKey) {
        parentBlock = containerBlock;
      }
      if (container &amp;&amp; container.nodeType === 3 &amp;&amp; offset &gt;= container.nodeValue.length) {
        if (!hasRightSideContent(editor.schema, container, parentBlock)) {
          brElm = dom.create('br');
          rng.insertNode(brElm);
          rng.setStartAfter(brElm);
          rng.setEndAfter(brElm);
          extraBr = true;
        }
      }
      brElm = dom.create('br');
      rangeInsertNode(dom, rng, brElm);
      moveSelectionToBr(editor, brElm, extraBr);
      editor.undoManager.add();
    };
    var insertBrBefore = function (editor, inline) {
      var br = SugarElement.fromTag('br');
      before(SugarElement.fromDom(inline), br);
      editor.undoManager.add();
    };
    var insertBrAfter = function (editor, inline) {
      if (!hasBrAfter(editor.getBody(), inline)) {
        after(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
      }
      var br = SugarElement.fromTag('br');
      after(SugarElement.fromDom(inline), br);
      moveSelectionToBr(editor, br.dom, false);
      editor.undoManager.add();
    };
    var isBeforeBr$1 = function (pos) {
      return isBr(pos.getNode());
    };
    var hasBrAfter = function (rootNode, startNode) {
      if (isBeforeBr$1(CaretPosition.after(startNode))) {
        return true;
      } else {
        return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
          return isBr(pos.getNode());
        }).getOr(false);
      }
    };
    var isAnchorLink = function (elm) {
      return elm &amp;&amp; elm.nodeName === 'A' &amp;&amp; 'href' in elm;
    };
    var isInsideAnchor = function (location) {
      return location.fold(never, isAnchorLink, isAnchorLink, never);
    };
    var readInlineAnchorLocation = function (editor) {
      var isInlineTarget$1 = curry(isInlineTarget, editor);
      var position = CaretPosition.fromRangeStart(editor.selection.getRng());
      return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
    };
    var insertBrOutsideAnchor = function (editor, location) {
      location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
    };
    var insert$2 = function (editor, evt) {
      var anchorLocation = readInlineAnchorLocation(editor);
      if (anchorLocation.isSome()) {
        anchorLocation.each(curry(insertBrOutsideAnchor, editor));
      } else {
        insertBrAtCaret(editor, evt);
      }
    };

    var matchesSelector = function (editor, selector) {
      return getParentBlock$2(editor).filter(function (parentBlock) {
        return selector.length &gt; 0 &amp;&amp; is$1(SugarElement.fromDom(parentBlock), selector);
      }).isSome();
    };
    var shouldInsertBr = function (editor) {
      return matchesSelector(editor, getBrNewLineSelector(editor));
    };
    var shouldBlockNewLine = function (editor) {
      return matchesSelector(editor, getNoNewLineSelector(editor));
    };

    var newLineAction = Adt.generate([
      { br: [] },
      { block: [] },
      { none: [] }
    ]);
    var shouldBlockNewLine$1 = function (editor, _shiftKey) {
      return shouldBlockNewLine(editor);
    };
    var isBrMode = function (requiredState) {
      return function (editor, _shiftKey) {
        var brMode = getForcedRootBlock(editor) === '';
        return brMode === requiredState;
      };
    };
    var inListBlock = function (requiredState) {
      return function (editor, _shiftKey) {
        return isListItemParentBlock(editor) === requiredState;
      };
    };
    var inBlock = function (blockName, requiredState) {
      return function (editor, _shiftKey) {
        var state = getParentBlockName(editor) === blockName.toUpperCase();
        return state === requiredState;
      };
    };
    var inPreBlock = function (requiredState) {
      return inBlock('pre', requiredState);
    };
    var inSummaryBlock = function () {
      return inBlock('summary', true);
    };
    var shouldPutBrInPre$1 = function (requiredState) {
      return function (editor, _shiftKey) {
        return shouldPutBrInPre(editor) === requiredState;
      };
    };
    var inBrContext = function (editor, _shiftKey) {
      return shouldInsertBr(editor);
    };
    var hasShiftKey = function (_editor, shiftKey) {
      return shiftKey;
    };
    var canInsertIntoEditableRoot = function (editor) {
      var forcedRootBlock = getForcedRootBlock(editor);
      var rootEditable = getEditableRoot(editor.dom, editor.selection.getStart());
      return rootEditable &amp;&amp; editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
    };
    var match$2 = function (predicates, action) {
      return function (editor, shiftKey) {
        var isMatch = foldl(predicates, function (res, p) {
          return res &amp;&amp; p(editor, shiftKey);
        }, true);
        return isMatch ? Optional.some(action) : Optional.none();
      };
    };
    var getAction$1 = function (editor, evt) {
      return evaluateUntil([
        match$2([shouldBlockNewLine$1], newLineAction.none()),
        match$2([inSummaryBlock()], newLineAction.br()),
        match$2([
          inPreBlock(true),
          shouldPutBrInPre$1(false),
          hasShiftKey
        ], newLineAction.br()),
        match$2([
          inPreBlock(true),
          shouldPutBrInPre$1(false)
        ], newLineAction.block()),
        match$2([
          inPreBlock(true),
          shouldPutBrInPre$1(true),
          hasShiftKey
        ], newLineAction.block()),
        match$2([
          inPreBlock(true),
          shouldPutBrInPre$1(true)
        ], newLineAction.br()),
        match$2([
          inListBlock(true),
          hasShiftKey
        ], newLineAction.br()),
        match$2([inListBlock(true)], newLineAction.block()),
        match$2([
          isBrMode(true),
          hasShiftKey,
          canInsertIntoEditableRoot
        ], newLineAction.block()),
        match$2([isBrMode(true)], newLineAction.br()),
        match$2([inBrContext], newLineAction.br()),
        match$2([
          isBrMode(false),
          hasShiftKey
        ], newLineAction.br()),
        match$2([canInsertIntoEditableRoot], newLineAction.block())
      ], [
        editor,
        !!(evt &amp;&amp; evt.shiftKey)
      ]).getOr(newLineAction.none());
    };

    var insert$3 = function (editor, evt) {
      getAction$1(editor, evt).fold(function () {
        insert$2(editor, evt);
      }, function () {
        insert$1(editor, evt);
      }, noop);
    };

    var handleEnterKeyEvent = function (editor, event) {
      if (event.isDefaultPrevented()) {
        return;
      }
      event.preventDefault();
      endTypingLevelIgnoreLocks(editor.undoManager);
      editor.undoManager.transact(function () {
        if (editor.selection.isCollapsed() === false) {
          editor.execCommand('Delete');
        }
        insert$3(editor, event);
      });
    };
    var setup$e = function (editor) {
      editor.on('keydown', function (event) {
        if (event.keyCode === VK.ENTER) {
          handleEnterKeyEvent(editor, event);
        }
      });
    };

    var executeKeydownOverride$2 = function (editor, caret, evt) {
      execute([
        {
          keyCode: VK.END,
          action: action(moveToLineEndPoint$2, editor, true)
        },
        {
          keyCode: VK.HOME,
          action: action(moveToLineEndPoint$2, editor, false)
        },
        {
          keyCode: VK.END,
          action: action(moveToLineEndPoint$3, editor, true)
        },
        {
          keyCode: VK.HOME,
          action: action(moveToLineEndPoint$3, editor, false)
        },
        {
          keyCode: VK.END,
          action: action(moveToLineEndPoint$1, editor, true, caret)
        },
        {
          keyCode: VK.HOME,
          action: action(moveToLineEndPoint$1, editor, false, caret)
        }
      ], evt).each(function (_) {
        evt.preventDefault();
      });
    };
    var setup$f = function (editor, caret) {
      editor.on('keydown', function (evt) {
        if (evt.isDefaultPrevented() === false) {
          executeKeydownOverride$2(editor, caret, evt);
        }
      });
    };

    var browser$4 = detect$3().browser;
    var setupIeInput = function (editor) {
      var keypressThrotter = first(function () {
        if (!editor.composing) {
          normalizeNbspsInEditor(editor);
        }
      }, 0);
      if (browser$4.isIE()) {
        editor.on('keypress', function (_e) {
          keypressThrotter.throttle();
        });
        editor.on('remove', function (_e) {
          keypressThrotter.cancel();
        });
      }
    };
    var setup$g = function (editor) {
      setupIeInput(editor);
      editor.on('input', function (e) {
        if (e.isComposing === false) {
          normalizeNbspsInEditor(editor);
        }
      });
    };

    var platform$2 = detect$3();
    var executeKeyupAction = function (editor, caret, evt) {
      execute([
        {
          keyCode: VK.PAGE_UP,
          action: action(moveToLineEndPoint$1, editor, false, caret)
        },
        {
          keyCode: VK.PAGE_DOWN,
          action: action(moveToLineEndPoint$1, editor, true, caret)
        }
      ], evt);
    };
    var stopImmediatePropagation = function (e) {
      return e.stopImmediatePropagation();
    };
    var isPageUpDown = function (evt) {
      return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
    };
    var setNodeChangeBlocker = function (blocked, editor, block) {
      if (block &amp;&amp; !blocked.get()) {
        editor.on('NodeChange', stopImmediatePropagation, true);
      } else if (!block &amp;&amp; blocked.get()) {
        editor.off('NodeChange', stopImmediatePropagation);
      }
      blocked.set(block);
    };
    var setup$h = function (editor, caret) {
      if (platform$2.os.isOSX()) {
        return;
      }
      var blocked = Cell(false);
      editor.on('keydown', function (evt) {
        if (isPageUpDown(evt)) {
          setNodeChangeBlocker(blocked, editor, true);
        }
      });
      editor.on('keyup', function (evt) {
        if (evt.isDefaultPrevented() === false) {
          executeKeyupAction(editor, caret, evt);
        }
        if (isPageUpDown(evt) &amp;&amp; blocked.get()) {
          setNodeChangeBlocker(blocked, editor, false);
          editor.nodeChanged();
        }
      });
    };

    var insertTextAtPosition = function (text, pos) {
      var container = pos.container();
      var offset = pos.offset();
      if (isText$1(container)) {
        container.insertData(offset, text);
        return Optional.some(CaretPosition(container, offset + text.length));
      } else {
        return getElementFromPosition(pos).map(function (elm) {
          var textNode = SugarElement.fromText(text);
          if (pos.isAtEnd()) {
            after(elm, textNode);
          } else {
            before(elm, textNode);
          }
          return CaretPosition(textNode.dom, text.length);
        });
      }
    };
    var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
    var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');

    var locationToCaretPosition = function (root) {
      return function (location) {
        return location.fold(function (element) {
          return prevPosition(root.dom, CaretPosition.before(element));
        }, function (element) {
          return firstPositionIn(element);
        }, function (element) {
          return lastPositionIn(element);
        }, function (element) {
          return nextPosition(root.dom, CaretPosition.after(element));
        });
      };
    };
    var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
      return function (checkPos) {
        return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
      };
    };
    var setSelection$1 = function (editor) {
      return function (pos) {
        editor.selection.setRng(pos.toRange());
        editor.nodeChanged();
        return true;
      };
    };
    var insertSpaceOrNbspAtSelection = function (editor) {
      var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
      var root = SugarElement.fromDom(editor.getBody());
      if (editor.selection.isCollapsed()) {
        var isInlineTarget$1 = curry(isInlineTarget, editor);
        var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
        return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection$1(editor));
      } else {
        return false;
      }
    };

    var executeKeydownOverride$3 = function (editor, evt) {
      execute([{
          keyCode: VK.SPACEBAR,
          action: action(insertSpaceOrNbspAtSelection, editor)
        }], evt).each(function (_) {
        evt.preventDefault();
      });
    };
    var setup$i = function (editor) {
      editor.on('keydown', function (evt) {
        if (evt.isDefaultPrevented() === false) {
          executeKeydownOverride$3(editor, evt);
        }
      });
    };

    var registerKeyboardOverrides = function (editor) {
      var caret = setupSelectedState(editor);
      setup$b(editor);
      setup$c(editor, caret);
      setup$d(editor, caret);
      setup$e(editor);
      setup$i(editor);
      setup$g(editor);
      setup$f(editor, caret);
      setup$h(editor, caret);
      return caret;
    };
    var setup$j = function (editor) {
      if (!isRtc(editor)) {
        return registerKeyboardOverrides(editor);
      } else {
        return Cell(null);
      }
    };

    var NodeChange = function () {
      function NodeChange(editor) {
        this.lastPath = [];
        this.editor = editor;
        var lastRng;
        var self = this;
        if (!('onselectionchange' in editor.getDoc())) {
          editor.on('NodeChange click mouseup keyup focus', function (e) {
            var nativeRng = editor.selection.getRng();
            var fakeRng = {
              startContainer: nativeRng.startContainer,
              startOffset: nativeRng.startOffset,
              endContainer: nativeRng.endContainer,
              endOffset: nativeRng.endOffset
            };
            if (e.type === 'nodechange' || !isEq$1(fakeRng, lastRng)) {
              editor.fire('SelectionChange');
            }
            lastRng = fakeRng;
          });
        }
        editor.on('contextmenu', function () {
          editor.fire('SelectionChange');
        });
        editor.on('SelectionChange', function () {
          var startElm = editor.selection.getStart(true);
          if (!startElm || !Env.range &amp;&amp; editor.selection.isCollapsed()) {
            return;
          }
          if (hasAnyRanges(editor) &amp;&amp; !self.isSameElementPath(startElm) &amp;&amp; editor.dom.isChildOf(startElm, editor.getBody())) {
            editor.nodeChanged({ selectionChange: true });
          }
        });
        editor.on('mouseup', function (e) {
          if (!e.isDefaultPrevented() &amp;&amp; hasAnyRanges(editor)) {
            if (editor.selection.getNode().nodeName === 'IMG') {
              Delay.setEditorTimeout(editor, function () {
                editor.nodeChanged();
              });
            } else {
              editor.nodeChanged();
            }
          }
        });
      }
      NodeChange.prototype.nodeChanged = function (args) {
        var selection = this.editor.selection;
        var node, parents, root;
        if (this.editor.initialized &amp;&amp; selection &amp;&amp; !shouldDisableNodeChange(this.editor) &amp;&amp; !this.editor.mode.isReadOnly()) {
          root = this.editor.getBody();
          node = selection.getStart(true) || root;
          if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
            node = root;
          }
          parents = [];
          this.editor.dom.getParent(node, function (node) {
            if (node === root) {
              return true;
            }
            parents.push(node);
          });
          args = args || {};
          args.element = node;
          args.parents = parents;
          this.editor.fire('NodeChange', args);
        }
      };
      NodeChange.prototype.isSameElementPath = function (startElm) {
        var i;
        var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
        if (currentPath.length === this.lastPath.length) {
          for (i = currentPath.length; i &gt;= 0; i--) {
            if (currentPath[i] !== this.lastPath[i]) {
              break;
            }
          }
          if (i === -1) {
            this.lastPath = currentPath;
            return true;
          }
        }
        this.lastPath = currentPath;
        return false;
      };
      return NodeChange;
    }();

    var preventSummaryToggle = function (editor) {
      editor.on('click', function (e) {
        if (editor.dom.getParent(e.target, 'details')) {
          e.preventDefault();
        }
      });
    };
    var filterDetails = function (editor) {
      editor.parser.addNodeFilter('details', function (elms) {
        each(elms, function (details) {
          details.attr('data-mce-open', details.attr('open'));
          details.attr('open', 'open');
        });
      });
      editor.serializer.addNodeFilter('details', function (elms) {
        each(elms, function (details) {
          var open = details.attr('data-mce-open');
          details.attr('open', isString(open) ? open : null);
          details.attr('data-mce-open', null);
        });
      });
    };
    var setup$k = function (editor) {
      preventSummaryToggle(editor);
      filterDetails(editor);
    };

    var isTextBlockNode = function (node) {
      return isElement$1(node) &amp;&amp; isTextBlock(SugarElement.fromDom(node));
    };
    var normalizeSelection$1 = function (editor) {
      var rng = editor.selection.getRng();
      var startPos = CaretPosition.fromRangeStart(rng);
      var endPos = CaretPosition.fromRangeEnd(rng);
      if (CaretPosition.isElementPosition(startPos)) {
        var container = startPos.container();
        if (isTextBlockNode(container)) {
          firstPositionIn(container).each(function (pos) {
            return rng.setStart(pos.container(), pos.offset());
          });
        }
      }
      if (CaretPosition.isElementPosition(endPos)) {
        var container = startPos.container();
        if (isTextBlockNode(container)) {
          lastPositionIn(container).each(function (pos) {
            return rng.setEnd(pos.container(), pos.offset());
          });
        }
      }
      editor.selection.setRng(normalize$2(rng));
    };
    var setup$l = function (editor) {
      editor.on('click', function (e) {
        if (e.detail &gt;= 3) {
          normalizeSelection$1(editor);
        }
      });
    };

    var value$1 = function () {
      var subject = Cell(Optional.none());
      var clear = function () {
        return subject.set(Optional.none());
      };
      var set = function (s) {
        return subject.set(Optional.some(s));
      };
      var isSet = function () {
        return subject.get().isSome();
      };
      var on = function (f) {
        return subject.get().each(f);
      };
      return {
        clear: clear,
        set: set,
        isSet: isSet,
        on: on
      };
    };

    var getAbsolutePosition = function (elm) {
      var clientRect = elm.getBoundingClientRect();
      var doc = elm.ownerDocument;
      var docElem = doc.documentElement;
      var win = doc.defaultView;
      return {
        top: clientRect.top + win.pageYOffset - docElem.clientTop,
        left: clientRect.left + win.pageXOffset - docElem.clientLeft
      };
    };
    var getBodyPosition = function (editor) {
      return editor.inline ? getAbsolutePosition(editor.getBody()) : {
        left: 0,
        top: 0
      };
    };
    var getScrollPosition = function (editor) {
      var body = editor.getBody();
      return editor.inline ? {
        left: body.scrollLeft,
        top: body.scrollTop
      } : {
        left: 0,
        top: 0
      };
    };
    var getBodyScroll = function (editor) {
      var body = editor.getBody(), docElm = editor.getDoc().documentElement;
      var inlineScroll = {
        left: body.scrollLeft,
        top: body.scrollTop
      };
      var iframeScroll = {
        left: body.scrollLeft || docElm.scrollLeft,
        top: body.scrollTop || docElm.scrollTop
      };
      return editor.inline ? inlineScroll : iframeScroll;
    };
    var getMousePosition = function (editor, event) {
      if (event.target.ownerDocument !== editor.getDoc()) {
        var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
        var scrollPosition = getBodyScroll(editor);
        return {
          left: event.pageX - iframePosition.left + scrollPosition.left,
          top: event.pageY - iframePosition.top + scrollPosition.top
        };
      }
      return {
        left: event.pageX,
        top: event.pageY
      };
    };
    var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
      return {
        pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
        pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
      };
    };
    var calc = function (editor, event) {
      return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
    };

    var isContentEditableFalse$a = isContentEditableFalse, isContentEditableTrue$3 = isContentEditableTrue;
    var isDraggable = function (rootElm, elm) {
      return isContentEditableFalse$a(elm) &amp;&amp; elm !== rootElm;
    };
    var isValidDropTarget = function (editor, targetElement, dragElement) {
      if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
        return false;
      }
      return !isContentEditableFalse$a(targetElement);
    };
    var cloneElement = function (elm) {
      var cloneElm = elm.cloneNode(true);
      cloneElm.removeAttribute('data-mce-selected');
      return cloneElm;
    };
    var createGhost = function (editor, elm, width, height) {
      var dom = editor.dom;
      var clonedElm = elm.cloneNode(true);
      dom.setStyles(clonedElm, {
        width: width,
        height: height
      });
      dom.setAttrib(clonedElm, 'data-mce-selected', null);
      var ghostElm = dom.create('div', {
        'class': 'mce-drag-container',
        'data-mce-bogus': 'all',
        'unselectable': 'on',
        'contenteditable': 'false'
      });
      dom.setStyles(ghostElm, {
        position: 'absolute',
        opacity: 0.5,
        overflow: 'hidden',
        border: 0,
        padding: 0,
        margin: 0,
        width: width,
        height: height
      });
      dom.setStyles(clonedElm, {
        margin: 0,
        boxSizing: 'border-box'
      });
      ghostElm.appendChild(clonedElm);
      return ghostElm;
    };
    var appendGhostToBody = function (ghostElm, bodyElm) {
      if (ghostElm.parentNode !== bodyElm) {
        bodyElm.appendChild(ghostElm);
      }
    };
    var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
      var overflowX = 0, overflowY = 0;
      ghostElm.style.left = position.pageX + 'px';
      ghostElm.style.top = position.pageY + 'px';
      if (position.pageX + width &gt; maxX) {
        overflowX = position.pageX + width - maxX;
      }
      if (position.pageY + height &gt; maxY) {
        overflowY = position.pageY + height - maxY;
      }
      ghostElm.style.width = width - overflowX + 'px';
      ghostElm.style.height = height - overflowY + 'px';
    };
    var removeElement = function (elm) {
      if (elm &amp;&amp; elm.parentNode) {
        elm.parentNode.removeChild(elm);
      }
    };
    var isLeftMouseButtonPressed = function (e) {
      return e.button === 0;
    };
    var applyRelPos = function (state, position) {
      return {
        pageX: position.pageX - state.relX,
        pageY: position.pageY + 5
      };
    };
    var start$1 = function (state, editor) {
      return function (e) {
        if (isLeftMouseButtonPressed(e)) {
          var ceElm = find(editor.dom.getParents(e.target), or(isContentEditableFalse$a, isContentEditableTrue$3)).getOr(null);
          if (isDraggable(editor.getBody(), ceElm)) {
            var elmPos = editor.dom.getPos(ceElm);
            var bodyElm = editor.getBody();
            var docElm = editor.getDoc().documentElement;
            state.set({
              element: ceElm,
              dragging: false,
              screenX: e.screenX,
              screenY: e.screenY,
              maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
              maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
              relX: e.pageX - elmPos.x,
              relY: e.pageY - elmPos.y,
              width: ceElm.offsetWidth,
              height: ceElm.offsetHeight,
              ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
            });
          }
        }
      };
    };
    var move$2 = function (state, editor) {
      var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
        editor._selectionOverrides.hideFakeCaret();
        editor.selection.placeCaretAt(clientX, clientY);
      }, 0);
      editor.on('remove', throttledPlaceCaretAt.stop);
      return function (e) {
        return state.on(function (state) {
          var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
          if (!state.dragging &amp;&amp; movement &gt; 10) {
            var args = editor.fire('dragstart', { target: state.element });
            if (args.isDefaultPrevented()) {
              return;
            }
            state.dragging = true;
            editor.focus();
          }
          if (state.dragging) {
            var targetPos = applyRelPos(state, calc(editor, e));
            appendGhostToBody(state.ghost, editor.getBody());
            moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
            throttledPlaceCaretAt(e.clientX, e.clientY);
          }
        });
      };
    };
    var getRawTarget = function (selection) {
      var rng = selection.getSel().getRangeAt(0);
      var startContainer = rng.startContainer;
      return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
    };
    var drop = function (state, editor) {
      return function (e) {
        state.on(function (state) {
          if (state.dragging) {
            if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
              var targetClone_1 = cloneElement(state.element);
              var args = editor.fire('drop', {
                clientX: e.clientX,
                clientY: e.clientY
              });
              if (!args.isDefaultPrevented()) {
                editor.undoManager.transact(function () {
                  removeElement(state.element);
                  editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
                  editor._selectionOverrides.hideFakeCaret();
                });
              }
            }
          }
        });
        removeDragState(state);
      };
    };
    var stop = function (state, editor) {
      return function () {
        state.on(function (state) {
          if (state.dragging) {
            editor.fire('dragend');
          }
        });
        removeDragState(state);
      };
    };
    var removeDragState = function (state) {
      state.on(function (state) {
        removeElement(state.ghost);
      });
      state.clear();
    };
    var bindFakeDragEvents = function (editor) {
      var state = value$1();
      var pageDom = DOMUtils.DOM;
      var rootDocument = document;
      var dragStartHandler = start$1(state, editor);
      var dragHandler = move$2(state, editor);
      var dropHandler = drop(state, editor);
      var dragEndHandler = stop(state, editor);
      editor.on('mousedown', dragStartHandler);
      editor.on('mousemove', dragHandler);
      editor.on('mouseup', dropHandler);
      pageDom.bind(rootDocument, 'mousemove', dragHandler);
      pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
      editor.on('remove', function () {
        pageDom.unbind(rootDocument, 'mousemove', dragHandler);
        pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
      });
    };
    var blockIeDrop = function (editor) {
      editor.on('drop', function (e) {
        var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
        if (isContentEditableFalse$a(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
          e.preventDefault();
        }
      });
    };
    var blockUnsupportedFileDrop = function (editor) {
      var preventFileDrop = function (e) {
        if (!e.isDefaultPrevented()) {
          var dataTransfer = e.dataTransfer;
          if (dataTransfer &amp;&amp; (contains(dataTransfer.types, 'Files') || dataTransfer.files.length &gt; 0)) {
            e.preventDefault();
            if (e.type === 'drop') {
              displayError(editor, 'Dropped file type is not supported');
            }
          }
        }
      };
      var preventFileDropIfUIElement = function (e) {
        if (isUIElement(editor, e.target)) {
          preventFileDrop(e);
        }
      };
      var setup = function () {
        var pageDom = DOMUtils.DOM;
        var dom = editor.dom;
        var doc = document;
        var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
        var eventNames = [
          'drop',
          'dragover'
        ];
        each(eventNames, function (name) {
          pageDom.bind(doc, name, preventFileDropIfUIElement);
          dom.bind(editorRoot, name, preventFileDrop);
        });
        editor.on('remove', function () {
          each(eventNames, function (name) {
            pageDom.unbind(doc, name, preventFileDropIfUIElement);
            dom.unbind(editorRoot, name, preventFileDrop);
          });
        });
      };
      editor.on('init', function () {
        Delay.setEditorTimeout(editor, setup, 0);
      });
    };
    var init = function (editor) {
      bindFakeDragEvents(editor);
      blockIeDrop(editor);
      if (shouldBlockUnsupportedDrop(editor)) {
        blockUnsupportedFileDrop(editor);
      }
    };

    var setup$m = function (editor) {
      var renderFocusCaret = first(function () {
        if (!editor.removed &amp;&amp; editor.getBody().contains(document.activeElement)) {
          var rng = editor.selection.getRng();
          if (rng.collapsed) {
            var caretRange = renderRangeCaret(editor, rng, false);
            editor.selection.setRng(caretRange);
          }
        }
      }, 0);
      editor.on('focus', function () {
        renderFocusCaret.throttle();
      });
      editor.on('blur', function () {
        renderFocusCaret.cancel();
      });
    };

    var setup$n = function (editor) {
      editor.on('init', function () {
        editor.on('focusin', function (e) {
          var target = e.target;
          if (isMedia(target)) {
            var ceRoot = getContentEditableRoot(editor.getBody(), target);
            var node = isContentEditableFalse(ceRoot) ? ceRoot : target;
            if (editor.selection.getNode() !== node) {
              selectNode(editor, node).each(function (rng) {
                return editor.selection.setRng(rng);
              });
            }
          }
        });
      });
    };

    var isContentEditableTrue$4 = isContentEditableTrue;
    var isContentEditableFalse$b = isContentEditableFalse;
    var getContentEditableRoot$1 = function (editor, node) {
      return getContentEditableRoot(editor.getBody(), node);
    };
    var SelectionOverrides = function (editor) {
      var selection = editor.selection, dom = editor.dom;
      var isBlock = dom.isBlock;
      var rootNode = editor.getBody();
      var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
        return hasFocus$1(editor);
      });
      var realSelectionId = 'sel-' + dom.uniqueId();
      var elementSelectionAttr = 'data-mce-selected';
      var selectedElement;
      var isFakeSelectionElement = function (node) {
        return dom.hasClass(node, 'mce-offscreen-selection');
      };
      var isFakeSelectionTargetElement = function (node) {
        return node !== rootNode &amp;&amp; (isContentEditableFalse$b(node) || isMedia(node)) &amp;&amp; dom.isChildOf(node, rootNode);
      };
      var isNearFakeSelectionElement = function (pos) {
        return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
      };
      var getRealSelectionElement = function () {
        var container = dom.get(realSelectionId);
        return container ? container.getElementsByTagName('*')[0] : container;
      };
      var setRange = function (range) {
        if (range) {
          selection.setRng(range);
        }
      };
      var getRange = selection.getRng;
      var showCaret = function (direction, node, before, scrollIntoView) {
        if (scrollIntoView === void 0) {
          scrollIntoView = true;
        }
        var e = editor.fire('ShowCaret', {
          target: node,
          direction: direction,
          before: before
        });
        if (e.isDefaultPrevented()) {
          return null;
        }
        if (scrollIntoView) {
          selection.scrollIntoView(node, direction === -1);
        }
        return fakeCaret.show(before, node);
      };
      var showBlockCaretContainer = function (blockCaretContainer) {
        if (blockCaretContainer.hasAttribute('data-mce-caret')) {
          showCaretContainerBlock(blockCaretContainer);
          setRange(getRange());
          selection.scrollIntoView(blockCaretContainer);
        }
      };
      var registerEvents = function () {
        editor.on('mouseup', function (e) {
          var range = getRange();
          if (range.collapsed &amp;&amp; isXYInContentArea(editor, e.clientX, e.clientY)) {
            renderCaretAtRange(editor, range, false).each(setRange);
          }
        });
        editor.on('click', function (e) {
          var contentEditableRoot = getContentEditableRoot$1(editor, e.target);
          if (contentEditableRoot) {
            if (isContentEditableFalse$b(contentEditableRoot)) {
              e.preventDefault();
              editor.focus();
            }
            if (isContentEditableTrue$4(contentEditableRoot)) {
              if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
                removeElementSelection();
              }
            }
          }
        });
        editor.on('blur NewBlock', removeElementSelection);
        editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
        var hasNormalCaretPosition = function (elm) {
          var caretWalker = CaretWalker(elm);
          if (!elm.firstChild) {
            return false;
          }
          var startPos = CaretPosition.before(elm.firstChild);
          var newPos = caretWalker.next(startPos);
          return newPos &amp;&amp; !isNearFakeSelectionElement(newPos);
        };
        var isInSameBlock = function (node1, node2) {
          var block1 = dom.getParent(node1, isBlock);
          var block2 = dom.getParent(node2, isBlock);
          return block1 === block2;
        };
        var hasBetterMouseTarget = function (targetNode, caretNode) {
          var targetBlock = dom.getParent(targetNode, isBlock);
          var caretBlock = dom.getParent(caretNode, isBlock);
          if (targetBlock &amp;&amp; targetNode !== caretBlock &amp;&amp; dom.isChildOf(targetBlock, caretBlock) &amp;&amp; isContentEditableFalse$b(getContentEditableRoot$1(editor, targetBlock)) === false) {
            return true;
          }
          return targetBlock &amp;&amp; !isInSameBlock(targetBlock, caretBlock) &amp;&amp; hasNormalCaretPosition(targetBlock);
        };
        editor.on('tap', function (e) {
          var targetElm = e.target;
          var contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
          if (isContentEditableFalse$b(contentEditableRoot)) {
            e.preventDefault();
            selectNode(editor, contentEditableRoot).each(setElementSelection);
          } else if (isFakeSelectionTargetElement(targetElm)) {
            selectNode(editor, targetElm).each(setElementSelection);
          }
        }, true);
        editor.on('mousedown', function (e) {
          var targetElm = e.target;
          if (targetElm !== rootNode &amp;&amp; targetElm.nodeName !== 'HTML' &amp;&amp; !dom.isChildOf(targetElm, rootNode)) {
            return;
          }
          if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
            return;
          }
          var contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
          if (contentEditableRoot) {
            if (isContentEditableFalse$b(contentEditableRoot)) {
              e.preventDefault();
              selectNode(editor, contentEditableRoot).each(setElementSelection);
            } else {
              removeElementSelection();
              if (!(isContentEditableTrue$4(contentEditableRoot) &amp;&amp; e.shiftKey) &amp;&amp; !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
                hideFakeCaret();
                selection.placeCaretAt(e.clientX, e.clientY);
              }
            }
          } else if (isFakeSelectionTargetElement(targetElm)) {
            selectNode(editor, targetElm).each(setElementSelection);
          } else if (isFakeCaretTarget(targetElm) === false) {
            removeElementSelection();
            hideFakeCaret();
            var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
            if (fakeCaretInfo) {
              if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
                e.preventDefault();
                var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
                editor.getBody().focus();
                setRange(range);
              }
            }
          }
        });
        editor.on('keypress', function (e) {
          if (VK.modifierPressed(e)) {
            return;
          }
          if (isContentEditableFalse$b(selection.getNode())) {
            e.preventDefault();
          }
        });
        editor.on('GetSelectionRange', function (e) {
          var rng = e.range;
          if (selectedElement) {
            if (!selectedElement.parentNode) {
              selectedElement = null;
              return;
            }
            rng = rng.cloneRange();
            rng.selectNode(selectedElement);
            e.range = rng;
          }
        });
        editor.on('SetSelectionRange', function (e) {
          e.range = normalizeShortEndedElementSelection(e.range);
          var rng = setElementSelection(e.range, e.forward);
          if (rng) {
            e.range = rng;
          }
        });
        var isPasteBin = function (node) {
          return node.id === 'mcepastebin';
        };
        editor.on('AfterSetSelectionRange', function (e) {
          var rng = e.range;
          var parentNode = rng.startContainer.parentNode;
          if (!isRangeInCaretContainer(rng) &amp;&amp; !isPasteBin(parentNode)) {
            hideFakeCaret();
          }
          if (!isFakeSelectionElement(parentNode)) {
            removeElementSelection();
          }
        });
        editor.on('copy', function (e) {
          var clipboardData = e.clipboardData;
          if (!e.isDefaultPrevented() &amp;&amp; e.clipboardData &amp;&amp; !Env.ie) {
            var realSelectionElement = getRealSelectionElement();
            if (realSelectionElement) {
              e.preventDefault();
              clipboardData.clearData();
              clipboardData.setData('text/html', realSelectionElement.outerHTML);
              clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
            }
          }
        });
        init(editor);
        setup$m(editor);
        setup$n(editor);
      };
      var isWithinCaretContainer = function (node) {
        return isCaretContainer(node) || startsWithCaretContainer(node) || endsWithCaretContainer(node);
      };
      var isRangeInCaretContainer = function (rng) {
        return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
      };
      var normalizeShortEndedElementSelection = function (rng) {
        var shortEndedElements = editor.schema.getShortEndedElements();
        var newRng = dom.createRng();
        var startContainer = rng.startContainer;
        var startOffset = rng.startOffset;
        var endContainer = rng.endContainer;
        var endOffset = rng.endOffset;
        if (has(shortEndedElements, startContainer.nodeName.toLowerCase())) {
          if (startOffset === 0) {
            newRng.setStartBefore(startContainer);
          } else {
            newRng.setStartAfter(startContainer);
          }
        } else {
          newRng.setStart(startContainer, startOffset);
        }
        if (has(shortEndedElements, endContainer.nodeName.toLowerCase())) {
          if (endOffset === 0) {
            newRng.setEndBefore(endContainer);
          } else {
            newRng.setEndAfter(endContainer);
          }
        } else {
          newRng.setEnd(endContainer, endOffset);
        }
        return newRng;
      };
      var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
        var $ = editor.$;
        var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
          return $([]);
        }, function (elm) {
          return $([elm.dom]);
        });
        if ($realSelectionContainer.length === 0) {
          $realSelectionContainer = $('&lt;div data-mce-bogus="all" class="mce-offscreen-selection"&gt;&lt;/div&gt;').attr('id', realSelectionId);
          $realSelectionContainer.appendTo(editor.getBody());
        }
        var newRange = dom.createRng();
        if (targetClone === origTargetClone &amp;&amp; Env.ie) {
          $realSelectionContainer.empty().append('&lt;p style="font-size: 0" data-mce-bogus="all"&gt;\xA0&lt;/p&gt;').append(targetClone);
          newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
          newRange.setEndAfter(targetClone);
        } else {
          $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
          newRange.setStart($realSelectionContainer[0].firstChild, 1);
          newRange.setEnd($realSelectionContainer[0].lastChild, 0);
        }
        $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
        $realSelectionContainer[0].focus();
        var sel = selection.getSel();
        sel.removeAllRanges();
        sel.addRange(newRange);
        return newRange;
      };
      var selectElement = function (elm) {
        var targetClone = elm.cloneNode(true);
        var e = editor.fire('ObjectSelected', {
          target: elm,
          targetClone: targetClone
        });
        if (e.isDefaultPrevented()) {
          return null;
        }
        var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
        var nodeElm = SugarElement.fromDom(elm);
        each(descendants$1(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
          if (!eq$2(nodeElm, elm)) {
            remove$1(elm, elementSelectionAttr);
          }
        });
        if (!dom.getAttrib(elm, elementSelectionAttr)) {
          elm.setAttribute(elementSelectionAttr, '1');
        }
        selectedElement = elm;
        hideFakeCaret();
        return range;
      };
      var setElementSelection = function (range, forward) {
        if (!range) {
          return null;
        }
        if (range.collapsed) {
          if (!isRangeInCaretContainer(range)) {
            var dir = forward ? 1 : -1;
            var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
            var beforeNode = caretPosition.getNode(!forward);
            if (isFakeCaretTarget(beforeNode)) {
              return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
            }
            var afterNode = caretPosition.getNode(forward);
            if (isFakeCaretTarget(afterNode)) {
              return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
            }
          }
          return null;
        }
        var startContainer = range.startContainer;
        var startOffset = range.startOffset;
        var endOffset = range.endOffset;
        if (startContainer.nodeType === 3 &amp;&amp; startOffset === 0 &amp;&amp; isContentEditableFalse$b(startContainer.parentNode)) {
          startContainer = startContainer.parentNode;
          startOffset = dom.nodeIndex(startContainer);
          startContainer = startContainer.parentNode;
        }
        if (startContainer.nodeType !== 1) {
          return null;
        }
        if (endOffset === startOffset + 1 &amp;&amp; startContainer === range.endContainer) {
          var node = startContainer.childNodes[startOffset];
          if (isFakeSelectionTargetElement(node)) {
            return selectElement(node);
          }
        }
        return null;
      };
      var removeElementSelection = function () {
        if (selectedElement) {
          selectedElement.removeAttribute(elementSelectionAttr);
        }
        descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove);
        selectedElement = null;
      };
      var destroy = function () {
        fakeCaret.destroy();
        selectedElement = null;
      };
      var hideFakeCaret = function () {
        fakeCaret.hide();
      };
      if (Env.ceFalse &amp;&amp; !isRtc(editor)) {
        registerEvents();
      }
      return {
        showCaret: showCaret,
        showBlockCaretContainer: showBlockCaretContainer,
        hideFakeCaret: hideFakeCaret,
        destroy: destroy
      };
    };

    var Quirks = function (editor) {
      var each = Tools.each;
      var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
      var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
      var mceInternalUrlPrefix = 'data:text/mce-internal,';
      var mceInternalDataType = isIE ? 'Text' : 'URL';
      var setEditorCommandState = function (cmd, state) {
        try {
          editor.getDoc().execCommand(cmd, false, state);
        } catch (ex) {
        }
      };
      var isDefaultPrevented = function (e) {
        return e.isDefaultPrevented();
      };
      var setMceInternalContent = function (e) {
        var selectionHtml, internalContent;
        if (e.dataTransfer) {
          if (editor.selection.isCollapsed() &amp;&amp; e.target.tagName === 'IMG') {
            selection.select(e.target);
          }
          selectionHtml = editor.selection.getContent();
          if (selectionHtml.length &gt; 0) {
            internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
            e.dataTransfer.setData(mceInternalDataType, internalContent);
          }
        }
      };
      var getMceInternalContent = function (e) {
        var internalContent;
        if (e.dataTransfer) {
          internalContent = e.dataTransfer.getData(mceInternalDataType);
          if (internalContent &amp;&amp; internalContent.indexOf(mceInternalUrlPrefix) &gt;= 0) {
            internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
            return {
              id: unescape(internalContent[0]),
              html: unescape(internalContent[1])
            };
          }
        }
        return null;
      };
      var insertClipboardContents = function (content, internal) {
        if (editor.queryCommandSupported('mceInsertClipboardContent')) {
          editor.execCommand('mceInsertClipboardContent', false, {
            content: content,
            internal: internal
          });
        } else {
          editor.execCommand('mceInsertContent', false, content);
        }
      };
      var emptyEditorWhenDeleting = function () {
        var serializeRng = function (rng) {
          var body = dom.create('body');
          var contents = rng.cloneContents();
          body.appendChild(contents);
          return selection.serializer.serialize(body, { format: 'html' });
        };
        var allContentsSelected = function (rng) {
          var selection = serializeRng(rng);
          var allRng = dom.createRng();
          allRng.selectNode(editor.getBody());
          var allSelection = serializeRng(allRng);
          return selection === allSelection;
        };
        editor.on('keydown', function (e) {
          var keyCode = e.keyCode;
          var isCollapsed, body;
          if (!isDefaultPrevented(e) &amp;&amp; (keyCode === DELETE || keyCode === BACKSPACE)) {
            isCollapsed = editor.selection.isCollapsed();
            body = editor.getBody();
            if (isCollapsed &amp;&amp; !dom.isEmpty(body)) {
              return;
            }
            if (!isCollapsed &amp;&amp; !allContentsSelected(editor.selection.getRng())) {
              return;
            }
            e.preventDefault();
            editor.setContent('');
            if (body.firstChild &amp;&amp; dom.isBlock(body.firstChild)) {
              editor.selection.setCursorLocation(body.firstChild, 0);
            } else {
              editor.selection.setCursorLocation(body, 0);
            }
            editor.nodeChanged();
          }
        });
      };
      var selectAll = function () {
        editor.shortcuts.add('meta+a', null, 'SelectAll');
      };
      var inputMethodFocus = function () {
        if (!editor.inline) {
          dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
            var rng;
            if (e.target === editor.getDoc().documentElement) {
              rng = selection.getRng();
              editor.getBody().focus();
              if (e.type === 'mousedown') {
                if (isCaretContainer(rng.startContainer)) {
                  return;
                }
                selection.placeCaretAt(e.clientX, e.clientY);
              } else {
                selection.setRng(rng);
              }
            }
          });
        }
      };
      var removeHrOnBackspace = function () {
        editor.on('keydown', function (e) {
          if (!isDefaultPrevented(e) &amp;&amp; e.keyCode === BACKSPACE) {
            if (!editor.getBody().getElementsByTagName('hr').length) {
              return;
            }
            if (selection.isCollapsed() &amp;&amp; selection.getRng().startOffset === 0) {
              var node = selection.getNode();
              var previousSibling = node.previousSibling;
              if (node.nodeName === 'HR') {
                dom.remove(node);
                e.preventDefault();
                return;
              }
              if (previousSibling &amp;&amp; previousSibling.nodeName &amp;&amp; previousSibling.nodeName.toLowerCase() === 'hr') {
                dom.remove(previousSibling);
                e.preventDefault();
              }
            }
          }
        });
      };
      var focusBody = function () {
        if (!Range.prototype.getClientRects) {
          editor.on('mousedown', function (e) {
            if (!isDefaultPrevented(e) &amp;&amp; e.target.nodeName === 'HTML') {
              var body_1 = editor.getBody();
              body_1.blur();
              Delay.setEditorTimeout(editor, function () {
                body_1.focus();
              });
            }
          });
        }
      };
      var selectControlElements = function () {
        editor.on('click', function (e) {
          var target = e.target;
          if (/^(IMG|HR)$/.test(target.nodeName) &amp;&amp; dom.getContentEditableParent(target) !== 'false') {
            e.preventDefault();
            editor.selection.select(target);
            editor.nodeChanged();
          }
          if (target.nodeName === 'A' &amp;&amp; dom.hasClass(target, 'mce-item-anchor')) {
            e.preventDefault();
            selection.select(target);
          }
        });
      };
      var removeStylesWhenDeletingAcrossBlockElements = function () {
        var getAttributeApplyFunction = function () {
          var template = dom.getAttribs(selection.getStart().cloneNode(false));
          return function () {
            var target = selection.getStart();
            if (target !== editor.getBody()) {
              dom.setAttrib(target, 'style', null);
              each(template, function (attr) {
                target.setAttributeNode(attr.cloneNode(true));
              });
            }
          };
        };
        var isSelectionAcrossElements = function () {
          return !selection.isCollapsed() &amp;&amp; dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
        };
        editor.on('keypress', function (e) {
          var applyAttributes;
          if (!isDefaultPrevented(e) &amp;&amp; (e.keyCode === 8 || e.keyCode === 46) &amp;&amp; isSelectionAcrossElements()) {
            applyAttributes = getAttributeApplyFunction();
            editor.getDoc().execCommand('delete', false, null);
            applyAttributes();
            e.preventDefault();
            return false;
          }
        });
        dom.bind(editor.getDoc(), 'cut', function (e) {
          var applyAttributes;
          if (!isDefaultPrevented(e) &amp;&amp; isSelectionAcrossElements()) {
            applyAttributes = getAttributeApplyFunction();
            Delay.setEditorTimeout(editor, function () {
              applyAttributes();
            });
          }
        });
      };
      var disableBackspaceIntoATable = function () {
        editor.on('keydown', function (e) {
          if (!isDefaultPrevented(e) &amp;&amp; e.keyCode === BACKSPACE) {
            if (selection.isCollapsed() &amp;&amp; selection.getRng().startOffset === 0) {
              var previousSibling = selection.getNode().previousSibling;
              if (previousSibling &amp;&amp; previousSibling.nodeName &amp;&amp; previousSibling.nodeName.toLowerCase() === 'table') {
                e.preventDefault();
                return false;
              }
            }
          }
        });
      };
      var removeBlockQuoteOnBackSpace = function () {
        editor.on('keydown', function (e) {
          var rng, parent;
          if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
            return;
          }
          rng = selection.getRng();
          var container = rng.startContainer;
          var offset = rng.startOffset;
          var root = dom.getRoot();
          parent = container;
          if (!rng.collapsed || offset !== 0) {
            return;
          }
          while (parent &amp;&amp; parent.parentNode &amp;&amp; parent.parentNode.firstChild === parent &amp;&amp; parent.parentNode !== root) {
            parent = parent.parentNode;
          }
          if (parent.tagName === 'BLOCKQUOTE') {
            editor.formatter.toggle('blockquote', null, parent);
            rng = dom.createRng();
            rng.setStart(container, 0);
            rng.setEnd(container, 0);
            selection.setRng(rng);
          }
        });
      };
      var setGeckoEditingOptions = function () {
        var setOpts = function () {
          setEditorCommandState('StyleWithCSS', false);
          setEditorCommandState('enableInlineTableEditing', false);
          if (!getObjectResizing(editor)) {
            setEditorCommandState('enableObjectResizing', false);
          }
        };
        if (!isReadOnly(editor)) {
          editor.on('BeforeExecCommand mousedown', setOpts);
        }
      };
      var addBrAfterLastLinks = function () {
        var fixLinks = function () {
          each(dom.select('a'), function (node) {
            var parentNode = node.parentNode;
            var root = dom.getRoot();
            if (parentNode.lastChild === node) {
              while (parentNode &amp;&amp; !dom.isBlock(parentNode)) {
                if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
                  return;
                }
                parentNode = parentNode.parentNode;
              }
              dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
            }
          });
        };
        editor.on('SetContent ExecCommand', function (e) {
          if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
            fixLinks();
          }
        });
      };
      var setDefaultBlockType = function () {
        if (getForcedRootBlock(editor)) {
          editor.on('init', function () {
            setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
          });
        }
      };
      var normalizeSelection = function () {
        editor.on('keyup focusin mouseup', function (e) {
          if (!VK.modifierPressed(e)) {
            selection.normalize();
          }
        }, true);
      };
      var showBrokenImageIcon = function () {
        editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
      };
      var restoreFocusOnKeyDown = function () {
        if (!editor.inline) {
          editor.on('keydown', function () {
            if (document.activeElement === document.body) {
              editor.getWin().focus();
            }
          });
        }
      };
      var bodyHeight = function () {
        if (!editor.inline) {
          editor.contentStyles.push('body {min-height: 150px}');
          editor.on('click', function (e) {
            var rng;
            if (e.target.nodeName === 'HTML') {
              if (Env.ie &gt; 11) {
                editor.getBody().focus();
                return;
              }
              rng = editor.selection.getRng();
              editor.getBody().focus();
              editor.selection.setRng(rng);
              editor.selection.normalize();
              editor.nodeChanged();
            }
          });
        }
      };
      var blockCmdArrowNavigation = function () {
        if (Env.mac) {
          editor.on('keydown', function (e) {
            if (VK.metaKeyPressed(e) &amp;&amp; !e.shiftKey &amp;&amp; (e.keyCode === 37 || e.keyCode === 39)) {
              e.preventDefault();
              var selection_1 = editor.selection.getSel();
              selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
            }
          });
        }
      };
      var disableAutoUrlDetect = function () {
        setEditorCommandState('AutoUrlDetect', false);
      };
      var tapLinksAndImages = function () {
        editor.on('click', function (e) {
          var elm = e.target;
          do {
            if (elm.tagName === 'A') {
              e.preventDefault();
              return;
            }
          } while (elm = elm.parentNode);
        });
        editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
      };
      var blockFormSubmitInsideEditor = function () {
        editor.on('init', function () {
          editor.dom.bind(editor.getBody(), 'submit', function (e) {
            e.preventDefault();
          });
        });
      };
      var removeAppleInterchangeBrs = function () {
        parser.addNodeFilter('br', function (nodes) {
          var i = nodes.length;
          while (i--) {
            if (nodes[i].attr('class') === 'Apple-interchange-newline') {
              nodes[i].remove();
            }
          }
        });
      };
      var ieInternalDragAndDrop = function () {
        editor.on('dragstart', function (e) {
          setMceInternalContent(e);
        });
        editor.on('drop', function (e) {
          if (!isDefaultPrevented(e)) {
            var internalContent = getMceInternalContent(e);
            if (internalContent &amp;&amp; internalContent.id !== editor.id) {
              e.preventDefault();
              var rng = fromPoint$1(e.x, e.y, editor.getDoc());
              selection.setRng(rng);
              insertClipboardContents(internalContent.html, true);
            }
          }
        });
      };
      var refreshContentEditable = noop;
      var isHidden = function () {
        if (!isGecko || editor.removed) {
          return false;
        }
        var sel = editor.selection.getSel();
        return !sel || !sel.rangeCount || sel.rangeCount === 0;
      };
      var setupRtc = function () {
        if (isWebKit) {
          selectControlElements();
          blockFormSubmitInsideEditor();
          selectAll();
          if (Env.iOS) {
            restoreFocusOnKeyDown();
            bodyHeight();
            tapLinksAndImages();
          }
        }
        if (isGecko) {
          focusBody();
          setGeckoEditingOptions();
          showBrokenImageIcon();
          blockCmdArrowNavigation();
        }
      };
      var setup = function () {
        removeBlockQuoteOnBackSpace();
        emptyEditorWhenDeleting();
        if (!Env.windowsPhone) {
          normalizeSelection();
        }
        if (isWebKit) {
          inputMethodFocus();
          selectControlElements();
          setDefaultBlockType();
          blockFormSubmitInsideEditor();
          disableBackspaceIntoATable();
          removeAppleInterchangeBrs();
          if (Env.iOS) {
            restoreFocusOnKeyDown();
            bodyHeight();
            tapLinksAndImages();
          } else {
            selectAll();
          }
        }
        if (Env.ie &gt;= 11) {
          bodyHeight();
          disableBackspaceIntoATable();
        }
        if (Env.ie) {
          selectAll();
          disableAutoUrlDetect();
          ieInternalDragAndDrop();
        }
        if (isGecko) {
          removeHrOnBackspace();
          focusBody();
          removeStylesWhenDeletingAcrossBlockElements();
          setGeckoEditingOptions();
          addBrAfterLastLinks();
          showBrokenImageIcon();
          blockCmdArrowNavigation();
          disableBackspaceIntoATable();
        }
      };
      if (isRtc(editor)) {
        setupRtc();
      } else {
        setup();
      }
      return {
        refreshContentEditable: refreshContentEditable,
        isHidden: isHidden
      };
    };

    var DOM$4 = DOMUtils.DOM;
    var appendStyle = function (editor, text) {
      var body = SugarElement.fromDom(editor.getBody());
      var container = getStyleContainer(getRootNode(body));
      var style = SugarElement.fromTag('style');
      set(style, 'type', 'text/css');
      append(style, SugarElement.fromText(text));
      append(container, style);
      editor.on('remove', function () {
        remove(style);
      });
    };
    var getRootName = function (editor) {
      return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
    };
    var removeUndefined = function (obj) {
      return filter$1(obj, function (v) {
        return isUndefined(v) === false;
      });
    };
    var mkParserSettings = function (editor) {
      var settings = editor.settings;
      var blobCache = editor.editorUpload.blobCache;
      return removeUndefined({
        allow_conditional_comments: settings.allow_conditional_comments,
        allow_html_data_urls: settings.allow_html_data_urls,
        allow_svg_data_urls: settings.allow_svg_data_urls,
        allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
        allow_script_urls: settings.allow_script_urls,
        allow_unsafe_link_target: settings.allow_unsafe_link_target,
        convert_fonts_to_spans: settings.convert_fonts_to_spans,
        fix_list_elements: settings.fix_list_elements,
        font_size_legacy_values: settings.font_size_legacy_values,
        forced_root_block: settings.forced_root_block,
        forced_root_block_attrs: settings.forced_root_block_attrs,
        padd_empty_with_br: settings.padd_empty_with_br,
        preserve_cdata: settings.preserve_cdata,
        remove_trailing_brs: settings.remove_trailing_brs,
        inline_styles: settings.inline_styles,
        root_name: getRootName(editor),
        validate: true,
        blob_cache: blobCache,
        images_dataimg_filter: settings.images_dataimg_filter
      });
    };
    var mkSerializerSettings = function (editor) {
      var settings = editor.settings;
      return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
        url_converter: settings.url_converter,
        url_converter_scope: settings.url_converter_scope,
        element_format: settings.element_format,
        entities: settings.entities,
        entity_encoding: settings.entity_encoding,
        indent: settings.indent,
        indent_after: settings.indent_after,
        indent_before: settings.indent_before,
        block_elements: settings.block_elements,
        boolean_attributes: settings.boolean_attributes,
        custom_elements: settings.custom_elements,
        extended_valid_elements: settings.extended_valid_elements,
        invalid_elements: settings.invalid_elements,
        invalid_styles: settings.invalid_styles,
        move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
        non_empty_elements: settings.non_empty_elements,
        schema: settings.schema,
        self_closing_elements: settings.self_closing_elements,
        short_ended_elements: settings.short_ended_elements,
        special: settings.special,
        text_block_elements: settings.text_block_elements,
        text_inline_elements: settings.text_inline_elements,
        valid_children: settings.valid_children,
        valid_classes: settings.valid_classes,
        valid_elements: settings.valid_elements,
        valid_styles: settings.valid_styles,
        verify_html: settings.verify_html,
        whitespace_elements: settings.whitespace_elements
      }));
    };
    var createParser = function (editor) {
      var parser = DomParser(mkParserSettings(editor), editor.schema);
      parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
        var i = nodes.length, node, value;
        var dom = editor.dom;
        var internalName = 'data-mce-' + name;
        while (i--) {
          node = nodes[i];
          value = node.attr(name);
          if (value &amp;&amp; !node.attr(internalName)) {
            if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
              continue;
            }
            if (name === 'style') {
              value = dom.serializeStyle(dom.parseStyle(value), node.name);
              if (!value.length) {
                value = null;
              }
              node.attr(internalName, value);
              node.attr(name, value);
            } else if (name === 'tabindex') {
              node.attr(internalName, value);
              node.attr(name, null);
            } else {
              node.attr(internalName, editor.convertURL(value, name, node.name));
            }
          }
        }
      });
      parser.addNodeFilter('script', function (nodes) {
        var i = nodes.length;
        while (i--) {
          var node = nodes[i];
          var type = node.attr('type') || 'no/type';
          if (type.indexOf('mce-') !== 0) {
            node.attr('type', 'mce-' + type);
          }
        }
      });
      if (editor.settings.preserve_cdata) {
        parser.addNodeFilter('#cdata', function (nodes) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            node.type = 8;
            node.name = '#comment';
            node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
          }
        });
      }
      parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
        var i = nodes.length;
        var nonEmptyElements = editor.schema.getNonEmptyElements();
        while (i--) {
          var node = nodes[i];
          if (node.isEmpty(nonEmptyElements) &amp;&amp; node.getAll('br').length === 0) {
            node.append(new AstNode('br', 1)).shortEnded = true;
          }
        }
      });
      return parser;
    };
    var autoFocus = function (editor) {
      if (editor.settings.auto_focus) {
        Delay.setEditorTimeout(editor, function () {
          var focusEditor;
          if (editor.settings.auto_focus === true) {
            focusEditor = editor;
          } else {
            focusEditor = editor.editorManager.get(editor.settings.auto_focus);
          }
          if (!focusEditor.destroyed) {
            focusEditor.focus();
          }
        }, 100);
      }
    };
    var moveSelectionToFirstCaretPosition = function (editor) {
      var root = editor.dom.getRoot();
      if (!editor.inline &amp;&amp; (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
        firstPositionIn(root).each(function (pos) {
          var node = pos.getNode();
          var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos;
          if (Env.browser.isIE()) {
            storeNative(editor, caretPos.toRange());
          } else {
            editor.selection.setRng(caretPos.toRange());
          }
        });
      }
    };
    var initEditor = function (editor) {
      editor.bindPendingEventDelegates();
      editor.initialized = true;
      fireInit(editor);
      editor.focus(true);
      moveSelectionToFirstCaretPosition(editor);
      editor.nodeChanged({ initial: true });
      editor.execCallback('init_instance_callback', editor);
      autoFocus(editor);
    };
    var getStyleSheetLoader = function (editor) {
      return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
    };
    var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
      var promises = [new promiseObj(function (resolve, reject) {
          return getStyleSheetLoader(editor).loadAll(css, resolve, reject);
        })];
      if (editor.inline) {
        return promises;
      } else {
        return promises.concat([new promiseObj(function (resolve, reject) {
            return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
          })]);
      }
    };
    var loadContentCss = function (editor, css) {
      var styleSheetLoader = getStyleSheetLoader(editor);
      var fontCss = getFontCss(editor);
      var removeCss = function () {
        styleSheetLoader.unloadAll(css);
        if (!editor.inline) {
          editor.ui.styleSheetLoader.unloadAll(fontCss);
        }
      };
      var loaded = function () {
        if (editor.removed) {
          removeCss();
        } else {
          editor.on('remove', removeCss);
          initEditor(editor);
        }
      };
      promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
    };
    var preInit = function (editor) {
      var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
      if (!settings.browser_spellcheck &amp;&amp; !settings.gecko_spellcheck) {
        doc.body.spellcheck = false;
        DOM$4.setAttrib(body, 'spellcheck', 'false');
      }
      editor.quirks = Quirks(editor);
      firePostRender(editor);
      var directionality = getDirectionality(editor);
      if (directionality !== undefined) {
        body.dir = directionality;
      }
      if (settings.protect) {
        editor.on('BeforeSetContent', function (e) {
          Tools.each(settings.protect, function (pattern) {
            e.content = e.content.replace(pattern, function (str) {
              return '&lt;!--mce:protected ' + escape(str) + '--&gt;';
            });
          });
        });
      }
      editor.on('SetContent', function () {
        editor.addVisual(editor.getBody());
      });
      if (!isRtc(editor)) {
        editor.load({
          initial: true,
          format: 'html'
        });
      }
      editor.startContent = editor.getContent({ format: 'raw' });
      editor.on('compositionstart compositionend', function (e) {
        editor.composing = e.type === 'compositionstart';
      });
      if (editor.contentStyles.length &gt; 0) {
        var contentCssText_1 = '';
        Tools.each(editor.contentStyles, function (style) {
          contentCssText_1 += style + '\r\n';
        });
        editor.dom.addStyle(contentCssText_1);
      }
      loadContentCss(editor, editor.contentCSS);
      if (settings.content_style) {
        appendStyle(editor, settings.content_style);
      }
    };
    var initContentBody = function (editor, skipWrite) {
      var settings = editor.settings;
      var targetElm = editor.getElement();
      var doc = editor.getDoc();
      if (!settings.inline) {
        editor.getElement().style.visibility = editor.orgVisibility;
      }
      if (!skipWrite &amp;&amp; !editor.inline) {
        doc.open();
        doc.write(editor.iframeHTML);
        doc.close();
      }
      if (editor.inline) {
        DOM$4.addClass(targetElm, 'mce-content-body');
        editor.contentDocument = doc = document;
        editor.contentWindow = window;
        editor.bodyElement = targetElm;
        editor.contentAreaContainer = targetElm;
      }
      var body = editor.getBody();
      body.disabled = true;
      editor.readonly = !!settings.readonly;
      if (!editor.readonly) {
        if (editor.inline &amp;&amp; DOM$4.getStyle(body, 'position', true) === 'static') {
          body.style.position = 'relative';
        }
        body.contentEditable = editor.getParam('content_editable_state', true);
      }
      body.disabled = false;
      editor.editorUpload = EditorUpload(editor);
      editor.schema = Schema(settings);
      editor.dom = DOMUtils(doc, {
        keep_values: true,
        url_converter: editor.convertURL,
        url_converter_scope: editor,
        hex_colors: settings.force_hex_style_colors,
        update_styles: true,
        root_element: editor.inline ? editor.getBody() : null,
        collect: function () {
          return editor.inline;
        },
        schema: editor.schema,
        contentCssCors: shouldUseContentCssCors(editor),
        referrerPolicy: getReferrerPolicy(editor),
        onSetAttrib: function (e) {
          editor.fire('SetAttrib', e);
        }
      });
      editor.parser = createParser(editor);
      editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
      editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
      editor.annotator = Annotator(editor);
      editor.formatter = Formatter(editor);
      editor.undoManager = UndoManager(editor);
      editor._nodeChangeDispatcher = new NodeChange(editor);
      editor._selectionOverrides = SelectionOverrides(editor);
      setup$9(editor);
      setup$k(editor);
      if (!isRtc(editor)) {
        setup$l(editor);
      }
      var caret = setup$j(editor);
      setup$8(editor, caret);
      setup$a(editor);
      setup$7(editor);
      firePreInit(editor);
      setup$5(editor).fold(function () {
        preInit(editor);
      }, function (loadingRtc) {
        editor.setProgressState(true);
        loadingRtc.then(function (_rtcMode) {
          editor.setProgressState(false);
          preInit(editor);
        }, function (err) {
          editor.notificationManager.open({
            type: 'error',
            text: String(err)
          });
          preInit(editor);
        });
      });
    };

    var DOM$5 = DOMUtils.DOM;
    var relaxDomain = function (editor, ifr) {
      if (document.domain !== window.location.hostname &amp;&amp; Env.browser.isIE()) {
        var bodyUuid = uuid('mce');
        editor[bodyUuid] = function () {
          initContentBody(editor);
        };
        var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()';
        DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
        return true;
      }
      return false;
    };
    var createIframeElement = function (id, title, height, customAttrs) {
      var iframe = SugarElement.fromTag('iframe');
      setAll(iframe, customAttrs);
      setAll(iframe, {
        id: id + '_ifr',
        frameBorder: '0',
        allowTransparency: 'true',
        title: title
      });
      add$3(iframe, 'tox-edit-area__iframe');
      return iframe;
    };
    var getIframeHtml = function (editor) {
      var iframeHTML = getDocType(editor) + '&lt;html&gt;&lt;head&gt;';
      if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
        iframeHTML += '&lt;base href="' + editor.documentBaseURI.getURI() + '" /&gt;';
      }
      iframeHTML += '&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;';
      var bodyId = getBodyId(editor);
      var bodyClass = getBodyClass(editor);
      if (getContentSecurityPolicy(editor)) {
        iframeHTML += '&lt;meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" /&gt;';
      }
      iframeHTML += '&lt;/head&gt;&lt;body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '"&gt;&lt;br&gt;&lt;/body&gt;&lt;/html&gt;';
      return iframeHTML;
    };
    var createIframe = function (editor, o) {
      var title = editor.editorManager.translate('Rich Text Area. Press ALT-0 for help.');
      var ifr = createIframeElement(editor.id, title, o.height, getIframeAttrs(editor)).dom;
      ifr.onload = function () {
        ifr.onload = null;
        editor.fire('load');
      };
      var isDomainRelaxed = relaxDomain(editor, ifr);
      editor.contentAreaContainer = o.iframeContainer;
      editor.iframeElement = ifr;
      editor.iframeHTML = getIframeHtml(editor);
      DOM$5.add(o.iframeContainer, ifr);
      return isDomainRelaxed;
    };
    var init$1 = function (editor, boxInfo) {
      var isDomainRelaxed = createIframe(editor, boxInfo);
      if (boxInfo.editorContainer) {
        DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
        editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
      }
      editor.getElement().style.display = 'none';
      DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
      if (!isDomainRelaxed) {
        initContentBody(editor);
      }
    };

    var DOM$6 = DOMUtils.DOM;
    var initPlugin = function (editor, initializedPlugins, plugin) {
      var Plugin = PluginManager.get(plugin);
      var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
      plugin = Tools.trim(plugin);
      if (Plugin &amp;&amp; Tools.inArray(initializedPlugins, plugin) === -1) {
        Tools.each(PluginManager.dependencies(plugin), function (dep) {
          initPlugin(editor, initializedPlugins, dep);
        });
        if (editor.plugins[plugin]) {
          return;
        }
        try {
          var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
          editor.plugins[plugin] = pluginInstance;
          if (pluginInstance.init) {
            pluginInstance.init(editor, pluginUrl);
            initializedPlugins.push(plugin);
          }
        } catch (e) {
          pluginInitError(editor, plugin, e);
        }
      }
    };
    var trimLegacyPrefix = function (name) {
      return name.replace(/^\-/, '');
    };
    var initPlugins = function (editor) {
      var initializedPlugins = [];
      Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
        initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
      });
    };
    var initIcons = function (editor) {
      var iconPackName = Tools.trim(getIconPackName(editor));
      var currentIcons = editor.ui.registry.getAll().icons;
      var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
      each$1(loadIcons, function (svgData, icon) {
        if (!has(currentIcons, icon)) {
          editor.ui.registry.addIcon(icon, svgData);
        }
      });
    };
    var initTheme = function (editor) {
      var theme = getTheme(editor);
      if (isString(theme)) {
        editor.settings.theme = trimLegacyPrefix(theme);
        var Theme = ThemeManager.get(theme);
        editor.theme = new Theme(editor, ThemeManager.urls[theme]);
        if (editor.theme.init) {
          editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
        }
      } else {
        editor.theme = {};
      }
    };
    var renderFromLoadedTheme = function (editor) {
      return editor.theme.renderUI();
    };
    var renderFromThemeFunc = function (editor) {
      var elm = editor.getElement();
      var theme = getTheme(editor);
      var info = theme(editor, elm);
      if (info.editorContainer.nodeType) {
        info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
      }
      if (info.iframeContainer &amp;&amp; info.iframeContainer.nodeType) {
        info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
      }
      info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
      return info;
    };
    var createThemeFalseResult = function (element) {
      return {
        editorContainer: element,
        iframeContainer: element,
        api: {}
      };
    };
    var renderThemeFalseIframe = function (targetElement) {
      var iframeContainer = DOM$6.create('div');
      DOM$6.insertAfter(iframeContainer, targetElement);
      return createThemeFalseResult(iframeContainer);
    };
    var renderThemeFalse = function (editor) {
      var targetElement = editor.getElement();
      return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
    };
    var renderThemeUi = function (editor) {
      var elm = editor.getElement();
      editor.orgDisplay = elm.style.display;
      if (isString(getTheme(editor))) {
        return renderFromLoadedTheme(editor);
      } else if (isFunction(getTheme(editor))) {
        return renderFromThemeFunc(editor);
      } else {
        return renderThemeFalse(editor);
      }
    };
    var augmentEditorUiApi = function (editor, api) {
      var uiApiFacade = {
        show: Optional.from(api.show).getOr(noop),
        hide: Optional.from(api.hide).getOr(noop),
        disable: Optional.from(api.disable).getOr(noop),
        isDisabled: Optional.from(api.isDisabled).getOr(never),
        enable: function () {
          if (!editor.mode.isReadOnly()) {
            Optional.from(api.enable).map(call);
          }
        }
      };
      editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
    };
    var init$2 = function (editor) {
      editor.fire('ScriptsLoaded');
      initIcons(editor);
      initTheme(editor);
      initPlugins(editor);
      var renderInfo = renderThemeUi(editor);
      augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
      var boxInfo = {
        editorContainer: renderInfo.editorContainer,
        iframeContainer: renderInfo.iframeContainer
      };
      editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
      appendContentCssFromSettings(editor);
      if (editor.inline) {
        return initContentBody(editor);
      } else {
        return init$1(editor, boxInfo);
      }
    };

    var DOM$7 = DOMUtils.DOM;
    var hasSkipLoadPrefix = function (name) {
      return name.charAt(0) === '-';
    };
    var loadLanguage = function (scriptLoader, editor) {
      var languageCode = getLanguageCode(editor);
      var languageUrl = getLanguageUrl(editor);
      if (I18n.hasCode(languageCode) === false &amp;&amp; languageCode !== 'en') {
        var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
        scriptLoader.add(url_1, noop, undefined, function () {
          languageLoadError(editor, url_1, languageCode);
        });
      }
    };
    var loadTheme = function (scriptLoader, editor, suffix, callback) {
      var theme = getTheme(editor);
      if (isString(theme)) {
        if (!hasSkipLoadPrefix(theme) &amp;&amp; !ThemeManager.urls.hasOwnProperty(theme)) {
          var themeUrl = getThemeUrl(editor);
          if (themeUrl) {
            ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
          } else {
            ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
          }
        }
        scriptLoader.loadQueue(function () {
          ThemeManager.waitFor(theme, callback);
        });
      } else {
        callback();
      }
    };
    var getIconsUrlMetaFromUrl = function (editor) {
      return Optional.from(getIconsUrl(editor)).filter(function (url) {
        return url.length &gt; 0;
      }).map(function (url) {
        return {
          url: url,
          name: Optional.none()
        };
      });
    };
    var getIconsUrlMetaFromName = function (editor, name, suffix) {
      return Optional.from(name).filter(function (name) {
        return name.length &gt; 0 &amp;&amp; !IconManager.has(name);
      }).map(function (name) {
        return {
          url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
          name: Optional.some(name)
        };
      });
    };
    var loadIcons = function (scriptLoader, editor, suffix) {
      var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
      var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
        return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
      });
      each(cat([
        defaultIconsUrl,
        customIconsUrl
      ]), function (urlMeta) {
        scriptLoader.add(urlMeta.url, noop, undefined, function () {
          iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
        });
      });
    };
    var loadPlugins = function (editor, suffix) {
      Tools.each(getExternalPlugins(editor), function (url, name) {
        PluginManager.load(name, url, noop, undefined, function () {
          pluginLoadError(editor, url, name);
        });
        editor.settings.plugins += ' ' + name;
      });
      Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
        plugin = Tools.trim(plugin);
        if (plugin &amp;&amp; !PluginManager.urls[plugin]) {
          if (hasSkipLoadPrefix(plugin)) {
            plugin = plugin.substr(1, plugin.length);
            var dependencies = PluginManager.dependencies(plugin);
            Tools.each(dependencies, function (depPlugin) {
              var defaultSettings = {
                prefix: 'plugins/',
                resource: depPlugin,
                suffix: '/plugin' + suffix + '.js'
              };
              var dep = PluginManager.createUrl(defaultSettings, depPlugin);
              PluginManager.load(dep.resource, dep, noop, undefined, function () {
                pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
              });
            });
          } else {
            var url_2 = {
              prefix: 'plugins/',
              resource: plugin,
              suffix: '/plugin' + suffix + '.js'
            };
            PluginManager.load(plugin, url_2, noop, undefined, function () {
              pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
            });
          }
        }
      });
    };
    var loadScripts = function (editor, suffix) {
      var scriptLoader = ScriptLoader.ScriptLoader;
      loadTheme(scriptLoader, editor, suffix, function () {
        loadLanguage(scriptLoader, editor);
        loadIcons(scriptLoader, editor, suffix);
        loadPlugins(editor, suffix);
        scriptLoader.loadQueue(function () {
          if (!editor.removed) {
            init$2(editor);
          }
        }, editor, function () {
          if (!editor.removed) {
            init$2(editor);
          }
        });
      });
    };
    var getStyleSheetLoader$1 = function (element, editor) {
      return instance.forElement(element, {
        contentCssCors: hasContentCssCors(editor),
        referrerPolicy: getReferrerPolicy(editor)
      });
    };
    var render = function (editor) {
      var id = editor.id;
      I18n.setCode(getLanguageCode(editor));
      var readyHandler = function () {
        DOM$7.unbind(window, 'ready', readyHandler);
        editor.render();
      };
      if (!EventUtils.Event.domLoaded) {
        DOM$7.bind(window, 'ready', readyHandler);
        return;
      }
      if (!editor.getElement()) {
        return;
      }
      if (!Env.contentEditable) {
        return;
      }
      var element = SugarElement.fromDom(editor.getElement());
      var snapshot = clone(element);
      editor.on('remove', function () {
        eachr(element.dom.attributes, function (attr) {
          return remove$1(element, attr.name);
        });
        setAll(element, snapshot);
      });
      editor.ui.styleSheetLoader = getStyleSheetLoader$1(element, editor);
      if (!isInline$1(editor)) {
        editor.orgVisibility = editor.getElement().style.visibility;
        editor.getElement().style.visibility = 'hidden';
      } else {
        editor.inline = true;
      }
      var form = editor.getElement().form || DOM$7.getParent(id, 'form');
      if (form) {
        editor.formElement = form;
        if (hasHiddenInput(editor) &amp;&amp; !isTextareaOrInput(editor.getElement())) {
          DOM$7.insertAfter(DOM$7.create('input', {
            type: 'hidden',
            name: id
          }), id);
          editor.hasHiddenInput = true;
        }
        editor.formEventDelegate = function (e) {
          editor.fire(e.type, e);
        };
        DOM$7.bind(form, 'submit reset', editor.formEventDelegate);
        editor.on('reset', function () {
          editor.resetContent();
        });
        if (shouldPatchSubmit(editor) &amp;&amp; !form.submit.nodeType &amp;&amp; !form.submit.length &amp;&amp; !form._mceOldSubmit) {
          form._mceOldSubmit = form.submit;
          form.submit = function () {
            editor.editorManager.triggerSave();
            editor.setDirty(false);
            return form._mceOldSubmit(form);
          };
        }
      }
      editor.windowManager = WindowManager(editor);
      editor.notificationManager = NotificationManager(editor);
      if (isEncodingXml(editor)) {
        editor.on('GetContent', function (e) {
          if (e.save) {
            e.content = DOM$7.encode(e.content);
          }
        });
      }
      if (shouldAddFormSubmitTrigger(editor)) {
        editor.on('submit', function () {
          if (editor.initialized) {
            editor.save();
          }
        });
      }
      if (shouldAddUnloadTrigger(editor)) {
        editor._beforeUnload = function () {
          if (editor.initialized &amp;&amp; !editor.destroyed &amp;&amp; !editor.isHidden()) {
            editor.save({
              format: 'raw',
              no_events: true,
              set_dirty: false
            });
          }
        };
        editor.editorManager.on('BeforeUnload', editor._beforeUnload);
      }
      editor.editorManager.add(editor);
      loadScripts(editor, editor.suffix);
    };

    var addVisual$1 = function (editor, elm) {
      return addVisual(editor, elm);
    };

    var legacyPropNames = {
      'font-size': 'size',
      'font-family': 'face'
    };
    var getSpecifiedFontProp = function (propName, rootElm, elm) {
      var getProperty = function (elm) {
        return getRaw(elm, propName).orThunk(function () {
          if (name(elm) === 'font') {
            return get$1(legacyPropNames, propName).bind(function (legacyPropName) {
              return getOpt(elm, legacyPropName);
            });
          } else {
            return Optional.none();
          }
        });
      };
      var isRoot = function (elm) {
        return eq$2(SugarElement.fromDom(rootElm), elm);
      };
      return closest$2(SugarElement.fromDom(elm), function (elm) {
        return getProperty(elm);
      }, isRoot);
    };
    var normalizeFontFamily = function (fontFamily) {
      return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
    };
    var getComputedFontProp = function (propName, elm) {
      return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
    };
    var getFontProp = function (propName) {
      return function (rootElm, elm) {
        return Optional.from(elm).map(SugarElement.fromDom).filter(isElement).bind(function (element) {
          return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
        }).getOr('');
      };
    };
    var getFontSize = getFontProp('font-size');
    var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));

    var findFirstCaretElement = function (editor) {
      return firstPositionIn(editor.getBody()).map(function (caret) {
        var container = caret.container();
        return isText$1(container) ? container.parentNode : container;
      });
    };
    var getCaretElement = function (editor) {
      return Optional.from(editor.selection.getRng()).bind(function (rng) {
        var root = editor.getBody();
        var atStartOfNode = rng.startContainer === root &amp;&amp; rng.startOffset === 0;
        return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
      });
    };
    var mapRange = function (editor, mapper) {
      return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement).map(mapper);
    };

    var fromFontSizeNumber = function (editor, value) {
      if (/^[0-9.]+$/.test(value)) {
        var fontSizeNumber = parseInt(value, 10);
        if (fontSizeNumber &gt;= 1 &amp;&amp; fontSizeNumber &lt;= 7) {
          var fontSizes = getFontStyleValues(editor);
          var fontClasses = getFontSizeClasses(editor);
          if (fontClasses) {
            return fontClasses[fontSizeNumber - 1] || value;
          } else {
            return fontSizes[fontSizeNumber - 1] || value;
          }
        } else {
          return value;
        }
      } else {
        return value;
      }
    };
    var normalizeFontNames = function (font) {
      var fonts = font.split(/\s*,\s*/);
      return map(fonts, function (font) {
        if (font.indexOf(' ') !== -1 &amp;&amp; !(startsWith(font, '"') || startsWith(font, '\''))) {
          return '\'' + font + '\'';
        } else {
          return font;
        }
      }).join(',');
    };
    var fontNameAction = function (editor, value) {
      var font = fromFontSizeNumber(editor, value);
      editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
      editor.nodeChanged();
    };
    var fontNameQuery = function (editor) {
      return mapRange(editor, function (elm) {
        return getFontFamily(editor.getBody(), elm.dom);
      }).getOr('');
    };
    var fontSizeAction = function (editor, value) {
      editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
      editor.nodeChanged();
    };
    var fontSizeQuery = function (editor) {
      return mapRange(editor, function (elm) {
        return getFontSize(editor.getBody(), elm.dom);
      }).getOr('');
    };

    var lineHeightQuery = function (editor) {
      return mapRange(editor, function (elm) {
        var root = SugarElement.fromDom(editor.getBody());
        var specifiedStyle = closest$2(elm, function (elm) {
          return getRaw(elm, 'line-height');
        }, curry(eq$2, root));
        var computedStyle = function () {
          var lineHeight = parseFloat(get$5(elm, 'line-height'));
          var fontSize = parseFloat(get$5(elm, 'font-size'));
          return String(lineHeight / fontSize);
        };
        return specifiedStyle.getOrThunk(computedStyle);
      }).getOr('');
    };
    var lineHeightAction = function (editor, lineHeight) {
      editor.formatter.toggle('lineheight', { value: String(lineHeight) });
      editor.nodeChanged();
    };

    var processValue = function (value) {
      var details;
      if (typeof value !== 'string') {
        details = Tools.extend({
          paste: value.paste,
          data: { paste: value.paste }
        }, value);
        return {
          content: value.content,
          details: details
        };
      }
      return {
        content: value,
        details: {}
      };
    };
    var insertAtCaret$1 = function (editor, value) {
      var result = processValue(value);
      insertContent(editor, result.content, result.details);
    };

    var each$f = Tools.each;
    var map$3 = Tools.map, inArray$2 = Tools.inArray;
    var EditorCommands = function () {
      function EditorCommands(editor) {
        this.commands = {
          state: {},
          exec: {},
          value: {}
        };
        this.editor = editor;
        this.setupCommands(editor);
      }
      EditorCommands.prototype.execCommand = function (command, ui, value, args) {
        var func, state = false;
        var self = this;
        if (self.editor.removed) {
          return;
        }
        if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) &amp;&amp; (!args || !args.skip_focus)) {
          self.editor.focus();
        } else {
          restore(self.editor);
        }
        args = self.editor.fire('BeforeExecCommand', {
          command: command,
          ui: ui,
          value: value
        });
        if (args.isDefaultPrevented()) {
          return false;
        }
        var customCommand = command.toLowerCase();
        if (func = self.commands.exec[customCommand]) {
          func(customCommand, ui, value);
          self.editor.fire('ExecCommand', {
            command: command,
            ui: ui,
            value: value
          });
          return true;
        }
        each$f(this.editor.plugins, function (p) {
          if (p.execCommand &amp;&amp; p.execCommand(command, ui, value)) {
            self.editor.fire('ExecCommand', {
              command: command,
              ui: ui,
              value: value
            });
            state = true;
            return false;
          }
        });
        if (state) {
          return state;
        }
        if (self.editor.theme &amp;&amp; self.editor.theme.execCommand &amp;&amp; self.editor.theme.execCommand(command, ui, value)) {
          self.editor.fire('ExecCommand', {
            command: command,
            ui: ui,
            value: value
          });
          return true;
        }
        try {
          state = self.editor.getDoc().execCommand(command, ui, value);
        } catch (ex) {
        }
        if (state) {
          self.editor.fire('ExecCommand', {
            command: command,
            ui: ui,
            value: value
          });
          return true;
        }
        return false;
      };
      EditorCommands.prototype.queryCommandState = function (command) {
        var func;
        if (this.editor.quirks.isHidden() || this.editor.removed) {
          return;
        }
        command = command.toLowerCase();
        if (func = this.commands.state[command]) {
          return func(command);
        }
        try {
          return this.editor.getDoc().queryCommandState(command);
        } catch (ex) {
        }
        return false;
      };
      EditorCommands.prototype.queryCommandValue = function (command) {
        var func;
        if (this.editor.quirks.isHidden() || this.editor.removed) {
          return;
        }
        command = command.toLowerCase();
        if (func = this.commands.value[command]) {
          return func(command);
        }
        try {
          return this.editor.getDoc().queryCommandValue(command);
        } catch (ex) {
        }
      };
      EditorCommands.prototype.addCommands = function (commandList, type) {
        if (type === void 0) {
          type = 'exec';
        }
        var self = this;
        each$f(commandList, function (callback, command) {
          each$f(command.toLowerCase().split(','), function (command) {
            self.commands[type][command] = callback;
          });
        });
      };
      EditorCommands.prototype.addCommand = function (command, callback, scope) {
        var _this = this;
        command = command.toLowerCase();
        this.commands.exec[command] = function (command, ui, value, args) {
          return callback.call(scope || _this.editor, ui, value, args);
        };
      };
      EditorCommands.prototype.queryCommandSupported = function (command) {
        command = command.toLowerCase();
        if (this.commands.exec[command]) {
          return true;
        }
        try {
          return this.editor.getDoc().queryCommandSupported(command);
        } catch (ex) {
        }
        return false;
      };
      EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
        var _this = this;
        command = command.toLowerCase();
        this.commands.state[command] = function () {
          return callback.call(scope || _this.editor);
        };
      };
      EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
        var _this = this;
        command = command.toLowerCase();
        this.commands.value[command] = function () {
          return callback.call(scope || _this.editor);
        };
      };
      EditorCommands.prototype.hasCustomCommand = function (command) {
        command = command.toLowerCase();
        return !!this.commands.exec[command];
      };
      EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
        if (ui === undefined) {
          ui = false;
        }
        if (value === undefined) {
          value = null;
        }
        return this.editor.getDoc().execCommand(command, ui, value);
      };
      EditorCommands.prototype.isFormatMatch = function (name) {
        return this.editor.formatter.match(name);
      };
      EditorCommands.prototype.toggleFormat = function (name, value) {
        this.editor.formatter.toggle(name, value ? { value: value } : undefined);
        this.editor.nodeChanged();
      };
      EditorCommands.prototype.storeSelection = function (type) {
        this.selectionBookmark = this.editor.selection.getBookmark(type);
      };
      EditorCommands.prototype.restoreSelection = function () {
        this.editor.selection.moveToBookmark(this.selectionBookmark);
      };
      EditorCommands.prototype.setupCommands = function (editor) {
        var self = this;
        this.addCommands({
          'mceResetDesignMode,mceBeginUndoLevel': noop,
          'mceEndUndoLevel,mceAddUndoLevel': function () {
            editor.undoManager.add();
          },
          'Cut,Copy,Paste': function (command) {
            var doc = editor.getDoc();
            var failed;
            try {
              self.execNativeCommand(command);
            } catch (ex) {
              failed = true;
            }
            if (command === 'paste' &amp;&amp; !doc.queryCommandEnabled(command)) {
              failed = true;
            }
            if (failed || !doc.queryCommandSupported(command)) {
              var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
              if (Env.mac) {
                msg = msg.replace(/Ctrl\+/g, '\u2318+');
              }
              editor.notificationManager.open({
                text: msg,
                type: 'error'
              });
            }
          },
          'unlink': function () {
            if (editor.selection.isCollapsed()) {
              var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
              if (elm) {
                editor.dom.remove(elm, true);
              }
              return;
            }
            editor.formatter.remove('link');
          },
          'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
            var align = command.substring(7);
            if (align === 'full') {
              align = 'justify';
            }
            each$f('left,center,right,justify'.split(','), function (name) {
              if (align !== name) {
                editor.formatter.remove('align' + name);
              }
            });
            if (align !== 'none') {
              self.toggleFormat('align' + align);
            }
          },
          'InsertUnorderedList,InsertOrderedList': function (command) {
            var listParent;
            self.execNativeCommand(command);
            var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
            if (listElm) {
              listParent = listElm.parentNode;
              if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
                self.storeSelection();
                editor.dom.split(listParent, listElm);
                self.restoreSelection();
              }
            }
          },
          'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
            self.toggleFormat(command);
          },
          'ForeColor,HiliteColor': function (command, ui, value) {
            self.toggleFormat(command, value);
          },
          'FontName': function (command, ui, value) {
            fontNameAction(editor, value);
          },
          'FontSize': function (command, ui, value) {
            fontSizeAction(editor, value);
          },
          'LineHeight': function (command, ui, value) {
            lineHeightAction(editor, value);
          },
          'RemoveFormat': function (command) {
            editor.formatter.remove(command);
          },
          'mceBlockQuote': function () {
            self.toggleFormat('blockquote');
          },
          'FormatBlock': function (command, ui, value) {
            return self.toggleFormat(value || 'p');
          },
          'mceCleanup': function () {
            var bookmark = editor.selection.getBookmark();
            editor.setContent(editor.getContent());
            editor.selection.moveToBookmark(bookmark);
          },
          'mceRemoveNode': function (command, ui, value) {
            var node = value || editor.selection.getNode();
            if (node !== editor.getBody()) {
              self.storeSelection();
              editor.dom.remove(node, true);
              self.restoreSelection();
            }
          },
          'mceSelectNodeDepth': function (command, ui, value) {
            var counter = 0;
            editor.dom.getParent(editor.selection.getNode(), function (node) {
              if (node.nodeType === 1 &amp;&amp; counter++ === value) {
                editor.selection.select(node);
                return false;
              }
            }, editor.getBody());
          },
          'mceSelectNode': function (command, ui, value) {
            editor.selection.select(value);
          },
          'mceInsertContent': function (command, ui, value) {
            insertAtCaret$1(editor, value);
          },
          'mceInsertRawHTML': function (command, ui, value) {
            editor.selection.setContent('tiny_mce_marker');
            var content = editor.getContent();
            editor.setContent(content.replace(/tiny_mce_marker/g, function () {
              return value;
            }));
          },
          'mceInsertNewLine': function (command, ui, value) {
            insert$3(editor, value);
          },
          'mceToggleFormat': function (command, ui, value) {
            self.toggleFormat(value);
          },
          'mceSetContent': function (command, ui, value) {
            editor.setContent(value);
          },
          'Indent,Outdent': function (command) {
            handle(editor, command);
          },
          'mceRepaint': noop,
          'InsertHorizontalRule': function () {
            editor.execCommand('mceInsertContent', false, '&lt;hr /&gt;');
          },
          'mceToggleVisualAid': function () {
            editor.hasVisual = !editor.hasVisual;
            editor.addVisual();
          },
          'mceReplaceContent': function (command, ui, value) {
            editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
          },
          'mceInsertLink': function (command, ui, value) {
            if (typeof value === 'string') {
              value = { href: value };
            }
            var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
            value.href = value.href.replace(/ /g, '%20');
            if (!anchor || !value.href) {
              editor.formatter.remove('link');
            }
            if (value.href) {
              editor.formatter.apply('link', value, anchor);
            }
          },
          'selectAll': function () {
            var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue);
            if (editingHost) {
              var rng = editor.dom.createRng();
              rng.selectNodeContents(editingHost);
              editor.selection.setRng(rng);
            }
          },
          'mceNewDocument': function () {
            editor.setContent('');
          },
          'InsertLineBreak': function (command, ui, value) {
            insert$2(editor, value);
            return true;
          }
        });
        var alignStates = function (name) {
          return function () {
            var selection = editor.selection;
            var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
            var matches = map$3(nodes, function (node) {
              return !!editor.formatter.matchNode(node, name);
            });
            return inArray$2(matches, true) !== -1;
          };
        };
        self.addCommands({
          'JustifyLeft': alignStates('alignleft'),
          'JustifyCenter': alignStates('aligncenter'),
          'JustifyRight': alignStates('alignright'),
          'JustifyFull': alignStates('alignjustify'),
          'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
            return self.isFormatMatch(command);
          },
          'mceBlockQuote': function () {
            return self.isFormatMatch('blockquote');
          },
          'Outdent': function () {
            return canOutdent(editor);
          },
          'InsertUnorderedList,InsertOrderedList': function (command) {
            var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
            return list &amp;&amp; (command === 'insertunorderedlist' &amp;&amp; list.tagName === 'UL' || command === 'insertorderedlist' &amp;&amp; list.tagName === 'OL');
          }
        }, 'state');
        self.addCommands({
          Undo: function () {
            editor.undoManager.undo();
          },
          Redo: function () {
            editor.undoManager.redo();
          }
        });
        self.addQueryValueHandler('FontName', function () {
          return fontNameQuery(editor);
        }, this);
        self.addQueryValueHandler('FontSize', function () {
          return fontSizeQuery(editor);
        }, this);
        self.addQueryValueHandler('LineHeight', function () {
          return lineHeightQuery(editor);
        }, this);
      };
      return EditorCommands;
    }();

    var internalContentEditableAttr = 'data-mce-contenteditable';
    var toggleClass = function (elm, cls, state) {
      if (has$2(elm, cls) &amp;&amp; state === false) {
        remove$4(elm, cls);
      } else if (state) {
        add$3(elm, cls);
      }
    };
    var setEditorCommandState = function (editor, cmd, state) {
      try {
        editor.getDoc().execCommand(cmd, false, String(state));
      } catch (ex) {
      }
    };
    var setContentEditable = function (elm, state) {
      elm.dom.contentEditable = state ? 'true' : 'false';
    };
    var switchOffContentEditableTrue = function (elm) {
      each(descendants$1(elm, '*[contenteditable="true"]'), function (elm) {
        set(elm, internalContentEditableAttr, 'true');
        setContentEditable(elm, false);
      });
    };
    var switchOnContentEditableTrue = function (elm) {
      each(descendants$1(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
        remove$1(elm, internalContentEditableAttr);
        setContentEditable(elm, true);
      });
    };
    var removeFakeSelection = function (editor) {
      Optional.from(editor.selection.getNode()).each(function (elm) {
        elm.removeAttribute('data-mce-selected');
      });
    };
    var restoreFakeSelection = function (editor) {
      editor.selection.setRng(editor.selection.getRng());
    };
    var toggleReadOnly = function (editor, state) {
      var body = SugarElement.fromDom(editor.getBody());
      toggleClass(body, 'mce-content-readonly', state);
      if (state) {
        editor.selection.controlSelection.hideResizeRect();
        editor._selectionOverrides.hideFakeCaret();
        removeFakeSelection(editor);
        editor.readonly = true;
        setContentEditable(body, false);
        switchOffContentEditableTrue(body);
      } else {
        editor.readonly = false;
        setContentEditable(body, true);
        switchOnContentEditableTrue(body);
        setEditorCommandState(editor, 'StyleWithCSS', false);
        setEditorCommandState(editor, 'enableInlineTableEditing', false);
        setEditorCommandState(editor, 'enableObjectResizing', false);
        if (hasEditorOrUiFocus(editor)) {
          editor.focus();
        }
        restoreFakeSelection(editor);
        editor.nodeChanged();
      }
    };
    var isReadOnly$1 = function (editor) {
      return editor.readonly;
    };
    var registerFilters = function (editor) {
      editor.parser.addAttributeFilter('contenteditable', function (nodes) {
        if (isReadOnly$1(editor)) {
          each(nodes, function (node) {
            node.attr(internalContentEditableAttr, node.attr('contenteditable'));
            node.attr('contenteditable', 'false');
          });
        }
      });
      editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
        if (isReadOnly$1(editor)) {
          each(nodes, function (node) {
            node.attr('contenteditable', node.attr(internalContentEditableAttr));
          });
        }
      });
      editor.serializer.addTempAttr(internalContentEditableAttr);
    };
    var registerReadOnlyContentFilters = function (editor) {
      if (editor.serializer) {
        registerFilters(editor);
      } else {
        editor.on('PreInit', function () {
          registerFilters(editor);
        });
      }
    };
    var isClickEvent = function (e) {
      return e.type === 'click';
    };
    var getAnchorHrefOpt = function (editor, elm) {
      var isRoot = function (elm) {
        return eq$2(elm, SugarElement.fromDom(editor.getBody()));
      };
      return closest$1(elm, 'a', isRoot).bind(function (a) {
        return getOpt(a, 'href');
      });
    };
    var processReadonlyEvents = function (editor, e) {
      if (isClickEvent(e) &amp;&amp; !VK.metaKeyPressed(e)) {
        var elm = SugarElement.fromDom(e.target);
        getAnchorHrefOpt(editor, elm).each(function (href) {
          e.preventDefault();
          if (/^#/.test(href)) {
            var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
            if (targetEl.length) {
              editor.selection.scrollIntoView(targetEl[0], true);
            }
          } else {
            window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
          }
        });
      }
    };
    var registerReadOnlySelectionBlockers = function (editor) {
      editor.on('ShowCaret', function (e) {
        if (isReadOnly$1(editor)) {
          e.preventDefault();
        }
      });
      editor.on('ObjectSelected', function (e) {
        if (isReadOnly$1(editor)) {
          e.preventDefault();
        }
      });
    };

    var nativeEvents = Tools.makeMap('focus blur focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange ' + 'mouseout mouseenter mouseleave wheel keydown keypress keyup input beforeinput contextmenu dragstart dragend dragover ' + 'draggesture dragdrop drop drag submit ' + 'compositionstart compositionend compositionupdate touchstart touchmove touchend touchcancel', ' ');
    var EventDispatcher = function () {
      function EventDispatcher(settings) {
        this.bindings = {};
        this.settings = settings || {};
        this.scope = this.settings.scope || this;
        this.toggleEvent = this.settings.toggleEvent || never;
      }
      EventDispatcher.isNative = function (name) {
        return !!nativeEvents[name.toLowerCase()];
      };
      EventDispatcher.prototype.fire = function (nameIn, argsIn) {
        var name = nameIn.toLowerCase();
        var args = argsIn || {};
        args.type = name;
        if (!args.target) {
          args.target = this.scope;
        }
        if (!args.preventDefault) {
          args.preventDefault = function () {
            args.isDefaultPrevented = always;
          };
          args.stopPropagation = function () {
            args.isPropagationStopped = always;
          };
          args.stopImmediatePropagation = function () {
            args.isImmediatePropagationStopped = always;
          };
          args.isDefaultPrevented = never;
          args.isPropagationStopped = never;
          args.isImmediatePropagationStopped = never;
        }
        if (this.settings.beforeFire) {
          this.settings.beforeFire(args);
        }
        var handlers = this.bindings[name];
        if (handlers) {
          for (var i = 0, l = handlers.length; i &lt; l; i++) {
            var callback = handlers[i];
            if (callback.once) {
              this.off(name, callback.func);
            }
            if (args.isImmediatePropagationStopped()) {
              args.stopPropagation();
              return args;
            }
            if (callback.func.call(this.scope, args) === false) {
              args.preventDefault();
              return args;
            }
          }
        }
        return args;
      };
      EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
        if (callback === false) {
          callback = never;
        }
        if (callback) {
          var wrappedCallback = { func: callback };
          if (extra) {
            Tools.extend(wrappedCallback, extra);
          }
          var names = name.toLowerCase().split(' ');
          var i = names.length;
          while (i--) {
            var currentName = names[i];
            var handlers = this.bindings[currentName];
            if (!handlers) {
              handlers = this.bindings[currentName] = [];
              this.toggleEvent(currentName, true);
            }
            if (prepend) {
              handlers.unshift(wrappedCallback);
            } else {
              handlers.push(wrappedCallback);
            }
          }
        }
        return this;
      };
      EventDispatcher.prototype.off = function (name, callback) {
        var _this = this;
        if (name) {
          var names = name.toLowerCase().split(' ');
          var i = names.length;
          while (i--) {
            var currentName = names[i];
            var handlers = this.bindings[currentName];
            if (!currentName) {
              each$1(this.bindings, function (_value, bindingName) {
                _this.toggleEvent(bindingName, false);
                delete _this.bindings[bindingName];
              });
              return this;
            }
            if (handlers) {
              if (!callback) {
                handlers.length = 0;
              } else {
                var hi = handlers.length;
                while (hi--) {
                  if (handlers[hi].func === callback) {
                    handlers = handlers.slice(0, hi).concat(handlers.slice(hi + 1));
                    this.bindings[currentName] = handlers;
                  }
                }
              }
              if (!handlers.length) {
                this.toggleEvent(name, false);
                delete this.bindings[currentName];
              }
            }
          }
        } else {
          each$1(this.bindings, function (_value, name) {
            _this.toggleEvent(name, false);
          });
          this.bindings = {};
        }
        return this;
      };
      EventDispatcher.prototype.once = function (name, callback, prepend) {
        return this.on(name, callback, prepend, { once: true });
      };
      EventDispatcher.prototype.has = function (name) {
        name = name.toLowerCase();
        return !(!this.bindings[name] || this.bindings[name].length === 0);
      };
      return EventDispatcher;
    }();

    var getEventDispatcher = function (obj) {
      if (!obj._eventDispatcher) {
        obj._eventDispatcher = new EventDispatcher({
          scope: obj,
          toggleEvent: function (name, state) {
            if (EventDispatcher.isNative(name) &amp;&amp; obj.toggleNativeEvent) {
              obj.toggleNativeEvent(name, state);
            }
          }
        });
      }
      return obj._eventDispatcher;
    };
    var Observable = {
      fire: function (name, args, bubble) {
        var self = this;
        if (self.removed &amp;&amp; name !== 'remove' &amp;&amp; name !== 'detach') {
          return args;
        }
        var dispatcherArgs = getEventDispatcher(self).fire(name, args);
        if (bubble !== false &amp;&amp; self.parent) {
          var parent_1 = self.parent();
          while (parent_1 &amp;&amp; !dispatcherArgs.isPropagationStopped()) {
            parent_1.fire(name, dispatcherArgs, false);
            parent_1 = parent_1.parent();
          }
        }
        return dispatcherArgs;
      },
      on: function (name, callback, prepend) {
        return getEventDispatcher(this).on(name, callback, prepend);
      },
      off: function (name, callback) {
        return getEventDispatcher(this).off(name, callback);
      },
      once: function (name, callback) {
        return getEventDispatcher(this).once(name, callback);
      },
      hasEventListeners: function (name) {
        return getEventDispatcher(this).has(name);
      }
    };

    var DOM$8 = DOMUtils.DOM;
    var customEventRootDelegates;
    var getEventTarget = function (editor, eventName) {
      if (eventName === 'selectionchange') {
        return editor.getDoc();
      }
      if (!editor.inline &amp;&amp; /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
        return editor.getDoc().documentElement;
      }
      var eventRoot = getEventRoot(editor);
      if (eventRoot) {
        if (!editor.eventRoot) {
          editor.eventRoot = DOM$8.select(eventRoot)[0];
        }
        return editor.eventRoot;
      }
      return editor.getBody();
    };
    var isListening = function (editor) {
      return !editor.hidden &amp;&amp; !isReadOnly$1(editor);
    };
    var fireEvent = function (editor, eventName, e) {
      if (isListening(editor)) {
        editor.fire(eventName, e);
      } else if (isReadOnly$1(editor)) {
        processReadonlyEvents(editor, e);
      }
    };
    var bindEventDelegate = function (editor, eventName) {
      var delegate;
      if (!editor.delegates) {
        editor.delegates = {};
      }
      if (editor.delegates[eventName] || editor.removed) {
        return;
      }
      var eventRootElm = getEventTarget(editor, eventName);
      if (getEventRoot(editor)) {
        if (!customEventRootDelegates) {
          customEventRootDelegates = {};
          editor.editorManager.on('removeEditor', function () {
            if (!editor.editorManager.activeEditor) {
              if (customEventRootDelegates) {
                each$1(customEventRootDelegates, function (_value, name) {
                  editor.dom.unbind(getEventTarget(editor, name));
                });
                customEventRootDelegates = null;
              }
            }
          });
        }
        if (customEventRootDelegates[eventName]) {
          return;
        }
        delegate = function (e) {
          var target = e.target;
          var editors = editor.editorManager.get();
          var i = editors.length;
          while (i--) {
            var body = editors[i].getBody();
            if (body === target || DOM$8.isChildOf(target, body)) {
              fireEvent(editors[i], eventName, e);
            }
          }
        };
        customEventRootDelegates[eventName] = delegate;
        DOM$8.bind(eventRootElm, eventName, delegate);
      } else {
        delegate = function (e) {
          fireEvent(editor, eventName, e);
        };
        DOM$8.bind(eventRootElm, eventName, delegate);
        editor.delegates[eventName] = delegate;
      }
    };
    var EditorObservable = __assign(__assign({}, Observable), {
      bindPendingEventDelegates: function () {
        var self = this;
        Tools.each(self._pendingNativeEvents, function (name) {
          bindEventDelegate(self, name);
        });
      },
      toggleNativeEvent: function (name, state) {
        var self = this;
        if (name === 'focus' || name === 'blur') {
          return;
        }
        if (state) {
          if (self.initialized) {
            bindEventDelegate(self, name);
          } else {
            if (!self._pendingNativeEvents) {
              self._pendingNativeEvents = [name];
            } else {
              self._pendingNativeEvents.push(name);
            }
          }
        } else if (self.initialized) {
          self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
          delete self.delegates[name];
        }
      },
      unbindAllNativeEvents: function () {
        var self = this;
        var body = self.getBody();
        var dom = self.dom;
        if (self.delegates) {
          each$1(self.delegates, function (value, name) {
            self.dom.unbind(getEventTarget(self, name), name, value);
          });
          delete self.delegates;
        }
        if (!self.inline &amp;&amp; body &amp;&amp; dom) {
          body.onload = null;
          dom.unbind(self.getWin());
          dom.unbind(self.getDoc());
        }
        if (dom) {
          dom.unbind(body);
          dom.unbind(self.getContainer());
        }
      }
    });

    var defaultModes = [
      'design',
      'readonly'
    ];
    var switchToMode = function (editor, activeMode, availableModes, mode) {
      var oldMode = availableModes[activeMode.get()];
      var newMode = availableModes[mode];
      try {
        newMode.activate();
      } catch (e) {
        console.error('problem while activating editor mode ' + mode + ':', e);
        return;
      }
      oldMode.deactivate();
      if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
        toggleReadOnly(editor, newMode.editorReadOnly);
      }
      activeMode.set(mode);
      fireSwitchMode(editor, mode);
    };
    var setMode = function (editor, availableModes, activeMode, mode) {
      if (mode === activeMode.get()) {
        return;
      } else if (!has(availableModes, mode)) {
        throw new Error('Editor mode \'' + mode + '\' is invalid');
      }
      if (editor.initialized) {
        switchToMode(editor, activeMode, availableModes, mode);
      } else {
        editor.on('init', function () {
          return switchToMode(editor, activeMode, availableModes, mode);
        });
      }
    };
    var registerMode = function (availableModes, mode, api) {
      var _a;
      if (contains(defaultModes, mode)) {
        throw new Error('Cannot override default mode ' + mode);
      }
      return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
        deactivate: function () {
          try {
            api.deactivate();
          } catch (e) {
            console.error('problem while deactivating editor mode ' + mode + ':', e);
          }
        }
      }), _a));
    };

    var create$5 = function (editor) {
      var activeMode = Cell('design');
      var availableModes = Cell({
        design: {
          activate: noop,
          deactivate: noop,
          editorReadOnly: false
        },
        readonly: {
          activate: noop,
          deactivate: noop,
          editorReadOnly: true
        }
      });
      registerReadOnlyContentFilters(editor);
      registerReadOnlySelectionBlockers(editor);
      return {
        isReadOnly: function () {
          return isReadOnly$1(editor);
        },
        set: function (mode) {
          return setMode(editor, availableModes.get(), activeMode, mode);
        },
        get: function () {
          return activeMode.get();
        },
        register: function (mode, api) {
          availableModes.set(registerMode(availableModes.get(), mode, api));
        }
      };
    };

    var each$g = Tools.each, explode$3 = Tools.explode;
    var keyCodeLookup = {
      f1: 112,
      f2: 113,
      f3: 114,
      f4: 115,
      f5: 116,
      f6: 117,
      f7: 118,
      f8: 119,
      f9: 120,
      f10: 121,
      f11: 122,
      f12: 123
    };
    var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
    var parseShortcut = function (pattern) {
      var key;
      var shortcut = {};
      each$g(explode$3(pattern.toLowerCase(), '+'), function (value) {
        if (value in modifierNames) {
          shortcut[value] = true;
        } else {
          if (/^[0-9]{2,}$/.test(value)) {
            shortcut.keyCode = parseInt(value, 10);
          } else {
            shortcut.charCode = value.charCodeAt(0);
            shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
          }
        }
      });
      var id = [shortcut.keyCode];
      for (key in modifierNames) {
        if (shortcut[key]) {
          id.push(key);
        } else {
          shortcut[key] = false;
        }
      }
      shortcut.id = id.join(',');
      if (shortcut.access) {
        shortcut.alt = true;
        if (Env.mac) {
          shortcut.ctrl = true;
        } else {
          shortcut.shift = true;
        }
      }
      if (shortcut.meta) {
        if (Env.mac) {
          shortcut.meta = true;
        } else {
          shortcut.ctrl = true;
          shortcut.meta = false;
        }
      }
      return shortcut;
    };
    var Shortcuts = function () {
      function Shortcuts(editor) {
        this.shortcuts = {};
        this.pendingPatterns = [];
        this.editor = editor;
        var self = this;
        editor.on('keyup keypress keydown', function (e) {
          if ((self.hasModifier(e) || self.isFunctionKey(e)) &amp;&amp; !e.isDefaultPrevented()) {
            each$g(self.shortcuts, function (shortcut) {
              if (self.matchShortcut(e, shortcut)) {
                self.pendingPatterns = shortcut.subpatterns.slice(0);
                if (e.type === 'keydown') {
                  self.executeShortcutAction(shortcut);
                }
                return true;
              }
            });
            if (self.matchShortcut(e, self.pendingPatterns[0])) {
              if (self.pendingPatterns.length === 1) {
                if (e.type === 'keydown') {
                  self.executeShortcutAction(self.pendingPatterns[0]);
                }
              }
              self.pendingPatterns.shift();
            }
          }
        });
      }
      Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
        var self = this;
        var func = self.normalizeCommandFunc(cmdFunc);
        each$g(explode$3(Tools.trim(pattern)), function (pattern) {
          var shortcut = self.createShortcut(pattern, desc, func, scope);
          self.shortcuts[shortcut.id] = shortcut;
        });
        return true;
      };
      Shortcuts.prototype.remove = function (pattern) {
        var shortcut = this.createShortcut(pattern);
        if (this.shortcuts[shortcut.id]) {
          delete this.shortcuts[shortcut.id];
          return true;
        }
        return false;
      };
      Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
        var self = this;
        var cmd = cmdFunc;
        if (typeof cmd === 'string') {
          return function () {
            self.editor.execCommand(cmd, false, null);
          };
        } else if (Tools.isArray(cmd)) {
          return function () {
            self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
          };
        } else {
          return cmd;
        }
      };
      Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
        var shortcuts = Tools.map(explode$3(pattern, '&gt;'), parseShortcut);
        shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
          func: cmdFunc,
          scope: scope || this.editor
        });
        return Tools.extend(shortcuts[0], {
          desc: this.editor.translate(desc),
          subpatterns: shortcuts.slice(1)
        });
      };
      Shortcuts.prototype.hasModifier = function (e) {
        return e.altKey || e.ctrlKey || e.metaKey;
      };
      Shortcuts.prototype.isFunctionKey = function (e) {
        return e.type === 'keydown' &amp;&amp; e.keyCode &gt;= 112 &amp;&amp; e.keyCode &lt;= 123;
      };
      Shortcuts.prototype.matchShortcut = function (e, shortcut) {
        if (!shortcut) {
          return false;
        }
        if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
          return false;
        }
        if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
          return false;
        }
        if (e.keyCode === shortcut.keyCode || e.charCode &amp;&amp; e.charCode === shortcut.charCode) {
          e.preventDefault();
          return true;
        }
        return false;
      };
      Shortcuts.prototype.executeShortcutAction = function (shortcut) {
        return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
      };
      return Shortcuts;
    }();

    var create$6 = function () {
      var buttons = {};
      var menuItems = {};
      var popups = {};
      var icons = {};
      var contextMenus = {};
      var contextToolbars = {};
      var sidebars = {};
      var add = function (collection, type) {
        return function (name, spec) {
          return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
        };
      };
      var addIcon = function (name, svgData) {
        return icons[name.toLowerCase()] = svgData;
      };
      return {
        addButton: add(buttons, 'button'),
        addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
        addToggleButton: add(buttons, 'togglebutton'),
        addMenuButton: add(buttons, 'menubutton'),
        addSplitButton: add(buttons, 'splitbutton'),
        addMenuItem: add(menuItems, 'menuitem'),
        addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
        addToggleMenuItem: add(menuItems, 'togglemenuitem'),
        addAutocompleter: add(popups, 'autocompleter'),
        addContextMenu: add(contextMenus, 'contextmenu'),
        addContextToolbar: add(contextToolbars, 'contexttoolbar'),
        addContextForm: add(contextToolbars, 'contextform'),
        addSidebar: add(sidebars, 'sidebar'),
        addIcon: addIcon,
        getAll: function () {
          return {
            buttons: buttons,
            menuItems: menuItems,
            icons: icons,
            popups: popups,
            contextMenus: contextMenus,
            contextToolbars: contextToolbars,
            sidebars: sidebars
          };
        }
      };
    };

    var registry = function () {
      var bridge = create$6();
      return {
        addAutocompleter: bridge.addAutocompleter,
        addButton: bridge.addButton,
        addContextForm: bridge.addContextForm,
        addContextMenu: bridge.addContextMenu,
        addContextToolbar: bridge.addContextToolbar,
        addIcon: bridge.addIcon,
        addMenuButton: bridge.addMenuButton,
        addMenuItem: bridge.addMenuItem,
        addNestedMenuItem: bridge.addNestedMenuItem,
        addSidebar: bridge.addSidebar,
        addSplitButton: bridge.addSplitButton,
        addToggleButton: bridge.addToggleButton,
        addGroupToolbarButton: bridge.addGroupToolbarButton,
        addToggleMenuItem: bridge.addToggleMenuItem,
        getAll: bridge.getAll
      };
    };

    var each$h = Tools.each, trim$4 = Tools.trim;
    var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
    var DEFAULT_PORTS = {
      ftp: 21,
      http: 80,
      https: 443,
      mailto: 25
    };
    var URI = function () {
      function URI(url, settings) {
        url = trim$4(url);
        this.settings = settings || {};
        var baseUri = this.settings.base_uri;
        var self = this;
        if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
          self.source = url;
          return;
        }
        var isProtocolRelative = url.indexOf('//') === 0;
        if (url.indexOf('/') === 0 &amp;&amp; !isProtocolRelative) {
          url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
        }
        if (!/^[\w\-]*:?\/\//.test(url)) {
          var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
          if (this.settings.base_uri &amp;&amp; this.settings.base_uri.protocol == '') {
            url = '//mce_host' + self.toAbsPath(baseUrl, url);
          } else {
            var match = /([^#?]*)([#?]?.*)/.exec(url);
            url = (baseUri &amp;&amp; baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
          }
        }
        url = url.replace(/@@/g, '(mce_at)');
        var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
        each$h(queryParts, function (v, i) {
          var part = urlMatch[i];
          if (part) {
            part = part.replace(/\(mce_at\)/g, '@@');
          }
          self[v] = part;
        });
        if (baseUri) {
          if (!self.protocol) {
            self.protocol = baseUri.protocol;
          }
          if (!self.userInfo) {
            self.userInfo = baseUri.userInfo;
          }
          if (!self.port &amp;&amp; self.host === 'mce_host') {
            self.port = baseUri.port;
          }
          if (!self.host || self.host === 'mce_host') {
            self.host = baseUri.host;
          }
          self.source = '';
        }
        if (isProtocolRelative) {
          self.protocol = '';
        }
      }
      URI.parseDataUri = function (uri) {
        var type;
        var uriComponents = decodeURIComponent(uri).split(',');
        var matches = /data:([^;]+)/.exec(uriComponents[0]);
        if (matches) {
          type = matches[1];
        }
        return {
          type: type,
          data: uriComponents[1]
        };
      };
      URI.getDocumentBaseUrl = function (loc) {
        var baseUrl;
        if (loc.protocol.indexOf('http') !== 0 &amp;&amp; loc.protocol !== 'file:') {
          baseUrl = loc.href;
        } else {
          baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
        }
        if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
          baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
          if (!/[\/\\]$/.test(baseUrl)) {
            baseUrl += '/';
          }
        }
        return baseUrl;
      };
      URI.prototype.setPath = function (path) {
        var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
        this.path = pathMatch[0];
        this.directory = pathMatch[1];
        this.file = pathMatch[2];
        this.source = '';
        this.getURI();
      };
      URI.prototype.toRelative = function (uri) {
        var output;
        if (uri === './') {
          return uri;
        }
        var relativeUri = new URI(uri, { base_uri: this });
        if (relativeUri.host !== 'mce_host' &amp;&amp; this.host !== relativeUri.host &amp;&amp; relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol &amp;&amp; relativeUri.protocol !== '') {
          return relativeUri.getURI();
        }
        var tu = this.getURI(), uu = relativeUri.getURI();
        if (tu === uu || tu.charAt(tu.length - 1) === '/' &amp;&amp; tu.substr(0, tu.length - 1) === uu) {
          return tu;
        }
        output = this.toRelPath(this.path, relativeUri.path);
        if (relativeUri.query) {
          output += '?' + relativeUri.query;
        }
        if (relativeUri.anchor) {
          output += '#' + relativeUri.anchor;
        }
        return output;
      };
      URI.prototype.toAbsolute = function (uri, noHost) {
        var absoluteUri = new URI(uri, { base_uri: this });
        return absoluteUri.getURI(noHost &amp;&amp; this.isSameOrigin(absoluteUri));
      };
      URI.prototype.isSameOrigin = function (uri) {
        if (this.host == uri.host &amp;&amp; this.protocol == uri.protocol) {
          if (this.port == uri.port) {
            return true;
          }
          var defaultPort = DEFAULT_PORTS[this.protocol];
          if (defaultPort &amp;&amp; (this.port || defaultPort) == (uri.port || defaultPort)) {
            return true;
          }
        }
        return false;
      };
      URI.prototype.toRelPath = function (base, path) {
        var breakPoint = 0, out = '', i, l;
        var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
        var items = path.split('/');
        if (normalizedBase.length &gt;= items.length) {
          for (i = 0, l = normalizedBase.length; i &lt; l; i++) {
            if (i &gt;= items.length || normalizedBase[i] !== items[i]) {
              breakPoint = i + 1;
              break;
            }
          }
        }
        if (normalizedBase.length &lt; items.length) {
          for (i = 0, l = items.length; i &lt; l; i++) {
            if (i &gt;= normalizedBase.length || normalizedBase[i] !== items[i]) {
              breakPoint = i + 1;
              break;
            }
          }
        }
        if (breakPoint === 1) {
          return path;
        }
        for (i = 0, l = normalizedBase.length - (breakPoint - 1); i &lt; l; i++) {
          out += '../';
        }
        for (i = breakPoint - 1, l = items.length; i &lt; l; i++) {
          if (i !== breakPoint - 1) {
            out += '/' + items[i];
          } else {
            out += items[i];
          }
        }
        return out;
      };
      URI.prototype.toAbsPath = function (base, path) {
        var i, nb = 0, o = [], outPath;
        var tr = /\/$/.test(path) ? '/' : '';
        var normalizedBase = base.split('/');
        var normalizedPath = path.split('/');
        each$h(normalizedBase, function (k) {
          if (k) {
            o.push(k);
          }
        });
        normalizedBase = o;
        for (i = normalizedPath.length - 1, o = []; i &gt;= 0; i--) {
          if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
            continue;
          }
          if (normalizedPath[i] === '..') {
            nb++;
            continue;
          }
          if (nb &gt; 0) {
            nb--;
            continue;
          }
          o.push(normalizedPath[i]);
        }
        i = normalizedBase.length - nb;
        if (i &lt;= 0) {
          outPath = reverse(o).join('/');
        } else {
          outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
        }
        if (outPath.indexOf('/') !== 0) {
          outPath = '/' + outPath;
        }
        if (tr &amp;&amp; outPath.lastIndexOf('/') !== outPath.length - 1) {
          outPath += tr;
        }
        return outPath;
      };
      URI.prototype.getURI = function (noProtoHost) {
        if (noProtoHost === void 0) {
          noProtoHost = false;
        }
        var s;
        if (!this.source || noProtoHost) {
          s = '';
          if (!noProtoHost) {
            if (this.protocol) {
              s += this.protocol + '://';
            } else {
              s += '//';
            }
            if (this.userInfo) {
              s += this.userInfo + '@';
            }
            if (this.host) {
              s += this.host;
            }
            if (this.port) {
              s += ':' + this.port;
            }
          }
          if (this.path) {
            s += this.path;
          }
          if (this.query) {
            s += '?' + this.query;
          }
          if (this.anchor) {
            s += '#' + this.anchor;
          }
          this.source = s;
        }
        return this.source;
      };
      return URI;
    }();

    var DOM$9 = DOMUtils.DOM;
    var extend$3 = Tools.extend, each$i = Tools.each;
    var resolve$3 = Tools.resolve;
    var ie$1 = Env.ie;
    var Editor = function () {
      function Editor(id, settings, editorManager) {
        var _this = this;
        this.plugins = {};
        this.contentCSS = [];
        this.contentStyles = [];
        this.loadedCSS = {};
        this.isNotDirty = false;
        this.editorManager = editorManager;
        this.documentBaseUrl = editorManager.documentBaseURL;
        extend$3(this, EditorObservable);
        this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
        if (this.settings.suffix) {
          editorManager.suffix = this.settings.suffix;
        }
        this.suffix = editorManager.suffix;
        if (this.settings.base_url) {
          editorManager._setBaseUrl(this.settings.base_url);
        }
        this.baseUri = editorManager.baseURI;
        if (this.settings.referrer_policy) {
          ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
          DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
        }
        AddOnManager.languageLoad = this.settings.language_load;
        AddOnManager.baseURL = editorManager.baseURL;
        this.id = id;
        this.setDirty(false);
        this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
        this.baseURI = this.baseUri;
        this.inline = !!this.settings.inline;
        this.shortcuts = new Shortcuts(this);
        this.editorCommands = new EditorCommands(this);
        if (this.settings.cache_suffix) {
          Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&amp;]+/, '');
        }
        this.ui = {
          registry: registry(),
          styleSheetLoader: undefined,
          show: noop,
          hide: noop,
          enable: noop,
          disable: noop,
          isDisabled: never
        };
        var self = this;
        var modeInstance = create$5(self);
        this.mode = modeInstance;
        this.setMode = modeInstance.set;
        editorManager.fire('SetupEditor', { editor: this });
        this.execCallback('setup', this);
        this.$ = DomQuery.overrideDefaults(function () {
          return {
            context: _this.inline ? _this.getBody() : _this.getDoc(),
            element: _this.getBody()
          };
        });
      }
      Editor.prototype.render = function () {
        render(this);
      };
      Editor.prototype.focus = function (skipFocus) {
        focus$1(this, skipFocus);
      };
      Editor.prototype.hasFocus = function () {
        return hasFocus$1(this);
      };
      Editor.prototype.execCallback = function (name) {
        var x = [];
        for (var _i = 1; _i &lt; arguments.length; _i++) {
          x[_i - 1] = arguments[_i];
        }
        var self = this;
        var callback = self.settings[name], scope;
        if (!callback) {
          return;
        }
        if (self.callbackLookup &amp;&amp; (scope = self.callbackLookup[name])) {
          callback = scope.func;
          scope = scope.scope;
        }
        if (typeof callback === 'string') {
          scope = callback.replace(/\.\w+$/, '');
          scope = scope ? resolve$3(scope) : 0;
          callback = resolve$3(callback);
          self.callbackLookup = self.callbackLookup || {};
          self.callbackLookup[name] = {
            func: callback,
            scope: scope
          };
        }
        return callback.apply(scope || self, x);
      };
      Editor.prototype.translate = function (text) {
        return I18n.translate(text);
      };
      Editor.prototype.getParam = function (name, defaultVal, type) {
        return getParam(this, name, defaultVal, type);
      };
      Editor.prototype.hasPlugin = function (name, loaded) {
        var hasPlugin = contains(getPlugins(this).split(/[ ,]/), name);
        if (hasPlugin) {
          return loaded ? PluginManager.get(name) !== undefined : true;
        } else {
          return false;
        }
      };
      Editor.prototype.nodeChanged = function (args) {
        this._nodeChangeDispatcher.nodeChanged(args);
      };
      Editor.prototype.addCommand = function (name, callback, scope) {
        this.editorCommands.addCommand(name, callback, scope);
      };
      Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
        this.editorCommands.addQueryStateHandler(name, callback, scope);
      };
      Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
        this.editorCommands.addQueryValueHandler(name, callback, scope);
      };
      Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
        this.shortcuts.add(pattern, desc, cmdFunc, scope);
      };
      Editor.prototype.execCommand = function (cmd, ui, value, args) {
        return this.editorCommands.execCommand(cmd, ui, value, args);
      };
      Editor.prototype.queryCommandState = function (cmd) {
        return this.editorCommands.queryCommandState(cmd);
      };
      Editor.prototype.queryCommandValue = function (cmd) {
        return this.editorCommands.queryCommandValue(cmd);
      };
      Editor.prototype.queryCommandSupported = function (cmd) {
        return this.editorCommands.queryCommandSupported(cmd);
      };
      Editor.prototype.show = function () {
        var self = this;
        if (self.hidden) {
          self.hidden = false;
          if (self.inline) {
            self.getBody().contentEditable = 'true';
          } else {
            DOM$9.show(self.getContainer());
            DOM$9.hide(self.id);
          }
          self.load();
          self.fire('show');
        }
      };
      Editor.prototype.hide = function () {
        var self = this, doc = self.getDoc();
        if (!self.hidden) {
          if (ie$1 &amp;&amp; doc &amp;&amp; !self.inline) {
            doc.execCommand('SelectAll');
          }
          self.save();
          if (self.inline) {
            self.getBody().contentEditable = 'false';
            if (self === self.editorManager.focusedEditor) {
              self.editorManager.focusedEditor = null;
            }
          } else {
            DOM$9.hide(self.getContainer());
            DOM$9.setStyle(self.id, 'display', self.orgDisplay);
          }
          self.hidden = true;
          self.fire('hide');
        }
      };
      Editor.prototype.isHidden = function () {
        return !!this.hidden;
      };
      Editor.prototype.setProgressState = function (state, time) {
        this.fire('ProgressState', {
          state: state,
          time: time
        });
      };
      Editor.prototype.load = function (args) {
        var self = this;
        var elm = self.getElement(), html;
        if (self.removed) {
          return '';
        }
        if (elm) {
          args = args || {};
          args.load = true;
          var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
          html = self.setContent(value, args);
          args.element = elm;
          if (!args.no_events) {
            self.fire('LoadContent', args);
          }
          args.element = elm = null;
          return html;
        }
      };
      Editor.prototype.save = function (args) {
        var self = this;
        var elm = self.getElement(), html, form;
        if (!elm || !self.initialized || self.removed) {
          return;
        }
        args = args || {};
        args.save = true;
        args.element = elm;
        html = args.content = self.getContent(args);
        if (!args.no_events) {
          self.fire('SaveContent', args);
        }
        if (args.format === 'raw') {
          self.fire('RawSaveContent', args);
        }
        html = args.content;
        if (!isTextareaOrInput(elm)) {
          if (args.is_removing || !self.inline) {
            elm.innerHTML = html;
          }
          if (form = DOM$9.getParent(self.id, 'form')) {
            each$i(form.elements, function (elm) {
              if (elm.name === self.id) {
                elm.value = html;
                return false;
              }
            });
          }
        } else {
          elm.value = html;
        }
        args.element = elm = null;
        if (args.set_dirty !== false) {
          self.setDirty(false);
        }
        return html;
      };
      Editor.prototype.setContent = function (content, args) {
        return setContent$2(this, content, args);
      };
      Editor.prototype.getContent = function (args) {
        return getContent$2(this, args);
      };
      Editor.prototype.insertContent = function (content, args) {
        if (args) {
          content = extend$3({ content: content }, args);
        }
        this.execCommand('mceInsertContent', false, content);
      };
      Editor.prototype.resetContent = function (initialContent) {
        if (initialContent === undefined) {
          setContent$2(this, this.startContent, { format: 'raw' });
        } else {
          setContent$2(this, initialContent);
        }
        this.undoManager.reset();
        this.setDirty(false);
        this.nodeChanged();
      };
      Editor.prototype.isDirty = function () {
        return !this.isNotDirty;
      };
      Editor.prototype.setDirty = function (state) {
        var oldState = !this.isNotDirty;
        this.isNotDirty = !state;
        if (state &amp;&amp; state !== oldState) {
          this.fire('dirty');
        }
      };
      Editor.prototype.getContainer = function () {
        var self = this;
        if (!self.container) {
          self.container = DOM$9.get(self.editorContainer || self.id + '_parent');
        }
        return self.container;
      };
      Editor.prototype.getContentAreaContainer = function () {
        return this.contentAreaContainer;
      };
      Editor.prototype.getElement = function () {
        if (!this.targetElm) {
          this.targetElm = DOM$9.get(this.id);
        }
        return this.targetElm;
      };
      Editor.prototype.getWin = function () {
        var self = this;
        var elm;
        if (!self.contentWindow) {
          elm = self.iframeElement;
          if (elm) {
            self.contentWindow = elm.contentWindow;
          }
        }
        return self.contentWindow;
      };
      Editor.prototype.getDoc = function () {
        var self = this;
        var win;
        if (!self.contentDocument) {
          win = self.getWin();
          if (win) {
            self.contentDocument = win.document;
          }
        }
        return self.contentDocument;
      };
      Editor.prototype.getBody = function () {
        var doc = this.getDoc();
        return this.bodyElement || (doc ? doc.body : null);
      };
      Editor.prototype.convertURL = function (url, name, elm) {
        var self = this, settings = self.settings;
        if (settings.urlconverter_callback) {
          return self.execCallback('urlconverter_callback', url, elm, true, name);
        }
        if (!settings.convert_urls || elm &amp;&amp; elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
          return url;
        }
        if (settings.relative_urls) {
          return self.documentBaseURI.toRelative(url);
        }
        url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
        return url;
      };
      Editor.prototype.addVisual = function (elm) {
        addVisual$1(this, elm);
      };
      Editor.prototype.remove = function () {
        remove$7(this);
      };
      Editor.prototype.destroy = function (automatic) {
        destroy(this, automatic);
      };
      Editor.prototype.uploadImages = function (callback) {
        return this.editorUpload.uploadImages(callback);
      };
      Editor.prototype._scanForImages = function () {
        return this.editorUpload.scanForImages();
      };
      Editor.prototype.addButton = function () {
        throw new Error('editor.addButton has been removed in tinymce 5x, use editor.ui.registry.addButton or editor.ui.registry.addToggleButton or editor.ui.registry.addSplitButton instead');
      };
      Editor.prototype.addSidebar = function () {
        throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
      };
      Editor.prototype.addMenuItem = function () {
        throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
      };
      Editor.prototype.addContextToolbar = function () {
        throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
      };
      return Editor;
    }();

    var DOM$a = DOMUtils.DOM;
    var explode$4 = Tools.explode, each$j = Tools.each, extend$4 = Tools.extend;
    var instanceCounter = 0, boundGlobalEvents = false;
    var beforeUnloadDelegate;
    var legacyEditors = [];
    var editors = [];
    var isValidLegacyKey = function (id) {
      return id !== 'length';
    };
    var globalEventDelegate = function (e) {
      var type = e.type;
      each$j(EditorManager.get(), function (editor) {
        switch (type) {
        case 'scroll':
          editor.fire('ScrollWindow', e);
          break;
        case 'resize':
          editor.fire('ResizeWindow', e);
          break;
        }
      });
    };
    var toggleGlobalEvents = function (state) {
      if (state !== boundGlobalEvents) {
        if (state) {
          DomQuery(window).on('resize scroll', globalEventDelegate);
        } else {
          DomQuery(window).off('resize scroll', globalEventDelegate);
        }
        boundGlobalEvents = state;
      }
    };
    var removeEditorFromList = function (targetEditor) {
      var oldEditors = editors;
      delete legacyEditors[targetEditor.id];
      for (var i = 0; i &lt; legacyEditors.length; i++) {
        if (legacyEditors[i] === targetEditor) {
          legacyEditors.splice(i, 1);
          break;
        }
      }
      editors = filter(editors, function (editor) {
        return targetEditor !== editor;
      });
      if (EditorManager.activeEditor === targetEditor) {
        EditorManager.activeEditor = editors.length &gt; 0 ? editors[0] : null;
      }
      if (EditorManager.focusedEditor === targetEditor) {
        EditorManager.focusedEditor = null;
      }
      return oldEditors.length !== editors.length;
    };
    var purgeDestroyedEditor = function (editor) {
      if (editor &amp;&amp; editor.initialized &amp;&amp; !(editor.getContainer() || editor.getBody()).parentNode) {
        removeEditorFromList(editor);
        editor.unbindAllNativeEvents();
        editor.destroy(true);
        editor.removed = true;
        editor = null;
      }
      return editor;
    };
    var isQuirksMode = document.compatMode !== 'CSS1Compat';
    var EditorManager = __assign(__assign({}, Observable), {
      baseURI: null,
      baseURL: null,
      defaultSettings: {},
      documentBaseURL: null,
      suffix: null,
      $: DomQuery,
      majorVersion: '5',
      minorVersion: '8.2',
      releaseDate: '2021-06-23',
      editors: legacyEditors,
      i18n: I18n,
      activeEditor: null,
      focusedEditor: null,
      settings: {},
      setup: function () {
        var self = this;
        var baseURL, documentBaseURL, suffix = '';
        documentBaseURL = URI.getDocumentBaseUrl(document.location);
        if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
          documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
          if (!/[\/\\]$/.test(documentBaseURL)) {
            documentBaseURL += '/';
          }
        }
        var preInit = window.tinymce || window.tinyMCEPreInit;
        if (preInit) {
          baseURL = preInit.base || preInit.baseURL;
          suffix = preInit.suffix;
        } else {
          var scripts = document.getElementsByTagName('script');
          for (var i = 0; i &lt; scripts.length; i++) {
            var src = scripts[i].src || '';
            if (src === '') {
              continue;
            }
            var srcScript = src.substring(src.lastIndexOf('/'));
            if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
              if (srcScript.indexOf('.min') !== -1) {
                suffix = '.min';
              }
              baseURL = src.substring(0, src.lastIndexOf('/'));
              break;
            }
          }
          if (!baseURL &amp;&amp; document.currentScript) {
            var src = document.currentScript.src;
            if (src.indexOf('.min') !== -1) {
              suffix = '.min';
            }
            baseURL = src.substring(0, src.lastIndexOf('/'));
          }
        }
        self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
        self.documentBaseURL = documentBaseURL;
        self.baseURI = new URI(self.baseURL);
        self.suffix = suffix;
        setup$2(self);
      },
      overrideDefaults: function (defaultSettings) {
        var baseUrl = defaultSettings.base_url;
        if (baseUrl) {
          this._setBaseUrl(baseUrl);
        }
        var suffix = defaultSettings.suffix;
        if (defaultSettings.suffix) {
          this.suffix = suffix;
        }
        this.defaultSettings = defaultSettings;
        var pluginBaseUrls = defaultSettings.plugin_base_urls;
        if (pluginBaseUrls !== undefined) {
          each$1(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
            AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
          });
        }
      },
      init: function (settings) {
        var self = this;
        var result;
        var invalidInlineTargets = Tools.makeMap('area base basefont br col frame hr img input isindex link meta param embed source wbr track ' + 'colgroup option table tbody tfoot thead tr th td script noscript style textarea video audio iframe object menu', ' ');
        var isInvalidInlineTarget = function (settings, elm) {
          return settings.inline &amp;&amp; elm.tagName.toLowerCase() in invalidInlineTargets;
        };
        var createId = function (elm) {
          var id = elm.id;
          if (!id) {
            id = get$1(elm, 'name').filter(function (name) {
              return !DOM$a.get(name);
            }).getOrThunk(DOM$a.uniqueId);
            elm.setAttribute('id', id);
          }
          return id;
        };
        var execCallback = function (name) {
          var callback = settings[name];
          if (!callback) {
            return;
          }
          return callback.apply(self, []);
        };
        var hasClass = function (elm, className) {
          return className.constructor === RegExp ? className.test(elm.className) : DOM$a.hasClass(elm, className);
        };
        var findTargets = function (settings) {
          var targets = [];
          if (Env.browser.isIE() &amp;&amp; Env.browser.version.major &lt; 11) {
            initError('TinyMCE does not support the browser you are using. For a list of supported' + ' browsers please see: https://www.tinymce.com/docs/get-started/system-requirements/');
            return [];
          } else if (isQuirksMode) {
            initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
            return [];
          }
          if (settings.types) {
            each$j(settings.types, function (type) {
              targets = targets.concat(DOM$a.select(type.selector));
            });
            return targets;
          } else if (settings.selector) {
            return DOM$a.select(settings.selector);
          } else if (settings.target) {
            return [settings.target];
          }
          switch (settings.mode) {
          case 'exact':
            var l = settings.elements || '';
            if (l.length &gt; 0) {
              each$j(explode$4(l), function (id) {
                var elm = DOM$a.get(id);
                if (elm) {
                  targets.push(elm);
                } else {
                  each$j(document.forms, function (f) {
                    each$j(f.elements, function (e) {
                      if (e.name === id) {
                        id = 'mce_editor_' + instanceCounter++;
                        DOM$a.setAttrib(e, 'id', id);
                        targets.push(e);
                      }
                    });
                  });
                }
              });
            }
            break;
          case 'textareas':
          case 'specific_textareas':
            each$j(DOM$a.select('textarea'), function (elm) {
              if (settings.editor_deselector &amp;&amp; hasClass(elm, settings.editor_deselector)) {
                return;
              }
              if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
                targets.push(elm);
              }
            });
            break;
          }
          return targets;
        };
        var provideResults = function (editors) {
          result = editors;
        };
        var initEditors = function () {
          var initCount = 0;
          var editors = [];
          var targets;
          var createEditor = function (id, settings, targetElm) {
            var editor = new Editor(id, settings, self);
            editors.push(editor);
            editor.on('init', function () {
              if (++initCount === targets.length) {
                provideResults(editors);
              }
            });
            editor.targetElm = editor.targetElm || targetElm;
            editor.render();
          };
          DOM$a.unbind(window, 'ready', initEditors);
          execCallback('onpageload');
          targets = DomQuery.unique(findTargets(settings));
          if (settings.types) {
            each$j(settings.types, function (type) {
              Tools.each(targets, function (elm) {
                if (DOM$a.is(elm, type.selector)) {
                  createEditor(createId(elm), extend$4({}, settings, type), elm);
                  return false;
                }
                return true;
              });
            });
            return;
          }
          Tools.each(targets, function (elm) {
            purgeDestroyedEditor(self.get(elm.id));
          });
          targets = Tools.grep(targets, function (elm) {
            return !self.get(elm.id);
          });
          if (targets.length === 0) {
            provideResults([]);
          } else {
            each$j(targets, function (elm) {
              if (isInvalidInlineTarget(settings, elm)) {
                initError('Could not initialize inline editor on invalid inline target element', elm);
              } else {
                createEditor(createId(elm), settings, elm);
              }
            });
          }
        };
        self.settings = settings;
        DOM$a.bind(window, 'ready', initEditors);
        return new promiseObj(function (resolve) {
          if (result) {
            resolve(result);
          } else {
            provideResults = function (editors) {
              resolve(editors);
            };
          }
        });
      },
      get: function (id) {
        if (arguments.length === 0) {
          return editors.slice(0);
        } else if (isString(id)) {
          return find(editors, function (editor) {
            return editor.id === id;
          }).getOr(null);
        } else if (isNumber(id)) {
          return editors[id] ? editors[id] : null;
        } else {
          return null;
        }
      },
      add: function (editor) {
        var self = this;
        var existingEditor = legacyEditors[editor.id];
        if (existingEditor === editor) {
          return editor;
        }
        if (self.get(editor.id) === null) {
          if (isValidLegacyKey(editor.id)) {
            legacyEditors[editor.id] = editor;
          }
          legacyEditors.push(editor);
          editors.push(editor);
        }
        toggleGlobalEvents(true);
        self.activeEditor = editor;
        self.fire('AddEditor', { editor: editor });
        if (!beforeUnloadDelegate) {
          beforeUnloadDelegate = function (e) {
            var event = self.fire('BeforeUnload');
            if (event.returnValue) {
              e.preventDefault();
              e.returnValue = event.returnValue;
              return event.returnValue;
            }
          };
          window.addEventListener('beforeunload', beforeUnloadDelegate);
        }
        return editor;
      },
      createEditor: function (id, settings) {
        return this.add(new Editor(id, settings, this));
      },
      remove: function (selector) {
        var self = this;
        var i, editor;
        if (!selector) {
          for (i = editors.length - 1; i &gt;= 0; i--) {
            self.remove(editors[i]);
          }
          return;
        }
        if (isString(selector)) {
          each$j(DOM$a.select(selector), function (elm) {
            editor = self.get(elm.id);
            if (editor) {
              self.remove(editor);
            }
          });
          return;
        }
        editor = selector;
        if (isNull(self.get(editor.id))) {
          return null;
        }
        if (removeEditorFromList(editor)) {
          self.fire('RemoveEditor', { editor: editor });
        }
        if (editors.length === 0) {
          window.removeEventListener('beforeunload', beforeUnloadDelegate);
        }
        editor.remove();
        toggleGlobalEvents(editors.length &gt; 0);
        return editor;
      },
      execCommand: function (cmd, ui, value) {
        var self = this, editor = self.get(value);
        switch (cmd) {
        case 'mceAddEditor':
          if (!self.get(value)) {
            new Editor(value, self.settings, self).render();
          }
          return true;
        case 'mceRemoveEditor':
          if (editor) {
            editor.remove();
          }
          return true;
        case 'mceToggleEditor':
          if (!editor) {
            self.execCommand('mceAddEditor', false, value);
            return true;
          }
          if (editor.isHidden()) {
            editor.show();
          } else {
            editor.hide();
          }
          return true;
        }
        if (self.activeEditor) {
          return self.activeEditor.execCommand(cmd, ui, value);
        }
        return false;
      },
      triggerSave: function () {
        each$j(editors, function (editor) {
          editor.save();
        });
      },
      addI18n: function (code, items) {
        I18n.add(code, items);
      },
      translate: function (text) {
        return I18n.translate(text);
      },
      setActive: function (editor) {
        var activeEditor = this.activeEditor;
        if (this.activeEditor !== editor) {
          if (activeEditor) {
            activeEditor.fire('deactivate', { relatedTarget: editor });
          }
          editor.fire('activate', { relatedTarget: activeEditor });
        }
        this.activeEditor = editor;
      },
      _setBaseUrl: function (baseUrl) {
        this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
        this.baseURI = new URI(this.baseURL);
      }
    });
    EditorManager.setup();

    var min = Math.min, max = Math.max, round$1 = Math.round;
    var relativePosition = function (rect, targetRect, rel) {
      var x = targetRect.x;
      var y = targetRect.y;
      var w = rect.w;
      var h = rect.h;
      var targetW = targetRect.w;
      var targetH = targetRect.h;
      var relChars = (rel || '').split('');
      if (relChars[0] === 'b') {
        y += targetH;
      }
      if (relChars[1] === 'r') {
        x += targetW;
      }
      if (relChars[0] === 'c') {
        y += round$1(targetH / 2);
      }
      if (relChars[1] === 'c') {
        x += round$1(targetW / 2);
      }
      if (relChars[3] === 'b') {
        y -= h;
      }
      if (relChars[4] === 'r') {
        x -= w;
      }
      if (relChars[3] === 'c') {
        y -= round$1(h / 2);
      }
      if (relChars[4] === 'c') {
        x -= round$1(w / 2);
      }
      return create$7(x, y, w, h);
    };
    var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
      var pos, i;
      for (i = 0; i &lt; rels.length; i++) {
        pos = relativePosition(rect, targetRect, rels[i]);
        if (pos.x &gt;= constrainRect.x &amp;&amp; pos.x + pos.w &lt;= constrainRect.w + constrainRect.x &amp;&amp; pos.y &gt;= constrainRect.y &amp;&amp; pos.y + pos.h &lt;= constrainRect.h + constrainRect.y) {
          return rels[i];
        }
      }
      return null;
    };
    var inflate = function (rect, w, h) {
      return create$7(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
    };
    var intersect = function (rect, cropRect) {
      var x1 = max(rect.x, cropRect.x);
      var y1 = max(rect.y, cropRect.y);
      var x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
      var y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
      if (x2 - x1 &lt; 0 || y2 - y1 &lt; 0) {
        return null;
      }
      return create$7(x1, y1, x2 - x1, y2 - y1);
    };
    var clamp$1 = function (rect, clampRect, fixedSize) {
      var x1 = rect.x;
      var y1 = rect.y;
      var x2 = rect.x + rect.w;
      var y2 = rect.y + rect.h;
      var cx2 = clampRect.x + clampRect.w;
      var cy2 = clampRect.y + clampRect.h;
      var underflowX1 = max(0, clampRect.x - x1);
      var underflowY1 = max(0, clampRect.y - y1);
      var overflowX2 = max(0, x2 - cx2);
      var overflowY2 = max(0, y2 - cy2);
      x1 += underflowX1;
      y1 += underflowY1;
      if (fixedSize) {
        x2 += underflowX1;
        y2 += underflowY1;
        x1 -= overflowX2;
        y1 -= overflowY2;
      }
      x2 -= overflowX2;
      y2 -= overflowY2;
      return create$7(x1, y1, x2 - x1, y2 - y1);
    };
    var create$7 = function (x, y, w, h) {
      return {
        x: x,
        y: y,
        w: w,
        h: h
      };
    };
    var fromClientRect = function (clientRect) {
      return create$7(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
    };
    var Rect = {
      inflate: inflate,
      relativePosition: relativePosition,
      findBestRelativePosition: findBestRelativePosition,
      intersect: intersect,
      clamp: clamp$1,
      create: create$7,
      fromClientRect: fromClientRect
    };

    var awaiter = function (resolveCb, rejectCb, timeout) {
      if (timeout === void 0) {
        timeout = 1000;
      }
      var done = false;
      var timer = null;
      var complete = function (completer) {
        return function () {
          var args = [];
          for (var _i = 0; _i &lt; arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          if (!done) {
            done = true;
            if (timer !== null) {
              clearTimeout(timer);
              timer = null;
            }
            completer.apply(null, args);
          }
        };
      };
      var resolve = complete(resolveCb);
      var reject = complete(rejectCb);
      var start = function () {
        var args = [];
        for (var _i = 0; _i &lt; arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        if (!done &amp;&amp; timer === null) {
          timer = setTimeout(function () {
            return reject.apply(null, args);
          }, timeout);
        }
      };
      return {
        start: start,
        resolve: resolve,
        reject: reject
      };
    };
    var create$8 = function () {
      var tasks = {};
      var resultFns = {};
      var load = function (id, url) {
        var loadErrMsg = 'Script at URL "' + url + '" failed to load';
        var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
        if (tasks[id] !== undefined) {
          return tasks[id];
        } else {
          var task = new promiseObj(function (resolve, reject) {
            var waiter = awaiter(resolve, reject);
            resultFns[id] = waiter.resolve;
            ScriptLoader.ScriptLoader.loadScript(url, function () {
              return waiter.start(runErrMsg);
            }, function () {
              return waiter.reject(loadErrMsg);
            });
          });
          tasks[id] = task;
          return task;
        }
      };
      var add = function (id, data) {
        if (resultFns[id] !== undefined) {
          resultFns[id](data);
          delete resultFns[id];
        }
        tasks[id] = promiseObj.resolve(data);
      };
      return {
        load: load,
        add: add
      };
    };
    var Resource = create$8();

    var each$k = Tools.each, extend$5 = Tools.extend;
    var extendClass, initializing;
    var Class = function () {
    };
    Class.extend = extendClass = function (props) {
      var self = this;
      var _super = self.prototype;
      var Class = function () {
        var i, mixins, mixin;
        var self = this;
        if (!initializing) {
          if (self.init) {
            self.init.apply(self, arguments);
          }
          mixins = self.Mixins;
          if (mixins) {
            i = mixins.length;
            while (i--) {
              mixin = mixins[i];
              if (mixin.init) {
                mixin.init.apply(self, arguments);
              }
            }
          }
        }
      };
      var dummy = function () {
        return this;
      };
      var createMethod = function (name, fn) {
        return function () {
          var self = this;
          var tmp = self._super;
          self._super = _super[name];
          var ret = fn.apply(self, arguments);
          self._super = tmp;
          return ret;
        };
      };
      initializing = true;
      var prototype = new self();
      initializing = false;
      if (props.Mixins) {
        each$k(props.Mixins, function (mixin) {
          for (var name_1 in mixin) {
            if (name_1 !== 'init') {
              props[name_1] = mixin[name_1];
            }
          }
        });
        if (_super.Mixins) {
          props.Mixins = _super.Mixins.concat(props.Mixins);
        }
      }
      if (props.Methods) {
        each$k(props.Methods.split(','), function (name) {
          props[name] = dummy;
        });
      }
      if (props.Properties) {
        each$k(props.Properties.split(','), function (name) {
          var fieldName = '_' + name;
          props[name] = function (value) {
            var self = this;
            if (value !== undefined) {
              self[fieldName] = value;
              return self;
            }
            return self[fieldName];
          };
        });
      }
      if (props.Statics) {
        each$k(props.Statics, function (func, name) {
          Class[name] = func;
        });
      }
      if (props.Defaults &amp;&amp; _super.Defaults) {
        props.Defaults = extend$5({}, _super.Defaults, props.Defaults);
      }
      each$1(props, function (member, name) {
        if (typeof member === 'function' &amp;&amp; _super[name]) {
          prototype[name] = createMethod(name, member);
        } else {
          prototype[name] = member;
        }
      });
      Class.prototype = prototype;
      Class.constructor = Class;
      Class.extend = extendClass;
      return Class;
    };

    var min$1 = Math.min, max$1 = Math.max, round$2 = Math.round;
    var Color = function (value) {
      var self = {};
      var r = 0, g = 0, b = 0;
      var rgb2hsv = function (r, g, b) {
        var h, s, v;
        h = 0;
        s = 0;
        v = 0;
        r = r / 255;
        g = g / 255;
        b = b / 255;
        var minRGB = min$1(r, min$1(g, b));
        var maxRGB = max$1(r, max$1(g, b));
        if (minRGB === maxRGB) {
          v = minRGB;
          return {
            h: 0,
            s: 0,
            v: v * 100
          };
        }
        var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
        h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
        h = 60 * (h - d / (maxRGB - minRGB));
        s = (maxRGB - minRGB) / maxRGB;
        v = maxRGB;
        return {
          h: round$2(h),
          s: round$2(s * 100),
          v: round$2(v * 100)
        };
      };
      var hsvToRgb = function (hue, saturation, brightness) {
        hue = (parseInt(hue, 10) || 0) % 360;
        saturation = parseInt(saturation, 10) / 100;
        brightness = parseInt(brightness, 10) / 100;
        saturation = max$1(0, min$1(saturation, 1));
        brightness = max$1(0, min$1(brightness, 1));
        if (saturation === 0) {
          r = g = b = round$2(255 * brightness);
          return;
        }
        var side = hue / 60;
        var chroma = brightness * saturation;
        var x = chroma * (1 - Math.abs(side % 2 - 1));
        var match = brightness - chroma;
        switch (Math.floor(side)) {
        case 0:
          r = chroma;
          g = x;
          b = 0;
          break;
        case 1:
          r = x;
          g = chroma;
          b = 0;
          break;
        case 2:
          r = 0;
          g = chroma;
          b = x;
          break;
        case 3:
          r = 0;
          g = x;
          b = chroma;
          break;
        case 4:
          r = x;
          g = 0;
          b = chroma;
          break;
        case 5:
          r = chroma;
          g = 0;
          b = x;
          break;
        default:
          r = g = b = 0;
        }
        r = round$2(255 * (r + match));
        g = round$2(255 * (g + match));
        b = round$2(255 * (b + match));
      };
      var toHex = function () {
        var hex = function (val) {
          val = parseInt(val, 10).toString(16);
          return val.length &gt; 1 ? val : '0' + val;
        };
        return '#' + hex(r) + hex(g) + hex(b);
      };
      var toRgb = function () {
        return {
          r: r,
          g: g,
          b: b
        };
      };
      var toHsv = function () {
        return rgb2hsv(r, g, b);
      };
      var parse = function (value) {
        var matches;
        if (typeof value === 'object') {
          if ('r' in value) {
            r = value.r;
            g = value.g;
            b = value.b;
          } else if ('v' in value) {
            hsvToRgb(value.h, value.s, value.v);
          }
        } else {
          if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
            r = parseInt(matches[1], 10);
            g = parseInt(matches[2], 10);
            b = parseInt(matches[3], 10);
          } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
            r = parseInt(matches[1], 16);
            g = parseInt(matches[2], 16);
            b = parseInt(matches[3], 16);
          } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
            r = parseInt(matches[1] + matches[1], 16);
            g = parseInt(matches[2] + matches[2], 16);
            b = parseInt(matches[3] + matches[3], 16);
          }
        }
        r = r &lt; 0 ? 0 : r &gt; 255 ? 255 : r;
        g = g &lt; 0 ? 0 : g &gt; 255 ? 255 : g;
        b = b &lt; 0 ? 0 : b &gt; 255 ? 255 : b;
        return self;
      };
      if (value) {
        parse(value);
      }
      self.toRgb = toRgb;
      self.toHsv = toHsv;
      self.toHex = toHex;
      self.parse = parse;
      return self;
    };

    var serialize = function (obj) {
      var data = JSON.stringify(obj);
      if (!isString(data)) {
        return data;
      }
      return data.replace(/[\u0080-\uFFFF]/g, function (match) {
        var hexCode = match.charCodeAt(0).toString(16);
        return '\\u' + '0000'.substring(hexCode.length) + hexCode;
      });
    };
    var JSONUtils = {
      serialize: serialize,
      parse: function (text) {
        try {
          return JSON.parse(text);
        } catch (ex) {
        }
      }
    };

    var JSONP = {
      callbacks: {},
      count: 0,
      send: function (settings) {
        var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
        var id = 'tinymce_jsonp_' + count;
        self.callbacks[count] = function (json) {
          dom.remove(id);
          delete self.callbacks[count];
          settings.callback(json);
        };
        dom.add(dom.doc.body, 'script', {
          id: id,
          src: settings.url,
          type: 'text/javascript'
        });
        self.count++;
      }
    };

    var XHR = __assign(__assign({}, Observable), {
      send: function (settings) {
        var xhr, count = 0;
        var ready = function () {
          if (!settings.async || xhr.readyState === 4 || count++ &gt; 10000) {
            if (settings.success &amp;&amp; count &lt; 10000 &amp;&amp; xhr.status === 200) {
              settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
            } else if (settings.error) {
              settings.error.call(settings.error_scope, count &gt; 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
            }
            xhr = null;
          } else {
            Delay.setTimeout(ready, 10);
          }
        };
        settings.scope = settings.scope || this;
        settings.success_scope = settings.success_scope || settings.scope;
        settings.error_scope = settings.error_scope || settings.scope;
        settings.async = settings.async !== false;
        settings.data = settings.data || '';
        XHR.fire('beforeInitialize', { settings: settings });
        xhr = new XMLHttpRequest();
        if (xhr.overrideMimeType) {
          xhr.overrideMimeType(settings.content_type);
        }
        xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
        if (settings.crossDomain) {
          xhr.withCredentials = true;
        }
        if (settings.content_type) {
          xhr.setRequestHeader('Content-Type', settings.content_type);
        }
        if (settings.requestheaders) {
          Tools.each(settings.requestheaders, function (header) {
            xhr.setRequestHeader(header.key, header.value);
          });
        }
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr = XHR.fire('beforeSend', {
          xhr: xhr,
          settings: settings
        }).xhr;
        xhr.send(settings.data);
        if (!settings.async) {
          return ready();
        }
        Delay.setTimeout(ready, 10);
      }
    });

    var extend$6 = Tools.extend;
    var JSONRequest = function () {
      function JSONRequest(settings) {
        this.settings = extend$6({}, settings);
        this.count = 0;
      }
      JSONRequest.sendRPC = function (o) {
        return new JSONRequest().send(o);
      };
      JSONRequest.prototype.send = function (args) {
        var ecb = args.error, scb = args.success;
        var xhrArgs = extend$6(this.settings, args);
        xhrArgs.success = function (c, x) {
          c = JSONUtils.parse(c);
          if (typeof c === 'undefined') {
            c = { error: 'JSON Parse error.' };
          }
          if (c.error) {
            ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
          } else {
            scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
          }
        };
        xhrArgs.error = function (ty, x) {
          if (ecb) {
            ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
          }
        };
        xhrArgs.data = JSONUtils.serialize({
          id: args.id || 'c' + this.count++,
          method: args.method,
          params: args.params
        });
        xhrArgs.content_type = 'application/json';
        XHR.send(xhrArgs);
      };
      return JSONRequest;
    }();

    var create$9 = function () {
      return function () {
        var data = {};
        var keys = [];
        var storage = {
          getItem: function (key) {
            var item = data[key];
            return item ? item : null;
          },
          setItem: function (key, value) {
            keys.push(key);
            data[key] = String(value);
          },
          key: function (index) {
            return keys[index];
          },
          removeItem: function (key) {
            keys = keys.filter(function (k) {
              return k === key;
            });
            delete data[key];
          },
          clear: function () {
            keys = [];
            data = {};
          },
          length: 0
        };
        Object.defineProperty(storage, 'length', {
          get: function () {
            return keys.length;
          },
          configurable: false,
          enumerable: false
        });
        return storage;
      }();
    };

    var localStorage;
    try {
      var test = '__storage_test__';
      localStorage = window.localStorage;
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
    } catch (e) {
      localStorage = create$9();
    }
    var LocalStorage = localStorage;

    var publicApi = {
      geom: { Rect: Rect },
      util: {
        Promise: promiseObj,
        Delay: Delay,
        Tools: Tools,
        VK: VK,
        URI: URI,
        Class: Class,
        EventDispatcher: EventDispatcher,
        Observable: Observable,
        I18n: I18n,
        XHR: XHR,
        JSON: JSONUtils,
        JSONRequest: JSONRequest,
        JSONP: JSONP,
        LocalStorage: LocalStorage,
        Color: Color,
        ImageUploader: ImageUploader
      },
      dom: {
        EventUtils: EventUtils,
        Sizzle: Sizzle,
        DomQuery: DomQuery,
        TreeWalker: DomTreeWalker,
        TextSeeker: TextSeeker,
        DOMUtils: DOMUtils,
        ScriptLoader: ScriptLoader,
        RangeUtils: RangeUtils,
        Serializer: DomSerializer,
        StyleSheetLoader: StyleSheetLoader,
        ControlSelection: ControlSelection,
        BookmarkManager: BookmarkManager,
        Selection: EditorSelection,
        Event: EventUtils.Event
      },
      html: {
        Styles: Styles,
        Entities: Entities,
        Node: AstNode,
        Schema: Schema,
        SaxParser: SaxParser,
        DomParser: DomParser,
        Writer: Writer,
        Serializer: HtmlSerializer
      },
      Env: Env,
      AddOnManager: AddOnManager,
      Annotator: Annotator,
      Formatter: Formatter,
      UndoManager: UndoManager,
      EditorCommands: EditorCommands,
      WindowManager: WindowManager,
      NotificationManager: NotificationManager,
      EditorObservable: EditorObservable,
      Shortcuts: Shortcuts,
      Editor: Editor,
      FocusManager: FocusManager,
      EditorManager: EditorManager,
      DOM: DOMUtils.DOM,
      ScriptLoader: ScriptLoader.ScriptLoader,
      PluginManager: PluginManager,
      ThemeManager: ThemeManager,
      IconManager: IconManager,
      Resource: Resource,
      trim: Tools.trim,
      isArray: Tools.isArray,
      is: Tools.is,
      toArray: Tools.toArray,
      makeMap: Tools.makeMap,
      each: Tools.each,
      map: Tools.map,
      grep: Tools.grep,
      inArray: Tools.inArray,
      extend: Tools.extend,
      create: Tools.create,
      walk: Tools.walk,
      createNS: Tools.createNS,
      resolve: Tools.resolve,
      explode: Tools.explode,
      _addCacheSuffix: Tools._addCacheSuffix,
      isOpera: Env.opera,
      isWebKit: Env.webkit,
      isIE: Env.ie,
      isGecko: Env.gecko,
      isMac: Env.mac
    };
    var tinymce = Tools.extend(EditorManager, publicApi);

    var exportToModuleLoaders = function (tinymce) {
      if (typeof module === 'object') {
        try {
          module.exports = tinymce;
        } catch (_) {
        }
      }
    };
    var exportToWindowGlobal = function (tinymce) {
      window.tinymce = tinymce;
      window.tinyMCE = tinymce;
    };
    exportToWindowGlobal(tinymce);
    exportToModuleLoaders(tinymce);

}());
//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters &amp; Editors
//     Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i&gt;=0&amp;&amp;o&gt;i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&amp;&amp;m.keys(r),a=(o||r).length,c=n&gt;0?0:a-1;return arguments.length&lt;3&amp;&amp;(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n&gt;0?0:u-1;i&gt;=0&amp;&amp;u&gt;i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n&gt;0?o=i&gt;=0?i:Math.max(i+a,o):a=i&gt;=0?Math.min(i+1,a):i+a+1;else if(r&amp;&amp;i&amp;&amp;a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i&gt;=0?i+o:-1;for(i=n&gt;0?o:a-1;i&gt;=0&amp;&amp;a&gt;i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&amp;&amp;e.prototype||a,i="constructor";for(m.has(n,i)&amp;&amp;!m.contains(t,i)&amp;&amp;t.push(i);r--;)i=I[r],i in n&amp;&amp;n[i]!==u[i]&amp;&amp;!m.contains(t,i)&amp;&amp;t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&amp;&amp;module.exports&amp;&amp;(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2&gt;e||null==r)return r;for(var u=1;e&gt;u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a&gt;c;c++){var f=o[c];t&amp;&amp;r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&amp;&amp;t&gt;=0&amp;&amp;A&gt;=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u&gt;e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u&gt;e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&amp;&amp;m.keys(n),u=(e||n).length,i=Array(u),o=0;u&gt;o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&amp;&amp;e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&amp;&amp;e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&amp;&amp;m.keys(n),u=(e||n).length,i=0;u&gt;i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&amp;&amp;m.keys(n),u=(e||n).length,i=0;u&gt;i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&amp;&amp;(r=0),m.indexOf(n,t,r)&gt;=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&amp;&amp;null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c&gt;a;a++)e=n[a],e&gt;i&amp;&amp;(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u&gt;o||u===-1/0&amp;&amp;i===-1/0)&amp;&amp;(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&amp;&amp;null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c&gt;a;a++)e=n[a],i&gt;e&amp;&amp;(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o&gt;u||1/0===u&amp;&amp;1/0===i)&amp;&amp;(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e&gt;i;i++)t=m.random(0,i),t!==i&amp;&amp;(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r&gt;e||r===void 0)return 1;if(e&gt;r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a&gt;o;o++){var c=n[o];if(k(c)&amp;&amp;(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l&gt;f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&amp;&amp;(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a&gt;o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&amp;&amp;i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u&gt;e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r&gt;o&amp;&amp;m.contains(arguments[o],i);o++);o===r&amp;&amp;t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&amp;&amp;m.max(n,O).length||0,r=Array(t),e=0;t&gt;e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u&gt;e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o&gt;i;){var a=Math.floor((i+o)/2);r(n[a])&lt;u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&amp;&amp;(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e&gt;i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&amp;&amp;n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u&gt;o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e&lt;arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1&gt;=e)throw new Error("bindAll must be passed function names");for(t=1;e&gt;t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0&gt;=l||l&gt;t?(o&amp;&amp;(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t&gt;f&amp;&amp;f&gt;=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&amp;&amp;!e;return e||(e=setTimeout(c,t)),f&amp;&amp;(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n&lt;1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n&gt;0&amp;&amp;(r=t.apply(this,arguments)),1&gt;=n&amp;&amp;(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&amp;&amp;t.push(r);return M&amp;&amp;e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&amp;&amp;e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r&gt;u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i&gt;a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r&gt;u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u&gt;e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&amp;&amp;t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o&gt;i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c&gt;a;a++){var f=u[a],l=o[f];e(l,f,o)&amp;&amp;(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&amp;&amp;m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e&gt;i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&amp;&amp;(n=n._wrapped),t instanceof m&amp;&amp;(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&amp;&amp;!(m.isFunction(o)&amp;&amp;o instanceof o&amp;&amp;m.isFunction(a)&amp;&amp;a instanceof a)&amp;&amp;"constructor"in n&amp;&amp;"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&amp;&amp;(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&amp;&amp;!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&amp;&amp;"object"!=typeof Int8Array&amp;&amp;(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&amp;&amp;!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&amp;&amp;n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&amp;&amp;p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n&gt;u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&amp;&amp;(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&amp;":"&amp;amp;","&lt;":"&amp;lt;","&gt;":"&amp;gt;",'"':"&amp;quot;","'":"&amp;#x27;","`":"&amp;#x60;"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&amp;&amp;(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/&lt;%([\s\S]+?)%&gt;/g,interpolate:/&lt;%=([\s\S]+?)%&gt;/g,escape:/&lt;%-([\s\S]+?)%&gt;/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&amp;&amp;r&amp;&amp;(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&amp;&amp;(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&amp;&amp;"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&amp;&amp;define.amd&amp;&amp;define("underscore",[],function(){return m})}).call(this);
/*!
 * JSON API Serializer 3.6.7
 * https://github.com/SeyZ/jsonapi-serializer
 *
 * Copyright (c) 2015 Sandro Munda
 * Released under the MIT license
 */
require=function(){return function e(t,r,n){function i(o,s){if(!r[o]){if(!t[o]){var u="function"==typeof require&amp;&amp;require;if(!s&amp;&amp;u)return u(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[o]={exports:{}};t[o][0].call(l.exports,function(e){return i(t[o][1][e]||e)},l,l.exports,e,t,r,n)}return r[o].exports}for(var a="function"==typeof require&amp;&amp;require,o=0;o&lt;n.length;o++)i(n[o]);return i}}()({1:[function(e,t,r){"use strict";var n=e("lodash/isPlainObject"),i=e("lodash/isFunction"),a=e("lodash/find"),o=e("lodash/extend"),s=e("lodash/transform"),u=e("./inflector");t.exports=function(e,t,r){function c(e){return Array.isArray(e)||n(e)}function l(e){return n(e)?s(e,function(e,t,r){c(t)?e[l(r)]=l(t):e[l(r)]=t}):Array.isArray(e)?e.map(function(e){return c(e)?l(e):e}):i(r.keyForAttribute)?r.keyForAttribute(e):u.caserize(e,r)}function f(e){var t=l(e.attributes||{});return"id"in e&amp;&amp;(t[r.id||"id"]=e.id),r.typeAsAttribute&amp;&amp;"type"in e&amp;&amp;(t.type=e.type),"meta"in e&amp;&amp;(t.meta=l(e.meta||{})),t}function p(e,t){if(e.relationships){var r={};return Promise.all(Object.keys(e.relationships).map(function(n){var i=e.relationships[n];if(null!==i.data)return Array.isArray(i.data)?Promise.all(i.data.map(function(e){return _(e,t)})).then(function(e){e&amp;&amp;(r[l(n)]=e)}):_(i.data,t).then(function(e){e&amp;&amp;(r[l(n)]=e)});r[l(n)]=null})).then(function(){return r})}}function _(t,n){return function(t,r){return new Promise(function(n){e.included&amp;&amp;t||n(null);var i=a(e.included,{id:t.id,type:t.type});return i?r.indexOf(i.type)&gt;-1?Promise.all([f(i)]).then(function(e){var t=e[0],r=e[1];n(o(t,r))}):Promise.all([f(i),p(i,r+":"+i.type+i.id)]).then(function(e){var t=e[0],r=e[1];n(o(t,r))}):n(null)})}(t,n).then(function(e){var n=function(e,t){return r&amp;&amp;e&amp;&amp;r[e.type]?(0,r[e.type].valueForRelationship)(e,t):t}(t,e);return n&amp;&amp;i(n.then)?n.then(function(e){return e}):n})}this.perform=function(){return Promise.all([f(t),p(t,t.type+t.id)]).then(function(t){var n=t[0],i=t[1],a=o(n,i);return e.links&amp;&amp;(a.links=e.links),r&amp;&amp;r.transform&amp;&amp;(a=r.transform(a)),a})}}},{"./inflector":5,"lodash/extend":158,"lodash/find":159,"lodash/isFunction":171,"lodash/isPlainObject":176,"lodash/transform":195}],2:[function(e,t,r){"use strict";var n=e("lodash/isFunction"),i=e("./deserializer-utils");t.exports=function(e){e||(e={}),this.deserialize=function(t,r){return Array.isArray(t.data)?Promise.all(t.data.map(function(r){return new i(t,r,e).perform()})).then(function(e){return n(r)&amp;&amp;r(null,e),e}):new i(t,t.data,e).perform().then(function(e){return n(r)&amp;&amp;r(null,e),e})}}},{"./deserializer-utils":1,"lodash/isFunction":171}],3:[function(e,t,r){"use strict";t.exports=function(e){var t={errors:[]};return e.forEach(function(e){var r={};e.id&amp;&amp;(r.id=e.id),e.status&amp;&amp;(r.status=e.status),e.code&amp;&amp;(r.code=e.code),e.title&amp;&amp;(r.title=e.title),e.detail&amp;&amp;(r.detail=e.detail),e.source&amp;&amp;(r.source={},e.source.pointer&amp;&amp;(r.source.pointer=e.source.pointer),e.source.parameter&amp;&amp;(r.source.parameter=e.source.parameter)),e.links&amp;&amp;(r.links={about:e.links.about}),e.meta&amp;&amp;(r.meta=e.meta),t.errors.push(r)}),t}},{}],4:[function(e,t,r){"use strict";var n=e("./error-utils");t.exports=function(e){return e||(e=[]),Array.isArray(e)?new n(e):new n([e])}},{"./error-utils":3}],5:[function(e,t,r){"use strict";var n=e("inflected");t.exports={caserize:function(e,t){switch(e=n.underscore(e),t.keyForAttribute){case"dash-case":case"lisp-case":case"spinal-case":case"kebab-case":return n.dasherize(e);case"underscore_case":case"snake_case":return e;case"CamelCase":return n.camelize(e);case"camelCase":return n.camelize(e,!1);default:return n.dasherize(e)}},pluralize:function(e){return n.pluralize(e)}}},{inflected:8}],6:[function(e,t,r){"use strict";var n=e("lodash/isPlainObject"),i=e("lodash/isFunction"),a=e("lodash/find"),o=e("lodash/merge"),s=e("lodash/identity"),u=e("lodash/transform"),c=e("lodash/mapValues"),l=e("lodash/mapKeys"),f=e("lodash/pick"),p=e("lodash/pickBy"),_=(e("lodash/keys"),e("lodash/each")),h=e("lodash/isNil"),y=e("./inflector");t.exports=function(e,t,r,v){function b(e){return Array.isArray(e)||n(e)}function d(e){return n(e)?u(e,function(e,t,r){b(t)?e[d(r)]=d(t):e[d(r)]=t}):Array.isArray(e)?e.map(function(e){return b(e)?d(e):e}):i(v.keyForAttribute)?v.keyForAttribute(e):y.caserize(e,v)}function g(){return v.id||"id"}function x(e,t){var r;return t=t||{},i(v.typeForAttribute)&amp;&amp;(r=v.typeForAttribute(e,t)),void 0!==v.pluralizeType&amp;&amp;!v.pluralizeType||void 0!==r||(r=y.pluralize(e)),void 0===r&amp;&amp;(r=e),r}function m(e,r,n){return c(r,function(r){return i(r)?r(t,e,n):r})}function A(e,r){return i(r)?r(t):c(r,function(r){return i(r)?r(t,e):r})}function j(e,t){return l(f(e,t),function(e,t){return d(t)})}function O(e,t){var n,i=(n=t,a(r.included,{id:n.id,type:n.type}));i?(i.relationships=o(i.relationships,p(t.relationships,s)),i.attributes=o(i.attributes,p(t.attributes,s))):(e.included||(e.included=[]),e.included.push(t))}this.serialize=function(e,t,r,i){var a=this,o=null;if(i&amp;&amp;i.ref){if(e.relationships||(e.relationships={}),o=Array.isArray(t[r])?t[r].map(function(e){return a.serializeRef(e,t,r,i)}):a.serializeRef(t[r],t,r,i),e.relationships[d(r)]={},i.ignoreRelationshipData||(e.relationships[d(r)].data=o),i.relationshipLinks){var s=m(t[r],i.relationshipLinks,e);s.related&amp;&amp;(e.relationships[d(r)].links=s)}i.relationshipMeta&amp;&amp;(e.relationships[d(r)].meta=A(t[r],i.relationshipMeta))}else Array.isArray(t[r])?(o=t[r].length&amp;&amp;n(t[r][0])?t[r].map(function(e){return a.serializeNested(e,t,r,i)}):t[r],e.attributes[d(r)]=o):n(t[r])?(o=a.serializeNested(t[r],t,r,i),e.attributes[d(r)]=o):e.attributes[d(r)]=t[r]},this.serializeRef=function(e,t,n,a){var o=this,s=function(e,t,r){if(i(r.ref))return r.ref(e,t);if(!0===r.ref){if(Array.isArray(t))return t.map(function(e){return String(e)});if(t)return String(t)}else if(t&amp;&amp;t[r.ref])return String(t[r.ref])}(t,e,a),u=x(n,e),c=[],l=[];a.attributes&amp;&amp;(e&amp;&amp;a.attributes.forEach(function(t){a[t]&amp;&amp;!e[t]&amp;&amp;a[t].nullIfMissing&amp;&amp;(e[t]=null)}),c=a.attributes.filter(function(e){return a[e]}),l=a.attributes.filter(function(e){return!a[e]}));var f={type:u,id:s};return l&amp;&amp;(f.attributes=j(e,l)),c.forEach(function(t){e&amp;&amp;(b(e[t])||null===e[t])&amp;&amp;o.serialize(f,e,t,a[t])}),l.length&amp;&amp;(void 0===a.included||a.included)&amp;&amp;(a.includedLinks&amp;&amp;(f.links=m(e,a.includedLinks)),void 0!==s&amp;&amp;O(r,f)),void 0!==s?{type:u,id:s}:null},this.serializeNested=function(e,t,r,n){var i=this,a=[],o=[],s={};return n&amp;&amp;n.attributes?(a=n.attributes.filter(function(e){return n[e]}),(o=n.attributes.filter(function(e){return!n[e]}))&amp;&amp;(s.attributes=j(e,o)),a.forEach(function(t){b(e[t])&amp;&amp;i.serialize(s,e,t,n[t])})):s.attributes=e,s.attributes},this.perform=function(){var r=this;if(null===t)return null;v&amp;&amp;v.transform&amp;&amp;(t=v.transform(t));var n={type:x(e,t)};return h(t[g()])||(n.id=String(t[g()])),v.dataLinks&amp;&amp;(n.links=m(t,v.dataLinks)),v.dataMeta&amp;&amp;(n.meta=A(t,v.dataMeta)),_(v.attributes,function(e){var i=e.split(":");if(v[e]&amp;&amp;!t[e]&amp;&amp;v[e].nullIfMissing&amp;&amp;(t[e]=null),i[0]in t){n.attributes||(n.attributes={});var a=e;i.length&gt;1&amp;&amp;(e=i[0],a=i[1]),r.serialize(n,t,e,v[a])}}),n}}},{"./inflector":5,"lodash/each":156,"lodash/find":159,"lodash/identity":165,"lodash/isFunction":171,"lodash/isNil":173,"lodash/isPlainObject":176,"lodash/keys":179,"lodash/mapKeys":181,"lodash/mapValues":182,"lodash/merge":184,"lodash/pick":185,"lodash/pickBy":186,"lodash/transform":195}],7:[function(e,t,r){"use strict";var n=e("lodash/isFunction"),i=e("lodash/mapValues"),a=e("./serializer-utils");t.exports=function(e,t,r){if(this.serialize=function(e){var t,r=this,o={};return r.opts.topLevelLinks&amp;&amp;(o.links=(t=r.opts.topLevelLinks,i(t,function(t){return n(t)?t(e):t}))),r.opts.meta&amp;&amp;(o.meta=i(r.opts.meta,function(t){return n(t)?t(e):t})),Array.isArray(e)?(o.data=[],e.forEach(function(e){var t=new a(r.collectionName,e,o,r.opts);o.data.push(t.perform())}),o):(o.data=new a(r.collectionName,e,o,r.opts).perform(e),o)},3===arguments.length)return this.collectionName=e,this.opts=r,this.serialize(t);this.collectionName=e,this.opts=t}},{"./serializer-utils":6,"lodash/isFunction":171,"lodash/mapValues":182}],8:[function(e,t,r){"use strict";t.exports=e("./lib/Inflector")},{"./lib/Inflector":10}],9:[function(e,t,r){(function(r,n){"use strict";var i=e("./hasProp"),a=e("./remove"),o=e("./icPart");function s(){this.plurals=[],this.singulars=[],this.uncountables=[],this.humans=[],this.acronyms={},this.acronymRegex=/(?=a)b/}s.getInstance=function(e){var t=void 0!==r?r:n;return t.__Inflector_Inflections=t.__Inflector_Inflections||{},t.__Inflector_Inflections[e]=t.__Inflector_Inflections[e]||new s,t.__Inflector_Inflections[e]},s.prototype.acronym=function(e){this.acronyms[e.toLowerCase()]=e;var t=[];for(var r in this.acronyms)i(this.acronyms,r)&amp;&amp;t.push(this.acronyms[r]);this.acronymRegex=new RegExp(t.join("|"))},s.prototype.plural=function(e,t){"string"==typeof e&amp;&amp;a(this.uncountables,e),a(this.uncountables,t),this.plurals.unshift([e,t])},s.prototype.singular=function(e,t){"string"==typeof e&amp;&amp;a(this.uncountables,e),a(this.uncountables,t),this.singulars.unshift([e,t])},s.prototype.irregular=function(e,t){a(this.uncountables,e),a(this.uncountables,t);var r=e[0],n=e.substr(1),i=t[0],s=t.substr(1);if(r.toUpperCase()===i.toUpperCase())this.plural(new RegExp("("+r+")"+n+"$","i"),"$1"+s),this.plural(new RegExp("("+i+")"+s+"$","i"),"$1"+s),this.singular(new RegExp("("+r+")"+n+"$","i"),"$1"+n),this.singular(new RegExp("("+i+")"+s+"$","i"),"$1"+n);else{var u=o(n),c=o(s);this.plural(new RegExp(r.toUpperCase()+u+"$"),i.toUpperCase()+s),this.plural(new RegExp(r.toLowerCase()+u+"$"),i.toLowerCase()+s),this.plural(new RegExp(i.toUpperCase()+c+"$"),i.toUpperCase()+s),this.plural(new RegExp(i.toLowerCase()+c+"$"),i.toLowerCase()+s),this.singular(new RegExp(r.toUpperCase()+u+"$"),r.toUpperCase()+n),this.singular(new RegExp(r.toLowerCase()+u+"$"),r.toLowerCase()+n),this.singular(new RegExp(i.toUpperCase()+c+"$"),r.toUpperCase()+n),this.singular(new RegExp(i.toLowerCase()+c+"$"),r.toLowerCase()+n)}},s.prototype.uncountable=function(){var e=Array.prototype.slice.call(arguments,0);this.uncountables=this.uncountables.concat(e)},s.prototype.human=function(e,t){this.humans.unshift([e,t])},s.prototype.clear=function(e){"all"===(e=e||"all")?(this.plurals=[],this.singulars=[],this.uncountables=[],this.humans=[]):this[e]=[]},t.exports=s}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./hasProp":14,"./icPart":15,"./remove":17,_process:196}],10:[function(e,t,r){"use strict";var n=e("./Inflections"),i=e("./Transliterator"),a=e("./Methods"),o=e("./defaults"),s=e("./isFunc"),u=a;for(var c in u.inflections=function(e,t){if(s(e)&amp;&amp;(t=e,e=null),e=e||"en",!t)return n.getInstance(e);t(n.getInstance(e))},u.transliterations=function(e,t){if(s(e)&amp;&amp;(t=e,e=null),e=e||"en",!t)return i.getInstance(e);t(i.getInstance(e))},o)u.inflections(c,o[c]);t.exports=u},{"./Inflections":9,"./Methods":11,"./Transliterator":12,"./defaults":13,"./isFunc":16}],11:[function(e,t,r){"use strict";var n={pluralize:function(e,t){return t=t||"en",this._applyInflections(e,this.inflections(t).plurals)},singularize:function(e,t){return t=t||"en",this._applyInflections(e,this.inflections(t).singulars)},camelize:function(e,t){null==t&amp;&amp;(t=!0);var r=""+e,n=this;return r=(r=t?r.replace(/^[a-z\d]*/,function(e){return n.inflections().acronyms[e]||n.capitalize(e)}):r.replace(new RegExp("^(?:"+this.inflections().acronymRegex.source+"(?=\\b|[A-Z_])|\\w)"),function(e){return e.toLowerCase()})).replace(/(?:_|(\/))([a-z\d]*)/gi,function(e,t,r,i,a){return t||(t=""),""+t+(n.inflections().acronyms[r]||n.capitalize(r))})},underscore:function(e){var t=""+e;return(t=(t=(t=(t=t.replace(new RegExp("(?:([A-Za-z\\d])|^)("+this.inflections().acronymRegex.source+")(?=\\b|[^a-z])","g"),function(e,t,r){return(t||"")+(t?"_":"")+r.toLowerCase()})).replace(/([A-Z\d]+)([A-Z][a-z])/g,"$1_$2")).replace(/([a-z\d])([A-Z])/g,"$1_$2")).replace(/-/g,"_")).toLowerCase()},humanize:function(e,t){var r,n,i,a=""+e,o=this.inflections().humans,s=this;null!==(t=t||{}).capitalize&amp;&amp;void 0!==t.capitalize||(t.capitalize=!0);for(var u=0,c=o.length;u&lt;c;u++)if(n=(r=o[u])[0],i=r[1],n.test&amp;&amp;n.test(a)||a.indexOf(n)&gt;-1){a=a.replace(n,i);break}return a=(a=(a=a.replace(/_id$/,"")).replace(/_/g," ")).replace(/([a-z\d]*)/gi,function(e){return s.inflections().acronyms[e]||e.toLowerCase()}),t.capitalize&amp;&amp;(a=a.replace(/^\w/,function(e){return e.toUpperCase()})),a},capitalize:function(e){var t=null==e?"":String(e);return t.charAt(0).toUpperCase()+t.slice(1)},titleize:function(e){return this.humanize(this.underscore(e)).replace(/(^|[\sÂ¿\/]+)([a-z])/g,function(e,t,r,n,i){return e.replace(r,r.toUpperCase())})},tableize:function(e){return this.pluralize(this.underscore(e))},classify:function(e){return this.camelize(this.singularize(e.replace(/.*\./g,"")))},dasherize:function(e){return e.replace(/_/g,"-")},foreignKey:function(e,t){return null==t&amp;&amp;(t=!0),this.underscore(e)+(t?"_id":"id")},ordinal:function(e){var t=Math.abs(Number(e)),r=t%100;if(11===r||12===r||13===r)return"th";switch(t%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},ordinalize:function(e){return""+e+this.ordinal(e)},transliterate:function(e,t){var r=(t=t||{}).locale||"en",n=t.replacement||"?";return this.transliterations(r).transliterate(e,n)},parameterize:function(e,t){void 0===(t=t||{}).separator&amp;&amp;(t.separator="-"),null===t.separator&amp;&amp;(t.separator="");var r=this.transliterate(e,t);if(r=r.replace(/[^a-z0-9\-_]+/gi,t.separator),t.separator.length){var n=new RegExp(t.separator);r=(r=r.replace(new RegExp(n.source+"{2,}"),t.separator)).replace(new RegExp("^"+n.source+"|"+n.source+"$","i"),"")}return r.toLowerCase()},_applyInflections:function(e,t){var r,n,i,a=""+e;if(0===a.length)return a;var o=a.toLowerCase().match(/\b\w+$/);if(o&amp;&amp;this.inflections().uncountables.indexOf(o[0])&gt;-1)return a;for(var s=0,u=t.length;s&lt;u;s++)if(n=(r=t[s])[0],i=r[1],a.match(n)){a=a.replace(n,i);break}return a}};t.exports=n},{}],12:[function(e,t,r){(function(e,r){"use strict";var n={"Ã€":"A","Ã":"A","Ã‚":"A","Ãƒ":"A","Ã„":"A","Ã…":"A","Ã†":"AE","Ã‡":"C","Ãˆ":"E","Ã‰":"E","ÃŠ":"E","Ã‹":"E","ÃŒ":"I","Ã":"I","ÃŽ":"I","Ã":"I","Ã":"D","Ã‘":"N","Ã’":"O","Ã“":"O","Ã”":"O","Ã•":"O","Ã–":"O","Ã—":"x","Ã˜":"O","Ã™":"U","Ãš":"U","Ã›":"U","Ãœ":"U","Ã":"Y","Ãž":"Th","ÃŸ":"ss","Ã&nbsp;":"a","Ã¡":"a","Ã¢":"a","Ã£":"a","Ã¤":"a","Ã¥":"a","Ã¦":"ae","Ã§":"c","Ã¨":"e","Ã©":"e","Ãª":"e","Ã«":"e","Ã¬":"i","Ã­":"i","Ã®":"i","Ã¯":"i","Ã°":"d","Ã±":"n","Ã²":"o","Ã³":"o","Ã´":"o","Ãµ":"o","Ã¶":"o","Ã¸":"o","Ã¹":"u","Ãº":"u","Ã»":"u","Ã¼":"u","Ã½":"y","Ã¾":"th","Ã¿":"y","Ä€":"A","Ä":"a","Ä‚":"A","Äƒ":"a","Ä„":"A","Ä…":"a","Ä†":"C","Ä‡":"c","Äˆ":"C","Ä‰":"c","ÄŠ":"C","Ä‹":"c","ÄŒ":"C","Ä":"c","ÄŽ":"D","Ä":"d","Ä":"D","Ä‘":"d","Ä’":"E","Ä“":"e","Ä”":"E","Ä•":"e","Ä–":"E","Ä—":"e","Ä˜":"E","Ä™":"e","Äš":"E","Ä›":"e","Äœ":"G","Ä":"g","Äž":"G","ÄŸ":"g","Ä&nbsp;":"G","Ä¡":"g","Ä¢":"G","Ä£":"g","Ä¤":"H","Ä¥":"h","Ä¦":"H","Ä§":"h","Ä¨":"I","Ä©":"i","Äª":"I","Ä«":"i","Ä¬":"I","Ä­":"i","Ä®":"I","Ä¯":"i","Ä°":"I","Ä±":"i","Ä²":"IJ","Ä³":"ij","Ä´":"J","Äµ":"j","Ä¶":"K","Ä·":"k","Ä¸":"k","Ä¹":"L","Äº":"l","Ä»":"L","Ä¼":"l","Ä½":"L","Ä¾":"l","Ä¿":"L","Å€":"l","Å":"L","Å‚":"l","Åƒ":"N","Å„":"n","Å…":"N","Å†":"n","Å‡":"N","Åˆ":"n","Å‰":"'n","ÅŠ":"NG","Å‹":"ng","ÅŒ":"O","Å":"o","ÅŽ":"O","Å":"o","Å":"O","Å‘":"o","Å’":"OE","Å“":"oe","Å”":"R","Å•":"r","Å–":"R","Å—":"r","Å˜":"R","Å™":"r","Åš":"S","Å›":"s","Åœ":"S","Å":"s","Åž":"S","ÅŸ":"s","Å&nbsp;":"S","Å¡":"s","Å¢":"T","Å£":"t","Å¤":"T","Å¥":"t","Å¦":"T","Å§":"t","Å¨":"U","Å©":"u","Åª":"U","Å«":"u","Å¬":"U","Å­":"u","Å®":"U","Å¯":"u","Å°":"U","Å±":"u","Å²":"U","Å³":"u","Å´":"W","Åµ":"w","Å¶":"Y","Å·":"y","Å¸":"Y","Å¹":"Z","Åº":"z","Å»":"Z","Å¼":"z","Å½":"Z","Å¾":"z"};function i(){for(var e in this.approximations={},n)this.approximate(e,n[e])}i.getInstance=function(t){var n=void 0!==e?e:r;return n.__Inflector_Transliterator=n.__Inflector_Transliterator||{},n.__Inflector_Transliterator[t]=n.__Inflector_Transliterator[t]||new i,n.__Inflector_Transliterator[t]},i.prototype.approximate=function(e,t){this.approximations[e]=t},i.prototype.transliterate=function(e,t){var r=this;return e.replace(/[^\u0000-\u007f]/g,function(e){return r.approximations[e]||t||"?"})},t.exports=i}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:196}],13:[function(e,t,r){"use strict";t.exports={en:function(e){e.plural(/$/,"s"),e.plural(/s$/i,"s"),e.plural(/^(ax|test)is$/i,"$1es"),e.plural(/(octop|vir)us$/i,"$1i"),e.plural(/(octop|vir)i$/i,"$1i"),e.plural(/(alias|status)$/i,"$1es"),e.plural(/(bu)s$/i,"$1ses"),e.plural(/(buffal|tomat)o$/i,"$1oes"),e.plural(/([ti])um$/i,"$1a"),e.plural(/([ti])a$/i,"$1a"),e.plural(/sis$/i,"ses"),e.plural(/(?:([^f])fe|([lr])f)$/i,"$1$2ves"),e.plural(/(hive)$/i,"$1s"),e.plural(/([^aeiouy]|qu)y$/i,"$1ies"),e.plural(/(x|ch|ss|sh)$/i,"$1es"),e.plural(/(matr|vert|ind)(?:ix|ex)$/i,"$1ices"),e.plural(/^(m|l)ouse$/i,"$1ice"),e.plural(/^(m|l)ice$/i,"$1ice"),e.plural(/^(ox)$/i,"$1en"),e.plural(/^(oxen)$/i,"$1"),e.plural(/(quiz)$/i,"$1zes"),e.singular(/s$/i,""),e.singular(/(ss)$/i,"$1"),e.singular(/(n)ews$/i,"$1ews"),e.singular(/([ti])a$/i,"$1um"),e.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i,"$1sis"),e.singular(/(^analy)(sis|ses)$/i,"$1sis"),e.singular(/([^f])ves$/i,"$1fe"),e.singular(/(hive)s$/i,"$1"),e.singular(/(tive)s$/i,"$1"),e.singular(/([lr])ves$/i,"$1f"),e.singular(/([^aeiouy]|qu)ies$/i,"$1y"),e.singular(/(s)eries$/i,"$1eries"),e.singular(/(m)ovies$/i,"$1ovie"),e.singular(/(x|ch|ss|sh)es$/i,"$1"),e.singular(/^(m|l)ice$/i,"$1ouse"),e.singular(/(bus)(es)?$/i,"$1"),e.singular(/(o)es$/i,"$1"),e.singular(/(shoe)s$/i,"$1"),e.singular(/(cris|test)(is|es)$/i,"$1is"),e.singular(/^(a)x[ie]s$/i,"$1xis"),e.singular(/(octop|vir)(us|i)$/i,"$1us"),e.singular(/(alias|status)(es)?$/i,"$1"),e.singular(/^(ox)en/i,"$1"),e.singular(/(vert|ind)ices$/i,"$1ex"),e.singular(/(matr)ices$/i,"$1ix"),e.singular(/(quiz)zes$/i,"$1"),e.singular(/(database)s$/i,"$1"),e.irregular("person","people"),e.irregular("man","men"),e.irregular("child","children"),e.irregular("sex","sexes"),e.irregular("move","moves"),e.irregular("zombie","zombies"),e.uncountable("equipment","information","rice","money","species","series","fish","sheep","jeans","police")}}},{}],14:[function(e,t,r){"use strict";var n=Object.prototype.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],15:[function(e,t,r){"use strict";t.exports=function(e){return e.split("").map(function(e){return"(?:"+[e.toUpperCase(),e.toLowerCase()].join("|")+")"}).join("")}},{}],16:[function(e,t,r){"use strict";var n=Object.prototype.toString;t.exports=function(e){return"[object Function]"===n.call(e)}},{}],17:[function(e,t,r){"use strict";var n=Array.prototype.splice;t.exports=function(e,t){for(var r=e.length-1;r&gt;=0;r--)e[r]===t&amp;&amp;n.call(e,r,1)}},{}],18:[function(e,t,r){var n=e("./_getNative")(e("./_root"),"DataView");t.exports=n},{"./_getNative":97,"./_root":139}],19:[function(e,t,r){var n=e("./_hashClear"),i=e("./_hashDelete"),a=e("./_hashGet"),o=e("./_hashHas"),s=e("./_hashSet");function u(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t&lt;r;){var n=e[t];this.set(n[0],n[1])}}u.prototype.clear=n,u.prototype.delete=i,u.prototype.get=a,u.prototype.has=o,u.prototype.set=s,t.exports=u},{"./_hashClear":105,"./_hashDelete":106,"./_hashGet":107,"./_hashHas":108,"./_hashSet":109}],20:[function(e,t,r){var n=e("./_listCacheClear"),i=e("./_listCacheDelete"),a=e("./_listCacheGet"),o=e("./_listCacheHas"),s=e("./_listCacheSet");function u(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t&lt;r;){var n=e[t];this.set(n[0],n[1])}}u.prototype.clear=n,u.prototype.delete=i,u.prototype.get=a,u.prototype.has=o,u.prototype.set=s,t.exports=u},{"./_listCacheClear":119,"./_listCacheDelete":120,"./_listCacheGet":121,"./_listCacheHas":122,"./_listCacheSet":123}],21:[function(e,t,r){var n=e("./_getNative")(e("./_root"),"Map");t.exports=n},{"./_getNative":97,"./_root":139}],22:[function(e,t,r){var n=e("./_mapCacheClear"),i=e("./_mapCacheDelete"),a=e("./_mapCacheGet"),o=e("./_mapCacheHas"),s=e("./_mapCacheSet");function u(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t&lt;r;){var n=e[t];this.set(n[0],n[1])}}u.prototype.clear=n,u.prototype.delete=i,u.prototype.get=a,u.prototype.has=o,u.prototype.set=s,t.exports=u},{"./_mapCacheClear":124,"./_mapCacheDelete":125,"./_mapCacheGet":126,"./_mapCacheHas":127,"./_mapCacheSet":128}],23:[function(e,t,r){var n=e("./_getNative")(e("./_root"),"Promise");t.exports=n},{"./_getNative":97,"./_root":139}],24:[function(e,t,r){var n=e("./_getNative")(e("./_root"),"Set");t.exports=n},{"./_getNative":97,"./_root":139}],25:[function(e,t,r){var n=e("./_MapCache"),i=e("./_setCacheAdd"),a=e("./_setCacheHas");function o(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new n;++t&lt;r;)this.add(e[t])}o.prototype.add=o.prototype.push=i,o.prototype.has=a,t.exports=o},{"./_MapCache":22,"./_setCacheAdd":141,"./_setCacheHas":142}],26:[function(e,t,r){var n=e("./_ListCache"),i=e("./_stackClear"),a=e("./_stackDelete"),o=e("./_stackGet"),s=e("./_stackHas"),u=e("./_stackSet");function c(e){var t=this.__data__=new n(e);this.size=t.size}c.prototype.clear=i,c.prototype.delete=a,c.prototype.get=o,c.prototype.has=s,c.prototype.set=u,t.exports=c},{"./_ListCache":20,"./_stackClear":146,"./_stackDelete":147,"./_stackGet":148,"./_stackHas":149,"./_stackSet":150}],27:[function(e,t,r){var n=e("./_root").Symbol;t.exports=n},{"./_root":139}],28:[function(e,t,r){var n=e("./_root").Uint8Array;t.exports=n},{"./_root":139}],29:[function(e,t,r){var n=e("./_getNative")(e("./_root"),"WeakMap");t.exports=n},{"./_getNative":97,"./_root":139}],30:[function(e,t,r){t.exports=function(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}},{}],31:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=null==e?0:e.length;++r&lt;n&amp;&amp;!1!==t(e[r],r,e););return e}},{}],32:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,a=[];++r&lt;n;){var o=e[r];t(o,r,e)&amp;&amp;(a[i++]=o)}return a}},{}],33:[function(e,t,r){var n=e("./_baseTimes"),i=e("./isArguments"),a=e("./isArray"),o=e("./isBuffer"),s=e("./_isIndex"),u=e("./isTypedArray"),c=Object.prototype.hasOwnProperty;t.exports=function(e,t){var r=a(e),l=!r&amp;&amp;i(e),f=!r&amp;&amp;!l&amp;&amp;o(e),p=!r&amp;&amp;!l&amp;&amp;!f&amp;&amp;u(e),_=r||l||f||p,h=_?n(e.length,String):[],y=h.length;for(var v in e)!t&amp;&amp;!c.call(e,v)||_&amp;&amp;("length"==v||f&amp;&amp;("offset"==v||"parent"==v)||p&amp;&amp;("buffer"==v||"byteLength"==v||"byteOffset"==v)||s(v,y))||h.push(v);return h}},{"./_baseTimes":71,"./_isIndex":112,"./isArguments":166,"./isArray":167,"./isBuffer":170,"./isTypedArray":178}],34:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r&lt;n;)i[r]=t(e[r],r,e);return i}},{}],35:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=t.length,i=e.length;++r&lt;n;)e[i+r]=t[r];return e}},{}],36:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=null==e?0:e.length;++r&lt;n;)if(t(e[r],r,e))return!0;return!1}},{}],37:[function(e,t,r){var n=e("./_baseAssignValue"),i=e("./eq");t.exports=function(e,t,r){(void 0===r||i(e[t],r))&amp;&amp;(void 0!==r||t in e)||n(e,t,r)}},{"./_baseAssignValue":40,"./eq":157}],38:[function(e,t,r){var n=e("./_baseAssignValue"),i=e("./eq"),a=Object.prototype.hasOwnProperty;t.exports=function(e,t,r){var o=e[t];a.call(e,t)&amp;&amp;i(o,r)&amp;&amp;(void 0!==r||t in e)||n(e,t,r)}},{"./_baseAssignValue":40,"./eq":157}],39:[function(e,t,r){var n=e("./eq");t.exports=function(e,t){for(var r=e.length;r--;)if(n(e[r][0],t))return r;return-1}},{"./eq":157}],40:[function(e,t,r){var n=e("./_defineProperty");t.exports=function(e,t,r){"__proto__"==t&amp;&amp;n?n(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}},{"./_defineProperty":87}],41:[function(e,t,r){var n=e("./isObject"),i=Object.create,a=function(){function e(){}return function(t){if(!n(t))return{};if(i)return i(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();t.exports=a},{"./isObject":174}],42:[function(e,t,r){var n=e("./_baseForOwn"),i=e("./_createBaseEach")(n);t.exports=i},{"./_baseForOwn":46,"./_createBaseEach":84}],43:[function(e,t,r){t.exports=function(e,t,r,n){for(var i=e.length,a=r+(n?1:-1);n?a--:++a&lt;i;)if(t(e[a],a,e))return a;return-1}},{}],44:[function(e,t,r){var n=e("./_arrayPush"),i=e("./_isFlattenable");t.exports=function e(t,r,a,o,s){var u=-1,c=t.length;for(a||(a=i),s||(s=[]);++u&lt;c;){var l=t[u];r&gt;0&amp;&amp;a(l)?r&gt;1?e(l,r-1,a,o,s):n(s,l):o||(s[s.length]=l)}return s}},{"./_arrayPush":35,"./_isFlattenable":111}],45:[function(e,t,r){var n=e("./_createBaseFor")();t.exports=n},{"./_createBaseFor":85}],46:[function(e,t,r){var n=e("./_baseFor"),i=e("./keys");t.exports=function(e,t){return e&amp;&amp;n(e,t,i)}},{"./_baseFor":45,"./keys":179}],47:[function(e,t,r){var n=e("./_castPath"),i=e("./_toKey");t.exports=function(e,t){for(var r=0,a=(t=n(t,e)).length;null!=e&amp;&amp;r&lt;a;)e=e[i(t[r++])];return r&amp;&amp;r==a?e:void 0}},{"./_castPath":76,"./_toKey":152}],48:[function(e,t,r){var n=e("./_arrayPush"),i=e("./isArray");t.exports=function(e,t,r){var a=t(e);return i(e)?a:n(a,r(e))}},{"./_arrayPush":35,"./isArray":167}],49:[function(e,t,r){var n=e("./_Symbol"),i=e("./_getRawTag"),a=e("./_objectToString"),o="[object Null]",s="[object Undefined]",u=n?n.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?s:o:u&amp;&amp;u in Object(e)?i(e):a(e)}},{"./_Symbol":27,"./_getRawTag":99,"./_objectToString":136}],50:[function(e,t,r){t.exports=function(e,t){return null!=e&amp;&amp;t in Object(e)}},{}],51:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObjectLike"),a="[object Arguments]";t.exports=function(e){return i(e)&amp;&amp;n(e)==a}},{"./_baseGetTag":49,"./isObjectLike":175}],52:[function(e,t,r){var n=e("./_baseIsEqualDeep"),i=e("./isObjectLike");t.exports=function e(t,r,a,o,s){return t===r||(null==t||null==r||!i(t)&amp;&amp;!i(r)?t!=t&amp;&amp;r!=r:n(t,r,a,o,e,s))}},{"./_baseIsEqualDeep":53,"./isObjectLike":175}],53:[function(e,t,r){var n=e("./_Stack"),i=e("./_equalArrays"),a=e("./_equalByTag"),o=e("./_equalObjects"),s=e("./_getTag"),u=e("./isArray"),c=e("./isBuffer"),l=e("./isTypedArray"),f=1,p="[object Arguments]",_="[object Array]",h="[object Object]",y=Object.prototype.hasOwnProperty;t.exports=function(e,t,r,v,b,d){var g=u(e),x=u(t),m=g?_:s(e),A=x?_:s(t),j=(m=m==p?h:m)==h,O=(A=A==p?h:A)==h,w=m==A;if(w&amp;&amp;c(e)){if(!c(t))return!1;g=!0,j=!1}if(w&amp;&amp;!j)return d||(d=new n),g||l(e)?i(e,t,r,v,b,d):a(e,t,m,r,v,b,d);if(!(r&amp;f)){var $=j&amp;&amp;y.call(e,"__wrapped__"),k=O&amp;&amp;y.call(t,"__wrapped__");if($||k){var I=$?e.value():e,C=k?t.value():t;return d||(d=new n),b(I,C,r,v,d)}}return!!w&amp;&amp;(d||(d=new n),o(e,t,r,v,b,d))}},{"./_Stack":26,"./_equalArrays":88,"./_equalByTag":89,"./_equalObjects":90,"./_getTag":102,"./isArray":167,"./isBuffer":170,"./isTypedArray":178}],54:[function(e,t,r){var n=e("./_Stack"),i=e("./_baseIsEqual"),a=1,o=2;t.exports=function(e,t,r,s){var u=r.length,c=u,l=!s;if(null==e)return!c;for(e=Object(e);u--;){var f=r[u];if(l&amp;&amp;f[2]?f[1]!==e[f[0]]:!(f[0]in e))return!1}for(;++u&lt;c;){var p=(f=r[u])[0],_=e[p],h=f[1];if(l&amp;&amp;f[2]){if(void 0===_&amp;&amp;!(p in e))return!1}else{var y=new n;if(s)var v=s(_,h,p,e,t,y);if(!(void 0===v?i(h,_,a|o,s,y):v))return!1}}return!0}},{"./_Stack":26,"./_baseIsEqual":52}],55:[function(e,t,r){var n=e("./isFunction"),i=e("./_isMasked"),a=e("./isObject"),o=e("./_toSource"),s=/^\[object .+?Constructor\]$/,u=Function.prototype,c=Object.prototype,l=u.toString,f=c.hasOwnProperty,p=RegExp("^"+l.call(f).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&amp;").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(e){return!(!a(e)||i(e))&amp;&amp;(n(e)?p:s).test(o(e))}},{"./_isMasked":116,"./_toSource":153,"./isFunction":171,"./isObject":174}],56:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isLength"),a=e("./isObjectLike"),o={};o["[object Float32Array]"]=o["[object Float64Array]"]=o["[object Int8Array]"]=o["[object Int16Array]"]=o["[object Int32Array]"]=o["[object Uint8Array]"]=o["[object Uint8ClampedArray]"]=o["[object Uint16Array]"]=o["[object Uint32Array]"]=!0,o["[object Arguments]"]=o["[object Array]"]=o["[object ArrayBuffer]"]=o["[object Boolean]"]=o["[object DataView]"]=o["[object Date]"]=o["[object Error]"]=o["[object Function]"]=o["[object Map]"]=o["[object Number]"]=o["[object Object]"]=o["[object RegExp]"]=o["[object Set]"]=o["[object String]"]=o["[object WeakMap]"]=!1,t.exports=function(e){return a(e)&amp;&amp;i(e.length)&amp;&amp;!!o[n(e)]}},{"./_baseGetTag":49,"./isLength":172,"./isObjectLike":175}],57:[function(e,t,r){var n=e("./_baseMatches"),i=e("./_baseMatchesProperty"),a=e("./identity"),o=e("./isArray"),s=e("./property");t.exports=function(e){return"function"==typeof e?e:null==e?a:"object"==typeof e?o(e)?i(e[0],e[1]):n(e):s(e)}},{"./_baseMatches":60,"./_baseMatchesProperty":61,"./identity":165,"./isArray":167,"./property":187}],58:[function(e,t,r){var n=e("./_isPrototype"),i=e("./_nativeKeys"),a=Object.prototype.hasOwnProperty;t.exports=function(e){if(!n(e))return i(e);var t=[];for(var r in Object(e))a.call(e,r)&amp;&amp;"constructor"!=r&amp;&amp;t.push(r);return t}},{"./_isPrototype":117,"./_nativeKeys":133}],59:[function(e,t,r){var n=e("./isObject"),i=e("./_isPrototype"),a=e("./_nativeKeysIn"),o=Object.prototype.hasOwnProperty;t.exports=function(e){if(!n(e))return a(e);var t=i(e),r=[];for(var s in e)("constructor"!=s||!t&amp;&amp;o.call(e,s))&amp;&amp;r.push(s);return r}},{"./_isPrototype":117,"./_nativeKeysIn":134,"./isObject":174}],60:[function(e,t,r){var n=e("./_baseIsMatch"),i=e("./_getMatchData"),a=e("./_matchesStrictComparable");t.exports=function(e){var t=i(e);return 1==t.length&amp;&amp;t[0][2]?a(t[0][0],t[0][1]):function(r){return r===e||n(r,e,t)}}},{"./_baseIsMatch":54,"./_getMatchData":96,"./_matchesStrictComparable":130}],61:[function(e,t,r){var n=e("./_baseIsEqual"),i=e("./get"),a=e("./hasIn"),o=e("./_isKey"),s=e("./_isStrictComparable"),u=e("./_matchesStrictComparable"),c=e("./_toKey"),l=1,f=2;t.exports=function(e,t){return o(e)&amp;&amp;s(t)?u(c(e),t):function(r){var o=i(r,e);return void 0===o&amp;&amp;o===t?a(r,e):n(t,o,l|f)}}},{"./_baseIsEqual":52,"./_isKey":114,"./_isStrictComparable":118,"./_matchesStrictComparable":130,"./_toKey":152,"./get":163,"./hasIn":164}],62:[function(e,t,r){var n=e("./_Stack"),i=e("./_assignMergeValue"),a=e("./_baseFor"),o=e("./_baseMergeDeep"),s=e("./isObject"),u=e("./keysIn"),c=e("./_safeGet");t.exports=function e(t,r,l,f,p){t!==r&amp;&amp;a(r,function(a,u){if(s(a))p||(p=new n),o(t,r,u,l,e,f,p);else{var _=f?f(c(t,u),a,u+"",t,r,p):void 0;void 0===_&amp;&amp;(_=a),i(t,u,_)}},u)}},{"./_Stack":26,"./_assignMergeValue":37,"./_baseFor":45,"./_baseMergeDeep":63,"./_safeGet":140,"./isObject":174,"./keysIn":180}],63:[function(e,t,r){var n=e("./_assignMergeValue"),i=e("./_cloneBuffer"),a=e("./_cloneTypedArray"),o=e("./_copyArray"),s=e("./_initCloneObject"),u=e("./isArguments"),c=e("./isArray"),l=e("./isArrayLikeObject"),f=e("./isBuffer"),p=e("./isFunction"),_=e("./isObject"),h=e("./isPlainObject"),y=e("./isTypedArray"),v=e("./_safeGet"),b=e("./toPlainObject");t.exports=function(e,t,r,d,g,x,m){var A=v(e,r),j=v(t,r),O=m.get(j);if(O)n(e,r,O);else{var w=x?x(A,j,r+"",e,t,m):void 0,$=void 0===w;if($){var k=c(j),I=!k&amp;&amp;f(j),C=!k&amp;&amp;!I&amp;&amp;y(j);w=j,k||I||C?c(A)?w=A:l(A)?w=o(A):I?($=!1,w=i(j,!0)):C?($=!1,w=a(j,!0)):w=[]:h(j)||u(j)?(w=A,u(A)?w=b(A):_(A)&amp;&amp;!p(A)||(w=s(j))):$=!1}$&amp;&amp;(m.set(j,w),g(w,j,d,x,m),m.delete(j)),n(e,r,w)}}},{"./_assignMergeValue":37,"./_cloneBuffer":78,"./_cloneTypedArray":79,"./_copyArray":80,"./_initCloneObject":110,"./_safeGet":140,"./isArguments":166,"./isArray":167,"./isArrayLikeObject":169,"./isBuffer":170,"./isFunction":171,"./isObject":174,"./isPlainObject":176,"./isTypedArray":178,"./toPlainObject":193}],64:[function(e,t,r){var n=e("./_basePickBy"),i=e("./hasIn");t.exports=function(e,t){return n(e,t,function(t,r){return i(e,r)})}},{"./_basePickBy":65,"./hasIn":164}],65:[function(e,t,r){var n=e("./_baseGet"),i=e("./_baseSet"),a=e("./_castPath");t.exports=function(e,t,r){for(var o=-1,s=t.length,u={};++o&lt;s;){var c=t[o],l=n(e,c);r(l,c)&amp;&amp;i(u,a(c,e),l)}return u}},{"./_baseGet":47,"./_baseSet":69,"./_castPath":76}],66:[function(e,t,r){t.exports=function(e){return function(t){return null==t?void 0:t[e]}}},{}],67:[function(e,t,r){var n=e("./_baseGet");t.exports=function(e){return function(t){return n(t,e)}}},{"./_baseGet":47}],68:[function(e,t,r){var n=e("./identity"),i=e("./_overRest"),a=e("./_setToString");t.exports=function(e,t){return a(i(e,t,n),e+"")}},{"./_overRest":138,"./_setToString":144,"./identity":165}],69:[function(e,t,r){var n=e("./_assignValue"),i=e("./_castPath"),a=e("./_isIndex"),o=e("./isObject"),s=e("./_toKey");t.exports=function(e,t,r,u){if(!o(e))return e;for(var c=-1,l=(t=i(t,e)).length,f=l-1,p=e;null!=p&amp;&amp;++c&lt;l;){var _=s(t[c]),h=r;if(c!=f){var y=p[_];void 0===(h=u?u(y,_,p):void 0)&amp;&amp;(h=o(y)?y:a(t[c+1])?[]:{})}n(p,_,h),p=p[_]}return e}},{"./_assignValue":38,"./_castPath":76,"./_isIndex":112,"./_toKey":152,"./isObject":174}],70:[function(e,t,r){var n=e("./constant"),i=e("./_defineProperty"),a=e("./identity"),o=i?function(e,t){return i(e,"toString",{configurable:!0,enumerable:!1,value:n(t),writable:!0})}:a;t.exports=o},{"./_defineProperty":87,"./constant":155,"./identity":165}],71:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=Array(e);++r&lt;e;)n[r]=t(r);return n}},{}],72:[function(e,t,r){var n=e("./_Symbol"),i=e("./_arrayMap"),a=e("./isArray"),o=e("./isSymbol"),s=1/0,u=n?n.prototype:void 0,c=u?u.toString:void 0;t.exports=function e(t){if("string"==typeof t)return t;if(a(t))return i(t,e)+"";if(o(t))return c?c.call(t):"";var r=t+"";return"0"==r&amp;&amp;1/t==-s?"-0":r}},{"./_Symbol":27,"./_arrayMap":34,"./isArray":167,"./isSymbol":177}],73:[function(e,t,r){t.exports=function(e){return function(t){return e(t)}}},{}],74:[function(e,t,r){t.exports=function(e,t){return e.has(t)}},{}],75:[function(e,t,r){var n=e("./identity");t.exports=function(e){return"function"==typeof e?e:n}},{"./identity":165}],76:[function(e,t,r){var n=e("./isArray"),i=e("./_isKey"),a=e("./_stringToPath"),o=e("./toString");t.exports=function(e,t){return n(e)?e:i(e,t)?[e]:a(o(e))}},{"./_isKey":114,"./_stringToPath":151,"./isArray":167,"./toString":194}],77:[function(e,t,r){var n=e("./_Uint8Array");t.exports=function(e){var t=new e.constructor(e.byteLength);return new n(t).set(new n(e)),t}},{"./_Uint8Array":28}],78:[function(e,t,r){var n=e("./_root"),i="object"==typeof r&amp;&amp;r&amp;&amp;!r.nodeType&amp;&amp;r,a=i&amp;&amp;"object"==typeof t&amp;&amp;t&amp;&amp;!t.nodeType&amp;&amp;t,o=a&amp;&amp;a.exports===i?n.Buffer:void 0,s=o?o.allocUnsafe:void 0;t.exports=function(e,t){if(t)return e.slice();var r=e.length,n=s?s(r):new e.constructor(r);return e.copy(n),n}},{"./_root":139}],79:[function(e,t,r){var n=e("./_cloneArrayBuffer");t.exports=function(e,t){var r=t?n(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}},{"./_cloneArrayBuffer":77}],80:[function(e,t,r){t.exports=function(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r&lt;n;)t[r]=e[r];return t}},{}],81:[function(e,t,r){var n=e("./_assignValue"),i=e("./_baseAssignValue");t.exports=function(e,t,r,a){var o=!r;r||(r={});for(var s=-1,u=t.length;++s&lt;u;){var c=t[s],l=a?a(r[c],e[c],c,r,e):void 0;void 0===l&amp;&amp;(l=e[c]),o?i(r,c,l):n(r,c,l)}return r}},{"./_assignValue":38,"./_baseAssignValue":40}],82:[function(e,t,r){var n=e("./_root")["__core-js_shared__"];t.exports=n},{"./_root":139}],83:[function(e,t,r){var n=e("./_baseRest"),i=e("./_isIterateeCall");t.exports=function(e){return n(function(t,r){var n=-1,a=r.length,o=a&gt;1?r[a-1]:void 0,s=a&gt;2?r[2]:void 0;for(o=e.length&gt;3&amp;&amp;"function"==typeof o?(a--,o):void 0,s&amp;&amp;i(r[0],r[1],s)&amp;&amp;(o=a&lt;3?void 0:o,a=1),t=Object(t);++n&lt;a;){var u=r[n];u&amp;&amp;e(t,u,n,o)}return t})}},{"./_baseRest":68,"./_isIterateeCall":113}],84:[function(e,t,r){var n=e("./isArrayLike");t.exports=function(e,t){return function(r,i){if(null==r)return r;if(!n(r))return e(r,i);for(var a=r.length,o=t?a:-1,s=Object(r);(t?o--:++o&lt;a)&amp;&amp;!1!==i(s[o],o,s););return r}}},{"./isArrayLike":168}],85:[function(e,t,r){t.exports=function(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),s=o.length;s--;){var u=o[e?s:++i];if(!1===r(a[u],u,a))break}return t}}},{}],86:[function(e,t,r){var n=e("./_baseIteratee"),i=e("./isArrayLike"),a=e("./keys");t.exports=function(e){return function(t,r,o){var s=Object(t);if(!i(t)){var u=n(r,3);t=a(t),r=function(e){return u(s[e],e,s)}}var c=e(t,r,o);return c&gt;-1?s[u?t[c]:c]:void 0}}},{"./_baseIteratee":57,"./isArrayLike":168,"./keys":179}],87:[function(e,t,r){var n=e("./_getNative"),i=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();t.exports=i},{"./_getNative":97}],88:[function(e,t,r){var n=e("./_SetCache"),i=e("./_arraySome"),a=e("./_cacheHas"),o=1,s=2;t.exports=function(e,t,r,u,c,l){var f=r&amp;o,p=e.length,_=t.length;if(p!=_&amp;&amp;!(f&amp;&amp;_&gt;p))return!1;var h=l.get(e);if(h&amp;&amp;l.get(t))return h==t;var y=-1,v=!0,b=r&amp;s?new n:void 0;for(l.set(e,t),l.set(t,e);++y&lt;p;){var d=e[y],g=t[y];if(u)var x=f?u(g,d,y,t,e,l):u(d,g,y,e,t,l);if(void 0!==x){if(x)continue;v=!1;break}if(b){if(!i(t,function(e,t){if(!a(b,t)&amp;&amp;(d===e||c(d,e,r,u,l)))return b.push(t)})){v=!1;break}}else if(d!==g&amp;&amp;!c(d,g,r,u,l)){v=!1;break}}return l.delete(e),l.delete(t),v}},{"./_SetCache":25,"./_arraySome":36,"./_cacheHas":74}],89:[function(e,t,r){var n=e("./_Symbol"),i=e("./_Uint8Array"),a=e("./eq"),o=e("./_equalArrays"),s=e("./_mapToArray"),u=e("./_setToArray"),c=1,l=2,f="[object Boolean]",p="[object Date]",_="[object Error]",h="[object Map]",y="[object Number]",v="[object RegExp]",b="[object Set]",d="[object String]",g="[object Symbol]",x="[object ArrayBuffer]",m="[object DataView]",A=n?n.prototype:void 0,j=A?A.valueOf:void 0;t.exports=function(e,t,r,n,A,O,w){switch(r){case m:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case x:return!(e.byteLength!=t.byteLength||!O(new i(e),new i(t)));case f:case p:case y:return a(+e,+t);case _:return e.name==t.name&amp;&amp;e.message==t.message;case v:case d:return e==t+"";case h:var $=s;case b:var k=n&amp;c;if($||($=u),e.size!=t.size&amp;&amp;!k)return!1;var I=w.get(e);if(I)return I==t;n|=l,w.set(e,t);var C=o($(e),$(t),n,A,O,w);return w.delete(e),C;case g:if(j)return j.call(e)==j.call(t)}return!1}},{"./_Symbol":27,"./_Uint8Array":28,"./_equalArrays":88,"./_mapToArray":129,"./_setToArray":143,"./eq":157}],90:[function(e,t,r){var n=e("./_getAllKeys"),i=1,a=Object.prototype.hasOwnProperty;t.exports=function(e,t,r,o,s,u){var c=r&amp;i,l=n(e),f=l.length;if(f!=n(t).length&amp;&amp;!c)return!1;for(var p=f;p--;){var _=l[p];if(!(c?_ in t:a.call(t,_)))return!1}var h=u.get(e);if(h&amp;&amp;u.get(t))return h==t;var y=!0;u.set(e,t),u.set(t,e);for(var v=c;++p&lt;f;){var b=e[_=l[p]],d=t[_];if(o)var g=c?o(d,b,_,t,e,u):o(b,d,_,e,t,u);if(!(void 0===g?b===d||s(b,d,r,o,u):g)){y=!1;break}v||(v="constructor"==_)}if(y&amp;&amp;!v){var x=e.constructor,m=t.constructor;x!=m&amp;&amp;"constructor"in e&amp;&amp;"constructor"in t&amp;&amp;!("function"==typeof x&amp;&amp;x instanceof x&amp;&amp;"function"==typeof m&amp;&amp;m instanceof m)&amp;&amp;(y=!1)}return u.delete(e),u.delete(t),y}},{"./_getAllKeys":93}],91:[function(e,t,r){var n=e("./flatten"),i=e("./_overRest"),a=e("./_setToString");t.exports=function(e){return a(i(e,void 0,n),e+"")}},{"./_overRest":138,"./_setToString":144,"./flatten":161}],92:[function(e,t,r){(function(e){var r="object"==typeof e&amp;&amp;e&amp;&amp;e.Object===Object&amp;&amp;e;t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],93:[function(e,t,r){var n=e("./_baseGetAllKeys"),i=e("./_getSymbols"),a=e("./keys");t.exports=function(e){return n(e,a,i)}},{"./_baseGetAllKeys":48,"./_getSymbols":100,"./keys":179}],94:[function(e,t,r){var n=e("./_baseGetAllKeys"),i=e("./_getSymbolsIn"),a=e("./keysIn");t.exports=function(e){return n(e,a,i)}},{"./_baseGetAllKeys":48,"./_getSymbolsIn":101,"./keysIn":180}],95:[function(e,t,r){var n=e("./_isKeyable");t.exports=function(e,t){var r=e.__data__;return n(t)?r["string"==typeof t?"string":"hash"]:r.map}},{"./_isKeyable":115}],96:[function(e,t,r){var n=e("./_isStrictComparable"),i=e("./keys");t.exports=function(e){for(var t=i(e),r=t.length;r--;){var a=t[r],o=e[a];t[r]=[a,o,n(o)]}return t}},{"./_isStrictComparable":118,"./keys":179}],97:[function(e,t,r){var n=e("./_baseIsNative"),i=e("./_getValue");t.exports=function(e,t){var r=i(e,t);return n(r)?r:void 0}},{"./_baseIsNative":55,"./_getValue":103}],98:[function(e,t,r){var n=e("./_overArg")(Object.getPrototypeOf,Object);t.exports=n},{"./_overArg":137}],99:[function(e,t,r){var n=e("./_Symbol"),i=Object.prototype,a=i.hasOwnProperty,o=i.toString,s=n?n.toStringTag:void 0;t.exports=function(e){var t=a.call(e,s),r=e[s];try{e[s]=void 0;var n=!0}catch(e){}var i=o.call(e);return n&amp;&amp;(t?e[s]=r:delete e[s]),i}},{"./_Symbol":27}],100:[function(e,t,r){var n=e("./_arrayFilter"),i=e("./stubArray"),a=Object.prototype.propertyIsEnumerable,o=Object.getOwnPropertySymbols,s=o?function(e){return null==e?[]:(e=Object(e),n(o(e),function(t){return a.call(e,t)}))}:i;t.exports=s},{"./_arrayFilter":32,"./stubArray":188}],101:[function(e,t,r){var n=e("./_arrayPush"),i=e("./_getPrototype"),a=e("./_getSymbols"),o=e("./stubArray"),s=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)n(t,a(e)),e=i(e);return t}:o;t.exports=s},{"./_arrayPush":35,"./_getPrototype":98,"./_getSymbols":100,"./stubArray":188}],102:[function(e,t,r){var n=e("./_DataView"),i=e("./_Map"),a=e("./_Promise"),o=e("./_Set"),s=e("./_WeakMap"),u=e("./_baseGetTag"),c=e("./_toSource"),l=c(n),f=c(i),p=c(a),_=c(o),h=c(s),y=u;(n&amp;&amp;"[object DataView]"!=y(new n(new ArrayBuffer(1)))||i&amp;&amp;"[object Map]"!=y(new i)||a&amp;&amp;"[object Promise]"!=y(a.resolve())||o&amp;&amp;"[object Set]"!=y(new o)||s&amp;&amp;"[object WeakMap]"!=y(new s))&amp;&amp;(y=function(e){var t=u(e),r="[object Object]"==t?e.constructor:void 0,n=r?c(r):"";if(n)switch(n){case l:return"[object DataView]";case f:return"[object Map]";case p:return"[object Promise]";case _:return"[object Set]";case h:return"[object WeakMap]"}return t}),t.exports=y},{"./_DataView":18,"./_Map":21,"./_Promise":23,"./_Set":24,"./_WeakMap":29,"./_baseGetTag":49,"./_toSource":153}],103:[function(e,t,r){t.exports=function(e,t){return null==e?void 0:e[t]}},{}],104:[function(e,t,r){var n=e("./_castPath"),i=e("./isArguments"),a=e("./isArray"),o=e("./_isIndex"),s=e("./isLength"),u=e("./_toKey");t.exports=function(e,t,r){for(var c=-1,l=(t=n(t,e)).length,f=!1;++c&lt;l;){var p=u(t[c]);if(!(f=null!=e&amp;&amp;r(e,p)))break;e=e[p]}return f||++c!=l?f:!!(l=null==e?0:e.length)&amp;&amp;s(l)&amp;&amp;o(p,l)&amp;&amp;(a(e)||i(e))}},{"./_castPath":76,"./_isIndex":112,"./_toKey":152,"./isArguments":166,"./isArray":167,"./isLength":172}],105:[function(e,t,r){var n=e("./_nativeCreate");t.exports=function(){this.__data__=n?n(null):{},this.size=0}},{"./_nativeCreate":132}],106:[function(e,t,r){t.exports=function(e){var t=this.has(e)&amp;&amp;delete this.__data__[e];return this.size-=t?1:0,t}},{}],107:[function(e,t,r){var n=e("./_nativeCreate"),i="__lodash_hash_undefined__",a=Object.prototype.hasOwnProperty;t.exports=function(e){var t=this.__data__;if(n){var r=t[e];return r===i?void 0:r}return a.call(t,e)?t[e]:void 0}},{"./_nativeCreate":132}],108:[function(e,t,r){var n=e("./_nativeCreate"),i=Object.prototype.hasOwnProperty;t.exports=function(e){var t=this.__data__;return n?void 0!==t[e]:i.call(t,e)}},{"./_nativeCreate":132}],109:[function(e,t,r){var n=e("./_nativeCreate"),i="__lodash_hash_undefined__";t.exports=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=n&amp;&amp;void 0===t?i:t,this}},{"./_nativeCreate":132}],110:[function(e,t,r){var n=e("./_baseCreate"),i=e("./_getPrototype"),a=e("./_isPrototype");t.exports=function(e){return"function"!=typeof e.constructor||a(e)?{}:n(i(e))}},{"./_baseCreate":41,"./_getPrototype":98,"./_isPrototype":117}],111:[function(e,t,r){var n=e("./_Symbol"),i=e("./isArguments"),a=e("./isArray"),o=n?n.isConcatSpreadable:void 0;t.exports=function(e){return a(e)||i(e)||!!(o&amp;&amp;e&amp;&amp;e[o])}},{"./_Symbol":27,"./isArguments":166,"./isArray":167}],112:[function(e,t,r){var n=9007199254740991,i=/^(?:0|[1-9]\d*)$/;t.exports=function(e,t){var r=typeof e;return!!(t=null==t?n:t)&amp;&amp;("number"==r||"symbol"!=r&amp;&amp;i.test(e))&amp;&amp;e&gt;-1&amp;&amp;e%1==0&amp;&amp;e&lt;t}},{}],113:[function(e,t,r){var n=e("./eq"),i=e("./isArrayLike"),a=e("./_isIndex"),o=e("./isObject");t.exports=function(e,t,r){if(!o(r))return!1;var s=typeof t;return!!("number"==s?i(r)&amp;&amp;a(t,r.length):"string"==s&amp;&amp;t in r)&amp;&amp;n(r[t],e)}},{"./_isIndex":112,"./eq":157,"./isArrayLike":168,"./isObject":174}],114:[function(e,t,r){var n=e("./isArray"),i=e("./isSymbol"),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,o=/^\w*$/;t.exports=function(e,t){if(n(e))return!1;var r=typeof e;return!("number"!=r&amp;&amp;"symbol"!=r&amp;&amp;"boolean"!=r&amp;&amp;null!=e&amp;&amp;!i(e))||o.test(e)||!a.test(e)||null!=t&amp;&amp;e in Object(t)}},{"./isArray":167,"./isSymbol":177}],115:[function(e,t,r){t.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},{}],116:[function(e,t,r){var n,i=e("./_coreJsData"),a=(n=/[^.]+$/.exec(i&amp;&amp;i.keys&amp;&amp;i.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"";t.exports=function(e){return!!a&amp;&amp;a in e}},{"./_coreJsData":82}],117:[function(e,t,r){var n=Object.prototype;t.exports=function(e){var t=e&amp;&amp;e.constructor;return e===("function"==typeof t&amp;&amp;t.prototype||n)}},{}],118:[function(e,t,r){var n=e("./isObject");t.exports=function(e){return e==e&amp;&amp;!n(e)}},{"./isObject":174}],119:[function(e,t,r){t.exports=function(){this.__data__=[],this.size=0}},{}],120:[function(e,t,r){var n=e("./_assocIndexOf"),i=Array.prototype.splice;t.exports=function(e){var t=this.__data__,r=n(t,e);return!(r&lt;0||(r==t.length-1?t.pop():i.call(t,r,1),--this.size,0))}},{"./_assocIndexOf":39}],121:[function(e,t,r){var n=e("./_assocIndexOf");t.exports=function(e){var t=this.__data__,r=n(t,e);return r&lt;0?void 0:t[r][1]}},{"./_assocIndexOf":39}],122:[function(e,t,r){var n=e("./_assocIndexOf");t.exports=function(e){return n(this.__data__,e)&gt;-1}},{"./_assocIndexOf":39}],123:[function(e,t,r){var n=e("./_assocIndexOf");t.exports=function(e,t){var r=this.__data__,i=n(r,e);return i&lt;0?(++this.size,r.push([e,t])):r[i][1]=t,this}},{"./_assocIndexOf":39}],124:[function(e,t,r){var n=e("./_Hash"),i=e("./_ListCache"),a=e("./_Map");t.exports=function(){this.size=0,this.__data__={hash:new n,map:new(a||i),string:new n}}},{"./_Hash":19,"./_ListCache":20,"./_Map":21}],125:[function(e,t,r){var n=e("./_getMapData");t.exports=function(e){var t=n(this,e).delete(e);return this.size-=t?1:0,t}},{"./_getMapData":95}],126:[function(e,t,r){var n=e("./_getMapData");t.exports=function(e){return n(this,e).get(e)}},{"./_getMapData":95}],127:[function(e,t,r){var n=e("./_getMapData");t.exports=function(e){return n(this,e).has(e)}},{"./_getMapData":95}],128:[function(e,t,r){var n=e("./_getMapData");t.exports=function(e,t){var r=n(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}},{"./_getMapData":95}],129:[function(e,t,r){t.exports=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}},{}],130:[function(e,t,r){t.exports=function(e,t){return function(r){return null!=r&amp;&amp;r[e]===t&amp;&amp;(void 0!==t||e in Object(r))}}},{}],131:[function(e,t,r){var n=e("./memoize"),i=500;t.exports=function(e){var t=n(e,function(e){return r.size===i&amp;&amp;r.clear(),e}),r=t.cache;return t}},{"./memoize":183}],132:[function(e,t,r){var n=e("./_getNative")(Object,"create");t.exports=n},{"./_getNative":97}],133:[function(e,t,r){var n=e("./_overArg")(Object.keys,Object);t.exports=n},{"./_overArg":137}],134:[function(e,t,r){t.exports=function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}},{}],135:[function(e,t,r){var n=e("./_freeGlobal"),i="object"==typeof r&amp;&amp;r&amp;&amp;!r.nodeType&amp;&amp;r,a=i&amp;&amp;"object"==typeof t&amp;&amp;t&amp;&amp;!t.nodeType&amp;&amp;t,o=a&amp;&amp;a.exports===i&amp;&amp;n.process,s=function(){try{var e=a&amp;&amp;a.require&amp;&amp;a.require("util").types;return e||o&amp;&amp;o.binding&amp;&amp;o.binding("util")}catch(e){}}();t.exports=s},{"./_freeGlobal":92}],136:[function(e,t,r){var n=Object.prototype.toString;t.exports=function(e){return n.call(e)}},{}],137:[function(e,t,r){t.exports=function(e,t){return function(r){return e(t(r))}}},{}],138:[function(e,t,r){var n=e("./_apply"),i=Math.max;t.exports=function(e,t,r){return t=i(void 0===t?e.length-1:t,0),function(){for(var a=arguments,o=-1,s=i(a.length-t,0),u=Array(s);++o&lt;s;)u[o]=a[t+o];o=-1;for(var c=Array(t+1);++o&lt;t;)c[o]=a[o];return c[t]=r(u),n(e,this,c)}}},{"./_apply":30}],139:[function(e,t,r){var n=e("./_freeGlobal"),i="object"==typeof self&amp;&amp;self&amp;&amp;self.Object===Object&amp;&amp;self,a=n||i||Function("return this")();t.exports=a},{"./_freeGlobal":92}],140:[function(e,t,r){t.exports=function(e,t){if("__proto__"!=t)return e[t]}},{}],141:[function(e,t,r){var n="__lodash_hash_undefined__";t.exports=function(e){return this.__data__.set(e,n),this}},{}],142:[function(e,t,r){t.exports=function(e){return this.__data__.has(e)}},{}],143:[function(e,t,r){t.exports=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}},{}],144:[function(e,t,r){var n=e("./_baseSetToString"),i=e("./_shortOut")(n);t.exports=i},{"./_baseSetToString":70,"./_shortOut":145}],145:[function(e,t,r){var n=800,i=16,a=Date.now;t.exports=function(e){var t=0,r=0;return function(){var o=a(),s=i-(o-r);if(r=o,s&gt;0){if(++t&gt;=n)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}},{}],146:[function(e,t,r){var n=e("./_ListCache");t.exports=function(){this.__data__=new n,this.size=0}},{"./_ListCache":20}],147:[function(e,t,r){t.exports=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}},{}],148:[function(e,t,r){t.exports=function(e){return this.__data__.get(e)}},{}],149:[function(e,t,r){t.exports=function(e){return this.__data__.has(e)}},{}],150:[function(e,t,r){var n=e("./_ListCache"),i=e("./_Map"),a=e("./_MapCache"),o=200;t.exports=function(e,t){var r=this.__data__;if(r instanceof n){var s=r.__data__;if(!i||s.length&lt;o-1)return s.push([e,t]),this.size=++r.size,this;r=this.__data__=new a(s)}return r.set(e,t),this.size=r.size,this}},{"./_ListCache":20,"./_Map":21,"./_MapCache":22}],151:[function(e,t,r){var n=e("./_memoizeCapped"),i=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,a=/\\(\\)?/g,o=n(function(e){var t=[];return 46===e.charCodeAt(0)&amp;&amp;t.push(""),e.replace(i,function(e,r,n,i){t.push(n?i.replace(a,"$1"):r||e)}),t});t.exports=o},{"./_memoizeCapped":131}],152:[function(e,t,r){var n=e("./isSymbol"),i=1/0;t.exports=function(e){if("string"==typeof e||n(e))return e;var t=e+"";return"0"==t&amp;&amp;1/e==-i?"-0":t}},{"./isSymbol":177}],153:[function(e,t,r){var n=Function.prototype.toString;t.exports=function(e){if(null!=e){try{return n.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},{}],154:[function(e,t,r){var n=e("./_copyObject"),i=e("./_createAssigner"),a=e("./keysIn"),o=i(function(e,t){n(t,a(t),e)});t.exports=o},{"./_copyObject":81,"./_createAssigner":83,"./keysIn":180}],155:[function(e,t,r){t.exports=function(e){return function(){return e}}},{}],156:[function(e,t,r){t.exports=e("./forEach")},{"./forEach":162}],157:[function(e,t,r){t.exports=function(e,t){return e===t||e!=e&amp;&amp;t!=t}},{}],158:[function(e,t,r){t.exports=e("./assignIn")},{"./assignIn":154}],159:[function(e,t,r){var n=e("./_createFind")(e("./findIndex"));t.exports=n},{"./_createFind":86,"./findIndex":160}],160:[function(e,t,r){var n=e("./_baseFindIndex"),i=e("./_baseIteratee"),a=e("./toInteger"),o=Math.max;t.exports=function(e,t,r){var s=null==e?0:e.length;if(!s)return-1;var u=null==r?0:a(r);return u&lt;0&amp;&amp;(u=o(s+u,0)),n(e,i(t,3),u)}},{"./_baseFindIndex":43,"./_baseIteratee":57,"./toInteger":191}],161:[function(e,t,r){var n=e("./_baseFlatten");t.exports=function(e){return null!=e&amp;&amp;e.length?n(e,1):[]}},{"./_baseFlatten":44}],162:[function(e,t,r){var n=e("./_arrayEach"),i=e("./_baseEach"),a=e("./_castFunction"),o=e("./isArray");t.exports=function(e,t){return(o(e)?n:i)(e,a(t))}},{"./_arrayEach":31,"./_baseEach":42,"./_castFunction":75,"./isArray":167}],163:[function(e,t,r){var n=e("./_baseGet");t.exports=function(e,t,r){var i=null==e?void 0:n(e,t);return void 0===i?r:i}},{"./_baseGet":47}],164:[function(e,t,r){var n=e("./_baseHasIn"),i=e("./_hasPath");t.exports=function(e,t){return null!=e&amp;&amp;i(e,t,n)}},{"./_baseHasIn":50,"./_hasPath":104}],165:[function(e,t,r){t.exports=function(e){return e}},{}],166:[function(e,t,r){var n=e("./_baseIsArguments"),i=e("./isObjectLike"),a=Object.prototype,o=a.hasOwnProperty,s=a.propertyIsEnumerable,u=n(function(){return arguments}())?n:function(e){return i(e)&amp;&amp;o.call(e,"callee")&amp;&amp;!s.call(e,"callee")};t.exports=u},{"./_baseIsArguments":51,"./isObjectLike":175}],167:[function(e,t,r){var n=Array.isArray;t.exports=n},{}],168:[function(e,t,r){var n=e("./isFunction"),i=e("./isLength");t.exports=function(e){return null!=e&amp;&amp;i(e.length)&amp;&amp;!n(e)}},{"./isFunction":171,"./isLength":172}],169:[function(e,t,r){var n=e("./isArrayLike"),i=e("./isObjectLike");t.exports=function(e){return i(e)&amp;&amp;n(e)}},{"./isArrayLike":168,"./isObjectLike":175}],170:[function(e,t,r){var n=e("./_root"),i=e("./stubFalse"),a="object"==typeof r&amp;&amp;r&amp;&amp;!r.nodeType&amp;&amp;r,o=a&amp;&amp;"object"==typeof t&amp;&amp;t&amp;&amp;!t.nodeType&amp;&amp;t,s=o&amp;&amp;o.exports===a?n.Buffer:void 0,u=(s?s.isBuffer:void 0)||i;t.exports=u},{"./_root":139,"./stubFalse":189}],171:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObject"),a="[object AsyncFunction]",o="[object Function]",s="[object GeneratorFunction]",u="[object Proxy]";t.exports=function(e){if(!i(e))return!1;var t=n(e);return t==o||t==s||t==a||t==u}},{"./_baseGetTag":49,"./isObject":174}],172:[function(e,t,r){var n=9007199254740991;t.exports=function(e){return"number"==typeof e&amp;&amp;e&gt;-1&amp;&amp;e%1==0&amp;&amp;e&lt;=n}},{}],173:[function(e,t,r){t.exports=function(e){return null==e}},{}],174:[function(e,t,r){t.exports=function(e){var t=typeof e;return null!=e&amp;&amp;("object"==t||"function"==t)}},{}],175:[function(e,t,r){t.exports=function(e){return null!=e&amp;&amp;"object"==typeof e}},{}],176:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./_getPrototype"),a=e("./isObjectLike"),o="[object Object]",s=Function.prototype,u=Object.prototype,c=s.toString,l=u.hasOwnProperty,f=c.call(Object);t.exports=function(e){if(!a(e)||n(e)!=o)return!1;var t=i(e);if(null===t)return!0;var r=l.call(t,"constructor")&amp;&amp;t.constructor;return"function"==typeof r&amp;&amp;r instanceof r&amp;&amp;c.call(r)==f}},{"./_baseGetTag":49,"./_getPrototype":98,"./isObjectLike":175}],177:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObjectLike"),a="[object Symbol]";t.exports=function(e){return"symbol"==typeof e||i(e)&amp;&amp;n(e)==a}},{"./_baseGetTag":49,"./isObjectLike":175}],178:[function(e,t,r){var n=e("./_baseIsTypedArray"),i=e("./_baseUnary"),a=e("./_nodeUtil"),o=a&amp;&amp;a.isTypedArray,s=o?i(o):n;t.exports=s},{"./_baseIsTypedArray":56,"./_baseUnary":73,"./_nodeUtil":135}],179:[function(e,t,r){var n=e("./_arrayLikeKeys"),i=e("./_baseKeys"),a=e("./isArrayLike");t.exports=function(e){return a(e)?n(e):i(e)}},{"./_arrayLikeKeys":33,"./_baseKeys":58,"./isArrayLike":168}],180:[function(e,t,r){var n=e("./_arrayLikeKeys"),i=e("./_baseKeysIn"),a=e("./isArrayLike");t.exports=function(e){return a(e)?n(e,!0):i(e)}},{"./_arrayLikeKeys":33,"./_baseKeysIn":59,"./isArrayLike":168}],181:[function(e,t,r){var n=e("./_baseAssignValue"),i=e("./_baseForOwn"),a=e("./_baseIteratee");t.exports=function(e,t){var r={};return t=a(t,3),i(e,function(e,i,a){n(r,t(e,i,a),e)}),r}},{"./_baseAssignValue":40,"./_baseForOwn":46,"./_baseIteratee":57}],182:[function(e,t,r){var n=e("./_baseAssignValue"),i=e("./_baseForOwn"),a=e("./_baseIteratee");t.exports=function(e,t){var r={};return t=a(t,3),i(e,function(e,i,a){n(r,i,t(e,i,a))}),r}},{"./_baseAssignValue":40,"./_baseForOwn":46,"./_baseIteratee":57}],183:[function(e,t,r){var n=e("./_MapCache"),i="Expected a function";function a(e,t){if("function"!=typeof e||null!=t&amp;&amp;"function"!=typeof t)throw new TypeError(i);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(a.Cache||n),r}a.Cache=n,t.exports=a},{"./_MapCache":22}],184:[function(e,t,r){var n=e("./_baseMerge"),i=e("./_createAssigner")(function(e,t,r){n(e,t,r)});t.exports=i},{"./_baseMerge":62,"./_createAssigner":83}],185:[function(e,t,r){var n=e("./_basePick"),i=e("./_flatRest")(function(e,t){return null==e?{}:n(e,t)});t.exports=i},{"./_basePick":64,"./_flatRest":91}],186:[function(e,t,r){var n=e("./_arrayMap"),i=e("./_baseIteratee"),a=e("./_basePickBy"),o=e("./_getAllKeysIn");t.exports=function(e,t){if(null==e)return{};var r=n(o(e),function(e){return[e]});return t=i(t),a(e,r,function(e,r){return t(e,r[0])})}},{"./_arrayMap":34,"./_baseIteratee":57,"./_basePickBy":65,"./_getAllKeysIn":94}],187:[function(e,t,r){var n=e("./_baseProperty"),i=e("./_basePropertyDeep"),a=e("./_isKey"),o=e("./_toKey");t.exports=function(e){return a(e)?n(o(e)):i(e)}},{"./_baseProperty":66,"./_basePropertyDeep":67,"./_isKey":114,"./_toKey":152}],188:[function(e,t,r){t.exports=function(){return[]}},{}],189:[function(e,t,r){t.exports=function(){return!1}},{}],190:[function(e,t,r){var n=e("./toNumber"),i=1/0,a=1.7976931348623157e308;t.exports=function(e){return e?(e=n(e))===i||e===-i?(e&lt;0?-1:1)*a:e==e?e:0:0===e?e:0}},{"./toNumber":192}],191:[function(e,t,r){var n=e("./toFinite");t.exports=function(e){var t=n(e),r=t%1;return t==t?r?t-r:t:0}},{"./toFinite":190}],192:[function(e,t,r){var n=e("./isObject"),i=e("./isSymbol"),a=NaN,o=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,l=parseInt;t.exports=function(e){if("number"==typeof e)return e;if(i(e))return a;if(n(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=n(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(o,"");var r=u.test(e);return r||c.test(e)?l(e.slice(2),r?2:8):s.test(e)?a:+e}},{"./isObject":174,"./isSymbol":177}],193:[function(e,t,r){var n=e("./_copyObject"),i=e("./keysIn");t.exports=function(e){return n(e,i(e))}},{"./_copyObject":81,"./keysIn":180}],194:[function(e,t,r){var n=e("./_baseToString");t.exports=function(e){return null==e?"":n(e)}},{"./_baseToString":72}],195:[function(e,t,r){var n=e("./_arrayEach"),i=e("./_baseCreate"),a=e("./_baseForOwn"),o=e("./_baseIteratee"),s=e("./_getPrototype"),u=e("./isArray"),c=e("./isBuffer"),l=e("./isFunction"),f=e("./isObject"),p=e("./isTypedArray");t.exports=function(e,t,r){var _=u(e),h=_||c(e)||p(e);if(t=o(t,4),null==r){var y=e&amp;&amp;e.constructor;r=h?_?new y:[]:f(e)&amp;&amp;l(y)?i(s(e)):{}}return(h?n:a)(e,function(e,n,i){return t(r,e,n,i)}),r}},{"./_arrayEach":31,"./_baseCreate":41,"./_baseForOwn":46,"./_baseIteratee":57,"./_getPrototype":98,"./isArray":167,"./isBuffer":170,"./isFunction":171,"./isObject":174,"./isTypedArray":178}],196:[function(e,t,r){var n,i,a=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function u(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!n)&amp;&amp;setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{i="function"==typeof clearTimeout?clearTimeout:s}catch(e){i=s}}();var c,l=[],f=!1,p=-1;function _(){f&amp;&amp;c&amp;&amp;(f=!1,c.length?l=c.concat(l):p=-1,l.length&amp;&amp;h())}function h(){if(!f){var e=u(_);f=!0;for(var t=l.length;t;){for(c=l,l=[];++p&lt;t;)c&amp;&amp;c[p].run();p=-1,t=l.length}c=null,f=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===s||!i)&amp;&amp;clearTimeout)return i=clearTimeout,clearTimeout(e);try{i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}(e)}}function y(e,t){this.fun=e,this.array=t}function v(){}a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length&gt;1)for(var r=1;r&lt;arguments.length;r++)t[r-1]=arguments[r];l.push(new y(e,t)),1!==l.length||f||u(h)},y.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=v,a.addListener=v,a.once=v,a.off=v,a.removeListener=v,a.removeAllListeners=v,a.emit=v,a.prependListener=v,a.prependOnceListener=v,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],"jsonapi-serializer":[function(e,t,r){t.exports={Serializer:e("./lib/serializer"),Deserializer:e("./lib/deserializer"),Error:e("./lib/error")}},{"./lib/deserializer":2,"./lib/error":4,"./lib/serializer":7}]},{},["jsonapi-serializer"]);
/* global Swal */

document.addEventListener("spree:load", function () {
  var alertEl = document.querySelectorAll('[data-alert-type]');

  if (!alertEl) return;

  alertEl.forEach(function (elem) {
    var alertType = elem.dataset.alertType;
    var alertMessage = elem.innerHTML;

    show_flash(alertType, alertMessage);
  });
});

// eslint-disable-next-line camelcase
function show_flash(type, message) {
  var sanitizedType = DOMPurify.sanitize(type);
  var sanitizedMessage = DOMPurify.sanitize(message);

  if (sanitizedType === 'notice') sanitizedType = 'info';

  // Set up Swal toast alert defaults
  var Toast = Swal.mixin({
    toast: true,
    position: 'bottom',
    showConfirmButton: false,
    showCloseButton: true,
    timer: 4500,
    timerProgressBar: false,
    showClass: {
      popup: 'animate__animated animate__fadeInUp animate__faster',
      backdrop: '-',
      icon: '-'
    },
    hideClass: {
      popup: 'animate__animated animate__fadeOutDown animate__faster',
      backdrop: '-',
      icon: '-'
    }
  });

  Toast.fire({
    icon: sanitizedType,
    title: sanitizedMessage
  });

  appendToFlashAlertsContainer(sanitizedMessage, sanitizedType);
}

function appendToFlashAlertsContainer(message, type) {
  if (type === 'info') type = 'notice';

  var parnetNode = document.querySelector('#FlashAlertsContainer');
  var node = document.createElement('SPAN');
  var textNode = document.createTextNode(message);

  // Only the most recent alert should be left in the #FlashAlertsContainer.
  parnetNode.innerHTML = '';

  node.classList.add('d-none');
  node.setAttribute('data-alert-type', type);
  node.appendChild(textNode);

  parnetNode.appendChild(node);
};
/* eslint-disable no-unused-vars */

//
// Handle clearing out of animation styles from complete animation.
var animateCSS = function animateCSS(element, animation, speed) {
  var prefix = arguments.length &lt;= 3 || arguments[3] === undefined ? 'animate__' : arguments[3];
  return new Promise(function (resolve) {
    var animationName = '' + prefix + animation;
    var node = document.querySelector(element);

    node.classList.add(prefix + 'animated', animationName, prefix + speed);

    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(prefix + 'animated', animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, { once: true });
  });
};
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */

//
// Shows the progress bar on fech requests
var showProgressIndicator = function showProgressIndicator() {
  Turbo.navigator.delegate.adapter.progressBar.setValue(0);
  Turbo.navigator.delegate.adapter.progressBar.show();
};

//
// Hides the progress bar on fech requests
var hideProgressIndicator = function hideProgressIndicator() {
  Turbo.navigator.delegate.adapter.progressBar.setValue(1);
  Turbo.navigator.delegate.adapter.progressBar.hide();
};

//
// Handles the fetch request response.
// If the response has content it is returned, else if the response is a 204 no-content,
// the resolved text is returned.
var spreeHandleFetchRequestResponse = function spreeHandleFetchRequestResponse(response) {
  hideProgressIndicator();

  if (response.status === 204) {
    return response.text();
  } else {
    return response.json();
  }
};

//
// Handles fech request errors by triggering the appropriate flash alert type and displaying
// the response message.
var spreeHandleFetchRequestError = function spreeHandleFetchRequestError(data) {
  if (data.error != null) {
    show_flash('error', data.error);
  } else if (data.message != null) {
    show_flash('success', data.message);
  } else if (data.exception != null) {
    show_flash('info', data.exception);
  } else if (data.detail != null) {
    show_flash('info', data.detail);
  }
};

//
// Reloads the window.
var spreeWindowReload = function spreeWindowReload() {
  window.location.reload();
};

//
// SPREE FECTCH REQUEST
// Pass a json object containing your fetch request details and settings, you can also send a second optional
// argument, this second argument is your success response handler, and lastly a third argument that carries
// through a target element to the response method if needed, the second and third arguments are optional.
// When using spreeFetchRequest() the loading... progress bar, flash notice and errors are all handled for you.
//
// EXAMPLE SENDING A POST REQUEST TO CREATE A NEW SHIPMENT:
//    const data = {
//      order_id: 'H8213728798',
//      variant_id: 2,
//      quantity: 4,
//      stock_location_id: 1
//    }
//
//    const requestData = {
//      // request details
//      uri: Spree.routes.shipments_api_v2,
//      method: 'POST',
//      dataBody: data,
//
//   // Optional Settings
//   // disableProgressIndicator: true,   Allows you to disable the progress loader bar if needed.
//   // formatDataBody: false             If you have pre-formatted data, pass this option to stop the function performing the default stringify.
//    }
//    spreeFetchRequest(requestData, someCallbackFunction, this)
//
var spreeFetchRequest = function spreeFetchRequest(requstData) {
  var success = arguments.length &lt;= 1 || arguments[1] === undefined ? null : arguments[1];
  var target = arguments.length &lt;= 2 || arguments[2] === undefined ? null : arguments[2];

  if (!requstData.disableProgressIndicator === true) showProgressIndicator();

  var requestDataBody = undefined;

  var requestUri = requstData.uri || null;
  var requestMethod = requstData.method || 'GET';
  var requestContentType = requstData.ContentType || 'application/json';

  if (requstData.formatDataBody === false) {
    requestDataBody = requstData.dataBody;
  } else {
    requestDataBody = JSON.stringify(requstData.dataBody) || null;
  }

  if (requestUri == null) return;

  fetch(requestUri, {
    method: requestMethod,
    headers: {
      'Authorization': 'Bearer ' + OAUTH_TOKEN,
      'Content-Type': requestContentType
    },
    body: requestDataBody
  }).then(function (response) {
    return spreeHandleFetchRequestResponse(response).then(function (data) {
      if (response.ok) {
        if (success != null) success(data, target);
      } else {
        spreeHandleFetchRequestError(data);
      }
    });
  })['catch'](function (err) {
    return console.log(err);
  });
};
document.addEventListener("spree:load", function () {
  flatpickr.setDefaults({
    altInput: true,
    time_24hr: true,
    altInputClass: 'flatpickr-alt-input',
    locale: Spree.translations.flatpickr_locale
  });

  var dateFrom = flatpickr('.datePickerFrom', {
    onChange: function onChange(selectedDates) {
      dateTo.set('minDate', selectedDates[0]);
    }
  });

  var dateTo = flatpickr('.datePickerTo', {
    onChange: function onChange(selectedDates) {
      dateFrom.set('maxDate', selectedDates[0]);
    }
  });

  flatpickr('.datepicker', {});
});

document.addEventListener("turbo:before-cache", function () {
  document.querySelectorAll('.datePickerFrom, .datePickerTo, .datepicker').forEach(function (element) {
    element._flatpickr.destroy();
  });
});
document.addEventListener("spree:load", function () {
  var QuickSearchInput = document.getElementById('quick_search');

  if (QuickSearchInput) {
    var QuickSearchPlaceHolder = QuickSearchInput.placeholder;
    var TargetSearchFieldId = document.querySelector('input.js-quick-search-target').id;
    var AssociatedLabelName = document.querySelector('label[for="' + TargetSearchFieldId + '"]').innerHTML;

    QuickSearchInput.placeholder = QuickSearchPlaceHolder + ' ' + AssociatedLabelName;
  }

  $('.js-show-index-filters').click(function () {
    $('.filter-well').slideToggle();
    $(this).parents('.filter-wrap').toggleClass('collapsed');
  });

  // TODO: remove this js temp behaviour and fix this decent
  // Temp quick search
  // When there was a search term, copy it
  $('.js-quick-search').val($('.js-quick-search-target').val());

  // Catch the quick search form submit and submit the real form
  $('#quick-search').submit(function () {
    $('.js-quick-search-target').val($('.js-quick-search').val());
    $('#table-filter form').submit();
    return false;
  });

  // Clickable ransack filters
  $('.js-add-filter').click(function () {
    var ransackField = $(this).data('ransack-field');
    var ransackValue = $(this).data('ransack-value');

    $('#' + ransackField).val(ransackValue);
    $('#table-filter form').submit();
  });

  $(document).on('click', '.js-delete-filter', function () {
    var ransackField = $(this).parents('.js-filter').data('ransack-field');

    $('#' + ransackField).val('');
    $('#table-filter form').submit();
  });

  function ransackField(value) {
    switch (value) {
      case 'Date Range':
        return 'Start';
      case '':
        return 'Stop';
      default:
        return value.trim();
    }
  }

  // To appear in the filtered options, the elements id attribute must start with 'q_',
  // and it must have the class'.js-filterable'.
  $('[id^="q_"].js-filterable').each(function () {
    var $this = $(this);

    if ($this.val() !== null &amp;&amp; $this.val() !== '' &amp;&amp; $this.val().length !== 0) {
      var ransackValue, filter;
      var ransackFieldId = $this.attr('id');
      var label = $('label[for="' + ransackFieldId + '"]');

      if ($this.is('select')) {
        ransackValue = $this.find('option:selected').toArray().map(function (option) {
          return option.text;
        }).join(', ');
      } else {
        ransackValue = $this.val();
      }

      label = ransackField(label.text()) + ': ' + ransackValue;

      var cleanLabel = DOMPurify.sanitize(label);

      filter = '&lt;span class="js-filter badge badge-secondary d-inline-flex align-items-center" data-ransack-field="' + ransackFieldId + '"&gt;' + cleanLabel + '&lt;i class="icon icon-cancel ml-2 js-delete-filter"&gt;&lt;/i&gt;&lt;/span&gt;';
      $('.js-filters').append(filter).show();
    }
  });

  // per page drop-down
  // preserves all selected filters / queries supplied by user
  // changes only per_page value
  $('.js-per-page-select').change(function () {
    var form = $(this).closest('.js-per-page-form');
    var url = form.attr('action');
    var value = $(this).val().toString();
    if (url.match(/\?/)) {
      url += '&amp;per_page=' + value;
    } else {
      url += '?per_page=' + value;
    }
    Turbo.visit(url);
  });

  // injects per_page settings to all available search forms
  // so when user changes some filters / queries per_page is preserved
  document.addEventListener("spree:load", function () {
    var perPageDropdown = $('.js-per-page-select:first');
    if (perPageDropdown.length) {
      var perPageValue = perPageDropdown.val().toString();
      var perPageInput = '&lt;input class="hidden_per_page_input" type="hidden" name="per_page" value=' + perPageValue + ' /&gt;';

      $('.hidden_per_page_input').remove();
      $('#table-filter form').append(perPageInput);
    }
  });
});
/* global Swal */
document.addEventListener("spree:load", function () {
  var infoToggle = document.querySelectorAll('[data-show-info]');

  infoToggle.forEach(function (infoElem) {
    infoElem.addEventListener('click', function () {
      var alertType = infoElem.dataset.alertKind;
      var alertTitle = infoElem.dataset.alertTitle;
      var alertHtml = infoElem.dataset.alertHtml;
      var alertMessage = infoElem.dataset.alertMessage;

      showInfoAlert(alertType, alertTitle, alertMessage, alertHtml);
    });
  });
});

// eslint-disable-next-line no-unused-vars
function showInfoAlert() {
  var type = arguments.length &lt;= 0 || arguments[0] === undefined ? null : arguments[0];
  var title = arguments.length &lt;= 1 || arguments[1] === undefined ? null : arguments[1];
  var message = arguments.length &lt;= 2 || arguments[2] === undefined ? null : arguments[2];
  var html = arguments.length &lt;= 3 || arguments[3] === undefined ? null : arguments[3];

  var infoAlert = Swal.mixin({
    showConfirmButton: false,
    showCloseButton: true,
    timer: null,
    timerProgressBar: false,
    showClass: {
      popup: 'animate__animated animate__fadeInUp animate__faster'
    },
    hideClass: {
      popup: 'animate__animated animate__fadeOutDown animate__faster'
    }
  });

  infoAlert.fire({
    icon: type,
    title: title,
    text: message,
    html: html
  });
};
/**
  radioControlsVisibilityOfElement:
  Apply to individual radio button that makes another element visible when checked
**/
document.addEventListener("spree:load", function () {
  $.fn.radioControlsVisibilityOfElement = function (dependentElementSelector) {
    if (!this.get(0)) {
      return;
    }
    var showValue = this.get(0).value;
    var radioGroup = $("input[name='" + this.get(0).name + "']");
    radioGroup.each(function () {
      $(this).click(function () {
        // eslint-disable-next-line eqeqeq
        $(dependentElementSelector).visible(this.checked &amp;&amp; this.value == showValue);
      });
      if (this.checked) {
        this.click();
      }
    });
  };
});
document.addEventListener("spree:load", function () {
  var body = $('body');
  var modalBackdrop = $('#multi-backdrop');

  // Fail safe on screen resize
  var resizeTimer;
  window.addEventListener('resize', function () {
    document.body.classList.remove('modal-open', 'sidebar-open', 'contextualSideMenu-open');
    document.body.classList.add('resize-animation-stopper');
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function () {
      document.body.classList.remove('resize-animation-stopper');
    }, 400);
  });

  function closeAllMenus() {
    body.removeClass();
    body.addClass('admin');
    modalBackdrop.removeClass('show');
  }

  modalBackdrop.click(closeAllMenus);

  // Main Menu Functionality
  var sidebarOpen = $('#sidebar-open');
  var sidebarClose = $('#sidebar-close');
  var activeItem = $('#main-sidebar').find('.selected');

  activeItem.closest('.nav-sidebar').addClass('active-option');
  activeItem.closest('.nav-pills').addClass('in show');

  function openMenu() {
    closeAllMenus();
    body.addClass('sidebar-open modal-open');
    modalBackdrop.addClass('show');
  }
  sidebarOpen.click(openMenu);
  sidebarClose.click(closeAllMenus);

  // Contextual Sidebar Menu
  var contextualSidebarMenuToggle = $('#contextual-menu-toggle');
  var contextualSidebarMenuClose = $('#contextual-menu-close');

  function toggleContextualMenu() {
    if (document.body.classList.contains('contextualSideMenu-open')) {
      closeAllMenus();
    } else {
      closeAllMenus();
      body.addClass('contextualSideMenu-open modal-open');
      modalBackdrop.addClass('show');
    }
  }

  contextualSidebarMenuToggle.click(toggleContextualMenu);
  contextualSidebarMenuClose.click(toggleContextualMenu);
});
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

// SELECT2 AUTOCOMPLETE JS
//  The JavaScript in this file allows Spree developers to set up Select2 autocomplete search
//  using the API v2 by simply adding data attributes to a select element.

// REQUIRED ATTRIBUTES
//  You must provide a URL for the API V2, use the format shown below. See backend.js for other API V2 URL's.
//  REQUIRED:
//  data-autocomplete-url-value="products_api_v2"

//  OPTIONAL:
//  data-autocomplete-placeholder-value="Search Pages"     &lt;- Sets the placeholder | DEFAULT is: 'Search'.
//  data-autocomplete-clear-value=boolean                 &lt;- Allow select2 to be cleared | DEFAULT is: false (no clear button).
//  data-autocomplete-multiple-value=boolean              &lt;- Multiple or Single select | DEFAULT is: false (single).
//  data-autocomplete-return-attr-value="pretty_name"     &lt;- Return Attribute. | DEFAULT is: 'name'.
//  data-autocomplete-min-input-value="4"                 &lt;- Minimum input for search | DEFAULT is: 3.
//  data-autocomplete-search-query-value="title_i_cont"   &lt;- Custom search query | DEFAULT is: 'name_i_cont'.
//  data-autocomplete-custom-return-id-value="permalink"  &lt;- Return a custom attribute | DEFAULT: returns id.
//  data-autocomplete-debug-mode-value=boolean            &lt;- Turn on console login of data returned by the request.
//
//  Add your own custom URL params to the request as needed
//  EXAMPLE:
//  data-autocomplete-additional-url-params-value="filter[type_not_eq]=Spree::Cms::Pages::Homepage"

document.addEventListener("spree:load", function () {
  loadAutoCompleteParams();
});

// we need to delete select2 instances before document is saved to cache
// https://stackoverflow.com/questions/36497723/select2-with-ajax-gets-initialized-several-times-with-rails-turbolinks-events
document.addEventListener("turbo:before-cache", function () {
  var select2Autocompletes = document.querySelectorAll('select[data-autocomplete-url-value]');
  select2Autocompletes.forEach(function (element) {
    return $(element).select2('destroy');
  });
});

// eslint-disable-next-line no-unused-vars
function loadAutoCompleteParams() {
  var select2Autocompletes = document.querySelectorAll('select[data-autocomplete-url-value]');
  select2Autocompletes.forEach(function (element) {
    return buildParamsFromDataAttrs(element);
  });
}

function buildParamsFromDataAttrs(element) {
  $(element).select2Autocomplete({
    apiUrl: Spree.routes[element.dataset.autocompleteUrlValue],
    placeholder: element.dataset.autocompletePlaceholderValue,
    allow_clear: element.dataset.autocompleteClearValue,
    multiple: element.dataset.autocompleteMultipleValue,
    return_attribute: element.dataset.autocompleteReturnAttrValue,
    minimum_input: element.dataset.autocompleteMinInputValue,
    search_query: element.dataset.autocompleteSearchQueryValue,
    custom_return_id: element.dataset.autocompleteCustomReturnIdValue,
    additional_url_params: element.dataset.autocompleteAdditionalUrlParamsValue,
    debug_mode: element.dataset.autocompleteDebugModeValue
  });
}

$.fn.select2Autocomplete = function (params) {
  var apiUrl = null;
  var returnedFields = undefined;

  var resourcePlural = params.apiUrl.match(/([^/]*)\/*$/)[1];
  var resourceSingular = resourcePlural.slice(0, -1);
  var select2placeHolder = params.placeholder || Spree.translations.search;
  var select2Multiple = params.multiple || false;
  var select2allowClear = params.allow_clear || false;
  var returnAttribute = params.return_attribute || 'name';
  var minimumInput = params.minimum_input || 3;
  var searchQuery = params.search_query || 'name_i_cont';
  var customReturnId = params.custom_return_id || null;
  var additionalUrlParams = params.additional_url_params || null;
  var DebugMode = params.debug_mode || null;

  //
  // Set up a clean URL for sparseFields
  if (customReturnId == null) {
    returnedFields = returnAttribute;
  } else {
    returnedFields = returnAttribute + "," + customReturnId;
  }
  var sparseFields = "fields[" + resourceSingular + "]=" + returnedFields;

  //
  // Set up a clean URL for Additional URL Params
  if (additionalUrlParams != null) {
    // URL + Additional URL Params + Sparse Fields
    apiUrl = params.apiUrl + "?" + additionalUrlParams + "&amp;" + sparseFields;
  } else {
    // URL + Sparse Fields (the default response for a normal Select2)
    apiUrl = params.apiUrl + "?" + sparseFields;
  }

  if (DebugMode != null) console.log('Request URL:' + apiUrl);

  //
  // Format the returned values.
  function formatList(values) {
    if (customReturnId) {
      return values.map(function (obj) {
        return {
          id: obj.attributes[customReturnId],
          text: obj.attributes[returnAttribute]
        };
      });
    } else {
      return values.map(function (obj) {
        return {
          id: obj.id,
          text: obj.attributes[returnAttribute]
        };
      });
    }
  }

  //
  // Set-up Select2 and make AJAX request.
  this.select2({
    multiple: select2Multiple,
    allowClear: select2allowClear,
    placeholder: select2placeHolder,
    minimumInputLength: minimumInput,
    ajax: {
      url: apiUrl,
      headers: Spree.apiV2Authentication(),
      data: function data(params) {
        return {
          filter: _defineProperty({}, searchQuery, params.term)
        };
      },
      processResults: function processResults(json) {
        if (DebugMode != null) console.log(json);

        return {
          results: formatList(json.data)
        };
      }
    }
  });
};
/**
  populateSelectOptionsFromApi(params)
  Allows you to easily fetch data from API (Platform v2) and populate an empty &lt;select&gt; with &lt;option&gt; tags, including a selected &lt;option&gt; tag.

  ## EXAMPLE A
  # Populating a list of all taxons including a selected item

  populateSelectOptionsFromApi({
    targetElement: '#mySelectElement',
    apiUrl: Spree.routes.taxons_api_v2,
    returnAttribute: 'pretty_name',

    &lt;% if @menu_item.linked_resource_id %&gt;
      selectedOption: &lt;%= @menu_item.linked_resource_id %&gt;
    &lt;% end %&gt;
  })

  ## EXAMPLE B
  # Populating a single selected item using filter and returning an attribute other than the ID

  &lt;% if resource.link_one.present? %&gt;
    &lt;script&gt;
      populateSelectOptionsFromApi({
        targetElement: "#&lt;%= save_to %&gt;Select2",
        apiUrl: Spree.routes.taxons_api_v2 + "?filter[permalink_matches]=&lt;%= resource.send(save_to) %&gt;",
        returnValueFromAttributes: 'permalink',
        returnOptionText: 'pretty_name',

        &lt;% if resource.send(save_to) %&gt;
          selectedOption: "&lt;%= resource.send(save_to) %&gt;"
        &lt;% end %&gt;
      })
    &lt;/script&gt;
  &lt;% end %&gt;
**/

// eslint-disable-next-line no-unused-vars
var populateSelectOptionsFromApi = function populateSelectOptionsFromApi(params) {
  createRequest(params, updateSelectSuccess, updateSelectError);
};

var handleErrors = function handleErrors(response) {
  if (!response.ok) throw new Error(response.status + ': ' + response.statusText);

  return response.json();
};

var createRequest = function createRequest(params, succeed, fail) {
  var targetElement = params.targetElement;
  var apiUrl = params.apiUrl;
  var returnOptionText = params.returnOptionText;
  var returnValueFromAttributes = params.returnValueFromAttributes || null;
  var selectedOption = params.selectedOption;
  var selectEl = document.querySelector(targetElement);

  fetch(apiUrl, { headers: Spree.apiV2Authentication() }).then(function (response) {
    return handleErrors(response);
  }).then(function (json) {
    return succeed(json.data, returnValueFromAttributes, returnOptionText, selectEl, selectedOption);
  })['catch'](function (error) {
    return fail(error, selectEl);
  });
};

var updateSelectSuccess = function updateSelectSuccess(parsedData, returnValueFromAttributes, returnOptionText, selectEl, selectedOption) {
  var selectedOpt = selectEl.querySelector('option[selected]');

  parsedData.forEach(function (object) {
    var optionEl = document.createElement('option');

    if (returnValueFromAttributes == null) {
      optionEl.value = object.id;
      if (selectedOption === object.id) optionEl.selected = true;
    } else {
      optionEl.value = object.attributes[returnValueFromAttributes];
      if (selectedOpt.value === object.attributes[returnValueFromAttributes]) {
        selectedOpt.remove();

        optionEl.setAttribute('selected', 'selected');
      }
    }

    optionEl.innerHTML = object.attributes[returnOptionText];
    selectEl.appendChild(optionEl);
  });
};

var updateSelectError = function updateSelectError(error, selectEl) {
  console.log(error);
};
document.addEventListener("spree:load", function () {
  var parentEl = document.getElementsByClassName('sortable')[0];
  if (parentEl) {
    var element = parentEl.querySelector('tbody');
  }

  if (element) {
    Sortable.create(element, {
      handle: '.move-handle',
      animation: 550,
      ghostClass: 'bg-light',
      dragClass: 'sortable-drag-v',
      easing: 'cubic-bezier(1, 0, 0, 1)',
      swapThreshold: 0.9,
      forceFallback: true,
      onEnd: function onEnd(evt) {
        var itemEl = evt.item;
        var positions = { authenticity_token: AUTH_TOKEN };
        $.each($('tr', element), function (position, obj) {
          var reg = /spree_(\w+_?)+_(\d+)/;
          var parts = reg.exec($(obj).prop('id'));
          if (parts) {
            positions['positions[' + parts[2] + ']'] = position + 1;
          }
        });
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: $(itemEl).closest('table.sortable').data('sortable-link'),
          data: positions
        });
      }
    });
  }
});
document.addEventListener("spree:load", function () {
  var navWrapper = document.querySelectorAll('[data-nav-x-wrapper]');
  navWrapper.forEach(function (el) {
    return initHorizontalNav(el);
  });
});

var SETTINGS = {
  navBarTravelling: false,
  navBarTravelDirection: '',
  navBarTravelDistance: 150
};

function initHorizontalNav(containerEl) {
  var navAdvanceLeft = containerEl.querySelector('.nav-x_Advancer_Left');
  var navAdvanceRight = containerEl.querySelector('.nav-x_Advancer_Right');
  var navContainer = containerEl.querySelector('[data-nav-x-container]');
  var navContent = navContainer.querySelector('[data-nav-x-content]');
  var activeNavItem = navContent.querySelector('.active');

  // Trigger on spree:load
  setOverscrollIndicators();

  if (activeNavItem) focusActiveItem(navContainer, activeNavItem);

  window.addEventListener('resize', function () {
    // Trigger on window resize
    setOverscrollIndicators();
    focusActiveItem(navContainer, activeNavItem);
  });

  navContainer.addEventListener('scroll', function () {
    // Trigger on Side Scrolling
    setOverscrollIndicators();
  });

  function setOverscrollIndicators() {
    navContainer.setAttribute('data-overflowing', determineOverflow(navContent, navContainer));
  }

  navAdvanceLeft.addEventListener('click', function () {
    // If in the middle of a move return
    if (SETTINGS.navBarTravelling === true) return;

    // If we have content overflowing both sides or on the left
    if (determineOverflow(navContent, navContainer) === 'left' || determineOverflow(navContent, navContainer) === 'both') {
      // Find how far this panel has been scrolled
      var availableScrollLeft = navContainer.scrollLeft;
      // If the space available is less than two lots of our desired distance, just move the whole amount
      // otherwise, move by the amount in the settings
      if (availableScrollLeft &lt; SETTINGS.navBarTravelDistance * 2) {
        navContent.style.transform = 'translateX(' + availableScrollLeft + 'px)';
      } else {
        navContent.style.transform = 'translateX(' + SETTINGS.navBarTravelDistance + 'px)';
      }
      // We do want a transition (this is set in CSS) when moving so remove the class that would prevent that
      navContent.classList.remove('nav-x_Transition_None');
      // Update our settings
      SETTINGS.navBarTravelDirection = 'left';
      SETTINGS.navBarTravelling = true;
    }
    // Now update the attribute in the DOM
    navContainer.setAttribute('data-overflowing', determineOverflow(navContent, navContainer));
  });

  navAdvanceRight.addEventListener('click', function () {
    // If in the middle of a move return
    if (SETTINGS.navBarTravelling === true) return;

    // If we have content overflowing both sides or on the right
    if (determineOverflow(navContent, navContainer) === 'right' || determineOverflow(navContent, navContainer) === 'both') {
      // Get the right edge of the container and content
      var navBarRightEdge = navContent.getBoundingClientRect().right;
      var navBarScrollerRightEdge = navContainer.getBoundingClientRect().right;
      // Now we know how much space we have available to scroll
      var availableScrollRight = Math.floor(navBarRightEdge - navBarScrollerRightEdge);
      // If the space available is less than two lots of our desired distance, just move the whole amount
      // otherwise, move by the amount in the settings
      if (availableScrollRight &lt; SETTINGS.navBarTravelDistance * 2) {
        navContent.style.transform = 'translateX(-' + availableScrollRight + 'px)';
      } else {
        navContent.style.transform = 'translateX(-' + SETTINGS.navBarTravelDistance + 'px)';
      }
      // We do want a transition (this is set in CSS) when moving so remove the class that would prevent that
      navContent.classList.remove('nav-x_Transition_None');
      // Update our settings
      SETTINGS.navBarTravelDirection = 'right';
      SETTINGS.navBarTravelling = true;
    }
    // Now update the attribute in the DOM
    navContainer.setAttribute('data-overflowing', determineOverflow(navContent, navContainer));
  });

  navContent.addEventListener('transitionend', function () {
    // get the value of the transform, apply that to the current scroll position (so get the scroll pos first) and then remove the transform
    var styleOfTransform = window.getComputedStyle(navContent, null);
    var tr = styleOfTransform.getPropertyValue('transform') || styleOfTransform.getPropertyValue('transform');
    // If there is no transition we want to default to 0 and not null

    var amount = Math.abs(parseInt(tr.split(',')[4]) || 0);

    navContent.style.transform = 'none';
    navContent.classList.add('nav-x_Transition_None');
    // Now lets set the scroll position
    if (SETTINGS.navBarTravelDirection === 'left') {
      navContainer.scrollLeft = navContainer.scrollLeft - amount;
    } else {
      navContainer.scrollLeft = navContainer.scrollLeft + amount;
    }
    SETTINGS.navBarTravelling = false;
  });
}

// Set active link into view
function focusActiveItem(containerEl, activeEl) {
  if (!activeEl) return;

  containerEl.scrollLeft = activeEl.offsetLeft - 45;
}

// Determine Scroll status
function determineOverflow(content, container) {
  var containerMetrics = container.getBoundingClientRect();
  var containerMetricsRight = Math.floor(containerMetrics.right);
  var containerMetricsLeft = Math.floor(containerMetrics.left);
  var contentMetrics = content.getBoundingClientRect();
  var contentMetricsRight = Math.floor(contentMetrics.right);
  var contentMetricsLeft = Math.floor(contentMetrics.left);

  if (containerMetricsLeft &gt; contentMetricsLeft &amp;&amp; containerMetricsRight &lt; contentMetricsRight) {
    return 'both';
  } else if (contentMetricsLeft &lt; containerMetricsLeft) {
    return 'left';
  } else if (contentMetricsRight &gt; containerMetricsRight) {
    return 'right';
  } else {
    return 'none';
  }
};
document.addEventListener("spree:load", function () {
  tinymce.remove(); // Required for spree:load

  tinymce.init({
    selector: '.spree-rte',
    plugins: ['image table paste code link table'],
    menubar: false,
    toolbar: 'undo redo | styleselect | bold italic link forecolor backcolor | alignleft aligncenter alignright alignjustify | table | bullist numlist outdent indent | code '
  });
});













// we need to delete select2 instances before document is saved to cache
// https://stackoverflow.com/questions/36497723/select2-with-ajax-gets-initialized-several-times-with-rails-turbolinks-events
document.addEventListener("turbo:before-cache", function() {
  $('select.select2').select2('destroy')
  $('select.select2-clear').select2('destroy')
})

document.addEventListener("spree:load", function() {
  // Initiate a standard Select2 on any select element with the class .select2
  // Remember to add a place holder in the HTML as needed.
  $('select.select2').select2({})

  // Initiate a Select2 with the option to clear, on any select element with the class .select2-clear
  // Set: include_blank: true in the ERB.
  // A placeholder is auto-added here as it is required to clear the Select2.
  $('select.select2-clear').select2({
    placeholder: Spree.translations.select_an_option,
    allowClear: true
  })
})

$.fn.addSelect2Options = function (data) {
  var select = this

  function appendOption(select, data) {
    var option = null;
    if (data.attributes) {
      // API v2
      option = new Option(data.attributes.name, data.id, true, true)
    } else {
      // API v1
      option = new Option(data.name, data.id, true, true)
    }
    select.append(option).trigger('change')
  }

  if (Array.isArray(data)) {
    data.map(function(row) {
      appendOption(select, row)
    })
  } else {
    appendOption(select, data)
  }
  select.trigger({
    type: 'select2:select',
    params: {
      data: data
    }
  })
}

$.fn.select2.defaults.set('width', 'style')
$.fn.select2.defaults.set('dropdownAutoWidth', false)
$.fn.select2.defaults.set('theme', 'bootstrap4')

function formatSelect2Options(data) {
  var results = data.data.map(function (obj) {
    return {
      id: obj.id,
      text: obj.attributes.name
    }
  })

  return { results: results }
};
function updateAddressState(region, successCallback) {
  var countryId = $('#' + region + 'country select').val();
  var stateContainer = $('#' + region + 'state').parent();
  var stateSelect = $('#' + region + 'state select');
  var stateInput = $('#' + region + 'state input.state_name');

  if (!countryId) {
    return;
  }

  fetch(Spree.routes.countries_api_v2 + '/' + countryId + '?include=states', {
    headers: Spree.apiV2Authentication()
  }).then(function (response) {
    switch (response.status) {
      case 200:
        response.json().then(function (json) {
          var states = json.included;
          var statesRequired = json.data.attributes.states_required;
          if (states.length &gt; 0) {
            stateSelect.html('');
            $.each(states, function (_pos, state) {
              var opt = $(document.createElement('option')).prop('value', state.id).html(state.attributes.name);
              stateSelect.append(opt).trigger('change');
            });
            stateSelect.prop('disabled', false).show();
            stateSelect.select2();
            stateInput.hide().prop('disabled', true);
            stateContainer.show();
          } else {
            stateSelect.val(null).trigger('change');
            if (stateSelect.data('select2')) {
              stateSelect.select2('destroy');
            }
            stateSelect.hide();
            if (statesRequired) {
              stateInput.prop('disabled', false).show();
            } else {
              stateContainer.hide();
            }
          }
          if (successCallback) successCallback();
        });
        break;
    }
  });
};
/* global order_number, show_flash */
document.addEventListener("spree:load", function() {
  $('[data-hook=adjustments_new_coupon_code] #add_coupon_code').click(function () {
    var couponCode = $('#coupon_code').val()
    if (couponCode.length === 0) {
      return
    }
    $.ajax({
      type: 'PATCH',
      url: Spree.routes.apply_coupon_code(order_number),
      data: {
        coupon_code: couponCode,
      },
      headers: Spree.apiV2Authentication(),
    }).done(function () {
      window.location.reload()
    }).fail(function (message) {
      if (message.responseJSON['error']) {
        show_flash('error', message.responseJSON['error'])
      } else {
        show_flash('error', 'There was a problem adding this coupon code.')
      }
    })
  })
});
/* global order_number, show_flash */

document.addEventListener("spree:load", function() {
  /**
    OBSERVE FIELD:
  **/
  $('.observe_field').on('change', function() {
    var target = $(this).data('update')
    $(target).hide()
    $.ajax({
      dataType: 'html',
      url: $(this).data('base-url') + encodeURIComponent($(this).val()),
      type: 'GET'
    }).done(function(data) {
      $(target).html(data)
      $(target).show()
    })
  })

  /**
    ADD FIELDS
  **/
  var uniqueId = 1
  $('.spree_add_fields').click(function() {
    var target = $(this).data('target')
    var newTableRow = $(target + ' tr:visible:last').clone()
    var newId = new Date().getTime() + (uniqueId++)
    newTableRow.find('input, select').each(function() {
      var el = $(this)
      el.val('')
      el.prop('id', el.prop('id').replace(/\d+/, newId))
      el.prop('name', el.prop('name').replace(/\d+/, newId))
    })

    // When cloning a new row, set the href of all icons to be an empty "#"
    // This is so that clicking on them does not perform the actions for the
    // duplicated row
    newTableRow.find('a').each(function() {
      var el = $(this)
      el.prop('href', '#')
    })
    $(target).prepend(newTableRow)
  })

  /**
    DELETE RESOURCE
  **/
  $('body').on('click', '.delete-resource', function() {
    var el = $(this)
    if (confirm(el.data('confirm'))) {
      $.ajax({
        type: 'POST',
        url: $(this).prop('href'),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        dataType: 'script',
        complete: function() {
          el.blur()
        }
      }).done(function() {
        var $flashElement = $('#FlashAlertsContainer span[data-alert-type="success"]')
        if ($flashElement.length) {
          el.parents('tr').fadeOut('hide', function() {
            $(this).remove()
          })
          el.closest('.removable-dom-element').fadeOut('hide', function() {
            $(this).remove()
          })
          var livePreview = document.getElementById('pageLivePreview')
          if (livePreview) { livePreview.contentWindow.location.reload() }
        }
      }).fail(function(response) {
        show_flash('error', response.responseText)
      })
    } else {
      el.blur()
    }
    return false
  })

  /**
    REMOVE FIELDS
  **/
  $('body').on('click', 'a.spree_remove_fields', function() {
    var el = $(this)
    el.prev('input[type=hidden]').val('1')
    el.closest('.fields').hide()
    if (el.prop('href').substr(-1) === '#') {
      el.parents('tr').fadeOut('hide')
    } else if (el.prop('href')) {
      $.ajax({
        type: 'POST',
        url: el.prop('href'),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        }
      }).done(function() {
        el.parents('tr').fadeOut('hide', function() {
          $(this).remove()
        })
      }).fail(function(response) {
        show_flash('error', response.responseText)
      })
    }
    return false
  })

  /**
    SELECT PROPERTIES FROM PROTOTYPE
  **/
  $('body').on('click', '.select_properties_from_prototype', function() {
    $('#busy_indicator').show()
    var clickedLink = $(this)
    $.ajax({
      dataType: 'script',
      url: clickedLink.prop('href'),
      type: 'GET'
    }).done(function() {
      clickedLink.parent('td').parent('tr').hide()
      $('#busy_indicator').hide()
    })
    return false
  })

  /**
    UTILITY
  **/
  window.Spree.advanceOrder = function() {
    $.ajax({
      type: 'PATCH',
      async: false,
      headers: Spree.apiV2Authentication(),
      url: Spree.url(Spree.routes.orders_api_v2 + '/' + order_number + '/advance')
    }).done(function() {
      window.location.reload()
    })
  }
});
document.addEventListener("spree:load", function() {
  var calculatorSelect = $('select#calc_type')
  var originalCalcType = calculatorSelect.prop('value')
  $('.calculator-settings-warning').hide()
  calculatorSelect.change(function () {
    // eslint-disable-next-line
    if (calculatorSelect.prop('value') == originalCalcType) {
      $('div.calculator-settings').show()
      $('#shipping_method_calculator_attributes_preferred_currency').removeAttr('disabled')
      $('.calculator-settings-warning').hide()
      $('.calculator-settings').find('input, textarea').prop('disabled', false)
    } else {
      $('div.calculator-settings').hide()
      $('#shipping_method_calculator_attributes_preferred_currency').attr('disabled', 'disabled')
      $('.calculator-settings-warning').show()
      $('.calculator-settings').find('input, textarea').prop('disabled', true)
    }
  })
});
function clearAddressFields(addressKinds) {
  if (addressKinds === undefined) {
    addressKinds = ['ship', 'bill']
  }
  addressKinds.forEach(function(addressKind) {
    ADDRESS_FIELDS.forEach(function(field) {
      $('#order_' + addressKind + '_address_attributes_' + field).val('')
    })
  })
}

function formatCustomerResult(customer) {
  var escapedResult = window.customerTemplate({
    customer: customer,
    bill_address: customer.bill_address,
    ship_address: customer.ship_address
  })
  return $(escapedResult)
}

function formatCustomerAddress(address, kind) {
  $('#order_' + kind + '_address_attributes_firstname').val(address.firstname)
  $('#order_' + kind + '_address_attributes_lastname').val(address.lastname)
  $('#order_' + kind + '_address_attributes_address1').val(address.address1)
  $('#order_' + kind + '_address_attributes_company').val(address.company)
  $('#order_' + kind + '_address_attributes_address2').val(address.address2)
  $('#order_' + kind + '_address_attributes_city').val(address.city)
  $('#order_' + kind + '_address_attributes_zipcode').val(address.zipcode)
  $('#order_' + kind + '_address_attributes_phone').val(address.phone)
  $('#order_' + kind + '_address_attributes_phone').val(address.phone)
  $('#order_' + kind + '_address_attributes_country_id').val(address.country.id)
  $('#order_' + kind + '_address_attributes_country_id').trigger('change')

  var stateSelect = $('#order_' + kind + '_address_attributes_state_id')

  updateAddressState(kind.charAt(0), function() {
    if (address.state) {
      stateSelect.val(address.state.id).trigger('change')
    }
  })
}

function formatCustomerSelection(customer) {
  $('#order_email').val(customer.email)
  $('#order_user_id').val(customer.id)
  $('#guest_checkout_true').prop('checked', false)
  $('#guest_checkout_false').prop('checked', true)
  $('#guest_checkout_false').prop('disabled', false)

  var billAddress = customer.bill_address
  var shipAddress = customer.ship_address

  if (billAddress) {
    formatCustomerAddress(billAddress, 'bill')
  } else {
    clearAddressFields(['bill'])
  }

  if (shipAddress) {
    formatCustomerAddress(shipAddress, 'ship')
  } else {
    clearAddressFields(['ship'])
  }

  return customer.email
}

$.fn.customerAutocomplete = function() {
  var jsonApiUsers = {}

  this.select2({
    minimumInputLength: 3,
    placeholder: Spree.translations.choose_a_customer,
    ajax: {
      url: Spree.routes.users_api_v2,
      datatype: 'json',
      headers: Spree.apiV2Authentication(),
      data: function (params) {
        return {
          filter: {
            'm': 'or',
            email_i_cont: params.term,
            addresses_firstname_start: params.term,
            addresses_lastname_start: params.term
          },
          include: 'ship_address.country,ship_address.state,bill_address.country,bill_address.state'
        }
      },
      success: function(data) {
        var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer
        new JSONAPIDeserializer({ keyForAttribute: 'snake_case' }).deserialize(data, function (_err, users) {
          jsonApiUsers = users
        })
      },
      processResults: function (_data) {
        return { results: jsonApiUsers } // we need to return deserialized json api data
      }
    },
    templateResult: formatCustomerResult
  }).on('select2:select', function (e) {
    var data = e.params.data;
    formatCustomerSelection(data)
  })
}

document.addEventListener("spree:load", function() {
  $('#customer_search').customerAutocomplete()

  if ($('#customer_autocomplete_template').length &gt; 0) {
    window.customerTemplate = Handlebars.compile($('#customer_autocomplete_template').text())
  }

  // Handle Billing Shipping Address
  var orderUseBillingInput = $('input#order_use_billing')

  var orderUseBilling = function () {
    if (!orderUseBillingInput.is(':checked')) {
      $('#shipping').show()
    } else {
      $('#shipping').hide()
    }
  }

  // On page load hide shipping address from
  orderUseBilling()

  // On click togggle shipping address from
  orderUseBillingInput.click(orderUseBilling)

  // If guest checkout clear fields
  $('#guest_checkout_true').change(function () {
    $('#customer_search').val('')
    $('#order_user_id').val('')
    $('#order_email').val('')
    clearAddressFields()
  })
});
document.addEventListener("spree:load", function() {
  var originalGtwyType = $('#gtwy-type').prop('value')
  $('div#gateway-settings-warning').hide()
  $('#gtwy-type').change(function () {
    // eslint-disable-next-line
    if ($('#gtwy-type').prop('value') == originalGtwyType) {
      $('div.gateway-settings').show()
      $('div#gateway-settings-warning').hide()
    } else {
      $('div.gateway-settings').hide()
      $('div#gateway-settings-warning').show()
    }
  })
});
/* global show_flash */
document.addEventListener("spree:load", function() {
  $('[data-hook=general_settings_clear_cache] #clear_cache').click(function () {
    if (confirm(Spree.translations.are_you_sure)) {
      $.ajax({
        type: 'POST',
        url: Spree.routes.clear_cache,
        data: {
          authenticity_token: AUTH_TOKEN
        },
        dataType: 'json'
      }).done(function () {
        show_flash('success', 'Cache was flushed.')
      })
        .fail(function (message) {
          if (message.responseJSON['error']) {
            show_flash('error', message.responseJSON['error'])
          } else {
            show_flash('error', 'There was a problem while flushing cache.')
          }
        })
    }
  })
});
Handlebars.registerHelper('t', function (key) {
  if (Spree.translations[key]) {
    return Spree.translations[key]
  } else {
    console.error('No translation found for ' + key + '. Does it exist within spree/admin/shared/_translations.html.erb?')
  }
})
Handlebars.registerHelper('edit_product_url', function (productId) {
  return Spree.routes.edit_product(productId)
})
Handlebars.registerHelper('name_or_presentation', function (optionValue) {
  if (optionValue.option_type_name === 'color') {
    return optionValue.name
  } else {
    return optionValue.presentation
  }
});
/* global toggleItemEdit, order_number */
document.addEventListener("spree:load", function() {
  // handle edit click
  $('a.edit-line-item').click(toggleLineItemEdit)
  // handle cancel click
  $('a.cancel-line-item').click(toggleLineItemEdit)
  // handle save click
  $('a.save-line-item').click(function () {
    var save = $(this)
    var lineItemId = save.data('line-item-id')
    var quantity = parseInt(save.parents('tr').find('input.line_item_quantity').val())
    toggleItemEdit()
    adjustLineItem(lineItemId, quantity)
  })
  // handle delete click
  $('a.delete-line-item').click(function () {
    if (confirm(Spree.translations.are_you_sure_delete)) {
      var del = $(this)
      var lineItemId = del.data('line-item-id')
      toggleItemEdit()
      deleteLineItem(lineItemId)
    }
  })
})

function toggleLineItemEdit () {
  var link = $(this)
  var parent = link.parent()
  var tr = link.parents('tr')
  parent.find('a.edit-line-item').toggle()
  parent.find('a.cancel-line-item').toggle()
  parent.find('a.save-line-item').toggle()
  parent.find('a.delete-line-item').toggle()
  tr.find('td.line-item-qty-show').toggle()
  tr.find('td.line-item-qty-edit').toggle()
}

function lineItemURL (lineItemId) {
  // eslint-disable-next-line camelcase
  return Spree.routes.line_items_api_v2 + '/' + lineItemId
}

function adjustLineItem (lineItemId, quantity) {
  $.ajax({
    type: 'PATCH',
    url: Spree.url(lineItemURL(lineItemId)),
    data: {
      line_item: {
        quantity: quantity
      }
    },
    headers: Spree.apiV2Authentication(),
  }).done(function () {
    window.Spree.advanceOrder()
  })
}

function deleteLineItem (lineItemId) {
  $.ajax({
    type: 'DELETE',
    url: Spree.url(lineItemURL(lineItemId)),
    headers: Spree.apiV2Authentication(),
  }).done(function () {
    $('#line-item-' + lineItemId).remove()
    if ($('.line-items tr.line-item').length === 0) {
      $('.line-items').remove()
    }
    window.Spree.advanceOrder()
  })
};
/* global variantLineItemTemplate, order_number, order_id */
// This file contains the code for interacting with line items in the manual cart
document.addEventListener("spree:load", function() {
  'use strict'

  // handle variant selection, show stock level.
  $('#add_line_item_variant_id').change(function () {
    var variantId = $(this).val().toString()

    var variant = _.find(window.variants, function (variant) {
      // eslint-disable-next-line eqeqeq
      return variant.id.toString() == variantId
    })
    $('#stock_details').html(variantLineItemTemplate({ variant: variant }))
    $('#stock_details').show()
    $('button.add_variant').click(addVariant)
  })
})

function addVariant () {
  $('#stock_details').hide()
  var variantId = $('select.variant_autocomplete').val()
  var quantity = parseInt($('input#variant_quantity').val())

  adjustLineItems(order_id, variantId, quantity)
  return 1
}

adjustLineItems = function(order_id, variant_id, quantity){
  $.ajax({
    type: 'POST',
    url: Spree.routes.line_items_api_v2,
    data: {
      line_item: {
        order_id: order_id,
        variant_id: variant_id,
        quantity: quantity
      }
    },
    headers: Spree.apiV2Authentication()
  }).done(function () {
      window.Spree.advanceOrder()
      window.location.reload()
  }).fail(function (response) {
    show_flash('error', response.responseJSON.error)
  })
};























































Spree.routes.clear_cache = Spree.adminPathFor('general_settings/clear_cache')

Spree.routes.edit_product = function (productId) {
  return Spree.adminPathFor('products/' + productId + '/edit')
}
Spree.routes.apply_coupon_code = function (orderId) {
  return Spree.pathFor('api/v2/platform/orders/' + orderId + '/apply_coupon_code')
}

// API v2
Spree.routes.countries_api_v2 = Spree.pathFor('api/v2/platform/countries')
Spree.routes.classifications_api_v2 = Spree.pathFor('api/v2/platform/classifications')
Spree.routes.line_items_api_v2 = Spree.pathFor('api/v2/platform/line_items')
Spree.routes.menus_api_v2 = Spree.pathFor('api/v2/platform/menus')
Spree.routes.menus_items_api_v2 = Spree.pathFor('api/v2/platform/menu_items')
Spree.routes.option_types_api_v2 = Spree.pathFor('api/v2/platform/option_types')
Spree.routes.option_values_api_v2 = Spree.pathFor('api/v2/platform/option_values')
Spree.routes.orders_api_v2 = Spree.pathFor('api/v2/platform/orders')
Spree.routes.layouts_api_v2 = Spree.pathFor('api/v2/platform/cms_layouts')
Spree.routes.pages_api_v2 = Spree.pathFor('api/v2/platform/cms_pages')
Spree.routes.payments_api_v2 = Spree.pathFor('/api/v2/platform/payments')
Spree.routes.products_api_v2 = Spree.pathFor('/api/v2/platform/products')
Spree.routes.sections_api_v2 = Spree.pathFor('/api/v2/platform/cms_sections')
Spree.routes.shipments_api_v2 = Spree.pathFor('/api/v2/platform/shipments')
Spree.routes.stock_items_api_v2 = Spree.pathFor('/api/v2/platform/stock_items')
Spree.routes.stock_locations_api_v2 = Spree.pathFor('/api/v2/platform/stock_locations')
Spree.routes.taxons_api_v2 = Spree.pathFor('/api/v2/platform/taxons')
Spree.routes.users_api_v2 = Spree.pathFor('api/v2/platform/users')
Spree.routes.variants_api_v2 = Spree.pathFor('api/v2/platform/variants')

Spree.apiV2Authentication = function() {
  if (typeof(OAUTH_TOKEN) !== 'undefined') {
    return {
      'Authorization': 'Bearer ' + OAUTH_TOKEN
    }
  }
};

document.addEventListener("spree:load", function() {
  $.expr[':'].Contains = function (a, i, m) {
    return (
      (a.textContent || a.innerText || '')
        .toUpperCase()
        .indexOf(m[3].toUpperCase()) &gt;= 0
    )
  }

  function listFilter (list) {
    var input = $('#variant-price-search')

    $(input)
      .change(function () {
        var filter = $(this).val()
        if (filter) {
          $(list).find('.panel-title:not(:Contains(' + filter + '))').parent().hide()
          $(list).find('.panel-title:Contains(' + filter + ')').parent().show()
        } else {
          $(list)
            .find('.panel')
            .parent()
            .show()
        }
        return false
      })
      .keyup(function () {
        $(this).change()
      })
  }

  // ondomready
  document.addEventListener("spree:load", function() {
    listFilter($('#variant-prices'))
  })
});
$.fn.optionTypeAutocomplete = function () {
  'use strict'

  console.warn('optionTypeAutocomplete is deprecated and will be removed in Spree 5.0')

  this.select2({
    minimumInputLength: 2,
    multiple: true,
    ajax: {
      url: Spree.routes.option_types_api_v2,
      datatype: 'json',
      headers: Spree.apiV2Authentication(),
      data: function (params) {
        return {
          filter: {
            name_i_cont: params.term
          }
        }
      },
      processResults: function (data) {
        return formatSelect2Options(data)
      }
    }
  })
}

document.addEventListener("spree:load", function() {
  var productOptionTypeSelector = document.getElementById('product_option_type_ids')
  if (productOptionTypeSelector == null) return
  if (productOptionTypeSelector.hasAttribute('data-autocomplete-url-value')) return

  $('#product_option_type_ids').optionTypeAutocomplete()
});
$.fn.optionValueAutocomplete = function (options) {
  'use strict'

  // Default options
  options = options || {}
  var multiple = typeof (options.multiple) !== 'undefined' ? options.multiple : true
  var productSelect = options.productSelect
  var productId = options.productId
  var values = options.values
  var clearSelection = options.clearSelection

  function addOptions(select, productId, values) {
    $.ajax({
      type: 'GET',
      url: Spree.routes.option_values_api_v2,
      headers: Spree.apiV2Authentication(),
      dataType: 'json',
      data: {
        filter: {
          id_in: values,
          variants_product_id_eq: productId
        }
      }
    }).then(function (data) {
      select.addSelect2Options(data.data)
    })
  }

  this.select2({
    multiple: multiple,
    minimumInputLength: 1,
    ajax: {
      url: Spree.routes.option_values_api_v2,
      dataType: 'json',
      headers: Spree.apiV2Authentication(),
      data: function (params) {
        var selectedProductId = typeof (productSelect) !== 'undefined' ? productSelect.val() : null

        return {
          filter: {
            name_cont: params.term,
            variants_product_id_eq: selectedProductId
          }
        }
      },
      processResults: function(data) {
        return formatSelect2Options(data)
      }
    }
  })

  if (values &amp;&amp; productId &amp;&amp; !clearSelection) {
    addOptions(this, productId, values)
  }

  if (clearSelection) {
    this.val(null).trigger('change')
  }
};
document.addEventListener("spree:load", function() {
  'use strict'
  $('[data-hook="add_product_name"]').find('.variant_autocomplete').variantAutocomplete()
});
/* global show_flash */
document.addEventListener("spree:load", function() {
  var extend = function (child, parent) {
    for (var key in parent) {
      if (hasProp.call(parent, key)) child[key] = parent[key]
    }
    function Ctor () {
      this.constructor = child
    }
    Ctor.prototype = parent.prototype
    child.prototype = new Ctor()
    child.__super__ = parent.prototype
    return child
  }
  var hasProp = {}.hasOwnProperty
  var EditPaymentView, Payment, PaymentView, ShowPaymentView
  Payment = (function () {
    function Payment (id) {
      this.url = Spree.routes.payments_api_v2 + '/' + id
      this.json = $.ajax({
        dataType: "json",
        url: this.url,
        headers: Spree.apiV2Authentication(),
        success: function (data) {
          this.data = data.data
        }.bind(this)
      })
      this.updating = false
    }

    Payment.prototype.if_editable = function (callback) {
      return this.json.done(function (data) {
        var ref
        if ((ref = data.data.attributes.state) === 'checkout' || ref === 'pending') {
          return callback()
        }
      })
    }

    Payment.prototype.update = function (attributes, onDone) {
      this.updating = true
      var jqXHR = $.ajax({
        type: 'PATCH',
        url: this.url,
        data: {
          payment: attributes
        },
        headers: Spree.apiV2Authentication()
      })
      jqXHR.always(function () {
        this.updating = false
      }.bind(this))
      jqXHR.done(function (data) {
        this.data = data.data
        onDone()
      }.bind(this))
      jqXHR.fail(function () {
        var response = (jqXHR.responseJSON &amp;&amp; jqXHR.responseJSON.error) || jqXHR.statusText
        show_flash('error', response)
        onDone()
      })
      return jqXHR
    }

    Payment.prototype.amount = function () {
      return this.data.attributes.amount
    }

    Payment.prototype.display_amount = function () {
      return this.data.attributes.display_amount
    }
    return Payment
  })()

  PaymentView = (function () {
    function PaymentView ($el1, payment1) {
      this.$el = $el1
      this.payment = payment1
      this.render()
    }

    PaymentView.prototype.render = function () {
      return this.add_action_button()
    }

    PaymentView.prototype.show = function () {
      this.remove_buttons()
      return new ShowPaymentView(this.$el, this.payment)
    }

    PaymentView.prototype.edit = function () {
      this.remove_buttons()
      return new EditPaymentView(this.$el, this.payment)
    }

    PaymentView.prototype.add_action_button = function () {
      return this.$actions().prepend(this.$new_button(this.action))
    }

    PaymentView.prototype.remove_buttons = function () {
      return this.$buttons().remove()
    }

    PaymentView.prototype.$new_button = function (action) {
      return $('&lt;a&gt;&lt;i class="icon icon-' + action + '"&gt;&lt;/i&gt;&lt;/a&gt;').attr({
        'class': 'payment-action-' + action + ' btn btn-outline-secondary btn-sm no-filter',
        title: Spree.translations[action]
      }).data({
        action: action
      }).one({
        click: function (event) {
          event.preventDefault()
        },
        mouseup: function () {
          this[action]()
        }.bind(this)
      })
    }

    PaymentView.prototype.$buttons = function () {
      return this.$actions().find('.payment-action-' + this.action + ', .payment-action-cancel')
    }

    PaymentView.prototype.$actions = function () {
      return this.$el.find('.payment-action-buttons')
    }

    PaymentView.prototype.$amount = function () {
      return this.$el.find('td.amount')
    }

    return PaymentView
  })()
  ShowPaymentView = (function (superClass) {
    extend(ShowPaymentView, superClass)

    function ShowPaymentView () {
      return ShowPaymentView.__super__.constructor.apply(this, arguments)
    }

    ShowPaymentView.prototype.action = 'edit'

    ShowPaymentView.prototype.render = function () {
      ShowPaymentView.__super__.render.apply(this, arguments)
      this.set_actions_display()
      this.show_actions()
      return this.show_amount()
    }

    ShowPaymentView.prototype.set_actions_display = function () {
      var width = this.$actions().width()
      return this.$actions().width(width).css('text-align', 'left')
    }

    ShowPaymentView.prototype.show_actions = function () {
      return this.$actions().find('a').show()
    }

    ShowPaymentView.prototype.show_amount = function () {
      var amount = $('&lt;span /&gt;').html(this.payment.display_amount()).one('click', function () {
        this.edit().$input().focus()
      }.bind(this))
      return this.$amount().html(amount)
    }

    return ShowPaymentView
  })(PaymentView)
  EditPaymentView = (function (superClass) {
    extend(EditPaymentView, superClass)

    function EditPaymentView () {
      return EditPaymentView.__super__.constructor.apply(this, arguments)
    }

    EditPaymentView.prototype.action = 'save'

    EditPaymentView.prototype.render = function () {
      EditPaymentView.__super__.render.apply(this, arguments)
      this.hide_actions()
      this.edit_amount()
      return this.add_cancel_button()
    }

    EditPaymentView.prototype.add_cancel_button = function () {
      return this.$actions().append(this.$new_button('cancel'))
    }

    EditPaymentView.prototype.hide_actions = function () {
      return this.$actions().find('a').not(this.$buttons()).hide()
    }

    EditPaymentView.prototype.edit_amount = function () {
      var amount = this.$amount()
      return amount.html(this.$new_input(amount.find('span').width()))
    }

    EditPaymentView.prototype.save = function () {
      if (!this.payment.updating) {
        return this.payment.update(
          {
            amount: this.$input().val()
          },
          function () {
            this.show()
          }.bind(this)
        )
      }
    }

    EditPaymentView.prototype.cancel = EditPaymentView.prototype.show

    EditPaymentView.prototype.$new_input = function (width) {
      var amount = this.constructor.normalize_amount(this.payment.display_amount())
      return $('&lt;input /&gt;').prop({
        id: 'amount',
        class: 'form-control',
        value: amount
      }).width(width * 2).css({
        'text-align': 'right'
      })
    }

    EditPaymentView.prototype.$input = function () {
      return this.$amount().find('input')
    }

    EditPaymentView.normalize_amount = function (amount) {
      var separator = Spree.translations.currency_separator
      return amount.replace(RegExp('[^\\d' + separator + ']', 'g'), '')
    }

    return EditPaymentView
  })(PaymentView)
  return $('.admin tr[data-hook=payments_row]').each(function () {
    var $el = $(this)
    var payment = new Payment($el.attr('data-id'))
    return payment.if_editable(function () {
      return new ShowPaymentView($el, payment)
    })
  })
});
/* global Cleave */

document.addEventListener("spree:load", function() {
  if ($('#new_payment').length) {
    var cardCodeCleave;
    var updateCardCodeCleave = function (length) {
      if (cardCodeCleave) cardCodeCleave.destroy()

      cardCodeCleave = new Cleave('.cardCode', {
        numericOnly: true,
        blocks: [length]
      })
    }

    updateCardCodeCleave(3)

    /* eslint-disable no-new */
    new Cleave('.cardNumber', {
      creditCard: true,
      onCreditCardTypeChanged: function (type) {
        $('.ccType').val(type)

        if (type === 'amex') {
          updateCardCodeCleave(4)
        } else {
          updateCardCodeCleave(3)
        }
      }
    })
    /* eslint-disable no-new */
    new Cleave('.cardExpiry', {
      date: true,
      datePattern: ['m', 'Y']
    })

    $('.payment_methods_radios').click(
      function () {
        $('.payment-methods').hide()
        $('.payment-methods :input').prop('disabled', true)
        if (this.checked) {
          $('#payment_method_' + this.value + ' :input').prop('disabled', false)
          $('#payment_method_' + this.value).show()
        }
      }
    )

    $('.payment_methods_radios').each(
      function () {
        if (this.checked) {
          $('#payment_method_' + this.value + ' :input').prop('disabled', false)
          $('#payment_method_' + this.value).show()
        } else {
          $('#payment_method_' + this.value).hide()
          $('#payment_method_' + this.value + ' :input').prop('disabled', true)
        }

        if ($('#card_new' + this.value).is('*')) {
          $('#card_new' + this.value).radioControlsVisibilityOfElement('#card_form' + this.value)
        }
      }
    )
  }
});
$.fn.productAutocomplete = function (options) {
  'use strict'

  // Default options
  options = options || {}
  var multiple = typeof (options.multiple) !== 'undefined' ? options.multiple : true
  var values = typeof (options.values) !== 'undefined' ? options.values : null

  function addOptions(select, values) {
    $.ajax({
      url: Spree.routes.products_api_v2,
      dataType: 'json',
      data: {
        filter: {
          id_in: values
        },
        fields: {
          product: 'name'
        }
      },
      headers: Spree.apiV2Authentication(),
    }).then(function (data) {
      select.addSelect2Options(data.data)
    })
  }

  this.select2({
    multiple: multiple,
    minimumInputLength: 3,
    ajax: {
      url: Spree.routes.products_api_v2,
      dataType: 'json',
      data: function (params) {
        return {
          filter: {
            name_or_master_sku_cont: params.term
          },
          fields: {
            product: 'name'
          }
        }
      },
      headers: Spree.apiV2Authentication(),
      processResults: function(data) {
        return formatSelect2Options(data)
      }
    }
  })

  if (values) {
    addOptions(this, values)
  }
}

document.addEventListener("spree:load", function() {
  $('.product_picker').productAutocomplete()
});
document.addEventListener("spree:load", function() {
  $(document).ajaxStart(function () {
    Turbo.navigator.delegate.adapter.progressBar.setValue(0)
    Turbo.navigator.delegate.adapter.progressBar.show()
  })
  $(document).ajaxStop(function () {
    Turbo.navigator.delegate.adapter.progressBar.setValue(1)
    Turbo.navigator.delegate.adapter.progressBar.hide()
  })
});
function initProductActions () {
  'use strict'

  $('#promotion-filters').find('.variant_autocomplete').variantAutocomplete()

  $('.calculator-fields').each(function () {
    var $fieldsContainer = $(this)
    var $typeSelect = $fieldsContainer.find('.type-select')
    var $settings = $fieldsContainer.find('.settings')
    var $warning = $fieldsContainer.find('.js-warning')
    var originalType = $typeSelect.val()

    $warning.hide()
    $typeSelect.change(function () {
      if ($(this).val() === originalType) {
        $warning.hide()
        $settings.show()
        $settings.find('input').removeProp('disabled')
        $settings.find('select').removeProp('disabled')
      } else {
        $warning.show()
        $settings.hide()
        $settings.find('input').prop('disabled', 'disabled')
        $settings.find('select').prop('disabled', 'disabled')
      }
    })
  })

  //
  // Option Value Promo Rule
  //
  if ($('#promo-rule-option-value-template').length) {
    var optionValueSelectNameTemplate = Handlebars.compile($('#promo-rule-option-value-option-values-select-name-template').html())
    var optionValueTemplate = Handlebars.compile($('#promo-rule-option-value-template').html())
    var optionValuesList = $('.js-promo-rule-option-values')

    var addOptionValue = function (productId, values) {
      var template = optionValueTemplate({
        productId: productId
      })

      optionValuesList.append(template)

      var optionValueId = '#promo-rule-option-value-'
      if (productId) {
        optionValueId += productId.toString()
      }
      var optionValue = optionValuesList.find(optionValueId)

      var productSelect = optionValue.find('.js-promo-rule-option-value-product-select')
      var valuesSelect = optionValue.find('.js-promo-rule-option-value-option-values-select')

      productSelect.productAutocomplete({ multiple: false, values: productId })
      productSelect.on('select2:select', function(e) {
        valuesSelect.attr('disabled', false).removeClass('d-none').addClass('d-block')
        valuesSelect.attr('name', optionValueSelectNameTemplate({ productId: productSelect.val() }).trim())
        valuesSelect.optionValueAutocomplete({
          productId: productId,
          productSelect: productSelect,
          multiple: true,
          values: values,
          clearSelection: productId != productSelect.val()
        })
      })
    }

    var originalOptionValues = $('.js-original-promo-rule-option-values').data('original-option-values')
    if (!$('.js-original-promo-rule-option-values').data('loaded')) {
      if ($.isEmptyObject(originalOptionValues)) {
        addOptionValue(null, null)
      } else {
        $.each(originalOptionValues, addOptionValue)
      }
    }
    $('.js-original-promo-rule-option-values').data('loaded', true)

    $(document).on('click', '.js-add-promo-rule-option-value', function (event) {
      event.preventDefault()
      addOptionValue(null, null)
    })

    $(document).on('click', '.js-remove-promo-rule-option-value', function () {
      $(this).parents('.promo-rule-option-value').remove()
    })
  }

  //
  // Tiered Calculator
  //
  if ($('#tier-fields-template').length &amp;&amp; $('#tier-input-name').length) {
    var tierFieldsTemplate = Handlebars.compile($('#tier-fields-template').html())
    var tierInputNameTemplate = Handlebars.compile($('#tier-input-name').html())

    var originalTiers = $('.js-original-tiers').data('original-tiers')
    $.each(originalTiers, function (base, value) {
      var fieldName = tierInputNameTemplate({ base: base }).trim()
      $('.js-tiers').append(tierFieldsTemplate({
        baseField: { value: base },
        valueField: { name: fieldName, value: value }
      }))
    })

    $(document).on('click', '.js-add-tier', function (event) {
      event.preventDefault()
      $('.js-tiers').append(tierFieldsTemplate({ valueField: { name: null } }))
    })

    $(document).on('click', '.js-remove-tier', function (event) {
      $(this).parents('.tier').remove()
    })

    $(document).on('change', '.js-base-input', function (event) {
      var valueInput = $(this).parents('.tier').find('.js-value-input')
      valueInput.attr('name', tierInputNameTemplate({ base: $(this).val() }).trim())
    })
  }

  //
  // CreateLineItems Promotion Action
  //
  (function () {
    function hideOrShowItemTables () {
      $('.promotion_action table').each(function () {
        if ($(this).find('td').length === 0) {
          $(this).hide()
        } else {
          $(this).show()
        }
      })
    }
    hideOrShowItemTables()

    // Remove line item
    function setupRemoveLineItems () {
      $('.remove_promotion_line_item').on('click', function () {
        var lineItemsEl = $($('.line_items_string')[0])
        var finder = new RegExp($(this).data('variant-id') + 'x\\d+')
        lineItemsEl.val(lineItemsEl.val().replace(finder, ''))
        $(this).parents('tr').remove()
        hideOrShowItemTables()
      })
    }

    setupRemoveLineItems()
    // Add line item to list
    $('.promotion_action.create_line_items button.add').off('click').click(function () {
      var $container = $(this).parents('.promotion_action')
      var product_name = $container.find('input[name="add_product_name"]').val()
      var variant_id = $container.find('input[name="add_variant_id"]').val()
      var quantity = $container.find('input[name="add_quantity"]').val()
      if (variant_id) {
        // Add to the table
        var newRow = '&lt;tr&gt;&lt;td&gt;' + product_name + '&lt;/td&gt;&lt;td&gt;' + quantity + '&lt;/td&gt;&lt;td&gt;&lt;i class="icon icon-cancel"&gt;&lt;/i&gt;&lt;/td&gt;&lt;/tr&gt;'
        $container.find('table').append(newRow)
        // Add to serialized string in hidden text field
        var $hiddenField = $container.find('.line_items_string')
        $hiddenField.val($hiddenField.val() + ',' + variantId + 'x' + quantity)
        setupRemoveLineItems()
        hideOrShowItemTables()
      }
      return false
    })
  })()
}

document.addEventListener("spree:load", function() {
  var promotion_form = $('form.edit_promotion')

  if (promotion_form.length) {
    initProductActions()
  }
});
document.addEventListener("spree:load", function () {
  var pageVisabilityAttribute = document.querySelectorAll('[data-cms-page-id]');
  var pageTypeSelector = document.getElementById('cms_page_type');
  var el = document.getElementById('cmsPagesectionsArea');

  if (pageTypeSelector) updateCmsPageType();

  $(pageTypeSelector).on('change', function () {
    updateCmsPageType();
  });

  if (el) {
    Sortable.create(el, {
      handle: '.move-handle',
      ghostClass: 'moving-this',
      animation: 550,
      easing: 'cubic-bezier(1, 0, 0, 1)',
      swapThreshold: 0.9,
      forceFallback: true,
      onEnd: function onEnd(evt) {
        handleSectionReposition(evt);
      }
    });
  }

  pageVisabilityAttribute.forEach(function (elem) {
    elem.addEventListener('change', function () {
      handleTogglePageVisibility(this);
    });
  });
});

function handleTogglePageVisibility(obj) {
  var checkedState = null;
  if (obj.checked) checkedState = true;

  var pageId = obj.dataset.cmsPageId;

  var data = {
    cms_page: {
      visible: checkedState
    }
  };
  var requestData = {
    uri: Spree.routes.pages_api_v2 + ('/' + pageId),
    method: 'PATCH',
    dataBody: data
  };
  spreeFetchRequest(requestData, handleToggleSuccess);

  function handleToggleSuccess() {
    toggleVisibilityState(obj);
    reloadPreview();
  }
}

function toggleVisibilityState(obj) {
  var statusHolder = document.getElementById('visibilityStatus');
  var pageHidden = statusHolder.querySelector('.page_hidden');
  var pageVisible = statusHolder.querySelector('.page_visible');

  if (obj.checked) {
    pageHidden.classList.add('d-none');
    pageVisible.classList.remove('d-none');
  } else {
    pageVisible.classList.add('d-none');
    pageHidden.classList.remove('d-none');
  }
}

function reloadPreview() {
  var liveLiewArea = document.getElementById('pageLivePreview');

  if (!liveLiewArea) return;

  liveLiewArea.contentWindow.location.reload();
}

function handleSectionReposition(evt) {
  var sectionId = evt.item.dataset.sectionId;
  var data = {
    cms_section: {
      position: parseInt(evt.newIndex, 10) + 1
    }
  };
  var requestData = {
    uri: Spree.routes.sections_api_v2 + '/' + sectionId,
    method: 'PATCH',
    dataBody: data
  };
  spreeFetchRequest(requestData, reloadPreview);
}

function updateCmsPageType() {
  var slugField = document.getElementById('cms_page_slug');
  var updatePageType = document.getElementById('updatePageType');

  if (!slugField) return;

  var selectedLinkType = $('#cms_page_type').val();

  if (selectedLinkType === 'Spree::Cms::Pages::Homepage') {
    slugField.disabled = true;
  } else {
    slugField.disabled = false;
  }

  if (!updatePageType) return;

  var existingType = updatePageType.dataset.pageType;

  if (selectedLinkType === existingType) {
    updatePageType.classList.add('d-none');
  } else {
    updatePageType.classList.remove('d-none');
  }
};
document.addEventListener("spree:load", function () {
  var sectionKindSelector = $('#cms_section_type').select2();
  var layoutSwitcher = $('#cms_section_layout_style').select2();

  sectionKindSelector.on('change', function () {
    var selectedValue = $(sectionKindSelector).val();
    var message = document.getElementById('alertToClickUpdate');
    var activeSectionKind = document.getElementById('CmsSectionType');

    if (!activeSectionKind) return;

    var panelType = activeSectionKind.dataset.panelSectionType;

    if (selectedValue === panelType) {
      activeSectionKind.classList = '';
      activeSectionKind.classList.add('d-block');

      message.classList = '';
      message.classList.add('d-none');
    } else {
      activeSectionKind.classList = '';
      activeSectionKind.classList.add('d-none');

      message.classList = '';
      message.classList.add('d-block');
    }
  });

  if (!layoutSwitcher) return;

  layoutSwitcher.on('change', function () {
    var layoutDefault = document.querySelector('#Default');
    var layoutReverse = document.querySelector('#Reversed');

    if (this.value === 'Default') {
      layoutDefault.classList = 'd-block';
      layoutReverse.classList = 'd-none';
    } else {
      layoutDefault.classList = 'd-none';
      layoutReverse.classList = 'd-block';
    }
  });
});
document.addEventListener("spree:load", function () {
  var linkSwitcher = $('.link_switcher').select2();

  linkSwitcher.on('change', function () {
    var selectedLinkToValue = $(this).val();
    var linkSwitcherTarget = this.dataset.targetField || 'menu_item_link';
    var activePanel = document.querySelector('div[data-panel-id=\'' + linkSwitcherTarget + '\']');
    var messagePanel = document.querySelector('div[data-target-message-pannel=\'' + linkSwitcherTarget + '\']');
    var panelType = activePanel.dataset.panelType;

    if (selectedLinkToValue === panelType) {
      activePanel.classList = '';
      activePanel.classList.add('d-block');

      messagePanel.classList = '';
      messagePanel.classList.add('d-none');
    } else {
      activePanel.classList = '';
      activePanel.classList.add('d-none');

      messagePanel.classList = '';
      messagePanel.classList.add('d-block');
    }
  });
});
document.addEventListener("spree:load", function () {
  var LiveViewSwitcher = document.getElementById('LiveViewSwitcher');

  if (!LiveViewSwitcher) return;

  LiveViewSwitcher.addEventListener('click', function (event) {
    if (event.target &amp;&amp; event.target.matches("input[type='radio']")) {
      switchLiveViewClass(event.target.id);
    }
  });

  function switchLiveViewClass(value) {
    var liveViewCont = document.getElementById('liveViewCont');

    liveViewCont.classList = '';
    liveViewCont.classList.add(value);
  }

  var cmsSectionEditorFullScreen = document.getElementById('cmsSectionEditorFullScreen');

  cmsSectionEditorFullScreen.addEventListener('click', function (event) {
    if (this.getAttribute('aria-pressed') === 'true') {
      document.body.removeAttribute('data-sections-editor-full-screen');
    } else {
      document.body.setAttribute('data-sections-editor-full-screen', '');
    }
  });

  var queryString = window.location.search;
  var urlParams = new URLSearchParams(queryString);
  var fullScreenMode = urlParams.get('section_editor_full_screen_mode');

  if (fullScreenMode) cmsSectionEditorFullScreen.click();
});
document.addEventListener("spree:load", function () {
  var LayoutVisabilityAttribute = document.querySelectorAll('[data-cms-layout-id]');

  LayoutVisabilityAttribute.forEach(function (elem) {
    elem.addEventListener('change', function () {
      handleToggleLayoutVisibility(this);
    });
  });
});

function handleToggleLayoutVisibility(obj) {
  var checkedState = null;
  if (obj.checked) checkedState = true;

  var layoutId = obj.dataset.cmsLayoutId;

  var data = {
    cms_layout: {
      visible: checkedState
    }
  };
  var requestData = {
    uri: Spree.routes.layouts_api_v2 + ('/' + layoutId),
    method: 'PATCH',
    dataBody: data
  };
  spreeFetchRequest(requestData, handleToggleSuccess);

  function handleToggleSuccess() {
    toggleVisibilityState(obj);
  }
}

function toggleVisibilityState(obj) {
  var statusHolder = document.getElementById('visibilityStatus');
  var pageHidden = statusHolder.querySelector('.page_hidden');
  var pageVisible = statusHolder.querySelector('.page_visible');

  if (obj.checked) {
    pageHidden.classList.add('d-none');
    pageVisible.classList.remove('d-none');
  } else {
    pageVisible.classList.add('d-none');
    pageHidden.classList.remove('d-none');
  }
};
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

// This is CodeMirror (http://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .

(function(mod) {
    if (typeof exports == "object" &amp;&amp; typeof module == "object") // CommonJS
      module.exports = mod();
    else if (typeof define == "function" &amp;&amp; define.amd) // AMD
      return define([], mod);
    else // Plain browser env
      (this || window).CodeMirror = mod();
  })(function() {
    "use strict";
  
    // BROWSER SNIFFING
  
    // Kludges for bugs and behavior differences that can't be feature
    // detected are enabled based on userAgent etc sniffing.
    var userAgent = navigator.userAgent;
    var platform = navigator.platform;
  
    var gecko = /gecko\/\d/i.test(userAgent);
    var ie_upto10 = /MSIE \d/.test(userAgent);
    var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
    var ie = ie_upto10 || ie_11up;
    var ie_version = ie &amp;&amp; (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
    var webkit = /WebKit\//.test(userAgent);
    var qtwebkit = webkit &amp;&amp; /Qt\/\d+\.\d+/.test(userAgent);
    var chrome = /Chrome\//.test(userAgent);
    var presto = /Opera\//.test(userAgent);
    var safari = /Apple Computer/.test(navigator.vendor);
    var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
    var phantom = /PhantomJS/.test(userAgent);
  
    var ios = /AppleWebKit/.test(userAgent) &amp;&amp; /Mobile\/\w+/.test(userAgent);
    // This is woefully incomplete. Suggestions for alternative methods welcome.
    var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
    var mac = ios || /Mac/.test(platform);
    var chromeOS = /\bCrOS\b/.test(userAgent);
    var windows = /win/i.test(platform);
  
    var presto_version = presto &amp;&amp; userAgent.match(/Version\/(\d*\.\d*)/);
    if (presto_version) presto_version = Number(presto_version[1]);
    if (presto_version &amp;&amp; presto_version &gt;= 15) { presto = false; webkit = true; }
    // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
    var flipCtrlCmd = mac &amp;&amp; (qtwebkit || presto &amp;&amp; (presto_version == null || presto_version &lt; 12.11));
    var captureRightClick = gecko || (ie &amp;&amp; ie_version &gt;= 9);
  
    // Optimize some code when these features are not used.
    var sawReadOnlySpans = false, sawCollapsedSpans = false;
  
    // EDITOR CONSTRUCTOR
  
    // A CodeMirror instance represents an editor. This is the object
    // that user code is usually dealing with.
  
    function CodeMirror(place, options) {
      if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  
      this.options = options = options ? copyObj(options) : {};
      // Determine effective options based on given values and defaults.
      copyObj(defaults, options, false);
      setGuttersForLineNumbers(options);
  
      var doc = options.value;
      if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
      this.doc = doc;
  
      var input = new CodeMirror.inputStyles[options.inputStyle](this);
      var display = this.display = new Display(place, doc, input);
      display.wrapper.CodeMirror = this;
      updateGutters(this);
      themeChanged(this);
      if (options.lineWrapping)
        this.display.wrapper.className += " CodeMirror-wrap";
      if (options.autofocus &amp;&amp; !mobile) display.input.focus();
      initScrollbars(this);
  
      this.state = {
        keyMaps: [],  // stores maps added by addKeyMap
        overlays: [], // highlighting overlays, as added by addOverlay
        modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
        overwrite: false,
        delayingBlurEvent: false,
        focused: false,
        suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
        pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
        selectingText: false,
        draggingText: false,
        highlight: new Delayed(), // stores highlight worker timeout
        keySeq: null,  // Unfinished key sequence
        specialChars: null
      };
  
      var cm = this;
  
      // Override magic textarea content restore that IE sometimes does
      // on our hidden textarea on reload
      if (ie &amp;&amp; ie_version &lt; 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  
      registerEventHandlers(this);
      ensureGlobalHandlers();
  
      startOperation(this);
      this.curOp.forceUpdate = true;
      attachDoc(this, doc);
  
      if ((options.autofocus &amp;&amp; !mobile) || cm.hasFocus())
        setTimeout(bind(onFocus, this), 20);
      else
        onBlur(this);
  
      for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
        optionHandlers[opt](this, options[opt], Init);
      maybeUpdateLineNumberWidth(this);
      if (options.finishInit) options.finishInit(this);
      for (var i = 0; i &lt; initHooks.length; ++i) initHooks[i](this);
      endOperation(this);
      // Suppress optimizelegibility in Webkit, since it breaks text
      // measuring on line wrapping boundaries.
      if (webkit &amp;&amp; options.lineWrapping &amp;&amp;
          getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
        display.lineDiv.style.textRendering = "auto";
    }
  
    // DISPLAY CONSTRUCTOR
  
    // The display handles the DOM integration, both for input reading
    // and content drawing. It holds references to DOM nodes and
    // display-related state.
  
    function Display(place, doc, input) {
      var d = this;
      this.input = input;
  
      // Covers bottom-right square when both scrollbars are present.
      d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
      d.scrollbarFiller.setAttribute("cm-not-content", "true");
      // Covers bottom of gutter when coverGutterNextToScrollbar is on
      // and h scrollbar is present.
      d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
      d.gutterFiller.setAttribute("cm-not-content", "true");
      // Will contain the actual code, positioned to cover the viewport.
      d.lineDiv = elt("div", null, "CodeMirror-code");
      // Elements are added to these to represent selection and cursors.
      d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
      d.cursorDiv = elt("div", null, "CodeMirror-cursors");
      // A visibility: hidden element used to find the size of things.
      d.measure = elt("div", null, "CodeMirror-measure");
      // When lines outside of the viewport are measured, they are drawn in this.
      d.lineMeasure = elt("div", null, "CodeMirror-measure");
      // Wraps everything that needs to exist inside the vertically-padded coordinate system
      d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
                        null, "position: relative; outline: none");
      // Moved around its parent to cover visible view.
      d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
      // Set to the height of the document, allowing scrolling.
      d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
      d.sizerWidth = null;
      // Behavior of elts with overflow: auto and padding is
      // inconsistent across browsers. This is used to ensure the
      // scrollable area is big enough.
      d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
      // Will contain the gutters, if any.
      d.gutters = elt("div", null, "CodeMirror-gutters");
      d.lineGutter = null;
      // Actual scrollable element.
      d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
      d.scroller.setAttribute("tabIndex", "-1");
      // The element in which the editor lives.
      d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  
      // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
      if (ie &amp;&amp; ie_version &lt; 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
      if (!webkit &amp;&amp; !(gecko &amp;&amp; mobile)) d.scroller.draggable = true;
  
      if (place) {
        if (place.appendChild) place.appendChild(d.wrapper);
        else place(d.wrapper);
      }
  
      // Current rendered range (may be bigger than the view window).
      d.viewFrom = d.viewTo = doc.first;
      d.reportedViewFrom = d.reportedViewTo = doc.first;
      // Information about the rendered lines.
      d.view = [];
      d.renderedView = null;
      // Holds info about a single rendered line when it was rendered
      // for measurement, while not in view.
      d.externalMeasured = null;
      // Empty space (in pixels) above the view
      d.viewOffset = 0;
      d.lastWrapHeight = d.lastWrapWidth = 0;
      d.updateLineNumbers = null;
  
      d.nativeBarWidth = d.barHeight = d.barWidth = 0;
      d.scrollbarsClipped = false;
  
      // Used to only resize the line number gutter when necessary (when
      // the amount of lines crosses a boundary that makes its width change)
      d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
      // Set to true when a non-horizontal-scrolling line widget is
      // added. As an optimization, line widget aligning is skipped when
      // this is false.
      d.alignWidgets = false;
  
      d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  
      // Tracks the maximum line length so that the horizontal scrollbar
      // can be kept static when scrolling.
      d.maxLine = null;
      d.maxLineLength = 0;
      d.maxLineChanged = false;
  
      // Used for measuring wheel scrolling granularity
      d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  
      // True when shift is held down.
      d.shift = false;
  
      // Used to track whether anything happened since the context menu
      // was opened.
      d.selForContextMenu = null;
  
      d.activeTouch = null;
  
      input.init(d);
    }
  
    // STATE UPDATES
  
    // Used to get the editor into a consistent state again when options change.
  
    function loadMode(cm) {
      cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
      resetModeState(cm);
    }
  
    function resetModeState(cm) {
      cm.doc.iter(function(line) {
        if (line.stateAfter) line.stateAfter = null;
        if (line.styles) line.styles = null;
      });
      cm.doc.frontier = cm.doc.first;
      startWorker(cm, 100);
      cm.state.modeGen++;
      if (cm.curOp) regChange(cm);
    }
  
    function wrappingChanged(cm) {
      if (cm.options.lineWrapping) {
        addClass(cm.display.wrapper, "CodeMirror-wrap");
        cm.display.sizer.style.minWidth = "";
        cm.display.sizerWidth = null;
      } else {
        rmClass(cm.display.wrapper, "CodeMirror-wrap");
        findMaxLine(cm);
      }
      estimateLineHeights(cm);
      regChange(cm);
      clearCaches(cm);
      setTimeout(function(){updateScrollbars(cm);}, 100);
    }
  
    // Returns a function that estimates the height of a line, to use as
    // first approximation until the line becomes visible (and is thus
    // properly measurable).
    function estimateHeight(cm) {
      var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
      var perLine = wrapping &amp;&amp; Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
      return function(line) {
        if (lineIsHidden(cm.doc, line)) return 0;
  
        var widgetsHeight = 0;
        if (line.widgets) for (var i = 0; i &lt; line.widgets.length; i++) {
          if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
        }
  
        if (wrapping)
          return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
        else
          return widgetsHeight + th;
      };
    }
  
    function estimateLineHeights(cm) {
      var doc = cm.doc, est = estimateHeight(cm);
      doc.iter(function(line) {
        var estHeight = est(line);
        if (estHeight != line.height) updateLineHeight(line, estHeight);
      });
    }
  
    function themeChanged(cm) {
      cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
        cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
      clearCaches(cm);
    }
  
    function guttersChanged(cm) {
      updateGutters(cm);
      regChange(cm);
      setTimeout(function(){alignHorizontally(cm);}, 20);
    }
  
    // Rebuild the gutter elements, ensure the margin to the left of the
    // code matches their width.
    function updateGutters(cm) {
      var gutters = cm.display.gutters, specs = cm.options.gutters;
      removeChildren(gutters);
      for (var i = 0; i &lt; specs.length; ++i) {
        var gutterClass = specs[i];
        var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
        if (gutterClass == "CodeMirror-linenumbers") {
          cm.display.lineGutter = gElt;
          gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
        }
      }
      gutters.style.display = i ? "" : "none";
      updateGutterSpace(cm);
    }
  
    function updateGutterSpace(cm) {
      var width = cm.display.gutters.offsetWidth;
      cm.display.sizer.style.marginLeft = width + "px";
    }
  
    // Compute the character length of a line, taking into account
    // collapsed ranges (see markText) that might hide parts, and join
    // other lines onto it.
    function lineLength(line) {
      if (line.height == 0) return 0;
      var len = line.text.length, merged, cur = line;
      while (merged = collapsedSpanAtStart(cur)) {
        var found = merged.find(0, true);
        cur = found.from.line;
        len += found.from.ch - found.to.ch;
      }
      cur = line;
      while (merged = collapsedSpanAtEnd(cur)) {
        var found = merged.find(0, true);
        len -= cur.text.length - found.from.ch;
        cur = found.to.line;
        len += cur.text.length - found.to.ch;
      }
      return len;
    }
  
    // Find the longest line in the document.
    function findMaxLine(cm) {
      var d = cm.display, doc = cm.doc;
      d.maxLine = getLine(doc, doc.first);
      d.maxLineLength = lineLength(d.maxLine);
      d.maxLineChanged = true;
      doc.iter(function(line) {
        var len = lineLength(line);
        if (len &gt; d.maxLineLength) {
          d.maxLineLength = len;
          d.maxLine = line;
        }
      });
    }
  
    // Make sure the gutters options contains the element
    // "CodeMirror-linenumbers" when the lineNumbers option is true.
    function setGuttersForLineNumbers(options) {
      var found = indexOf(options.gutters, "CodeMirror-linenumbers");
      if (found == -1 &amp;&amp; options.lineNumbers) {
        options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
      } else if (found &gt; -1 &amp;&amp; !options.lineNumbers) {
        options.gutters = options.gutters.slice(0);
        options.gutters.splice(found, 1);
      }
    }
  
    // SCROLLBARS
  
    // Prepare DOM reads needed to update the scrollbars. Done in one
    // shot to minimize update/measure roundtrips.
    function measureForScrollbars(cm) {
      var d = cm.display, gutterW = d.gutters.offsetWidth;
      var docH = Math.round(cm.doc.height + paddingVert(cm.display));
      return {
        clientHeight: d.scroller.clientHeight,
        viewHeight: d.wrapper.clientHeight,
        scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
        viewWidth: d.wrapper.clientWidth,
        barLeft: cm.options.fixedGutter ? gutterW : 0,
        docHeight: docH,
        scrollHeight: docH + scrollGap(cm) + d.barHeight,
        nativeBarWidth: d.nativeBarWidth,
        gutterWidth: gutterW
      };
    }
  
    function NativeScrollbars(place, scroll, cm) {
      this.cm = cm;
      var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
      var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
      place(vert); place(horiz);
  
      on(vert, "scroll", function() {
        if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
      });
      on(horiz, "scroll", function() {
        if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
      });
  
      this.checkedZeroWidth = false;
      // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
      if (ie &amp;&amp; ie_version &lt; 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
    }
  
    NativeScrollbars.prototype = copyObj({
      update: function(measure) {
        var needsH = measure.scrollWidth &gt; measure.clientWidth + 1;
        var needsV = measure.scrollHeight &gt; measure.clientHeight + 1;
        var sWidth = measure.nativeBarWidth;
  
        if (needsV) {
          this.vert.style.display = "block";
          this.vert.style.bottom = needsH ? sWidth + "px" : "0";
          var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
          // A bug in IE8 can cause this value to be negative, so guard it.
          this.vert.firstChild.style.height =
            Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
        } else {
          this.vert.style.display = "";
          this.vert.firstChild.style.height = "0";
        }
  
        if (needsH) {
          this.horiz.style.display = "block";
          this.horiz.style.right = needsV ? sWidth + "px" : "0";
          this.horiz.style.left = measure.barLeft + "px";
          var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
          this.horiz.firstChild.style.width =
            (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
        } else {
          this.horiz.style.display = "";
          this.horiz.firstChild.style.width = "0";
        }
  
        if (!this.checkedZeroWidth &amp;&amp; measure.clientHeight &gt; 0) {
          if (sWidth == 0) this.zeroWidthHack();
          this.checkedZeroWidth = true;
        }
  
        return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
      },
      setScrollLeft: function(pos) {
        if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
        if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
      },
      setScrollTop: function(pos) {
        if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
        if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
      },
      zeroWidthHack: function() {
        var w = mac &amp;&amp; !mac_geMountainLion ? "12px" : "18px";
        this.horiz.style.height = this.vert.style.width = w;
        this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
        this.disableHoriz = new Delayed;
        this.disableVert = new Delayed;
      },
      enableZeroWidthBar: function(bar, delay) {
        bar.style.pointerEvents = "auto";
        function maybeDisable() {
          // To find out whether the scrollbar is still visible, we
          // check whether the element under the pixel in the bottom
          // left corner of the scrollbar box is the scrollbar box
          // itself (when the bar is still visible) or its filler child
          // (when the bar is hidden). If it is still visible, we keep
          // it enabled, if it's hidden, we disable pointer events.
          var box = bar.getBoundingClientRect();
          var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
          if (elt != bar) bar.style.pointerEvents = "none";
          else delay.set(1000, maybeDisable);
        }
        delay.set(1000, maybeDisable);
      },
      clear: function() {
        var parent = this.horiz.parentNode;
        parent.removeChild(this.horiz);
        parent.removeChild(this.vert);
      }
    }, NativeScrollbars.prototype);
  
    function NullScrollbars() {}
  
    NullScrollbars.prototype = copyObj({
      update: function() { return {bottom: 0, right: 0}; },
      setScrollLeft: function() {},
      setScrollTop: function() {},
      clear: function() {}
    }, NullScrollbars.prototype);
  
    CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  
    function initScrollbars(cm) {
      if (cm.display.scrollbars) {
        cm.display.scrollbars.clear();
        if (cm.display.scrollbars.addClass)
          rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
      }
  
      cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
        cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
        // Prevent clicks in the scrollbars from killing focus
        on(node, "mousedown", function() {
          if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
        });
        node.setAttribute("cm-not-content", "true");
      }, function(pos, axis) {
        if (axis == "horizontal") setScrollLeft(cm, pos);
        else setScrollTop(cm, pos);
      }, cm);
      if (cm.display.scrollbars.addClass)
        addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
    }
  
    function updateScrollbars(cm, measure) {
      if (!measure) measure = measureForScrollbars(cm);
      var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
      updateScrollbarsInner(cm, measure);
      for (var i = 0; i &lt; 4 &amp;&amp; startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
        if (startWidth != cm.display.barWidth &amp;&amp; cm.options.lineWrapping)
          updateHeightsInViewport(cm);
        updateScrollbarsInner(cm, measureForScrollbars(cm));
        startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
      }
    }
  
    // Re-synchronize the fake scrollbars with the actual size of the
    // content.
    function updateScrollbarsInner(cm, measure) {
      var d = cm.display;
      var sizes = d.scrollbars.update(measure);
  
      d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
      d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
      d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  
      if (sizes.right &amp;&amp; sizes.bottom) {
        d.scrollbarFiller.style.display = "block";
        d.scrollbarFiller.style.height = sizes.bottom + "px";
        d.scrollbarFiller.style.width = sizes.right + "px";
      } else d.scrollbarFiller.style.display = "";
      if (sizes.bottom &amp;&amp; cm.options.coverGutterNextToScrollbar &amp;&amp; cm.options.fixedGutter) {
        d.gutterFiller.style.display = "block";
        d.gutterFiller.style.height = sizes.bottom + "px";
        d.gutterFiller.style.width = measure.gutterWidth + "px";
      } else d.gutterFiller.style.display = "";
    }
  
    // Compute the lines that are visible in a given viewport (defaults
    // the the current scroll position). viewport may contain top,
    // height, and ensure (see op.scrollToPos) properties.
    function visibleLines(display, doc, viewport) {
      var top = viewport &amp;&amp; viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
      top = Math.floor(top - paddingTop(display));
      var bottom = viewport &amp;&amp; viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  
      var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
      // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
      // forces those lines into the viewport (if possible).
      if (viewport &amp;&amp; viewport.ensure) {
        var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
        if (ensureFrom &lt; from) {
          from = ensureFrom;
          to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
        } else if (Math.min(ensureTo, doc.lastLine()) &gt;= to) {
          from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
          to = ensureTo;
        }
      }
      return {from: from, to: Math.max(to, from + 1)};
    }
  
    // LINE NUMBERS
  
    // Re-align line numbers and gutter marks to compensate for
    // horizontal scrolling.
    function alignHorizontally(cm) {
      var display = cm.display, view = display.view;
      if (!display.alignWidgets &amp;&amp; (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
      var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
      var gutterW = display.gutters.offsetWidth, left = comp + "px";
      for (var i = 0; i &lt; view.length; i++) if (!view[i].hidden) {
        if (cm.options.fixedGutter &amp;&amp; view[i].gutter)
          view[i].gutter.style.left = left;
        var align = view[i].alignable;
        if (align) for (var j = 0; j &lt; align.length; j++)
          align[j].style.left = left;
      }
      if (cm.options.fixedGutter)
        display.gutters.style.left = (comp + gutterW) + "px";
    }
  
    // Used to ensure that the line number gutter is still the right
    // size for the current document size. Returns true when an update
    // is needed.
    function maybeUpdateLineNumberWidth(cm) {
      if (!cm.options.lineNumbers) return false;
      var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
      if (last.length != display.lineNumChars) {
        var test = display.measure.appendChild(elt("div", [elt("div", last)],
                                                   "CodeMirror-linenumber CodeMirror-gutter-elt"));
        var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
        display.lineGutter.style.width = "";
        display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
        display.lineNumWidth = display.lineNumInnerWidth + padding;
        display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
        display.lineGutter.style.width = display.lineNumWidth + "px";
        updateGutterSpace(cm);
        return true;
      }
      return false;
    }
  
    function lineNumberFor(options, i) {
      return String(options.lineNumberFormatter(i + options.firstLineNumber));
    }
  
    // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
    // but using getBoundingClientRect to get a sub-pixel-accurate
    // result.
    function compensateForHScroll(display) {
      return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
    }
  
    // DISPLAY DRAWING
  
    function DisplayUpdate(cm, viewport, force) {
      var display = cm.display;
  
      this.viewport = viewport;
      // Store some values that we'll need later (but don't want to force a relayout for)
      this.visible = visibleLines(display, cm.doc, viewport);
      this.editorIsHidden = !display.wrapper.offsetWidth;
      this.wrapperHeight = display.wrapper.clientHeight;
      this.wrapperWidth = display.wrapper.clientWidth;
      this.oldDisplayWidth = displayWidth(cm);
      this.force = force;
      this.dims = getDimensions(cm);
      this.events = [];
    }
  
    DisplayUpdate.prototype.signal = function(emitter, type) {
      if (hasHandler(emitter, type))
        this.events.push(arguments);
    };
    DisplayUpdate.prototype.finish = function() {
      for (var i = 0; i &lt; this.events.length; i++)
        signal.apply(null, this.events[i]);
    };
  
    function maybeClipScrollbars(cm) {
      var display = cm.display;
      if (!display.scrollbarsClipped &amp;&amp; display.scroller.offsetWidth) {
        display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
        display.heightForcer.style.height = scrollGap(cm) + "px";
        display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
        display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
        display.scrollbarsClipped = true;
      }
    }
  
    // Does the actual updating of the line display. Bails out
    // (returning false) when there is nothing to be done and forced is
    // false.
    function updateDisplayIfNeeded(cm, update) {
      var display = cm.display, doc = cm.doc;
  
      if (update.editorIsHidden) {
        resetView(cm);
        return false;
      }
  
      // Bail out if the visible area is already rendered and nothing changed.
      if (!update.force &amp;&amp;
          update.visible.from &gt;= display.viewFrom &amp;&amp; update.visible.to &lt;= display.viewTo &amp;&amp;
          (display.updateLineNumbers == null || display.updateLineNumbers &gt;= display.viewTo) &amp;&amp;
          display.renderedView == display.view &amp;&amp; countDirtyView(cm) == 0)
        return false;
  
      if (maybeUpdateLineNumberWidth(cm)) {
        resetView(cm);
        update.dims = getDimensions(cm);
      }
  
      // Compute a suitable new viewport (from &amp; to)
      var end = doc.first + doc.size;
      var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
      var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
      if (display.viewFrom &lt; from &amp;&amp; from - display.viewFrom &lt; 20) from = Math.max(doc.first, display.viewFrom);
      if (display.viewTo &gt; to &amp;&amp; display.viewTo - to &lt; 20) to = Math.min(end, display.viewTo);
      if (sawCollapsedSpans) {
        from = visualLineNo(cm.doc, from);
        to = visualLineEndNo(cm.doc, to);
      }
  
      var different = from != display.viewFrom || to != display.viewTo ||
        display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
      adjustView(cm, from, to);
  
      display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
      // Position the mover div to align with the current scroll position
      cm.display.mover.style.top = display.viewOffset + "px";
  
      var toUpdate = countDirtyView(cm);
      if (!different &amp;&amp; toUpdate == 0 &amp;&amp; !update.force &amp;&amp; display.renderedView == display.view &amp;&amp;
          (display.updateLineNumbers == null || display.updateLineNumbers &gt;= display.viewTo))
        return false;
  
      // For big changes, we hide the enclosing element during the
      // update, since that speeds up the operations on most browsers.
      var focused = activeElt();
      if (toUpdate &gt; 4) display.lineDiv.style.display = "none";
      patchDisplay(cm, display.updateLineNumbers, update.dims);
      if (toUpdate &gt; 4) display.lineDiv.style.display = "";
      display.renderedView = display.view;
      // There might have been a widget with a focused element that got
      // hidden or updated, if so re-focus it.
      if (focused &amp;&amp; activeElt() != focused &amp;&amp; focused.offsetHeight) focused.focus();
  
      // Prevent selection and cursors from interfering with the scroll
      // width and height.
      removeChildren(display.cursorDiv);
      removeChildren(display.selectionDiv);
      display.gutters.style.height = display.sizer.style.minHeight = 0;
  
      if (different) {
        display.lastWrapHeight = update.wrapperHeight;
        display.lastWrapWidth = update.wrapperWidth;
        startWorker(cm, 400);
      }
  
      display.updateLineNumbers = null;
  
      return true;
    }
  
    function postUpdateDisplay(cm, update) {
      var viewport = update.viewport;
  
      for (var first = true;; first = false) {
        if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
          // Clip forced viewport to actual scrollable area.
          if (viewport &amp;&amp; viewport.top != null)
            viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
          // Updated line heights might result in the drawn area not
          // actually covering the viewport. Keep looping until it does.
          update.visible = visibleLines(cm.display, cm.doc, viewport);
          if (update.visible.from &gt;= cm.display.viewFrom &amp;&amp; update.visible.to &lt;= cm.display.viewTo)
            break;
        }
        if (!updateDisplayIfNeeded(cm, update)) break;
        updateHeightsInViewport(cm);
        var barMeasure = measureForScrollbars(cm);
        updateSelection(cm);
        updateScrollbars(cm, barMeasure);
        setDocumentHeight(cm, barMeasure);
      }
  
      update.signal(cm, "update", cm);
      if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
        update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
        cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
      }
    }
  
    function updateDisplaySimple(cm, viewport) {
      var update = new DisplayUpdate(cm, viewport);
      if (updateDisplayIfNeeded(cm, update)) {
        updateHeightsInViewport(cm);
        postUpdateDisplay(cm, update);
        var barMeasure = measureForScrollbars(cm);
        updateSelection(cm);
        updateScrollbars(cm, barMeasure);
        setDocumentHeight(cm, barMeasure);
        update.finish();
      }
    }
  
    function setDocumentHeight(cm, measure) {
      cm.display.sizer.style.minHeight = measure.docHeight + "px";
      cm.display.heightForcer.style.top = measure.docHeight + "px";
      cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
    }
  
    // Read the actual heights of the rendered lines, and update their
    // stored heights to match.
    function updateHeightsInViewport(cm) {
      var display = cm.display;
      var prevBottom = display.lineDiv.offsetTop;
      for (var i = 0; i &lt; display.view.length; i++) {
        var cur = display.view[i], height;
        if (cur.hidden) continue;
        if (ie &amp;&amp; ie_version &lt; 8) {
          var bot = cur.node.offsetTop + cur.node.offsetHeight;
          height = bot - prevBottom;
          prevBottom = bot;
        } else {
          var box = cur.node.getBoundingClientRect();
          height = box.bottom - box.top;
        }
        var diff = cur.line.height - height;
        if (height &lt; 2) height = textHeight(display);
        if (diff &gt; .001 || diff &lt; -.001) {
          updateLineHeight(cur.line, height);
          updateWidgetHeight(cur.line);
          if (cur.rest) for (var j = 0; j &lt; cur.rest.length; j++)
            updateWidgetHeight(cur.rest[j]);
        }
      }
    }
  
    // Read and store the height of line widgets associated with the
    // given line.
    function updateWidgetHeight(line) {
      if (line.widgets) for (var i = 0; i &lt; line.widgets.length; ++i)
        line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
    }
  
    // Do a bulk-read of the DOM positions and sizes needed to draw the
    // view, so that we don't interleave reading and writing to the DOM.
    function getDimensions(cm) {
      var d = cm.display, left = {}, width = {};
      var gutterLeft = d.gutters.clientLeft;
      for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
        left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
        width[cm.options.gutters[i]] = n.clientWidth;
      }
      return {fixedPos: compensateForHScroll(d),
              gutterTotalWidth: d.gutters.offsetWidth,
              gutterLeft: left,
              gutterWidth: width,
              wrapperWidth: d.wrapper.clientWidth};
    }
  
    // Sync the actual display DOM structure with display.view, removing
    // nodes for lines that are no longer in view, and creating the ones
    // that are not there yet, and updating the ones that are out of
    // date.
    function patchDisplay(cm, updateNumbersFrom, dims) {
      var display = cm.display, lineNumbers = cm.options.lineNumbers;
      var container = display.lineDiv, cur = container.firstChild;
  
      function rm(node) {
        var next = node.nextSibling;
        // Works around a throw-scroll bug in OS X Webkit
        if (webkit &amp;&amp; mac &amp;&amp; cm.display.currentWheelTarget == node)
          node.style.display = "none";
        else
          node.parentNode.removeChild(node);
        return next;
      }
  
      var view = display.view, lineN = display.viewFrom;
      // Loop over the elements in the view, syncing cur (the DOM nodes
      // in display.lineDiv) with the view as we go.
      for (var i = 0; i &lt; view.length; i++) {
        var lineView = view[i];
        if (lineView.hidden) {
        } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
          var node = buildLineElement(cm, lineView, lineN, dims);
          container.insertBefore(node, cur);
        } else { // Already drawn
          while (cur != lineView.node) cur = rm(cur);
          var updateNumber = lineNumbers &amp;&amp; updateNumbersFrom != null &amp;&amp;
            updateNumbersFrom &lt;= lineN &amp;&amp; lineView.lineNumber;
          if (lineView.changes) {
            if (indexOf(lineView.changes, "gutter") &gt; -1) updateNumber = false;
            updateLineForChanges(cm, lineView, lineN, dims);
          }
          if (updateNumber) {
            removeChildren(lineView.lineNumber);
            lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
          }
          cur = lineView.node.nextSibling;
        }
        lineN += lineView.size;
      }
      while (cur) cur = rm(cur);
    }
  
    // When an aspect of a line changes, a string is added to
    // lineView.changes. This updates the relevant part of the line's
    // DOM structure.
    function updateLineForChanges(cm, lineView, lineN, dims) {
      for (var j = 0; j &lt; lineView.changes.length; j++) {
        var type = lineView.changes[j];
        if (type == "text") updateLineText(cm, lineView);
        else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
        else if (type == "class") updateLineClasses(lineView);
        else if (type == "widget") updateLineWidgets(cm, lineView, dims);
      }
      lineView.changes = null;
    }
  
    // Lines with gutter elements, widgets or a background class need to
    // be wrapped, and have the extra elements added to the wrapper div
    function ensureLineWrapped(lineView) {
      if (lineView.node == lineView.text) {
        lineView.node = elt("div", null, null, "position: relative");
        if (lineView.text.parentNode)
          lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
        lineView.node.appendChild(lineView.text);
        if (ie &amp;&amp; ie_version &lt; 8) lineView.node.style.zIndex = 2;
      }
      return lineView.node;
    }
  
    function updateLineBackground(lineView) {
      var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
      if (cls) cls += " CodeMirror-linebackground";
      if (lineView.background) {
        if (cls) lineView.background.className = cls;
        else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
      } else if (cls) {
        var wrap = ensureLineWrapped(lineView);
        lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
      }
    }
  
    // Wrapper around buildLineContent which will reuse the structure
    // in display.externalMeasured when possible.
    function getLineContent(cm, lineView) {
      var ext = cm.display.externalMeasured;
      if (ext &amp;&amp; ext.line == lineView.line) {
        cm.display.externalMeasured = null;
        lineView.measure = ext.measure;
        return ext.built;
      }
      return buildLineContent(cm, lineView);
    }
  
    // Redraw the line's text. Interacts with the background and text
    // classes because the mode may output tokens that influence these
    // classes.
    function updateLineText(cm, lineView) {
      var cls = lineView.text.className;
      var built = getLineContent(cm, lineView);
      if (lineView.text == lineView.node) lineView.node = built.pre;
      lineView.text.parentNode.replaceChild(built.pre, lineView.text);
      lineView.text = built.pre;
      if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
        lineView.bgClass = built.bgClass;
        lineView.textClass = built.textClass;
        updateLineClasses(lineView);
      } else if (cls) {
        lineView.text.className = cls;
      }
    }
  
    function updateLineClasses(lineView) {
      updateLineBackground(lineView);
      if (lineView.line.wrapClass)
        ensureLineWrapped(lineView).className = lineView.line.wrapClass;
      else if (lineView.node != lineView.text)
        lineView.node.className = "";
      var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
      lineView.text.className = textClass || "";
    }
  
    function updateLineGutter(cm, lineView, lineN, dims) {
      if (lineView.gutter) {
        lineView.node.removeChild(lineView.gutter);
        lineView.gutter = null;
      }
      if (lineView.gutterBackground) {
        lineView.node.removeChild(lineView.gutterBackground);
        lineView.gutterBackground = null;
      }
      if (lineView.line.gutterClass) {
        var wrap = ensureLineWrapped(lineView);
        lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
                                        "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
                                        "px; width: " + dims.gutterTotalWidth + "px");
        wrap.insertBefore(lineView.gutterBackground, lineView.text);
      }
      var markers = lineView.line.gutterMarkers;
      if (cm.options.lineNumbers || markers) {
        var wrap = ensureLineWrapped(lineView);
        var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
                                               (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
        cm.display.input.setUneditable(gutterWrap);
        wrap.insertBefore(gutterWrap, lineView.text);
        if (lineView.line.gutterClass)
          gutterWrap.className += " " + lineView.line.gutterClass;
        if (cm.options.lineNumbers &amp;&amp; (!markers || !markers["CodeMirror-linenumbers"]))
          lineView.lineNumber = gutterWrap.appendChild(
            elt("div", lineNumberFor(cm.options, lineN),
                "CodeMirror-linenumber CodeMirror-gutter-elt",
                "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
                + cm.display.lineNumInnerWidth + "px"));
        if (markers) for (var k = 0; k &lt; cm.options.gutters.length; ++k) {
          var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) &amp;&amp; markers[id];
          if (found)
            gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
                                       dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
        }
      }
    }
  
    function updateLineWidgets(cm, lineView, dims) {
      if (lineView.alignable) lineView.alignable = null;
      for (var node = lineView.node.firstChild, next; node; node = next) {
        var next = node.nextSibling;
        if (node.className == "CodeMirror-linewidget")
          lineView.node.removeChild(node);
      }
      insertLineWidgets(cm, lineView, dims);
    }
  
    // Build a line's DOM representation from scratch
    function buildLineElement(cm, lineView, lineN, dims) {
      var built = getLineContent(cm, lineView);
      lineView.text = lineView.node = built.pre;
      if (built.bgClass) lineView.bgClass = built.bgClass;
      if (built.textClass) lineView.textClass = built.textClass;
  
      updateLineClasses(lineView);
      updateLineGutter(cm, lineView, lineN, dims);
      insertLineWidgets(cm, lineView, dims);
      return lineView.node;
    }
  
    // A lineView may contain multiple logical lines (when merged by
    // collapsed spans). The widgets for all of them need to be drawn.
    function insertLineWidgets(cm, lineView, dims) {
      insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
      if (lineView.rest) for (var i = 0; i &lt; lineView.rest.length; i++)
        insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
    }
  
    function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
      if (!line.widgets) return;
      var wrap = ensureLineWrapped(lineView);
      for (var i = 0, ws = line.widgets; i &lt; ws.length; ++i) {
        var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
        if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
        positionLineWidget(widget, node, lineView, dims);
        cm.display.input.setUneditable(node);
        if (allowAbove &amp;&amp; widget.above)
          wrap.insertBefore(node, lineView.gutter || lineView.text);
        else
          wrap.appendChild(node);
        signalLater(widget, "redraw");
      }
    }
  
    function positionLineWidget(widget, node, lineView, dims) {
      if (widget.noHScroll) {
        (lineView.alignable || (lineView.alignable = [])).push(node);
        var width = dims.wrapperWidth;
        node.style.left = dims.fixedPos + "px";
        if (!widget.coverGutter) {
          width -= dims.gutterTotalWidth;
          node.style.paddingLeft = dims.gutterTotalWidth + "px";
        }
        node.style.width = width + "px";
      }
      if (widget.coverGutter) {
        node.style.zIndex = 5;
        node.style.position = "relative";
        if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
      }
    }
  
    // POSITION OBJECT
  
    // A Pos instance represents a position within the text.
    var Pos = CodeMirror.Pos = function(line, ch) {
      if (!(this instanceof Pos)) return new Pos(line, ch);
      this.line = line; this.ch = ch;
    };
  
    // Compare two positions, return 0 if they are the same, a negative
    // number when a is less, and a positive number otherwise.
    var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  
    function copyPos(x) {return Pos(x.line, x.ch);}
    function maxPos(a, b) { return cmp(a, b) &lt; 0 ? b : a; }
    function minPos(a, b) { return cmp(a, b) &lt; 0 ? a : b; }
  
    // INPUT HANDLING
  
    function ensureFocus(cm) {
      if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
    }
  
    // This will be set to a {lineWise: bool, text: [string]} object, so
    // that, when pasting, we know what kind of selections the copied
    // text was made out of.
    var lastCopied = null;
  
    function applyTextInput(cm, inserted, deleted, sel, origin) {
      var doc = cm.doc;
      cm.display.shift = false;
      if (!sel) sel = doc.sel;
  
      var paste = cm.state.pasteIncoming || origin == "paste";
      var textLines = doc.splitLines(inserted), multiPaste = null
      // When pasing N lines into N selections, insert one line per selection
      if (paste &amp;&amp; sel.ranges.length &gt; 1) {
        if (lastCopied &amp;&amp; lastCopied.text.join("\n") == inserted) {
          if (sel.ranges.length % lastCopied.text.length == 0) {
            multiPaste = [];
            for (var i = 0; i &lt; lastCopied.text.length; i++)
              multiPaste.push(doc.splitLines(lastCopied.text[i]));
          }
        } else if (textLines.length == sel.ranges.length) {
          multiPaste = map(textLines, function(l) { return [l]; });
        }
      }
  
      // Normal behavior is to insert the new text into every selection
      for (var i = sel.ranges.length - 1; i &gt;= 0; i--) {
        var range = sel.ranges[i];
        var from = range.from(), to = range.to();
        if (range.empty()) {
          if (deleted &amp;&amp; deleted &gt; 0) // Handle deletion
            from = Pos(from.line, from.ch - deleted);
          else if (cm.state.overwrite &amp;&amp; !paste) // Handle overwrite
            to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
          else if (lastCopied &amp;&amp; lastCopied.lineWise &amp;&amp; lastCopied.text.join("\n") == inserted)
            from = to = Pos(from.line, 0)
        }
        var updateInput = cm.curOp.updateInput;
        var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
                           origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
        makeChange(cm.doc, changeEvent);
        signalLater(cm, "inputRead", cm, changeEvent);
      }
      if (inserted &amp;&amp; !paste)
        triggerElectric(cm, inserted);
  
      ensureCursorVisible(cm);
      cm.curOp.updateInput = updateInput;
      cm.curOp.typing = true;
      cm.state.pasteIncoming = cm.state.cutIncoming = false;
    }
  
    function handlePaste(e, cm) {
      var pasted = e.clipboardData &amp;&amp; e.clipboardData.getData("text/plain");
      if (pasted) {
        e.preventDefault();
        if (!cm.isReadOnly() &amp;&amp; !cm.options.disableInput)
          runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
        return true;
      }
    }
  
    function triggerElectric(cm, inserted) {
      // When an 'electric' character is inserted, immediately trigger a reindent
      if (!cm.options.electricChars || !cm.options.smartIndent) return;
      var sel = cm.doc.sel;
  
      for (var i = sel.ranges.length - 1; i &gt;= 0; i--) {
        var range = sel.ranges[i];
        if (range.head.ch &gt; 100 || (i &amp;&amp; sel.ranges[i - 1].head.line == range.head.line)) continue;
        var mode = cm.getModeAt(range.head);
        var indented = false;
        if (mode.electricChars) {
          for (var j = 0; j &lt; mode.electricChars.length; j++)
            if (inserted.indexOf(mode.electricChars.charAt(j)) &gt; -1) {
              indented = indentLine(cm, range.head.line, "smart");
              break;
            }
        } else if (mode.electricInput) {
          if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
            indented = indentLine(cm, range.head.line, "smart");
        }
        if (indented) signalLater(cm, "electricInput", cm, range.head.line);
      }
    }
  
    function copyableRanges(cm) {
      var text = [], ranges = [];
      for (var i = 0; i &lt; cm.doc.sel.ranges.length; i++) {
        var line = cm.doc.sel.ranges[i].head.line;
        var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
        ranges.push(lineRange);
        text.push(cm.getRange(lineRange.anchor, lineRange.head));
      }
      return {text: text, ranges: ranges};
    }
  
    function disableBrowserMagic(field) {
      field.setAttribute("autocorrect", "off");
      field.setAttribute("autocapitalize", "off");
      field.setAttribute("spellcheck", "false");
    }
  
    // TEXTAREA INPUT STYLE
  
    function TextareaInput(cm) {
      this.cm = cm;
      // See input.poll and input.reset
      this.prevInput = "";
  
      // Flag that indicates whether we expect input to appear real soon
      // now (after some event like 'keypress' or 'input') and are
      // polling intensively.
      this.pollingFast = false;
      // Self-resetting timeout for the poller
      this.polling = new Delayed();
      // Tracks when input.reset has punted to just putting a short
      // string into the textarea instead of the full selection.
      this.inaccurateSelection = false;
      // Used to work around IE issue with selection being forgotten when focus moves away from textarea
      this.hasSelection = false;
      this.composing = null;
    };
  
    function hiddenTextarea() {
      var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
      var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
      // The textarea is kept positioned near the cursor to prevent the
      // fact that it'll be scrolled into view on input from scrolling
      // our fake cursor out of view. On webkit, when wrap=off, paste is
      // very slow. So make the area wide instead.
      if (webkit) te.style.width = "1000px";
      else te.setAttribute("wrap", "off");
      // If border: 0; -- iOS fails to open keyboard (issue #1287)
      if (ios) te.style.border = "1px solid black";
      disableBrowserMagic(te);
      return div;
    }
  
    TextareaInput.prototype = copyObj({
      init: function(display) {
        var input = this, cm = this.cm;
  
        // Wraps and hides input textarea
        var div = this.wrapper = hiddenTextarea();
        // The semihidden textarea that is focused when the editor is
        // focused, and receives input.
        var te = this.textarea = div.firstChild;
        display.wrapper.insertBefore(div, display.wrapper.firstChild);
  
        // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
        if (ios) te.style.width = "0px";
  
        on(te, "input", function() {
          if (ie &amp;&amp; ie_version &gt;= 9 &amp;&amp; input.hasSelection) input.hasSelection = null;
          input.poll();
        });
  
        on(te, "paste", function(e) {
          if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  
          cm.state.pasteIncoming = true;
          input.fastPoll();
        });
  
        function prepareCopyCut(e) {
          if (signalDOMEvent(cm, e)) return
          if (cm.somethingSelected()) {
            lastCopied = {lineWise: false, text: cm.getSelections()};
            if (input.inaccurateSelection) {
              input.prevInput = "";
              input.inaccurateSelection = false;
              te.value = lastCopied.text.join("\n");
              selectInput(te);
            }
          } else if (!cm.options.lineWiseCopyCut) {
            return;
          } else {
            var ranges = copyableRanges(cm);
            lastCopied = {lineWise: true, text: ranges.text};
            if (e.type == "cut") {
              cm.setSelections(ranges.ranges, null, sel_dontScroll);
            } else {
              input.prevInput = "";
              te.value = ranges.text.join("\n");
              selectInput(te);
            }
          }
          if (e.type == "cut") cm.state.cutIncoming = true;
        }
        on(te, "cut", prepareCopyCut);
        on(te, "copy", prepareCopyCut);
  
        on(display.scroller, "paste", function(e) {
          if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
          cm.state.pasteIncoming = true;
          input.focus();
        });
  
        // Prevent normal selection in the editor (we handle our own)
        on(display.lineSpace, "selectstart", function(e) {
          if (!eventInWidget(display, e)) e_preventDefault(e);
        });
  
        on(te, "compositionstart", function() {
          var start = cm.getCursor("from");
          if (input.composing) input.composing.range.clear()
          input.composing = {
            start: start,
            range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
          };
        });
        on(te, "compositionend", function() {
          if (input.composing) {
            input.poll();
            input.composing.range.clear();
            input.composing = null;
          }
        });
      },
  
      prepareSelection: function() {
        // Redraw the selection and/or cursor
        var cm = this.cm, display = cm.display, doc = cm.doc;
        var result = prepareSelection(cm);
  
        // Move the hidden textarea near the cursor to prevent scrolling artifacts
        if (cm.options.moveInputWithCursor) {
          var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
          var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
          result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
                                              headPos.top + lineOff.top - wrapOff.top));
          result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
                                               headPos.left + lineOff.left - wrapOff.left));
        }
  
        return result;
      },
  
      showSelection: function(drawn) {
        var cm = this.cm, display = cm.display;
        removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
        removeChildrenAndAdd(display.selectionDiv, drawn.selection);
        if (drawn.teTop != null) {
          this.wrapper.style.top = drawn.teTop + "px";
          this.wrapper.style.left = drawn.teLeft + "px";
        }
      },
  
      // Reset the input to correspond to the selection (or to be empty,
      // when not typing and nothing is selected)
      reset: function(typing) {
        if (this.contextMenuPending) return;
        var minimal, selected, cm = this.cm, doc = cm.doc;
        if (cm.somethingSelected()) {
          this.prevInput = "";
          var range = doc.sel.primary();
          minimal = hasCopyEvent &amp;&amp;
            (range.to().line - range.from().line &gt; 100 || (selected = cm.getSelection()).length &gt; 1000);
          var content = minimal ? "-" : selected || cm.getSelection();
          this.textarea.value = content;
          if (cm.state.focused) selectInput(this.textarea);
          if (ie &amp;&amp; ie_version &gt;= 9) this.hasSelection = content;
        } else if (!typing) {
          this.prevInput = this.textarea.value = "";
          if (ie &amp;&amp; ie_version &gt;= 9) this.hasSelection = null;
        }
        this.inaccurateSelection = minimal;
      },
  
      getField: function() { return this.textarea; },
  
      supportsTouch: function() { return false; },
  
      focus: function() {
        if (this.cm.options.readOnly != "nocursor" &amp;&amp; (!mobile || activeElt() != this.textarea)) {
          try { this.textarea.focus(); }
          catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
        }
      },
  
      blur: function() { this.textarea.blur(); },
  
      resetPosition: function() {
        this.wrapper.style.top = this.wrapper.style.left = 0;
      },
  
      receivedFocus: function() { this.slowPoll(); },
  
      // Poll for input changes, using the normal rate of polling. This
      // runs as long as the editor is focused.
      slowPoll: function() {
        var input = this;
        if (input.pollingFast) return;
        input.polling.set(this.cm.options.pollInterval, function() {
          input.poll();
          if (input.cm.state.focused) input.slowPoll();
        });
      },
  
      // When an event has just come in that is likely to add or change
      // something in the input textarea, we poll faster, to ensure that
      // the change appears on the screen quickly.
      fastPoll: function() {
        var missed = false, input = this;
        input.pollingFast = true;
        function p() {
          var changed = input.poll();
          if (!changed &amp;&amp; !missed) {missed = true; input.polling.set(60, p);}
          else {input.pollingFast = false; input.slowPoll();}
        }
        input.polling.set(20, p);
      },
  
      // Read input from the textarea, and update the document to match.
      // When something is selected, it is present in the textarea, and
      // selected (unless it is huge, in which case a placeholder is
      // used). When nothing is selected, the cursor sits after previously
      // seen text (can be empty), which is stored in prevInput (we must
      // not reset the textarea when typing, because that breaks IME).
      poll: function() {
        var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
        // Since this is called a *lot*, try to bail out as cheaply as
        // possible when it is clear that nothing happened. hasSelection
        // will be the case when there is a lot of text in the textarea,
        // in which case reading its value would be expensive.
        if (this.contextMenuPending || !cm.state.focused ||
            (hasSelection(input) &amp;&amp; !prevInput &amp;&amp; !this.composing) ||
            cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
          return false;
  
        var text = input.value;
        // If nothing changed, bail.
        if (text == prevInput &amp;&amp; !cm.somethingSelected()) return false;
        // Work around nonsensical selection resetting in IE9/10, and
        // inexplicable appearance of private area unicode characters on
        // some key combos in Mac (#2689).
        if (ie &amp;&amp; ie_version &gt;= 9 &amp;&amp; this.hasSelection === text ||
            mac &amp;&amp; /[\uf700-\uf7ff]/.test(text)) {
          cm.display.input.reset();
          return false;
        }
  
        if (cm.doc.sel == cm.display.selForContextMenu) {
          var first = text.charCodeAt(0);
          if (first == 0x200b &amp;&amp; !prevInput) prevInput = "\u200b";
          if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
        }
        // Find the part of the input that is actually new
        var same = 0, l = Math.min(prevInput.length, text.length);
        while (same &lt; l &amp;&amp; prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  
        var self = this;
        runInOp(cm, function() {
          applyTextInput(cm, text.slice(same), prevInput.length - same,
                         null, self.composing ? "*compose" : null);
  
          // Don't leave long text in the textarea, since it makes further polling slow
          if (text.length &gt; 1000 || text.indexOf("\n") &gt; -1) input.value = self.prevInput = "";
          else self.prevInput = text;
  
          if (self.composing) {
            self.composing.range.clear();
            self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
                                               {className: "CodeMirror-composing"});
          }
        });
        return true;
      },
  
      ensurePolled: function() {
        if (this.pollingFast &amp;&amp; this.poll()) this.pollingFast = false;
      },
  
      onKeyPress: function() {
        if (ie &amp;&amp; ie_version &gt;= 9) this.hasSelection = null;
        this.fastPoll();
      },
  
      onContextMenu: function(e) {
        var input = this, cm = input.cm, display = cm.display, te = input.textarea;
        var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
        if (!pos || presto) return; // Opera is difficult.
  
        // Reset the current text selection only if the click is done outside of the selection
        // and 'resetSelectionOnContextMenu' option is true.
        var reset = cm.options.resetSelectionOnContextMenu;
        if (reset &amp;&amp; cm.doc.sel.contains(pos) == -1)
          operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  
        var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
        input.wrapper.style.cssText = "position: absolute"
        var wrapperBox = input.wrapper.getBoundingClientRect()
        te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
          "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
          (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
          "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
        if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
        display.input.focus();
        if (webkit) window.scrollTo(null, oldScrollY);
        display.input.reset();
        // Adds "Select all" to context menu in FF
        if (!cm.somethingSelected()) te.value = input.prevInput = " ";
        input.contextMenuPending = true;
        display.selForContextMenu = cm.doc.sel;
        clearTimeout(display.detectingSelectAll);
  
        // Select-all will be greyed out if there's nothing to select, so
        // this adds a zero-width space so that we can later check whether
        // it got selected.
        function prepareSelectAllHack() {
          if (te.selectionStart != null) {
            var selected = cm.somethingSelected();
            var extval = "\u200b" + (selected ? te.value : "");
            te.value = "\u21da"; // Used to catch context-menu undo
            te.value = extval;
            input.prevInput = selected ? "" : "\u200b";
            te.selectionStart = 1; te.selectionEnd = extval.length;
            // Re-set this, in case some other handler touched the
            // selection in the meantime.
            display.selForContextMenu = cm.doc.sel;
          }
        }
        function rehide() {
          input.contextMenuPending = false;
          input.wrapper.style.cssText = oldWrapperCSS
          te.style.cssText = oldCSS;
          if (ie &amp;&amp; ie_version &lt; 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  
          // Try to detect the user choosing select-all
          if (te.selectionStart != null) {
            if (!ie || (ie &amp;&amp; ie_version &lt; 9)) prepareSelectAllHack();
            var i = 0, poll = function() {
              if (display.selForContextMenu == cm.doc.sel &amp;&amp; te.selectionStart == 0 &amp;&amp;
                  te.selectionEnd &gt; 0 &amp;&amp; input.prevInput == "\u200b")
                operation(cm, commands.selectAll)(cm);
              else if (i++ &lt; 10) display.detectingSelectAll = setTimeout(poll, 500);
              else display.input.reset();
            };
            display.detectingSelectAll = setTimeout(poll, 200);
          }
        }
  
        if (ie &amp;&amp; ie_version &gt;= 9) prepareSelectAllHack();
        if (captureRightClick) {
          e_stop(e);
          var mouseup = function() {
            off(window, "mouseup", mouseup);
            setTimeout(rehide, 20);
          };
          on(window, "mouseup", mouseup);
        } else {
          setTimeout(rehide, 50);
        }
      },
  
      readOnlyChanged: function(val) {
        if (!val) this.reset();
      },
  
      setUneditable: nothing,
  
      needsContentAttribute: false
    }, TextareaInput.prototype);
  
    // CONTENTEDITABLE INPUT STYLE
  
    function ContentEditableInput(cm) {
      this.cm = cm;
      this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
      this.polling = new Delayed();
      this.gracePeriod = false;
    }
  
    ContentEditableInput.prototype = copyObj({
      init: function(display) {
        var input = this, cm = input.cm;
        var div = input.div = display.lineDiv;
        disableBrowserMagic(div);
  
        on(div, "paste", function(e) {
          if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
        })
  
        on(div, "compositionstart", function(e) {
          var data = e.data;
          input.composing = {sel: cm.doc.sel, data: data, startData: data};
          if (!data) return;
          var prim = cm.doc.sel.primary();
          var line = cm.getLine(prim.head.line);
          var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
          if (found &gt; -1 &amp;&amp; found &lt;= prim.head.ch)
            input.composing.sel = simpleSelection(Pos(prim.head.line, found),
                                                  Pos(prim.head.line, found + data.length));
        });
        on(div, "compositionupdate", function(e) {
          input.composing.data = e.data;
        });
        on(div, "compositionend", function(e) {
          var ours = input.composing;
          if (!ours) return;
          if (e.data != ours.startData &amp;&amp; !/\u200b/.test(e.data))
            ours.data = e.data;
          // Need a small delay to prevent other code (input event,
          // selection polling) from doing damage when fired right after
          // compositionend.
          setTimeout(function() {
            if (!ours.handled)
              input.applyComposition(ours);
            if (input.composing == ours)
              input.composing = null;
          }, 50);
        });
  
        on(div, "touchstart", function() {
          input.forceCompositionEnd();
        });
  
        on(div, "input", function() {
          if (input.composing) return;
          if (cm.isReadOnly() || !input.pollContent())
            runInOp(input.cm, function() {regChange(cm);});
        });
  
        function onCopyCut(e) {
          if (signalDOMEvent(cm, e)) return
          if (cm.somethingSelected()) {
            lastCopied = {lineWise: false, text: cm.getSelections()};
            if (e.type == "cut") cm.replaceSelection("", null, "cut");
          } else if (!cm.options.lineWiseCopyCut) {
            return;
          } else {
            var ranges = copyableRanges(cm);
            lastCopied = {lineWise: true, text: ranges.text};
            if (e.type == "cut") {
              cm.operation(function() {
                cm.setSelections(ranges.ranges, 0, sel_dontScroll);
                cm.replaceSelection("", null, "cut");
              });
            }
          }
          // iOS exposes the clipboard API, but seems to discard content inserted into it
          if (e.clipboardData &amp;&amp; !ios) {
            e.preventDefault();
            e.clipboardData.clearData();
            e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
          } else {
            // Old-fashioned briefly-focus-a-textarea hack
            var kludge = hiddenTextarea(), te = kludge.firstChild;
            cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
            te.value = lastCopied.text.join("\n");
            var hadFocus = document.activeElement;
            selectInput(te);
            setTimeout(function() {
              cm.display.lineSpace.removeChild(kludge);
              hadFocus.focus();
            }, 50);
          }
        }
        on(div, "copy", onCopyCut);
        on(div, "cut", onCopyCut);
      },
  
      prepareSelection: function() {
        var result = prepareSelection(this.cm, false);
        result.focus = this.cm.state.focused;
        return result;
      },
  
      showSelection: function(info, takeFocus) {
        if (!info || !this.cm.display.view.length) return;
        if (info.focus || takeFocus) this.showPrimarySelection();
        this.showMultipleSelections(info);
      },
  
      showPrimarySelection: function() {
        var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
        var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
        var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
        if (curAnchor &amp;&amp; !curAnchor.bad &amp;&amp; curFocus &amp;&amp; !curFocus.bad &amp;&amp;
            cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &amp;&amp;
            cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
          return;
  
        var start = posToDOM(this.cm, prim.from());
        var end = posToDOM(this.cm, prim.to());
        if (!start &amp;&amp; !end) return;
  
        var view = this.cm.display.view;
        var old = sel.rangeCount &amp;&amp; sel.getRangeAt(0);
        if (!start) {
          start = {node: view[0].measure.map[2], offset: 0};
        } else if (!end) { // FIXME dangerously hacky
          var measure = view[view.length - 1].measure;
          var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
          end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
        }
  
        try { var rng = range(start.node, start.offset, end.offset, end.node); }
        catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
        if (rng) {
          if (!gecko &amp;&amp; this.cm.state.focused) {
            sel.collapse(start.node, start.offset);
            if (!rng.collapsed) sel.addRange(rng);
          } else {
            sel.removeAllRanges();
            sel.addRange(rng);
          }
          if (old &amp;&amp; sel.anchorNode == null) sel.addRange(old);
          else if (gecko) this.startGracePeriod();
        }
        this.rememberSelection();
      },
  
      startGracePeriod: function() {
        var input = this;
        clearTimeout(this.gracePeriod);
        this.gracePeriod = setTimeout(function() {
          input.gracePeriod = false;
          if (input.selectionChanged())
            input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
        }, 20);
      },
  
      showMultipleSelections: function(info) {
        removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
        removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
      },
  
      rememberSelection: function() {
        var sel = window.getSelection();
        this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
        this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
      },
  
      selectionInEditor: function() {
        var sel = window.getSelection();
        if (!sel.rangeCount) return false;
        var node = sel.getRangeAt(0).commonAncestorContainer;
        return contains(this.div, node);
      },
  
      focus: function() {
        if (this.cm.options.readOnly != "nocursor") this.div.focus();
      },
      blur: function() { this.div.blur(); },
      getField: function() { return this.div; },
  
      supportsTouch: function() { return true; },
  
      receivedFocus: function() {
        var input = this;
        if (this.selectionInEditor())
          this.pollSelection();
        else
          runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  
        function poll() {
          if (input.cm.state.focused) {
            input.pollSelection();
            input.polling.set(input.cm.options.pollInterval, poll);
          }
        }
        this.polling.set(this.cm.options.pollInterval, poll);
      },
  
      selectionChanged: function() {
        var sel = window.getSelection();
        return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
          sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
      },
  
      pollSelection: function() {
        if (!this.composing &amp;&amp; !this.gracePeriod &amp;&amp; this.selectionChanged()) {
          var sel = window.getSelection(), cm = this.cm;
          this.rememberSelection();
          var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
          var head = domToPos(cm, sel.focusNode, sel.focusOffset);
          if (anchor &amp;&amp; head) runInOp(cm, function() {
            setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
            if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
          });
        }
      },
  
      pollContent: function() {
        var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
        var from = sel.from(), to = sel.to();
        if (from.line &lt; display.viewFrom || to.line &gt; display.viewTo - 1) return false;
  
        var fromIndex;
        if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
          var fromLine = lineNo(display.view[0].line);
          var fromNode = display.view[0].node;
        } else {
          var fromLine = lineNo(display.view[fromIndex].line);
          var fromNode = display.view[fromIndex - 1].node.nextSibling;
        }
        var toIndex = findViewIndex(cm, to.line);
        if (toIndex == display.view.length - 1) {
          var toLine = display.viewTo - 1;
          var toNode = display.lineDiv.lastChild;
        } else {
          var toLine = lineNo(display.view[toIndex + 1].line) - 1;
          var toNode = display.view[toIndex + 1].node.previousSibling;
        }
  
        var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
        var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
        while (newText.length &gt; 1 &amp;&amp; oldText.length &gt; 1) {
          if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
          else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
          else break;
        }
  
        var cutFront = 0, cutEnd = 0;
        var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
        while (cutFront &lt; maxCutFront &amp;&amp; newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
          ++cutFront;
        var newBot = lst(newText), oldBot = lst(oldText);
        var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
                                 oldBot.length - (oldText.length == 1 ? cutFront : 0));
        while (cutEnd &lt; maxCutEnd &amp;&amp;
               newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
          ++cutEnd;
  
        newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
        newText[0] = newText[0].slice(cutFront);
  
        var chFrom = Pos(fromLine, cutFront);
        var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
        if (newText.length &gt; 1 || newText[0] || cmp(chFrom, chTo)) {
          replaceRange(cm.doc, newText, chFrom, chTo, "+input");
          return true;
        }
      },
  
      ensurePolled: function() {
        this.forceCompositionEnd();
      },
      reset: function() {
        this.forceCompositionEnd();
      },
      forceCompositionEnd: function() {
        if (!this.composing || this.composing.handled) return;
        this.applyComposition(this.composing);
        this.composing.handled = true;
        this.div.blur();
        this.div.focus();
      },
      applyComposition: function(composing) {
        if (this.cm.isReadOnly())
          operation(this.cm, regChange)(this.cm)
        else if (composing.data &amp;&amp; composing.data != composing.startData)
          operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
      },
  
      setUneditable: function(node) {
        node.contentEditable = "false"
      },
  
      onKeyPress: function(e) {
        e.preventDefault();
        if (!this.cm.isReadOnly())
          operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
      },
  
      readOnlyChanged: function(val) {
        this.div.contentEditable = String(val != "nocursor")
      },
  
      onContextMenu: nothing,
      resetPosition: nothing,
  
      needsContentAttribute: true
    }, ContentEditableInput.prototype);
  
    function posToDOM(cm, pos) {
      var view = findViewForLine(cm, pos.line);
      if (!view || view.hidden) return null;
      var line = getLine(cm.doc, pos.line);
      var info = mapFromLineView(view, line, pos.line);
  
      var order = getOrder(line), side = "left";
      if (order) {
        var partPos = getBidiPartAt(order, pos.ch);
        side = partPos % 2 ? "right" : "left";
      }
      var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
      result.offset = result.collapse == "right" ? result.end : result.start;
      return result;
    }
  
    function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  
    function domToPos(cm, node, offset) {
      var lineNode;
      if (node == cm.display.lineDiv) {
        lineNode = cm.display.lineDiv.childNodes[offset];
        if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
        node = null; offset = 0;
      } else {
        for (lineNode = node;; lineNode = lineNode.parentNode) {
          if (!lineNode || lineNode == cm.display.lineDiv) return null;
          if (lineNode.parentNode &amp;&amp; lineNode.parentNode == cm.display.lineDiv) break;
        }
      }
      for (var i = 0; i &lt; cm.display.view.length; i++) {
        var lineView = cm.display.view[i];
        if (lineView.node == lineNode)
          return locateNodeInLineView(lineView, node, offset);
      }
    }
  
    function locateNodeInLineView(lineView, node, offset) {
      var wrapper = lineView.text.firstChild, bad = false;
      if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
      if (node == wrapper) {
        bad = true;
        node = wrapper.childNodes[offset];
        offset = 0;
        if (!node) {
          var line = lineView.rest ? lst(lineView.rest) : lineView.line;
          return badPos(Pos(lineNo(line), line.text.length), bad);
        }
      }
  
      var textNode = node.nodeType == 3 ? node : null, topNode = node;
      if (!textNode &amp;&amp; node.childNodes.length == 1 &amp;&amp; node.firstChild.nodeType == 3) {
        textNode = node.firstChild;
        if (offset) offset = textNode.nodeValue.length;
      }
      while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
      var measure = lineView.measure, maps = measure.maps;
  
      function find(textNode, topNode, offset) {
        for (var i = -1; i &lt; (maps ? maps.length : 0); i++) {
          var map = i &lt; 0 ? measure.map : maps[i];
          for (var j = 0; j &lt; map.length; j += 3) {
            var curNode = map[j + 2];
            if (curNode == textNode || curNode == topNode) {
              var line = lineNo(i &lt; 0 ? lineView.line : lineView.rest[i]);
              var ch = map[j] + offset;
              if (offset &lt; 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
              return Pos(line, ch);
            }
          }
        }
      }
      var found = find(textNode, topNode, offset);
      if (found) return badPos(found, bad);
  
      // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
      for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
        found = find(after, after.firstChild, 0);
        if (found)
          return badPos(Pos(found.line, found.ch - dist), bad);
        else
          dist += after.textContent.length;
      }
      for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
        found = find(before, before.firstChild, -1);
        if (found)
          return badPos(Pos(found.line, found.ch + dist), bad);
        else
          dist += after.textContent.length;
      }
    }
  
    function domTextBetween(cm, from, to, fromLine, toLine) {
      var text = "", closing = false, lineSep = cm.doc.lineSeparator();
      function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
      function walk(node) {
        if (node.nodeType == 1) {
          var cmText = node.getAttribute("cm-text");
          if (cmText != null) {
            if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
            text += cmText;
            return;
          }
          var markerID = node.getAttribute("cm-marker"), range;
          if (markerID) {
            var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
            if (found.length &amp;&amp; (range = found[0].find()))
              text += getBetween(cm.doc, range.from, range.to).join(lineSep);
            return;
          }
          if (node.getAttribute("contenteditable") == "false") return;
          for (var i = 0; i &lt; node.childNodes.length; i++)
            walk(node.childNodes[i]);
          if (/^(pre|div|p)$/i.test(node.nodeName))
            closing = true;
        } else if (node.nodeType == 3) {
          var val = node.nodeValue;
          if (!val) return;
          if (closing) {
            text += lineSep;
            closing = false;
          }
          text += val;
        }
      }
      for (;;) {
        walk(from);
        if (from == to) break;
        from = from.nextSibling;
      }
      return text;
    }
  
    CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  
    // SELECTION / CURSOR
  
    // Selection objects are immutable. A new one is created every time
    // the selection changes. A selection is one or more non-overlapping
    // (and non-touching) ranges, sorted, and an integer that indicates
    // which one is the primary selection (the one that's scrolled into
    // view, that getCursor returns, etc).
    function Selection(ranges, primIndex) {
      this.ranges = ranges;
      this.primIndex = primIndex;
    }
  
    Selection.prototype = {
      primary: function() { return this.ranges[this.primIndex]; },
      equals: function(other) {
        if (other == this) return true;
        if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
        for (var i = 0; i &lt; this.ranges.length; i++) {
          var here = this.ranges[i], there = other.ranges[i];
          if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
        }
        return true;
      },
      deepCopy: function() {
        for (var out = [], i = 0; i &lt; this.ranges.length; i++)
          out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
        return new Selection(out, this.primIndex);
      },
      somethingSelected: function() {
        for (var i = 0; i &lt; this.ranges.length; i++)
          if (!this.ranges[i].empty()) return true;
        return false;
      },
      contains: function(pos, end) {
        if (!end) end = pos;
        for (var i = 0; i &lt; this.ranges.length; i++) {
          var range = this.ranges[i];
          if (cmp(end, range.from()) &gt;= 0 &amp;&amp; cmp(pos, range.to()) &lt;= 0)
            return i;
        }
        return -1;
      }
    };
  
    function Range(anchor, head) {
      this.anchor = anchor; this.head = head;
    }
  
    Range.prototype = {
      from: function() { return minPos(this.anchor, this.head); },
      to: function() { return maxPos(this.anchor, this.head); },
      empty: function() {
        return this.head.line == this.anchor.line &amp;&amp; this.head.ch == this.anchor.ch;
      }
    };
  
    // Take an unsorted, potentially overlapping set of ranges, and
    // build a selection out of it. 'Consumes' ranges array (modifying
    // it).
    function normalizeSelection(ranges, primIndex) {
      var prim = ranges[primIndex];
      ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
      primIndex = indexOf(ranges, prim);
      for (var i = 1; i &lt; ranges.length; i++) {
        var cur = ranges[i], prev = ranges[i - 1];
        if (cmp(prev.to(), cur.from()) &gt;= 0) {
          var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
          var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
          if (i &lt;= primIndex) --primIndex;
          ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
        }
      }
      return new Selection(ranges, primIndex);
    }
  
    function simpleSelection(anchor, head) {
      return new Selection([new Range(anchor, head || anchor)], 0);
    }
  
    // Most of the external API clips given positions to make sure they
    // actually exist within the document.
    function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
    function clipPos(doc, pos) {
      if (pos.line &lt; doc.first) return Pos(doc.first, 0);
      var last = doc.first + doc.size - 1;
      if (pos.line &gt; last) return Pos(last, getLine(doc, last).text.length);
      return clipToLen(pos, getLine(doc, pos.line).text.length);
    }
    function clipToLen(pos, linelen) {
      var ch = pos.ch;
      if (ch == null || ch &gt; linelen) return Pos(pos.line, linelen);
      else if (ch &lt; 0) return Pos(pos.line, 0);
      else return pos;
    }
    function isLine(doc, l) {return l &gt;= doc.first &amp;&amp; l &lt; doc.first + doc.size;}
    function clipPosArray(doc, array) {
      for (var out = [], i = 0; i &lt; array.length; i++) out[i] = clipPos(doc, array[i]);
      return out;
    }
  
    // SELECTION UPDATES
  
    // The 'scroll' parameter given to many of these indicated whether
    // the new cursor position should be scrolled into view after
    // modifying the selection.
  
    // If shift is held or the extend flag is set, extends a range to
    // include a given position (and optionally a second position).
    // Otherwise, simply returns the range between the given positions.
    // Used for cursor motion and such.
    function extendRange(doc, range, head, other) {
      if (doc.cm &amp;&amp; doc.cm.display.shift || doc.extend) {
        var anchor = range.anchor;
        if (other) {
          var posBefore = cmp(head, anchor) &lt; 0;
          if (posBefore != (cmp(other, anchor) &lt; 0)) {
            anchor = head;
            head = other;
          } else if (posBefore != (cmp(head, other) &lt; 0)) {
            head = other;
          }
        }
        return new Range(anchor, head);
      } else {
        return new Range(other || head, head);
      }
    }
  
    // Extend the primary selection range, discard the rest.
    function extendSelection(doc, head, other, options) {
      setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
    }
  
    // Extend all selections (pos is an array of selections with length
    // equal the number of selections)
    function extendSelections(doc, heads, options) {
      for (var out = [], i = 0; i &lt; doc.sel.ranges.length; i++)
        out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
      var newSel = normalizeSelection(out, doc.sel.primIndex);
      setSelection(doc, newSel, options);
    }
  
    // Updates a single range in the selection.
    function replaceOneSelection(doc, i, range, options) {
      var ranges = doc.sel.ranges.slice(0);
      ranges[i] = range;
      setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
    }
  
    // Reset the selection to a single range.
    function setSimpleSelection(doc, anchor, head, options) {
      setSelection(doc, simpleSelection(anchor, head), options);
    }
  
    // Give beforeSelectionChange handlers a change to influence a
    // selection update.
    function filterSelectionChange(doc, sel, options) {
      var obj = {
        ranges: sel.ranges,
        update: function(ranges) {
          this.ranges = [];
          for (var i = 0; i &lt; ranges.length; i++)
            this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
                                       clipPos(doc, ranges[i].head));
        },
        origin: options &amp;&amp; options.origin
      };
      signal(doc, "beforeSelectionChange", doc, obj);
      if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
      if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
      else return sel;
    }
  
    function setSelectionReplaceHistory(doc, sel, options) {
      var done = doc.history.done, last = lst(done);
      if (last &amp;&amp; last.ranges) {
        done[done.length - 1] = sel;
        setSelectionNoUndo(doc, sel, options);
      } else {
        setSelection(doc, sel, options);
      }
    }
  
    // Set a new selection.
    function setSelection(doc, sel, options) {
      setSelectionNoUndo(doc, sel, options);
      addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
    }
  
    function setSelectionNoUndo(doc, sel, options) {
      if (hasHandler(doc, "beforeSelectionChange") || doc.cm &amp;&amp; hasHandler(doc.cm, "beforeSelectionChange"))
        sel = filterSelectionChange(doc, sel, options);
  
      var bias = options &amp;&amp; options.bias ||
        (cmp(sel.primary().head, doc.sel.primary().head) &lt; 0 ? -1 : 1);
      setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  
      if (!(options &amp;&amp; options.scroll === false) &amp;&amp; doc.cm)
        ensureCursorVisible(doc.cm);
    }
  
    function setSelectionInner(doc, sel) {
      if (sel.equals(doc.sel)) return;
  
      doc.sel = sel;
  
      if (doc.cm) {
        doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
        signalCursorActivity(doc.cm);
      }
      signalLater(doc, "cursorActivity", doc);
    }
  
    // Verify that the selection does not partially select any atomic
    // marked ranges.
    function reCheckSelection(doc) {
      setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
    }
  
    // Return a selection that does not partially select any atomic
    // ranges.
    function skipAtomicInSelection(doc, sel, bias, mayClear) {
      var out;
      for (var i = 0; i &lt; sel.ranges.length; i++) {
        var range = sel.ranges[i];
        var old = sel.ranges.length == doc.sel.ranges.length &amp;&amp; doc.sel.ranges[i];
        var newAnchor = skipAtomic(doc, range.anchor, old &amp;&amp; old.anchor, bias, mayClear);
        var newHead = skipAtomic(doc, range.head, old &amp;&amp; old.head, bias, mayClear);
        if (out || newAnchor != range.anchor || newHead != range.head) {
          if (!out) out = sel.ranges.slice(0, i);
          out[i] = new Range(newAnchor, newHead);
        }
      }
      return out ? normalizeSelection(out, sel.primIndex) : sel;
    }
  
    function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
      var line = getLine(doc, pos.line);
      if (line.markedSpans) for (var i = 0; i &lt; line.markedSpans.length; ++i) {
        var sp = line.markedSpans[i], m = sp.marker;
        if ((sp.from == null || (m.inclusiveLeft ? sp.from &lt;= pos.ch : sp.from &lt; pos.ch)) &amp;&amp;
            (sp.to == null || (m.inclusiveRight ? sp.to &gt;= pos.ch : sp.to &gt; pos.ch))) {
          if (mayClear) {
            signal(m, "beforeCursorEnter");
            if (m.explicitlyCleared) {
              if (!line.markedSpans) break;
              else {--i; continue;}
            }
          }
          if (!m.atomic) continue;
  
          if (oldPos) {
            var near = m.find(dir &lt; 0 ? 1 : -1), diff;
            if (dir &lt; 0 ? m.inclusiveRight : m.inclusiveLeft)
              near = movePos(doc, near, -dir, near &amp;&amp; near.line == pos.line ? line : null);
            if (near &amp;&amp; near.line == pos.line &amp;&amp; (diff = cmp(near, oldPos)) &amp;&amp; (dir &lt; 0 ? diff &lt; 0 : diff &gt; 0))
              return skipAtomicInner(doc, near, pos, dir, mayClear);
          }
  
          var far = m.find(dir &lt; 0 ? -1 : 1);
          if (dir &lt; 0 ? m.inclusiveLeft : m.inclusiveRight)
            far = movePos(doc, far, dir, far.line == pos.line ? line : null);
          return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
        }
      }
      return pos;
    }
  
    // Ensure a given position is not inside an atomic range.
    function skipAtomic(doc, pos, oldPos, bias, mayClear) {
      var dir = bias || 1;
      var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
          (!mayClear &amp;&amp; skipAtomicInner(doc, pos, oldPos, dir, true)) ||
          skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
          (!mayClear &amp;&amp; skipAtomicInner(doc, pos, oldPos, -dir, true));
      if (!found) {
        doc.cantEdit = true;
        return Pos(doc.first, 0);
      }
      return found;
    }
  
    function movePos(doc, pos, dir, line) {
      if (dir &lt; 0 &amp;&amp; pos.ch == 0) {
        if (pos.line &gt; doc.first) return clipPos(doc, Pos(pos.line - 1));
        else return null;
      } else if (dir &gt; 0 &amp;&amp; pos.ch == (line || getLine(doc, pos.line)).text.length) {
        if (pos.line &lt; doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
        else return null;
      } else {
        return new Pos(pos.line, pos.ch + dir);
      }
    }
  
    // SELECTION DRAWING
  
    function updateSelection(cm) {
      cm.display.input.showSelection(cm.display.input.prepareSelection());
    }
  
    function prepareSelection(cm, primary) {
      var doc = cm.doc, result = {};
      var curFragment = result.cursors = document.createDocumentFragment();
      var selFragment = result.selection = document.createDocumentFragment();
  
      for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
        if (primary === false &amp;&amp; i == doc.sel.primIndex) continue;
        var range = doc.sel.ranges[i];
        if (range.from().line &gt;= cm.display.viewTo || range.to().line &lt; cm.display.viewFrom) continue;
        var collapsed = range.empty();
        if (collapsed || cm.options.showCursorWhenSelecting)
          drawSelectionCursor(cm, range.head, curFragment);
        if (!collapsed)
          drawSelectionRange(cm, range, selFragment);
      }
      return result;
    }
  
    // Draws a cursor for the given range
    function drawSelectionCursor(cm, head, output) {
      var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  
      var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
      cursor.style.left = pos.left + "px";
      cursor.style.top = pos.top + "px";
      cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  
      if (pos.other) {
        // Secondary cursor, shown when on a 'jump' in bi-directional text
        var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
        otherCursor.style.display = "";
        otherCursor.style.left = pos.other.left + "px";
        otherCursor.style.top = pos.other.top + "px";
        otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
      }
    }
  
    // Draws the given range as a highlighted selection
    function drawSelectionRange(cm, range, output) {
      var display = cm.display, doc = cm.doc;
      var fragment = document.createDocumentFragment();
      var padding = paddingH(cm.display), leftSide = padding.left;
      var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  
      function add(left, top, width, bottom) {
        if (top &lt; 0) top = 0;
        top = Math.round(top);
        bottom = Math.round(bottom);
        fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
                                 "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
                                 "px; height: " + (bottom - top) + "px"));
      }
  
      function drawForLine(line, fromArg, toArg) {
        var lineObj = getLine(doc, line);
        var lineLen = lineObj.text.length;
        var start, end;
        function coords(ch, bias) {
          return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
        }
  
        iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
          var leftPos = coords(from, "left"), rightPos, left, right;
          if (from == to) {
            rightPos = leftPos;
            left = right = leftPos.left;
          } else {
            rightPos = coords(to - 1, "right");
            if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
            left = leftPos.left;
            right = rightPos.right;
          }
          if (fromArg == null &amp;&amp; from == 0) left = leftSide;
          if (rightPos.top - leftPos.top &gt; 3) { // Different lines, draw top part
            add(left, leftPos.top, null, leftPos.bottom);
            left = leftSide;
            if (leftPos.bottom &lt; rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
          }
          if (toArg == null &amp;&amp; to == lineLen) right = rightSide;
          if (!start || leftPos.top &lt; start.top || leftPos.top == start.top &amp;&amp; leftPos.left &lt; start.left)
            start = leftPos;
          if (!end || rightPos.bottom &gt; end.bottom || rightPos.bottom == end.bottom &amp;&amp; rightPos.right &gt; end.right)
            end = rightPos;
          if (left &lt; leftSide + 1) left = leftSide;
          add(left, rightPos.top, right - left, rightPos.bottom);
        });
        return {start: start, end: end};
      }
  
      var sFrom = range.from(), sTo = range.to();
      if (sFrom.line == sTo.line) {
        drawForLine(sFrom.line, sFrom.ch, sTo.ch);
      } else {
        var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
        var singleVLine = visualLine(fromLine) == visualLine(toLine);
        var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
        var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
        if (singleVLine) {
          if (leftEnd.top &lt; rightStart.top - 2) {
            add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
            add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
          } else {
            add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
          }
        }
        if (leftEnd.bottom &lt; rightStart.top)
          add(leftSide, leftEnd.bottom, null, rightStart.top);
      }
  
      output.appendChild(fragment);
    }
  
    // Cursor-blinking
    function restartBlink(cm) {
      if (!cm.state.focused) return;
      var display = cm.display;
      clearInterval(display.blinker);
      var on = true;
      display.cursorDiv.style.visibility = "";
      if (cm.options.cursorBlinkRate &gt; 0)
        display.blinker = setInterval(function() {
          display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
        }, cm.options.cursorBlinkRate);
      else if (cm.options.cursorBlinkRate &lt; 0)
        display.cursorDiv.style.visibility = "hidden";
    }
  
    // HIGHLIGHT WORKER
  
    function startWorker(cm, time) {
      if (cm.doc.mode.startState &amp;&amp; cm.doc.frontier &lt; cm.display.viewTo)
        cm.state.highlight.set(time, bind(highlightWorker, cm));
    }
  
    function highlightWorker(cm) {
      var doc = cm.doc;
      if (doc.frontier &lt; doc.first) doc.frontier = doc.first;
      if (doc.frontier &gt;= cm.display.viewTo) return;
      var end = +new Date + cm.options.workTime;
      var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
      var changedLines = [];
  
      doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
        if (doc.frontier &gt;= cm.display.viewFrom) { // Visible
          var oldStyles = line.styles, tooLong = line.text.length &gt; cm.options.maxHighlightLength;
          var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
          line.styles = highlighted.styles;
          var oldCls = line.styleClasses, newCls = highlighted.classes;
          if (newCls) line.styleClasses = newCls;
          else if (oldCls) line.styleClasses = null;
          var ischange = !oldStyles || oldStyles.length != line.styles.length ||
            oldCls != newCls &amp;&amp; (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
          for (var i = 0; !ischange &amp;&amp; i &lt; oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
          if (ischange) changedLines.push(doc.frontier);
          line.stateAfter = tooLong ? state : copyState(doc.mode, state);
        } else {
          if (line.text.length &lt;= cm.options.maxHighlightLength)
            processLine(cm, line.text, state);
          line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
        }
        ++doc.frontier;
        if (+new Date &gt; end) {
          startWorker(cm, cm.options.workDelay);
          return true;
        }
      });
      if (changedLines.length) runInOp(cm, function() {
        for (var i = 0; i &lt; changedLines.length; i++)
          regLineChange(cm, changedLines[i], "text");
      });
    }
  
    // Finds the line to start with when starting a parse. Tries to
    // find a line with a stateAfter, so that it can start with a
    // valid state. If that fails, it returns the line with the
    // smallest indentation, which tends to need the least context to
    // parse correctly.
    function findStartLine(cm, n, precise) {
      var minindent, minline, doc = cm.doc;
      var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
      for (var search = n; search &gt; lim; --search) {
        if (search &lt;= doc.first) return doc.first;
        var line = getLine(doc, search - 1);
        if (line.stateAfter &amp;&amp; (!precise || search &lt;= doc.frontier)) return search;
        var indented = countColumn(line.text, null, cm.options.tabSize);
        if (minline == null || minindent &gt; indented) {
          minline = search - 1;
          minindent = indented;
        }
      }
      return minline;
    }
  
    function getStateBefore(cm, n, precise) {
      var doc = cm.doc, display = cm.display;
      if (!doc.mode.startState) return true;
      var pos = findStartLine(cm, n, precise), state = pos &gt; doc.first &amp;&amp; getLine(doc, pos-1).stateAfter;
      if (!state) state = startState(doc.mode);
      else state = copyState(doc.mode, state);
      doc.iter(pos, n, function(line) {
        processLine(cm, line.text, state);
        var save = pos == n - 1 || pos % 5 == 0 || pos &gt;= display.viewFrom &amp;&amp; pos &lt; display.viewTo;
        line.stateAfter = save ? copyState(doc.mode, state) : null;
        ++pos;
      });
      if (precise) doc.frontier = pos;
      return state;
    }
  
    // POSITION MEASUREMENT
  
    function paddingTop(display) {return display.lineSpace.offsetTop;}
    function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
    function paddingH(display) {
      if (display.cachedPaddingH) return display.cachedPaddingH;
      var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
      var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
      var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
      if (!isNaN(data.left) &amp;&amp; !isNaN(data.right)) display.cachedPaddingH = data;
      return data;
    }
  
    function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
    function displayWidth(cm) {
      return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
    }
    function displayHeight(cm) {
      return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
    }
  
    // Ensure the lineView.wrapping.heights array is populated. This is
    // an array of bottom offsets for the lines that make up a drawn
    // line. When lineWrapping is on, there might be more than one
    // height.
    function ensureLineHeights(cm, lineView, rect) {
      var wrapping = cm.options.lineWrapping;
      var curWidth = wrapping &amp;&amp; displayWidth(cm);
      if (!lineView.measure.heights || wrapping &amp;&amp; lineView.measure.width != curWidth) {
        var heights = lineView.measure.heights = [];
        if (wrapping) {
          lineView.measure.width = curWidth;
          var rects = lineView.text.firstChild.getClientRects();
          for (var i = 0; i &lt; rects.length - 1; i++) {
            var cur = rects[i], next = rects[i + 1];
            if (Math.abs(cur.bottom - next.bottom) &gt; 2)
              heights.push((cur.bottom + next.top) / 2 - rect.top);
          }
        }
        heights.push(rect.bottom - rect.top);
      }
    }
  
    // Find a line map (mapping character offsets to text nodes) and a
    // measurement cache for the given line number. (A line view might
    // contain multiple lines when collapsed ranges are present.)
    function mapFromLineView(lineView, line, lineN) {
      if (lineView.line == line)
        return {map: lineView.measure.map, cache: lineView.measure.cache};
      for (var i = 0; i &lt; lineView.rest.length; i++)
        if (lineView.rest[i] == line)
          return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
      for (var i = 0; i &lt; lineView.rest.length; i++)
        if (lineNo(lineView.rest[i]) &gt; lineN)
          return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
    }
  
    // Render a line into the hidden node display.externalMeasured. Used
    // when measurement is needed for a line that's not in the viewport.
    function updateExternalMeasurement(cm, line) {
      line = visualLine(line);
      var lineN = lineNo(line);
      var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
      view.lineN = lineN;
      var built = view.built = buildLineContent(cm, view);
      view.text = built.pre;
      removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
      return view;
    }
  
    // Get a {top, bottom, left, right} box (in line-local coordinates)
    // for a given character.
    function measureChar(cm, line, ch, bias) {
      return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
    }
  
    // Find a line view that corresponds to the given line number.
    function findViewForLine(cm, lineN) {
      if (lineN &gt;= cm.display.viewFrom &amp;&amp; lineN &lt; cm.display.viewTo)
        return cm.display.view[findViewIndex(cm, lineN)];
      var ext = cm.display.externalMeasured;
      if (ext &amp;&amp; lineN &gt;= ext.lineN &amp;&amp; lineN &lt; ext.lineN + ext.size)
        return ext;
    }
  
    // Measurement can be split in two steps, the set-up work that
    // applies to the whole line, and the measurement of the actual
    // character. Functions like coordsChar, that need to do a lot of
    // measurements in a row, can thus ensure that the set-up work is
    // only done once.
    function prepareMeasureForLine(cm, line) {
      var lineN = lineNo(line);
      var view = findViewForLine(cm, lineN);
      if (view &amp;&amp; !view.text) {
        view = null;
      } else if (view &amp;&amp; view.changes) {
        updateLineForChanges(cm, view, lineN, getDimensions(cm));
        cm.curOp.forceUpdate = true;
      }
      if (!view)
        view = updateExternalMeasurement(cm, line);
  
      var info = mapFromLineView(view, line, lineN);
      return {
        line: line, view: view, rect: null,
        map: info.map, cache: info.cache, before: info.before,
        hasHeights: false
      };
    }
  
    // Given a prepared measurement object, measures the position of an
    // actual character (or fetches it from the cache).
    function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
      if (prepared.before) ch = -1;
      var key = ch + (bias || ""), found;
      if (prepared.cache.hasOwnProperty(key)) {
        found = prepared.cache[key];
      } else {
        if (!prepared.rect)
          prepared.rect = prepared.view.text.getBoundingClientRect();
        if (!prepared.hasHeights) {
          ensureLineHeights(cm, prepared.view, prepared.rect);
          prepared.hasHeights = true;
        }
        found = measureCharInner(cm, prepared, ch, bias);
        if (!found.bogus) prepared.cache[key] = found;
      }
      return {left: found.left, right: found.right,
              top: varHeight ? found.rtop : found.top,
              bottom: varHeight ? found.rbottom : found.bottom};
    }
  
    var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  
    function nodeAndOffsetInLineMap(map, ch, bias) {
      var node, start, end, collapse;
      // First, search the line map for the text node corresponding to,
      // or closest to, the target character.
      for (var i = 0; i &lt; map.length; i += 3) {
        var mStart = map[i], mEnd = map[i + 1];
        if (ch &lt; mStart) {
          start = 0; end = 1;
          collapse = "left";
        } else if (ch &lt; mEnd) {
          start = ch - mStart;
          end = start + 1;
        } else if (i == map.length - 3 || ch == mEnd &amp;&amp; map[i + 3] &gt; ch) {
          end = mEnd - mStart;
          start = end - 1;
          if (ch &gt;= mEnd) collapse = "right";
        }
        if (start != null) {
          node = map[i + 2];
          if (mStart == mEnd &amp;&amp; bias == (node.insertLeft ? "left" : "right"))
            collapse = bias;
          if (bias == "left" &amp;&amp; start == 0)
            while (i &amp;&amp; map[i - 2] == map[i - 3] &amp;&amp; map[i - 1].insertLeft) {
              node = map[(i -= 3) + 2];
              collapse = "left";
            }
          if (bias == "right" &amp;&amp; start == mEnd - mStart)
            while (i &lt; map.length - 3 &amp;&amp; map[i + 3] == map[i + 4] &amp;&amp; !map[i + 5].insertLeft) {
              node = map[(i += 3) + 2];
              collapse = "right";
            }
          break;
        }
      }
      return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
    }
  
    function measureCharInner(cm, prepared, ch, bias) {
      var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
      var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  
      var rect;
      if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
        for (var i = 0; i &lt; 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
          while (start &amp;&amp; isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
          while (place.coverStart + end &lt; place.coverEnd &amp;&amp; isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
          if (ie &amp;&amp; ie_version &lt; 9 &amp;&amp; start == 0 &amp;&amp; end == place.coverEnd - place.coverStart) {
            rect = node.parentNode.getBoundingClientRect();
          } else if (ie &amp;&amp; cm.options.lineWrapping) {
            var rects = range(node, start, end).getClientRects();
            if (rects.length)
              rect = rects[bias == "right" ? rects.length - 1 : 0];
            else
              rect = nullRect;
          } else {
            rect = range(node, start, end).getBoundingClientRect() || nullRect;
          }
          if (rect.left || rect.right || start == 0) break;
          end = start;
          start = start - 1;
          collapse = "right";
        }
        if (ie &amp;&amp; ie_version &lt; 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
      } else { // If it is a widget, simply get the box for the whole widget.
        if (start &gt; 0) collapse = bias = "right";
        var rects;
        if (cm.options.lineWrapping &amp;&amp; (rects = node.getClientRects()).length &gt; 1)
          rect = rects[bias == "right" ? rects.length - 1 : 0];
        else
          rect = node.getBoundingClientRect();
      }
      if (ie &amp;&amp; ie_version &lt; 9 &amp;&amp; !start &amp;&amp; (!rect || !rect.left &amp;&amp; !rect.right)) {
        var rSpan = node.parentNode.getClientRects()[0];
        if (rSpan)
          rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
        else
          rect = nullRect;
      }
  
      var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
      var mid = (rtop + rbot) / 2;
      var heights = prepared.view.measure.heights;
      for (var i = 0; i &lt; heights.length - 1; i++)
        if (mid &lt; heights[i]) break;
      var top = i ? heights[i - 1] : 0, bot = heights[i];
      var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
                    right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
                    top: top, bottom: bot};
      if (!rect.left &amp;&amp; !rect.right) result.bogus = true;
      if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  
      return result;
    }
  
    // Work around problem with bounding client rects on ranges being
    // returned incorrectly when zoomed on IE10 and below.
    function maybeUpdateRectForZooming(measure, rect) {
      if (!window.screen || screen.logicalXDPI == null ||
          screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
        return rect;
      var scaleX = screen.logicalXDPI / screen.deviceXDPI;
      var scaleY = screen.logicalYDPI / screen.deviceYDPI;
      return {left: rect.left * scaleX, right: rect.right * scaleX,
              top: rect.top * scaleY, bottom: rect.bottom * scaleY};
    }
  
    function clearLineMeasurementCacheFor(lineView) {
      if (lineView.measure) {
        lineView.measure.cache = {};
        lineView.measure.heights = null;
        if (lineView.rest) for (var i = 0; i &lt; lineView.rest.length; i++)
          lineView.measure.caches[i] = {};
      }
    }
  
    function clearLineMeasurementCache(cm) {
      cm.display.externalMeasure = null;
      removeChildren(cm.display.lineMeasure);
      for (var i = 0; i &lt; cm.display.view.length; i++)
        clearLineMeasurementCacheFor(cm.display.view[i]);
    }
  
    function clearCaches(cm) {
      clearLineMeasurementCache(cm);
      cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
      if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
      cm.display.lineNumChars = null;
    }
  
    function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
    function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  
    // Converts a {top, bottom, left, right} box from line-local
    // coordinates into another coordinate system. Context may be one of
    // "line", "div" (display.lineDiv), "local"/null (editor), "window",
    // or "page".
    function intoCoordSystem(cm, lineObj, rect, context) {
      if (lineObj.widgets) for (var i = 0; i &lt; lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
        var size = widgetHeight(lineObj.widgets[i]);
        rect.top += size; rect.bottom += size;
      }
      if (context == "line") return rect;
      if (!context) context = "local";
      var yOff = heightAtLine(lineObj);
      if (context == "local") yOff += paddingTop(cm.display);
      else yOff -= cm.display.viewOffset;
      if (context == "page" || context == "window") {
        var lOff = cm.display.lineSpace.getBoundingClientRect();
        yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
        var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
        rect.left += xOff; rect.right += xOff;
      }
      rect.top += yOff; rect.bottom += yOff;
      return rect;
    }
  
    // Coverts a box from "div" coords to another coordinate system.
    // Context may be "window", "page", "div", or "local"/null.
    function fromCoordSystem(cm, coords, context) {
      if (context == "div") return coords;
      var left = coords.left, top = coords.top;
      // First move into "page" coordinate system
      if (context == "page") {
        left -= pageScrollX();
        top -= pageScrollY();
      } else if (context == "local" || !context) {
        var localBox = cm.display.sizer.getBoundingClientRect();
        left += localBox.left;
        top += localBox.top;
      }
  
      var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
      return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
    }
  
    function charCoords(cm, pos, context, lineObj, bias) {
      if (!lineObj) lineObj = getLine(cm.doc, pos.line);
      return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
    }
  
    // Returns a box for a given cursor position, which may have an
    // 'other' property containing the position of the secondary cursor
    // on a bidi boundary.
    function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
      lineObj = lineObj || getLine(cm.doc, pos.line);
      if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
      function get(ch, right) {
        var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
        if (right) m.left = m.right; else m.right = m.left;
        return intoCoordSystem(cm, lineObj, m, context);
      }
      function getBidi(ch, partPos) {
        var part = order[partPos], right = part.level % 2;
        if (ch == bidiLeft(part) &amp;&amp; partPos &amp;&amp; part.level &lt; order[partPos - 1].level) {
          part = order[--partPos];
          ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
          right = true;
        } else if (ch == bidiRight(part) &amp;&amp; partPos &lt; order.length - 1 &amp;&amp; part.level &lt; order[partPos + 1].level) {
          part = order[++partPos];
          ch = bidiLeft(part) - part.level % 2;
          right = false;
        }
        if (right &amp;&amp; ch == part.to &amp;&amp; ch &gt; part.from) return get(ch - 1);
        return get(ch, right);
      }
      var order = getOrder(lineObj), ch = pos.ch;
      if (!order) return get(ch);
      var partPos = getBidiPartAt(order, ch);
      var val = getBidi(ch, partPos);
      if (bidiOther != null) val.other = getBidi(ch, bidiOther);
      return val;
    }
  
    // Used to cheaply estimate the coordinates for a position. Used for
    // intermediate scroll updates.
    function estimateCoords(cm, pos) {
      var left = 0, pos = clipPos(cm.doc, pos);
      if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
      var lineObj = getLine(cm.doc, pos.line);
      var top = heightAtLine(lineObj) + paddingTop(cm.display);
      return {left: left, right: left, top: top, bottom: top + lineObj.height};
    }
  
    // Positions returned by coordsChar contain some extra information.
    // xRel is the relative x position of the input coordinates compared
    // to the found position (so xRel &gt; 0 means the coordinates are to
    // the right of the character position, for example). When outside
    // is true, that means the coordinates lie outside the line's
    // vertical range.
    function PosWithInfo(line, ch, outside, xRel) {
      var pos = Pos(line, ch);
      pos.xRel = xRel;
      if (outside) pos.outside = true;
      return pos;
    }
  
    // Compute the character position closest to the given coordinates.
    // Input must be lineSpace-local ("div" coordinate system).
    function coordsChar(cm, x, y) {
      var doc = cm.doc;
      y += cm.display.viewOffset;
      if (y &lt; 0) return PosWithInfo(doc.first, 0, true, -1);
      var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
      if (lineN &gt; last)
        return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
      if (x &lt; 0) x = 0;
  
      var lineObj = getLine(doc, lineN);
      for (;;) {
        var found = coordsCharInner(cm, lineObj, lineN, x, y);
        var merged = collapsedSpanAtEnd(lineObj);
        var mergedPos = merged &amp;&amp; merged.find(0, true);
        if (merged &amp;&amp; (found.ch &gt; mergedPos.from.ch || found.ch == mergedPos.from.ch &amp;&amp; found.xRel &gt; 0))
          lineN = lineNo(lineObj = mergedPos.to.line);
        else
          return found;
      }
    }
  
    function coordsCharInner(cm, lineObj, lineNo, x, y) {
      var innerOff = y - heightAtLine(lineObj);
      var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
      var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  
      function getX(ch) {
        var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
        wrongLine = true;
        if (innerOff &gt; sp.bottom) return sp.left - adjust;
        else if (innerOff &lt; sp.top) return sp.left + adjust;
        else wrongLine = false;
        return sp.left;
      }
  
      var bidi = getOrder(lineObj), dist = lineObj.text.length;
      var from = lineLeft(lineObj), to = lineRight(lineObj);
      var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  
      if (x &gt; toX) return PosWithInfo(lineNo, to, toOutside, 1);
      // Do a binary search between these bounds.
      for (;;) {
        if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from &lt;= 1) {
          var ch = x &lt; fromX || x - fromX &lt;= toX - x ? from : to;
          var outside = ch == from ? fromOutside : toOutside
          var xDiff = x - (ch == from ? fromX : toX);
          // This is a kludge to handle the case where the coordinates
          // are after a line-wrapped line. We should replace it with a
          // more general handling of cursor positions around line
          // breaks. (Issue #4078)
          if (toOutside &amp;&amp; !bidi &amp;&amp; !/\s/.test(lineObj.text.charAt(ch)) &amp;&amp; xDiff &gt; 0 &amp;&amp;
              ch &lt; lineObj.text.length &amp;&amp; preparedMeasure.view.measure.heights.length &gt; 1) {
            var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right");
            if (innerOff &lt;= charSize.bottom &amp;&amp; innerOff &gt;= charSize.top &amp;&amp; Math.abs(x - charSize.right) &lt; xDiff) {
              outside = false
              ch++
              xDiff = x - charSize.right
            }
          }
          while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
          var pos = PosWithInfo(lineNo, ch, outside, xDiff &lt; -1 ? -1 : xDiff &gt; 1 ? 1 : 0);
          return pos;
        }
        var step = Math.ceil(dist / 2), middle = from + step;
        if (bidi) {
          middle = from;
          for (var i = 0; i &lt; step; ++i) middle = moveVisually(lineObj, middle, 1);
        }
        var middleX = getX(middle);
        if (middleX &gt; x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
        else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
      }
    }
  
    var measureText;
    // Compute the default text height.
    function textHeight(display) {
      if (display.cachedTextHeight != null) return display.cachedTextHeight;
      if (measureText == null) {
        measureText = elt("pre");
        // Measure a bunch of lines, for browsers that compute
        // fractional heights.
        for (var i = 0; i &lt; 49; ++i) {
          measureText.appendChild(document.createTextNode("x"));
          measureText.appendChild(elt("br"));
        }
        measureText.appendChild(document.createTextNode("x"));
      }
      removeChildrenAndAdd(display.measure, measureText);
      var height = measureText.offsetHeight / 50;
      if (height &gt; 3) display.cachedTextHeight = height;
      removeChildren(display.measure);
      return height || 1;
    }
  
    // Compute the default character width.
    function charWidth(display) {
      if (display.cachedCharWidth != null) return display.cachedCharWidth;
      var anchor = elt("span", "xxxxxxxxxx");
      var pre = elt("pre", [anchor]);
      removeChildrenAndAdd(display.measure, pre);
      var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
      if (width &gt; 2) display.cachedCharWidth = width;
      return width || 10;
    }
  
    // OPERATIONS
  
    // Operations are used to wrap a series of changes to the editor
    // state in such a way that each change won't have to update the
    // cursor and display (which would be awkward, slow, and
    // error-prone). Instead, display updates are batched and then all
    // combined and executed at once.
  
    var operationGroup = null;
  
    var nextOpId = 0;
    // Start a new operation.
    function startOperation(cm) {
      cm.curOp = {
        cm: cm,
        viewChanged: false,      // Flag that indicates that lines might need to be redrawn
        startHeight: cm.doc.height, // Used to detect need to update scrollbar
        forceUpdate: false,      // Used to force a redraw
        updateInput: null,       // Whether to reset the input textarea
        typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
        changeObjs: null,        // Accumulated changes, for firing change events
        cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
        cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
        selectionChanged: false, // Whether the selection needs to be redrawn
        updateMaxLine: false,    // Set when the widest line needs to be determined anew
        scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
        scrollToPos: null,       // Used to scroll to a specific position
        focus: false,
        id: ++nextOpId           // Unique ID
      };
      if (operationGroup) {
        operationGroup.ops.push(cm.curOp);
      } else {
        cm.curOp.ownsGroup = operationGroup = {
          ops: [cm.curOp],
          delayedCallbacks: []
        };
      }
    }
  
    function fireCallbacksForOps(group) {
      // Calls delayed callbacks and cursorActivity handlers until no
      // new ones appear
      var callbacks = group.delayedCallbacks, i = 0;
      do {
        for (; i &lt; callbacks.length; i++)
          callbacks[i].call(null);
        for (var j = 0; j &lt; group.ops.length; j++) {
          var op = group.ops[j];
          if (op.cursorActivityHandlers)
            while (op.cursorActivityCalled &lt; op.cursorActivityHandlers.length)
              op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
        }
      } while (i &lt; callbacks.length);
    }
  
    // Finish an operation, updating the display and signalling delayed events
    function endOperation(cm) {
      var op = cm.curOp, group = op.ownsGroup;
      if (!group) return;
  
      try { fireCallbacksForOps(group); }
      finally {
        operationGroup = null;
        for (var i = 0; i &lt; group.ops.length; i++)
          group.ops[i].cm.curOp = null;
        endOperations(group);
      }
    }
  
    // The DOM updates done when an operation finishes are batched so
    // that the minimum number of relayouts are required.
    function endOperations(group) {
      var ops = group.ops;
      for (var i = 0; i &lt; ops.length; i++) // Read DOM
        endOperation_R1(ops[i]);
      for (var i = 0; i &lt; ops.length; i++) // Write DOM (maybe)
        endOperation_W1(ops[i]);
      for (var i = 0; i &lt; ops.length; i++) // Read DOM
        endOperation_R2(ops[i]);
      for (var i = 0; i &lt; ops.length; i++) // Write DOM (maybe)
        endOperation_W2(ops[i]);
      for (var i = 0; i &lt; ops.length; i++) // Read DOM
        endOperation_finish(ops[i]);
    }
  
    function endOperation_R1(op) {
      var cm = op.cm, display = cm.display;
      maybeClipScrollbars(cm);
      if (op.updateMaxLine) findMaxLine(cm);
  
      op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
        op.scrollToPos &amp;&amp; (op.scrollToPos.from.line &lt; display.viewFrom ||
                           op.scrollToPos.to.line &gt;= display.viewTo) ||
        display.maxLineChanged &amp;&amp; cm.options.lineWrapping;
      op.update = op.mustUpdate &amp;&amp;
        new DisplayUpdate(cm, op.mustUpdate &amp;&amp; {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
    }
  
    function endOperation_W1(op) {
      op.updatedDisplay = op.mustUpdate &amp;&amp; updateDisplayIfNeeded(op.cm, op.update);
    }
  
    function endOperation_R2(op) {
      var cm = op.cm, display = cm.display;
      if (op.updatedDisplay) updateHeightsInViewport(cm);
  
      op.barMeasure = measureForScrollbars(cm);
  
      // If the max line changed since it was last measured, measure it,
      // and ensure the document's width matches it.
      // updateDisplay_W2 will use these properties to do the actual resizing
      if (display.maxLineChanged &amp;&amp; !cm.options.lineWrapping) {
        op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
        cm.display.sizerWidth = op.adjustWidthTo;
        op.barMeasure.scrollWidth =
          Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
        op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
      }
  
      if (op.updatedDisplay || op.selectionChanged)
        op.preparedSelection = display.input.prepareSelection(op.focus);
    }
  
    function endOperation_W2(op) {
      var cm = op.cm;
  
      if (op.adjustWidthTo != null) {
        cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
        if (op.maxScrollLeft &lt; cm.doc.scrollLeft)
          setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
        cm.display.maxLineChanged = false;
      }
  
      var takeFocus = op.focus &amp;&amp; op.focus == activeElt() &amp;&amp; (!document.hasFocus || document.hasFocus())
      if (op.preparedSelection)
        cm.display.input.showSelection(op.preparedSelection, takeFocus);
      if (op.updatedDisplay || op.startHeight != cm.doc.height)
        updateScrollbars(cm, op.barMeasure);
      if (op.updatedDisplay)
        setDocumentHeight(cm, op.barMeasure);
  
      if (op.selectionChanged) restartBlink(cm);
  
      if (cm.state.focused &amp;&amp; op.updateInput)
        cm.display.input.reset(op.typing);
      if (takeFocus) ensureFocus(op.cm);
    }
  
    function endOperation_finish(op) {
      var cm = op.cm, display = cm.display, doc = cm.doc;
  
      if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  
      // Abort mouse wheel delta measurement, when scrolling explicitly
      if (display.wheelStartX != null &amp;&amp; (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
        display.wheelStartX = display.wheelStartY = null;
  
      // Propagate the scroll position to the actual DOM scroller
      if (op.scrollTop != null &amp;&amp; (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
        doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
        display.scrollbars.setScrollTop(doc.scrollTop);
        display.scroller.scrollTop = doc.scrollTop;
      }
      if (op.scrollLeft != null &amp;&amp; (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
        doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
        display.scrollbars.setScrollLeft(doc.scrollLeft);
        display.scroller.scrollLeft = doc.scrollLeft;
        alignHorizontally(cm);
      }
      // If we need to scroll a specific position into view, do so.
      if (op.scrollToPos) {
        var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
                                       clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
        if (op.scrollToPos.isCursor &amp;&amp; cm.state.focused) maybeScrollWindow(cm, coords);
      }
  
      // Fire events for markers that are hidden/unidden by editing or
      // undoing
      var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
      if (hidden) for (var i = 0; i &lt; hidden.length; ++i)
        if (!hidden[i].lines.length) signal(hidden[i], "hide");
      if (unhidden) for (var i = 0; i &lt; unhidden.length; ++i)
        if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  
      if (display.wrapper.offsetHeight)
        doc.scrollTop = cm.display.scroller.scrollTop;
  
      // Fire change events, and delayed event handlers
      if (op.changeObjs)
        signal(cm, "changes", cm, op.changeObjs);
      if (op.update)
        op.update.finish();
    }
  
    // Run the given function in an operation
    function runInOp(cm, f) {
      if (cm.curOp) return f();
      startOperation(cm);
      try { return f(); }
      finally { endOperation(cm); }
    }
    // Wraps a function in an operation. Returns the wrapped function.
    function operation(cm, f) {
      return function() {
        if (cm.curOp) return f.apply(cm, arguments);
        startOperation(cm);
        try { return f.apply(cm, arguments); }
        finally { endOperation(cm); }
      };
    }
    // Used to add methods to editor and doc instances, wrapping them in
    // operations.
    function methodOp(f) {
      return function() {
        if (this.curOp) return f.apply(this, arguments);
        startOperation(this);
        try { return f.apply(this, arguments); }
        finally { endOperation(this); }
      };
    }
    function docMethodOp(f) {
      return function() {
        var cm = this.cm;
        if (!cm || cm.curOp) return f.apply(this, arguments);
        startOperation(cm);
        try { return f.apply(this, arguments); }
        finally { endOperation(cm); }
      };
    }
  
    // VIEW TRACKING
  
    // These objects are used to represent the visible (currently drawn)
    // part of the document. A LineView may correspond to multiple
    // logical lines, if those are connected by collapsed ranges.
    function LineView(doc, line, lineN) {
      // The starting line
      this.line = line;
      // Continuing lines, if any
      this.rest = visualLineContinued(line);
      // Number of logical lines in this visual line
      this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
      this.node = this.text = null;
      this.hidden = lineIsHidden(doc, line);
    }
  
    // Create a range of LineView objects for the given lines.
    function buildViewArray(cm, from, to) {
      var array = [], nextPos;
      for (var pos = from; pos &lt; to; pos = nextPos) {
        var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
        nextPos = pos + view.size;
        array.push(view);
      }
      return array;
    }
  
    // Updates the display.view data structure for a given change to the
    // document. From and to are in pre-change coordinates. Lendiff is
    // the amount of lines added or subtracted by the change. This is
    // used for changes that span multiple lines, or change the way
    // lines are divided into visual lines. regLineChange (below)
    // registers single-line changes.
    function regChange(cm, from, to, lendiff) {
      if (from == null) from = cm.doc.first;
      if (to == null) to = cm.doc.first + cm.doc.size;
      if (!lendiff) lendiff = 0;
  
      var display = cm.display;
      if (lendiff &amp;&amp; to &lt; display.viewTo &amp;&amp;
          (display.updateLineNumbers == null || display.updateLineNumbers &gt; from))
        display.updateLineNumbers = from;
  
      cm.curOp.viewChanged = true;
  
      if (from &gt;= display.viewTo) { // Change after
        if (sawCollapsedSpans &amp;&amp; visualLineNo(cm.doc, from) &lt; display.viewTo)
          resetView(cm);
      } else if (to &lt;= display.viewFrom) { // Change before
        if (sawCollapsedSpans &amp;&amp; visualLineEndNo(cm.doc, to + lendiff) &gt; display.viewFrom) {
          resetView(cm);
        } else {
          display.viewFrom += lendiff;
          display.viewTo += lendiff;
        }
      } else if (from &lt;= display.viewFrom &amp;&amp; to &gt;= display.viewTo) { // Full overlap
        resetView(cm);
      } else if (from &lt;= display.viewFrom) { // Top overlap
        var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
        if (cut) {
          display.view = display.view.slice(cut.index);
          display.viewFrom = cut.lineN;
          display.viewTo += lendiff;
        } else {
          resetView(cm);
        }
      } else if (to &gt;= display.viewTo) { // Bottom overlap
        var cut = viewCuttingPoint(cm, from, from, -1);
        if (cut) {
          display.view = display.view.slice(0, cut.index);
          display.viewTo = cut.lineN;
        } else {
          resetView(cm);
        }
      } else { // Gap in the middle
        var cutTop = viewCuttingPoint(cm, from, from, -1);
        var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
        if (cutTop &amp;&amp; cutBot) {
          display.view = display.view.slice(0, cutTop.index)
            .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
            .concat(display.view.slice(cutBot.index));
          display.viewTo += lendiff;
        } else {
          resetView(cm);
        }
      }
  
      var ext = display.externalMeasured;
      if (ext) {
        if (to &lt; ext.lineN)
          ext.lineN += lendiff;
        else if (from &lt; ext.lineN + ext.size)
          display.externalMeasured = null;
      }
    }
  
    // Register a change to a single line. Type must be one of "text",
    // "gutter", "class", "widget"
    function regLineChange(cm, line, type) {
      cm.curOp.viewChanged = true;
      var display = cm.display, ext = cm.display.externalMeasured;
      if (ext &amp;&amp; line &gt;= ext.lineN &amp;&amp; line &lt; ext.lineN + ext.size)
        display.externalMeasured = null;
  
      if (line &lt; display.viewFrom || line &gt;= display.viewTo) return;
      var lineView = display.view[findViewIndex(cm, line)];
      if (lineView.node == null) return;
      var arr = lineView.changes || (lineView.changes = []);
      if (indexOf(arr, type) == -1) arr.push(type);
    }
  
    // Clear the view.
    function resetView(cm) {
      cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
      cm.display.view = [];
      cm.display.viewOffset = 0;
    }
  
    // Find the view element corresponding to a given line. Return null
    // when the line isn't visible.
    function findViewIndex(cm, n) {
      if (n &gt;= cm.display.viewTo) return null;
      n -= cm.display.viewFrom;
      if (n &lt; 0) return null;
      var view = cm.display.view;
      for (var i = 0; i &lt; view.length; i++) {
        n -= view[i].size;
        if (n &lt; 0) return i;
      }
    }
  
    function viewCuttingPoint(cm, oldN, newN, dir) {
      var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
      if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
        return {index: index, lineN: newN};
      for (var i = 0, n = cm.display.viewFrom; i &lt; index; i++)
        n += view[i].size;
      if (n != oldN) {
        if (dir &gt; 0) {
          if (index == view.length - 1) return null;
          diff = (n + view[index].size) - oldN;
          index++;
        } else {
          diff = n - oldN;
        }
        oldN += diff; newN += diff;
      }
      while (visualLineNo(cm.doc, newN) != newN) {
        if (index == (dir &lt; 0 ? 0 : view.length - 1)) return null;
        newN += dir * view[index - (dir &lt; 0 ? 1 : 0)].size;
        index += dir;
      }
      return {index: index, lineN: newN};
    }
  
    // Force the view to cover a given range, adding empty view element
    // or clipping off existing ones as needed.
    function adjustView(cm, from, to) {
      var display = cm.display, view = display.view;
      if (view.length == 0 || from &gt;= display.viewTo || to &lt;= display.viewFrom) {
        display.view = buildViewArray(cm, from, to);
        display.viewFrom = from;
      } else {
        if (display.viewFrom &gt; from)
          display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
        else if (display.viewFrom &lt; from)
          display.view = display.view.slice(findViewIndex(cm, from));
        display.viewFrom = from;
        if (display.viewTo &lt; to)
          display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
        else if (display.viewTo &gt; to)
          display.view = display.view.slice(0, findViewIndex(cm, to));
      }
      display.viewTo = to;
    }
  
    // Count the number of lines in the view whose DOM representation is
    // out of date (or nonexistent).
    function countDirtyView(cm) {
      var view = cm.display.view, dirty = 0;
      for (var i = 0; i &lt; view.length; i++) {
        var lineView = view[i];
        if (!lineView.hidden &amp;&amp; (!lineView.node || lineView.changes)) ++dirty;
      }
      return dirty;
    }
  
    // EVENT HANDLERS
  
    // Attach the necessary event handlers when initializing the editor
    function registerEventHandlers(cm) {
      var d = cm.display;
      on(d.scroller, "mousedown", operation(cm, onMouseDown));
      // Older IE's will not fire a second mousedown for a double click
      if (ie &amp;&amp; ie_version &lt; 11)
        on(d.scroller, "dblclick", operation(cm, function(e) {
          if (signalDOMEvent(cm, e)) return;
          var pos = posFromMouse(cm, e);
          if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
          e_preventDefault(e);
          var word = cm.findWordAt(pos);
          extendSelection(cm.doc, word.anchor, word.head);
        }));
      else
        on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
      // Some browsers fire contextmenu *after* opening the menu, at
      // which point we can't mess with it anymore. Context menu is
      // handled in onMouseDown for these browsers.
      if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  
      // Used to suppress mouse event handling when a touch happens
      var touchFinished, prevTouch = {end: 0};
      function finishTouch() {
        if (d.activeTouch) {
          touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
          prevTouch = d.activeTouch;
          prevTouch.end = +new Date;
        }
      };
      function isMouseLikeTouchEvent(e) {
        if (e.touches.length != 1) return false;
        var touch = e.touches[0];
        return touch.radiusX &lt;= 1 &amp;&amp; touch.radiusY &lt;= 1;
      }
      function farAway(touch, other) {
        if (other.left == null) return true;
        var dx = other.left - touch.left, dy = other.top - touch.top;
        return dx * dx + dy * dy &gt; 20 * 20;
      }
      on(d.scroller, "touchstart", function(e) {
        if (!signalDOMEvent(cm, e) &amp;&amp; !isMouseLikeTouchEvent(e)) {
          clearTimeout(touchFinished);
          var now = +new Date;
          d.activeTouch = {start: now, moved: false,
                           prev: now - prevTouch.end &lt;= 300 ? prevTouch : null};
          if (e.touches.length == 1) {
            d.activeTouch.left = e.touches[0].pageX;
            d.activeTouch.top = e.touches[0].pageY;
          }
        }
      });
      on(d.scroller, "touchmove", function() {
        if (d.activeTouch) d.activeTouch.moved = true;
      });
      on(d.scroller, "touchend", function(e) {
        var touch = d.activeTouch;
        if (touch &amp;&amp; !eventInWidget(d, e) &amp;&amp; touch.left != null &amp;&amp;
            !touch.moved &amp;&amp; new Date - touch.start &lt; 300) {
          var pos = cm.coordsChar(d.activeTouch, "page"), range;
          if (!touch.prev || farAway(touch, touch.prev)) // Single tap
            range = new Range(pos, pos);
          else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
            range = cm.findWordAt(pos);
          else // Triple tap
            range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
          cm.setSelection(range.anchor, range.head);
          cm.focus();
          e_preventDefault(e);
        }
        finishTouch();
      });
      on(d.scroller, "touchcancel", finishTouch);
  
      // Sync scrolling between fake scrollbars and real scrollable
      // area, ensure viewport is updated when scrolling.
      on(d.scroller, "scroll", function() {
        if (d.scroller.clientHeight) {
          setScrollTop(cm, d.scroller.scrollTop);
          setScrollLeft(cm, d.scroller.scrollLeft, true);
          signal(cm, "scroll", cm);
        }
      });
  
      // Listen to wheel events in order to try and update the viewport on time.
      on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
      on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  
      // Prevent wrapper from ever scrolling
      on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  
      d.dragFunctions = {
        enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
        over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
        start: function(e){onDragStart(cm, e);},
        drop: operation(cm, onDrop),
        leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
      };
  
      var inp = d.input.getField();
      on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
      on(inp, "keydown", operation(cm, onKeyDown));
      on(inp, "keypress", operation(cm, onKeyPress));
      on(inp, "focus", bind(onFocus, cm));
      on(inp, "blur", bind(onBlur, cm));
    }
  
    function dragDropChanged(cm, value, old) {
      var wasOn = old &amp;&amp; old != CodeMirror.Init;
      if (!value != !wasOn) {
        var funcs = cm.display.dragFunctions;
        var toggle = value ? on : off;
        toggle(cm.display.scroller, "dragstart", funcs.start);
        toggle(cm.display.scroller, "dragenter", funcs.enter);
        toggle(cm.display.scroller, "dragover", funcs.over);
        toggle(cm.display.scroller, "dragleave", funcs.leave);
        toggle(cm.display.scroller, "drop", funcs.drop);
      }
    }
  
    // Called when the window resizes
    function onResize(cm) {
      var d = cm.display;
      if (d.lastWrapHeight == d.wrapper.clientHeight &amp;&amp; d.lastWrapWidth == d.wrapper.clientWidth)
        return;
      // Might be a text scaling operation, clear size caches.
      d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
      d.scrollbarsClipped = false;
      cm.setSize();
    }
  
    // MOUSE EVENTS
  
    // Return true when the given mouse event happened in a widget
    function eventInWidget(display, e) {
      for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
        if (!n || (n.nodeType == 1 &amp;&amp; n.getAttribute("cm-ignore-events") == "true") ||
            (n.parentNode == display.sizer &amp;&amp; n != display.mover))
          return true;
      }
    }
  
    // Given a mouse event, find the corresponding position. If liberal
    // is false, it checks whether a gutter or scrollbar was clicked,
    // and returns null if it was. forRect is used by rectangular
    // selections, and tries to estimate a character position even for
    // coordinates beyond the right of the text.
    function posFromMouse(cm, e, liberal, forRect) {
      var display = cm.display;
      if (!liberal &amp;&amp; e_target(e).getAttribute("cm-not-content") == "true") return null;
  
      var x, y, space = display.lineSpace.getBoundingClientRect();
      // Fails unpredictably on IE[67] when mouse is dragged around quickly.
      try { x = e.clientX - space.left; y = e.clientY - space.top; }
      catch (e) { return null; }
      var coords = coordsChar(cm, x, y), line;
      if (forRect &amp;&amp; coords.xRel == 1 &amp;&amp; (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
        var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
        coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
      }
      return coords;
    }
  
    // A mouse down can be a single click, double click, triple click,
    // start of selection drag, start of text drag, new cursor
    // (ctrl-click), rectangle drag (alt-drag), or xwin
    // middle-click-paste. Or it might be a click on something we should
    // not interfere with, such as a scrollbar or widget.
    function onMouseDown(e) {
      var cm = this, display = cm.display;
      if (signalDOMEvent(cm, e) || display.activeTouch &amp;&amp; display.input.supportsTouch()) return;
      display.shift = e.shiftKey;
  
      if (eventInWidget(display, e)) {
        if (!webkit) {
          // Briefly turn off draggability, to allow widgets to do
          // normal dragging things.
          display.scroller.draggable = false;
          setTimeout(function(){display.scroller.draggable = true;}, 100);
        }
        return;
      }
      if (clickInGutter(cm, e)) return;
      var start = posFromMouse(cm, e);
      window.focus();
  
      switch (e_button(e)) {
      case 1:
        // #3261: make sure, that we're not starting a second selection
        if (cm.state.selectingText)
          cm.state.selectingText(e);
        else if (start)
          leftButtonDown(cm, e, start);
        else if (e_target(e) == display.scroller)
          e_preventDefault(e);
        break;
      case 2:
        if (webkit) cm.state.lastMiddleDown = +new Date;
        if (start) extendSelection(cm.doc, start);
        setTimeout(function() {display.input.focus();}, 20);
        e_preventDefault(e);
        break;
      case 3:
        if (captureRightClick) onContextMenu(cm, e);
        else delayBlurEvent(cm);
        break;
      }
    }
  
    var lastClick, lastDoubleClick;
    function leftButtonDown(cm, e, start) {
      if (ie) setTimeout(bind(ensureFocus, cm), 0);
      else cm.curOp.focus = activeElt();
  
      var now = +new Date, type;
      if (lastDoubleClick &amp;&amp; lastDoubleClick.time &gt; now - 400 &amp;&amp; cmp(lastDoubleClick.pos, start) == 0) {
        type = "triple";
      } else if (lastClick &amp;&amp; lastClick.time &gt; now - 400 &amp;&amp; cmp(lastClick.pos, start) == 0) {
        type = "double";
        lastDoubleClick = {time: now, pos: start};
      } else {
        type = "single";
        lastClick = {time: now, pos: start};
      }
  
      var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
      if (cm.options.dragDrop &amp;&amp; dragAndDrop &amp;&amp; !cm.isReadOnly() &amp;&amp;
          type == "single" &amp;&amp; (contained = sel.contains(start)) &gt; -1 &amp;&amp;
          (cmp((contained = sel.ranges[contained]).from(), start) &lt; 0 || start.xRel &gt; 0) &amp;&amp;
          (cmp(contained.to(), start) &gt; 0 || start.xRel &lt; 0))
        leftButtonStartDrag(cm, e, start, modifier);
      else
        leftButtonSelect(cm, e, start, type, modifier);
    }
  
    // Start a text drag. When it ends, see if any dragging actually
    // happen, and treat as a click if it didn't.
    function leftButtonStartDrag(cm, e, start, modifier) {
      var display = cm.display, startTime = +new Date;
      var dragEnd = operation(cm, function(e2) {
        if (webkit) display.scroller.draggable = false;
        cm.state.draggingText = false;
        off(document, "mouseup", dragEnd);
        off(display.scroller, "drop", dragEnd);
        if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) &lt; 10) {
          e_preventDefault(e2);
          if (!modifier &amp;&amp; +new Date - 200 &lt; startTime)
            extendSelection(cm.doc, start);
          // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
          if (webkit || ie &amp;&amp; ie_version == 9)
            setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
          else
            display.input.focus();
        }
      });
      // Let the drag handler handle this.
      if (webkit) display.scroller.draggable = true;
      cm.state.draggingText = dragEnd;
      dragEnd.copy = mac ? e.altKey : e.ctrlKey
      // IE's approach to draggable
      if (display.scroller.dragDrop) display.scroller.dragDrop();
      on(document, "mouseup", dragEnd);
      on(display.scroller, "drop", dragEnd);
    }
  
    // Normal selection, as opposed to text dragging.
    function leftButtonSelect(cm, e, start, type, addNew) {
      var display = cm.display, doc = cm.doc;
      e_preventDefault(e);
  
      var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
      if (addNew &amp;&amp; !e.shiftKey) {
        ourIndex = doc.sel.contains(start);
        if (ourIndex &gt; -1)
          ourRange = ranges[ourIndex];
        else
          ourRange = new Range(start, start);
      } else {
        ourRange = doc.sel.primary();
        ourIndex = doc.sel.primIndex;
      }
  
      if (chromeOS ? e.shiftKey &amp;&amp; e.metaKey : e.altKey) {
        type = "rect";
        if (!addNew) ourRange = new Range(start, start);
        start = posFromMouse(cm, e, true, true);
        ourIndex = -1;
      } else if (type == "double") {
        var word = cm.findWordAt(start);
        if (cm.display.shift || doc.extend)
          ourRange = extendRange(doc, ourRange, word.anchor, word.head);
        else
          ourRange = word;
      } else if (type == "triple") {
        var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
        if (cm.display.shift || doc.extend)
          ourRange = extendRange(doc, ourRange, line.anchor, line.head);
        else
          ourRange = line;
      } else {
        ourRange = extendRange(doc, ourRange, start);
      }
  
      if (!addNew) {
        ourIndex = 0;
        setSelection(doc, new Selection([ourRange], 0), sel_mouse);
        startSel = doc.sel;
      } else if (ourIndex == -1) {
        ourIndex = ranges.length;
        setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
                     {scroll: false, origin: "*mouse"});
      } else if (ranges.length &gt; 1 &amp;&amp; ranges[ourIndex].empty() &amp;&amp; type == "single" &amp;&amp; !e.shiftKey) {
        setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
                     {scroll: false, origin: "*mouse"});
        startSel = doc.sel;
      } else {
        replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
      }
  
      var lastPos = start;
      function extendTo(pos) {
        if (cmp(lastPos, pos) == 0) return;
        lastPos = pos;
  
        if (type == "rect") {
          var ranges = [], tabSize = cm.options.tabSize;
          var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
          var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
          var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
          for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
               line &lt;= end; line++) {
            var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
            if (left == right)
              ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
            else if (text.length &gt; leftPos)
              ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
          }
          if (!ranges.length) ranges.push(new Range(start, start));
          setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
                       {origin: "*mouse", scroll: false});
          cm.scrollIntoView(pos);
        } else {
          var oldRange = ourRange;
          var anchor = oldRange.anchor, head = pos;
          if (type != "single") {
            if (type == "double")
              var range = cm.findWordAt(pos);
            else
              var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
            if (cmp(range.anchor, anchor) &gt; 0) {
              head = range.head;
              anchor = minPos(oldRange.from(), range.anchor);
            } else {
              head = range.anchor;
              anchor = maxPos(oldRange.to(), range.head);
            }
          }
          var ranges = startSel.ranges.slice(0);
          ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
          setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
        }
      }
  
      var editorSize = display.wrapper.getBoundingClientRect();
      // Used to ensure timeout re-tries don't fire when another extend
      // happened in the meantime (clearTimeout isn't reliable -- at
      // least on Chrome, the timeouts still happen even when cleared,
      // if the clear happens after their scheduled firing time).
      var counter = 0;
  
      function extend(e) {
        var curCount = ++counter;
        var cur = posFromMouse(cm, e, true, type == "rect");
        if (!cur) return;
        if (cmp(cur, lastPos) != 0) {
          cm.curOp.focus = activeElt();
          extendTo(cur);
          var visible = visibleLines(display, doc);
          if (cur.line &gt;= visible.to || cur.line &lt; visible.from)
            setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
        } else {
          var outside = e.clientY &lt; editorSize.top ? -20 : e.clientY &gt; editorSize.bottom ? 20 : 0;
          if (outside) setTimeout(operation(cm, function() {
            if (counter != curCount) return;
            display.scroller.scrollTop += outside;
            extend(e);
          }), 50);
        }
      }
  
      function done(e) {
        cm.state.selectingText = false;
        counter = Infinity;
        e_preventDefault(e);
        display.input.focus();
        off(document, "mousemove", move);
        off(document, "mouseup", up);
        doc.history.lastSelOrigin = null;
      }
  
      var move = operation(cm, function(e) {
        if (!e_button(e)) done(e);
        else extend(e);
      });
      var up = operation(cm, done);
      cm.state.selectingText = up;
      on(document, "mousemove", move);
      on(document, "mouseup", up);
    }
  
    // Determines whether an event happened in the gutter, and fires the
    // handlers for the corresponding event.
    function gutterEvent(cm, e, type, prevent) {
      try { var mX = e.clientX, mY = e.clientY; }
      catch(e) { return false; }
      if (mX &gt;= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
      if (prevent) e_preventDefault(e);
  
      var display = cm.display;
      var lineBox = display.lineDiv.getBoundingClientRect();
  
      if (mY &gt; lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
      mY -= lineBox.top - display.viewOffset;
  
      for (var i = 0; i &lt; cm.options.gutters.length; ++i) {
        var g = display.gutters.childNodes[i];
        if (g &amp;&amp; g.getBoundingClientRect().right &gt;= mX) {
          var line = lineAtHeight(cm.doc, mY);
          var gutter = cm.options.gutters[i];
          signal(cm, type, cm, line, gutter, e);
          return e_defaultPrevented(e);
        }
      }
    }
  
    function clickInGutter(cm, e) {
      return gutterEvent(cm, e, "gutterClick", true);
    }
  
    // Kludge to work around strange IE behavior where it'll sometimes
    // re-fire a series of drag-related events right after the drop (#1551)
    var lastDrop = 0;
  
    function onDrop(e) {
      var cm = this;
      clearDragCursor(cm);
      if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
        return;
      e_preventDefault(e);
      if (ie) lastDrop = +new Date;
      var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
      if (!pos || cm.isReadOnly()) return;
      // Might be a file drop, in which case we simply extract the text
      // and insert it.
      if (files &amp;&amp; files.length &amp;&amp; window.FileReader &amp;&amp; window.File) {
        var n = files.length, text = Array(n), read = 0;
        var loadFile = function(file, i) {
          if (cm.options.allowDropFileTypes &amp;&amp;
              indexOf(cm.options.allowDropFileTypes, file.type) == -1)
            return;
  
          var reader = new FileReader;
          reader.onload = operation(cm, function() {
            var content = reader.result;
            if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
            text[i] = content;
            if (++read == n) {
              pos = clipPos(cm.doc, pos);
              var change = {from: pos, to: pos,
                            text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
                            origin: "paste"};
              makeChange(cm.doc, change);
              setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
            }
          });
          reader.readAsText(file);
        };
        for (var i = 0; i &lt; n; ++i) loadFile(files[i], i);
      } else { // Normal drop
        // Don't do a replace if the drop happened inside of the selected text.
        if (cm.state.draggingText &amp;&amp; cm.doc.sel.contains(pos) &gt; -1) {
          cm.state.draggingText(e);
          // Ensure the editor is re-focused
          setTimeout(function() {cm.display.input.focus();}, 20);
          return;
        }
        try {
          var text = e.dataTransfer.getData("Text");
          if (text) {
            if (cm.state.draggingText &amp;&amp; !cm.state.draggingText.copy)
              var selected = cm.listSelections();
            setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
            if (selected) for (var i = 0; i &lt; selected.length; ++i)
              replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
            cm.replaceSelection(text, "around", "paste");
            cm.display.input.focus();
          }
        }
        catch(e){}
      }
    }
  
    function onDragStart(cm, e) {
      if (ie &amp;&amp; (!cm.state.draggingText || +new Date - lastDrop &lt; 100)) { e_stop(e); return; }
      if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  
      e.dataTransfer.setData("Text", cm.getSelection());
      e.dataTransfer.effectAllowed = "copyMove"
  
      // Use dummy image instead of default browsers image.
      // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
      if (e.dataTransfer.setDragImage &amp;&amp; !safari) {
        var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
        img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
        if (presto) {
          img.width = img.height = 1;
          cm.display.wrapper.appendChild(img);
          // Force a relayout, or Opera won't use our image for some obscure reason
          img._top = img.offsetTop;
        }
        e.dataTransfer.setDragImage(img, 0, 0);
        if (presto) img.parentNode.removeChild(img);
      }
    }
  
    function onDragOver(cm, e) {
      var pos = posFromMouse(cm, e);
      if (!pos) return;
      var frag = document.createDocumentFragment();
      drawSelectionCursor(cm, pos, frag);
      if (!cm.display.dragCursor) {
        cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
        cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
      }
      removeChildrenAndAdd(cm.display.dragCursor, frag);
    }
  
    function clearDragCursor(cm) {
      if (cm.display.dragCursor) {
        cm.display.lineSpace.removeChild(cm.display.dragCursor);
        cm.display.dragCursor = null;
      }
    }
  
    // SCROLL EVENTS
  
    // Sync the scrollable area and scrollbars, ensure the viewport
    // covers the visible area.
    function setScrollTop(cm, val) {
      if (Math.abs(cm.doc.scrollTop - val) &lt; 2) return;
      cm.doc.scrollTop = val;
      if (!gecko) updateDisplaySimple(cm, {top: val});
      if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
      cm.display.scrollbars.setScrollTop(val);
      if (gecko) updateDisplaySimple(cm);
      startWorker(cm, 100);
    }
    // Sync scroller and scrollbar, ensure the gutter elements are
    // aligned.
    function setScrollLeft(cm, val, isScroller) {
      if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) &lt; 2) return;
      val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
      cm.doc.scrollLeft = val;
      alignHorizontally(cm);
      if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
      cm.display.scrollbars.setScrollLeft(val);
    }
  
    // Since the delta values reported on mouse wheel events are
    // unstandardized between browsers and even browser versions, and
    // generally horribly unpredictable, this code starts by measuring
    // the scroll effect that the first few mouse wheel events have,
    // and, from that, detects the way it can convert deltas to pixel
    // offsets afterwards.
    //
    // The reason we want to know the amount a wheel event will scroll
    // is that it gives us a chance to update the display before the
    // actual scrolling happens, reducing flickering.
  
    var wheelSamples = 0, wheelPixelsPerUnit = null;
    // Fill in a browser-detected starting value on browsers where we
    // know one. These don't have to be accurate -- the result of them
    // being wrong would just be a slight flicker on the first wheel
    // scroll (if it is large enough).
    if (ie) wheelPixelsPerUnit = -.53;
    else if (gecko) wheelPixelsPerUnit = 15;
    else if (chrome) wheelPixelsPerUnit = -.7;
    else if (safari) wheelPixelsPerUnit = -1/3;
  
    var wheelEventDelta = function(e) {
      var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
      if (dx == null &amp;&amp; e.detail &amp;&amp; e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
      if (dy == null &amp;&amp; e.detail &amp;&amp; e.axis == e.VERTICAL_AXIS) dy = e.detail;
      else if (dy == null) dy = e.wheelDelta;
      return {x: dx, y: dy};
    };
    CodeMirror.wheelEventPixels = function(e) {
      var delta = wheelEventDelta(e);
      delta.x *= wheelPixelsPerUnit;
      delta.y *= wheelPixelsPerUnit;
      return delta;
    };
  
    function onScrollWheel(cm, e) {
      var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  
      var display = cm.display, scroll = display.scroller;
      // Quit if there's nothing to scroll here
      var canScrollX = scroll.scrollWidth &gt; scroll.clientWidth;
      var canScrollY = scroll.scrollHeight &gt; scroll.clientHeight;
      if (!(dx &amp;&amp; canScrollX || dy &amp;&amp; canScrollY)) return;
  
      // Webkit browsers on OS X abort momentum scrolls when the target
      // of the scroll event is removed from the scrollable element.
      // This hack (see related code in patchDisplay) makes sure the
      // element is kept around.
      if (dy &amp;&amp; mac &amp;&amp; webkit) {
        outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
          for (var i = 0; i &lt; view.length; i++) {
            if (view[i].node == cur) {
              cm.display.currentWheelTarget = cur;
              break outer;
            }
          }
        }
      }
  
      // On some browsers, horizontal scrolling will cause redraws to
      // happen before the gutter has been realigned, causing it to
      // wriggle around in a most unseemly way. When we have an
      // estimated pixels/delta value, we just handle horizontal
      // scrolling entirely here. It'll be slightly off from native, but
      // better than glitching out.
      if (dx &amp;&amp; !gecko &amp;&amp; !presto &amp;&amp; wheelPixelsPerUnit != null) {
        if (dy &amp;&amp; canScrollY)
          setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
        setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
        // Only prevent default scrolling if vertical scrolling is
        // actually possible. Otherwise, it causes vertical scroll
        // jitter on OSX trackpads when deltaX is small and deltaY
        // is large (issue #3579)
        if (!dy || (dy &amp;&amp; canScrollY))
          e_preventDefault(e);
        display.wheelStartX = null; // Abort measurement, if in progress
        return;
      }
  
      // 'Project' the visible viewport to cover the area that is being
      // scrolled into view (if we know enough to estimate it).
      if (dy &amp;&amp; wheelPixelsPerUnit != null) {
        var pixels = dy * wheelPixelsPerUnit;
        var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
        if (pixels &lt; 0) top = Math.max(0, top + pixels - 50);
        else bot = Math.min(cm.doc.height, bot + pixels + 50);
        updateDisplaySimple(cm, {top: top, bottom: bot});
      }
  
      if (wheelSamples &lt; 20) {
        if (display.wheelStartX == null) {
          display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
          display.wheelDX = dx; display.wheelDY = dy;
          setTimeout(function() {
            if (display.wheelStartX == null) return;
            var movedX = scroll.scrollLeft - display.wheelStartX;
            var movedY = scroll.scrollTop - display.wheelStartY;
            var sample = (movedY &amp;&amp; display.wheelDY &amp;&amp; movedY / display.wheelDY) ||
              (movedX &amp;&amp; display.wheelDX &amp;&amp; movedX / display.wheelDX);
            display.wheelStartX = display.wheelStartY = null;
            if (!sample) return;
            wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
            ++wheelSamples;
          }, 200);
        } else {
          display.wheelDX += dx; display.wheelDY += dy;
        }
      }
    }
  
    // KEY EVENTS
  
    // Run a handler that was bound to a key.
    function doHandleBinding(cm, bound, dropShift) {
      if (typeof bound == "string") {
        bound = commands[bound];
        if (!bound) return false;
      }
      // Ensure previous input has been read, so that the handler sees a
      // consistent view of the document
      cm.display.input.ensurePolled();
      var prevShift = cm.display.shift, done = false;
      try {
        if (cm.isReadOnly()) cm.state.suppressEdits = true;
        if (dropShift) cm.display.shift = false;
        done = bound(cm) != Pass;
      } finally {
        cm.display.shift = prevShift;
        cm.state.suppressEdits = false;
      }
      return done;
    }
  
    function lookupKeyForEditor(cm, name, handle) {
      for (var i = 0; i &lt; cm.state.keyMaps.length; i++) {
        var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
        if (result) return result;
      }
      return (cm.options.extraKeys &amp;&amp; lookupKey(name, cm.options.extraKeys, handle, cm))
        || lookupKey(name, cm.options.keyMap, handle, cm);
    }
  
    var stopSeq = new Delayed;
    function dispatchKey(cm, name, e, handle) {
      var seq = cm.state.keySeq;
      if (seq) {
        if (isModifierKey(name)) return "handled";
        stopSeq.set(50, function() {
          if (cm.state.keySeq == seq) {
            cm.state.keySeq = null;
            cm.display.input.reset();
          }
        });
        name = seq + " " + name;
      }
      var result = lookupKeyForEditor(cm, name, handle);
  
      if (result == "multi")
        cm.state.keySeq = name;
      if (result == "handled")
        signalLater(cm, "keyHandled", cm, name, e);
  
      if (result == "handled" || result == "multi") {
        e_preventDefault(e);
        restartBlink(cm);
      }
  
      if (seq &amp;&amp; !result &amp;&amp; /\'$/.test(name)) {
        e_preventDefault(e);
        return true;
      }
      return !!result;
    }
  
    // Handle a key from the keydown event.
    function handleKeyBinding(cm, e) {
      var name = keyName(e, true);
      if (!name) return false;
  
      if (e.shiftKey &amp;&amp; !cm.state.keySeq) {
        // First try to resolve full name (including 'Shift-'). Failing
        // that, see if there is a cursor-motion command (starting with
        // 'go') bound to the keyname without 'Shift-'.
        return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
            || dispatchKey(cm, name, e, function(b) {
                 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
                   return doHandleBinding(cm, b);
               });
      } else {
        return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
      }
    }
  
    // Handle a key from the keypress event
    function handleCharBinding(cm, e, ch) {
      return dispatchKey(cm, "'" + ch + "'", e,
                         function(b) { return doHandleBinding(cm, b, true); });
    }
  
    var lastStoppedKey = null;
    function onKeyDown(e) {
      var cm = this;
      cm.curOp.focus = activeElt();
      if (signalDOMEvent(cm, e)) return;
      // IE does strange things with escape.
      if (ie &amp;&amp; ie_version &lt; 11 &amp;&amp; e.keyCode == 27) e.returnValue = false;
      var code = e.keyCode;
      cm.display.shift = code == 16 || e.shiftKey;
      var handled = handleKeyBinding(cm, e);
      if (presto) {
        lastStoppedKey = handled ? code : null;
        // Opera has no cut event... we try to at least catch the key combo
        if (!handled &amp;&amp; code == 88 &amp;&amp; !hasCopyEvent &amp;&amp; (mac ? e.metaKey : e.ctrlKey))
          cm.replaceSelection("", null, "cut");
      }
  
      // Turn mouse into crosshair when Alt is held on Mac.
      if (code == 18 &amp;&amp; !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
        showCrossHair(cm);
    }
  
    function showCrossHair(cm) {
      var lineDiv = cm.display.lineDiv;
      addClass(lineDiv, "CodeMirror-crosshair");
  
      function up(e) {
        if (e.keyCode == 18 || !e.altKey) {
          rmClass(lineDiv, "CodeMirror-crosshair");
          off(document, "keyup", up);
          off(document, "mouseover", up);
        }
      }
      on(document, "keyup", up);
      on(document, "mouseover", up);
    }
  
    function onKeyUp(e) {
      if (e.keyCode == 16) this.doc.sel.shift = false;
      signalDOMEvent(this, e);
    }
  
    function onKeyPress(e) {
      var cm = this;
      if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey &amp;&amp; !e.altKey || mac &amp;&amp; e.metaKey) return;
      var keyCode = e.keyCode, charCode = e.charCode;
      if (presto &amp;&amp; keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
      if ((presto &amp;&amp; (!e.which || e.which &lt; 10)) &amp;&amp; handleKeyBinding(cm, e)) return;
      var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
      if (handleCharBinding(cm, e, ch)) return;
      cm.display.input.onKeyPress(e);
    }
  
    // FOCUS/BLUR EVENTS
  
    function delayBlurEvent(cm) {
      cm.state.delayingBlurEvent = true;
      setTimeout(function() {
        if (cm.state.delayingBlurEvent) {
          cm.state.delayingBlurEvent = false;
          onBlur(cm);
        }
      }, 100);
    }
  
    function onFocus(cm) {
      if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  
      if (cm.options.readOnly == "nocursor") return;
      if (!cm.state.focused) {
        signal(cm, "focus", cm);
        cm.state.focused = true;
        addClass(cm.display.wrapper, "CodeMirror-focused");
        // This test prevents this from firing when a context
        // menu is closed (since the input reset would kill the
        // select-all detection hack)
        if (!cm.curOp &amp;&amp; cm.display.selForContextMenu != cm.doc.sel) {
          cm.display.input.reset();
          if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
        }
        cm.display.input.receivedFocus();
      }
      restartBlink(cm);
    }
    function onBlur(cm) {
      if (cm.state.delayingBlurEvent) return;
  
      if (cm.state.focused) {
        signal(cm, "blur", cm);
        cm.state.focused = false;
        rmClass(cm.display.wrapper, "CodeMirror-focused");
      }
      clearInterval(cm.display.blinker);
      setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
    }
  
    // CONTEXT MENU HANDLING
  
    // To make the context menu work, we need to briefly unhide the
    // textarea (making it as unobtrusive as possible) to let the
    // right-click take effect on it.
    function onContextMenu(cm, e) {
      if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
      if (signalDOMEvent(cm, e, "contextmenu")) return;
      cm.display.input.onContextMenu(e);
    }
  
    function contextMenuInGutter(cm, e) {
      if (!hasHandler(cm, "gutterContextMenu")) return false;
      return gutterEvent(cm, e, "gutterContextMenu", false);
    }
  
    // UPDATING
  
    // Compute the position of the end of a change (its 'to' property
    // refers to the pre-change end).
    var changeEnd = CodeMirror.changeEnd = function(change) {
      if (!change.text) return change.to;
      return Pos(change.from.line + change.text.length - 1,
                 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
    };
  
    // Adjust a position to refer to the post-change position of the
    // same text, or the end of the change if the change covers it.
    function adjustForChange(pos, change) {
      if (cmp(pos, change.from) &lt; 0) return pos;
      if (cmp(pos, change.to) &lt;= 0) return changeEnd(change);
  
      var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
      if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
      return Pos(line, ch);
    }
  
    function computeSelAfterChange(doc, change) {
      var out = [];
      for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
        var range = doc.sel.ranges[i];
        out.push(new Range(adjustForChange(range.anchor, change),
                           adjustForChange(range.head, change)));
      }
      return normalizeSelection(out, doc.sel.primIndex);
    }
  
    function offsetPos(pos, old, nw) {
      if (pos.line == old.line)
        return Pos(nw.line, pos.ch - old.ch + nw.ch);
      else
        return Pos(nw.line + (pos.line - old.line), pos.ch);
    }
  
    // Used by replaceSelections to allow moving the selection to the
    // start or around the replaced test. Hint may be "start" or "around".
    function computeReplacedSel(doc, changes, hint) {
      var out = [];
      var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
      for (var i = 0; i &lt; changes.length; i++) {
        var change = changes[i];
        var from = offsetPos(change.from, oldPrev, newPrev);
        var to = offsetPos(changeEnd(change), oldPrev, newPrev);
        oldPrev = change.to;
        newPrev = to;
        if (hint == "around") {
          var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) &lt; 0;
          out[i] = new Range(inv ? to : from, inv ? from : to);
        } else {
          out[i] = new Range(from, from);
        }
      }
      return new Selection(out, doc.sel.primIndex);
    }
  
    // Allow "beforeChange" event handlers to influence a change
    function filterChange(doc, change, update) {
      var obj = {
        canceled: false,
        from: change.from,
        to: change.to,
        text: change.text,
        origin: change.origin,
        cancel: function() { this.canceled = true; }
      };
      if (update) obj.update = function(from, to, text, origin) {
        if (from) this.from = clipPos(doc, from);
        if (to) this.to = clipPos(doc, to);
        if (text) this.text = text;
        if (origin !== undefined) this.origin = origin;
      };
      signal(doc, "beforeChange", doc, obj);
      if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  
      if (obj.canceled) return null;
      return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
    }
  
    // Apply a change to a document, and add it to the document's
    // history, and propagating it to all linked documents.
    function makeChange(doc, change, ignoreReadOnly) {
      if (doc.cm) {
        if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
        if (doc.cm.state.suppressEdits) return;
      }
  
      if (hasHandler(doc, "beforeChange") || doc.cm &amp;&amp; hasHandler(doc.cm, "beforeChange")) {
        change = filterChange(doc, change, true);
        if (!change) return;
      }
  
      // Possibly split or suppress the update based on the presence
      // of read-only spans in its range.
      var split = sawReadOnlySpans &amp;&amp; !ignoreReadOnly &amp;&amp; removeReadOnlyRanges(doc, change.from, change.to);
      if (split) {
        for (var i = split.length - 1; i &gt;= 0; --i)
          makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
      } else {
        makeChangeInner(doc, change);
      }
    }
  
    function makeChangeInner(doc, change) {
      if (change.text.length == 1 &amp;&amp; change.text[0] == "" &amp;&amp; cmp(change.from, change.to) == 0) return;
      var selAfter = computeSelAfterChange(doc, change);
      addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  
      makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
      var rebased = [];
  
      linkedDocs(doc, function(doc, sharedHist) {
        if (!sharedHist &amp;&amp; indexOf(rebased, doc.history) == -1) {
          rebaseHist(doc.history, change);
          rebased.push(doc.history);
        }
        makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
      });
    }
  
    // Revert a change stored in a document's history.
    function makeChangeFromHistory(doc, type, allowSelectionOnly) {
      if (doc.cm &amp;&amp; doc.cm.state.suppressEdits) return;
  
      var hist = doc.history, event, selAfter = doc.sel;
      var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  
      // Verify that there is a useable event (so that ctrl-z won't
      // needlessly clear selection events)
      for (var i = 0; i &lt; source.length; i++) {
        event = source[i];
        if (allowSelectionOnly ? event.ranges &amp;&amp; !event.equals(doc.sel) : !event.ranges)
          break;
      }
      if (i == source.length) return;
      hist.lastOrigin = hist.lastSelOrigin = null;
  
      for (;;) {
        event = source.pop();
        if (event.ranges) {
          pushSelectionToHistory(event, dest);
          if (allowSelectionOnly &amp;&amp; !event.equals(doc.sel)) {
            setSelection(doc, event, {clearRedo: false});
            return;
          }
          selAfter = event;
        }
        else break;
      }
  
      // Build up a reverse change object to add to the opposite history
      // stack (redo when undoing, and vice versa).
      var antiChanges = [];
      pushSelectionToHistory(selAfter, dest);
      dest.push({changes: antiChanges, generation: hist.generation});
      hist.generation = event.generation || ++hist.maxGeneration;
  
      var filter = hasHandler(doc, "beforeChange") || doc.cm &amp;&amp; hasHandler(doc.cm, "beforeChange");
  
      for (var i = event.changes.length - 1; i &gt;= 0; --i) {
        var change = event.changes[i];
        change.origin = type;
        if (filter &amp;&amp; !filterChange(doc, change, false)) {
          source.length = 0;
          return;
        }
  
        antiChanges.push(historyChangeFromChange(doc, change));
  
        var after = i ? computeSelAfterChange(doc, change) : lst(source);
        makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
        if (!i &amp;&amp; doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
        var rebased = [];
  
        // Propagate to the linked documents
        linkedDocs(doc, function(doc, sharedHist) {
          if (!sharedHist &amp;&amp; indexOf(rebased, doc.history) == -1) {
            rebaseHist(doc.history, change);
            rebased.push(doc.history);
          }
          makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
        });
      }
    }
  
    // Sub-views need their line numbers shifted when text is added
    // above or below them in the parent document.
    function shiftDoc(doc, distance) {
      if (distance == 0) return;
      doc.first += distance;
      doc.sel = new Selection(map(doc.sel.ranges, function(range) {
        return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
                         Pos(range.head.line + distance, range.head.ch));
      }), doc.sel.primIndex);
      if (doc.cm) {
        regChange(doc.cm, doc.first, doc.first - distance, distance);
        for (var d = doc.cm.display, l = d.viewFrom; l &lt; d.viewTo; l++)
          regLineChange(doc.cm, l, "gutter");
      }
    }
  
    // More lower-level change function, handling only a single document
    // (not linked ones).
    function makeChangeSingleDoc(doc, change, selAfter, spans) {
      if (doc.cm &amp;&amp; !doc.cm.curOp)
        return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  
      if (change.to.line &lt; doc.first) {
        shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
        return;
      }
      if (change.from.line &gt; doc.lastLine()) return;
  
      // Clip the change to the size of this doc
      if (change.from.line &lt; doc.first) {
        var shift = change.text.length - 1 - (doc.first - change.from.line);
        shiftDoc(doc, shift);
        change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
                  text: [lst(change.text)], origin: change.origin};
      }
      var last = doc.lastLine();
      if (change.to.line &gt; last) {
        change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
                  text: [change.text[0]], origin: change.origin};
      }
  
      change.removed = getBetween(doc, change.from, change.to);
  
      if (!selAfter) selAfter = computeSelAfterChange(doc, change);
      if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
      else updateDoc(doc, change, spans);
      setSelectionNoUndo(doc, selAfter, sel_dontScroll);
    }
  
    // Handle the interaction of a change to a document with the editor
    // that this document is part of.
    function makeChangeSingleDocInEditor(cm, change, spans) {
      var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  
      var recomputeMaxLength = false, checkWidthStart = from.line;
      if (!cm.options.lineWrapping) {
        checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
        doc.iter(checkWidthStart, to.line + 1, function(line) {
          if (line == display.maxLine) {
            recomputeMaxLength = true;
            return true;
          }
        });
      }
  
      if (doc.sel.contains(change.from, change.to) &gt; -1)
        signalCursorActivity(cm);
  
      updateDoc(doc, change, spans, estimateHeight(cm));
  
      if (!cm.options.lineWrapping) {
        doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
          var len = lineLength(line);
          if (len &gt; display.maxLineLength) {
            display.maxLine = line;
            display.maxLineLength = len;
            display.maxLineChanged = true;
            recomputeMaxLength = false;
          }
        });
        if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
      }
  
      // Adjust frontier, schedule worker
      doc.frontier = Math.min(doc.frontier, from.line);
      startWorker(cm, 400);
  
      var lendiff = change.text.length - (to.line - from.line) - 1;
      // Remember that these lines changed, for updating the display
      if (change.full)
        regChange(cm);
      else if (from.line == to.line &amp;&amp; change.text.length == 1 &amp;&amp; !isWholeLineUpdate(cm.doc, change))
        regLineChange(cm, from.line, "text");
      else
        regChange(cm, from.line, to.line + 1, lendiff);
  
      var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
      if (changeHandler || changesHandler) {
        var obj = {
          from: from, to: to,
          text: change.text,
          removed: change.removed,
          origin: change.origin
        };
        if (changeHandler) signalLater(cm, "change", cm, obj);
        if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
      }
      cm.display.selForContextMenu = null;
    }
  
    function replaceRange(doc, code, from, to, origin) {
      if (!to) to = from;
      if (cmp(to, from) &lt; 0) { var tmp = to; to = from; from = tmp; }
      if (typeof code == "string") code = doc.splitLines(code);
      makeChange(doc, {from: from, to: to, text: code, origin: origin});
    }
  
    // SCROLLING THINGS INTO VIEW
  
    // If an editor sits on the top or bottom of the window, partially
    // scrolled out of view, this ensures that the cursor is visible.
    function maybeScrollWindow(cm, coords) {
      if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  
      var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
      if (coords.top + box.top &lt; 0) doScroll = true;
      else if (coords.bottom + box.top &gt; (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
      if (doScroll != null &amp;&amp; !phantom) {
        var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
                             (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
                             (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
                             coords.left + "px; width: 2px;");
        cm.display.lineSpace.appendChild(scrollNode);
        scrollNode.scrollIntoView(doScroll);
        cm.display.lineSpace.removeChild(scrollNode);
      }
    }
  
    // Scroll a given position into view (immediately), verifying that
    // it actually became visible (as line heights are accurately
    // measured, the position of something may 'drift' during drawing).
    function scrollPosIntoView(cm, pos, end, margin) {
      if (margin == null) margin = 0;
      for (var limit = 0; limit &lt; 5; limit++) {
        var changed = false, coords = cursorCoords(cm, pos);
        var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
        var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
                                           Math.min(coords.top, endCoords.top) - margin,
                                           Math.max(coords.left, endCoords.left),
                                           Math.max(coords.bottom, endCoords.bottom) + margin);
        var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
        if (scrollPos.scrollTop != null) {
          setScrollTop(cm, scrollPos.scrollTop);
          if (Math.abs(cm.doc.scrollTop - startTop) &gt; 1) changed = true;
        }
        if (scrollPos.scrollLeft != null) {
          setScrollLeft(cm, scrollPos.scrollLeft);
          if (Math.abs(cm.doc.scrollLeft - startLeft) &gt; 1) changed = true;
        }
        if (!changed) break;
      }
      return coords;
    }
  
    // Scroll a given set of coordinates into view (immediately).
    function scrollIntoView(cm, x1, y1, x2, y2) {
      var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
      if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
      if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
    }
  
    // Calculate a new scroll position needed to scroll the given
    // rectangle into view. Returns an object with scrollTop and
    // scrollLeft properties. When these are undefined, the
    // vertical/horizontal position does not need to be adjusted.
    function calculateScrollPos(cm, x1, y1, x2, y2) {
      var display = cm.display, snapMargin = textHeight(cm.display);
      if (y1 &lt; 0) y1 = 0;
      var screentop = cm.curOp &amp;&amp; cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
      var screen = displayHeight(cm), result = {};
      if (y2 - y1 &gt; screen) y2 = y1 + screen;
      var docBottom = cm.doc.height + paddingVert(display);
      var atTop = y1 &lt; snapMargin, atBottom = y2 &gt; docBottom - snapMargin;
      if (y1 &lt; screentop) {
        result.scrollTop = atTop ? 0 : y1;
      } else if (y2 &gt; screentop + screen) {
        var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
        if (newTop != screentop) result.scrollTop = newTop;
      }
  
      var screenleft = cm.curOp &amp;&amp; cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
      var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
      var tooWide = x2 - x1 &gt; screenw;
      if (tooWide) x2 = x1 + screenw;
      if (x1 &lt; 10)
        result.scrollLeft = 0;
      else if (x1 &lt; screenleft)
        result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
      else if (x2 &gt; screenw + screenleft - 3)
        result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
      return result;
    }
  
    // Store a relative adjustment to the scroll position in the current
    // operation (to be applied when the operation finishes).
    function addToScrollPos(cm, left, top) {
      if (left != null || top != null) resolveScrollToPos(cm);
      if (left != null)
        cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
      if (top != null)
        cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
    }
  
    // Make sure that at the end of the operation the current cursor is
    // shown.
    function ensureCursorVisible(cm) {
      resolveScrollToPos(cm);
      var cur = cm.getCursor(), from = cur, to = cur;
      if (!cm.options.lineWrapping) {
        from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
        to = Pos(cur.line, cur.ch + 1);
      }
      cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
    }
  
    // When an operation has its scrollToPos property set, and another
    // scroll action is applied before the end of the operation, this
    // 'simulates' scrolling that position into view in a cheap way, so
    // that the effect of intermediate scroll commands is not ignored.
    function resolveScrollToPos(cm) {
      var range = cm.curOp.scrollToPos;
      if (range) {
        cm.curOp.scrollToPos = null;
        var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
        var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
                                      Math.min(from.top, to.top) - range.margin,
                                      Math.max(from.right, to.right),
                                      Math.max(from.bottom, to.bottom) + range.margin);
        cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
      }
    }
  
    // API UTILITIES
  
    // Indent the given line. The how parameter can be "smart",
    // "add"/null, "subtract", or "prev". When aggressive is false
    // (typically set to true for forced single-line indents), empty
    // lines are not indented, and places where the mode returns Pass
    // are left alone.
    function indentLine(cm, n, how, aggressive) {
      var doc = cm.doc, state;
      if (how == null) how = "add";
      if (how == "smart") {
        // Fall back to "prev" when the mode doesn't have an indentation
        // method.
        if (!doc.mode.indent) how = "prev";
        else state = getStateBefore(cm, n);
      }
  
      var tabSize = cm.options.tabSize;
      var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
      if (line.stateAfter) line.stateAfter = null;
      var curSpaceString = line.text.match(/^\s*/)[0], indentation;
      if (!aggressive &amp;&amp; !/\S/.test(line.text)) {
        indentation = 0;
        how = "not";
      } else if (how == "smart") {
        indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
        if (indentation == Pass || indentation &gt; 150) {
          if (!aggressive) return;
          how = "prev";
        }
      }
      if (how == "prev") {
        if (n &gt; doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
        else indentation = 0;
      } else if (how == "add") {
        indentation = curSpace + cm.options.indentUnit;
      } else if (how == "subtract") {
        indentation = curSpace - cm.options.indentUnit;
      } else if (typeof how == "number") {
        indentation = curSpace + how;
      }
      indentation = Math.max(0, indentation);
  
      var indentString = "", pos = 0;
      if (cm.options.indentWithTabs)
        for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
      if (pos &lt; indentation) indentString += spaceStr(indentation - pos);
  
      if (indentString != curSpaceString) {
        replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
        line.stateAfter = null;
        return true;
      } else {
        // Ensure that, if the cursor was in the whitespace at the start
        // of the line, it is moved to the end of that space.
        for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
          var range = doc.sel.ranges[i];
          if (range.head.line == n &amp;&amp; range.head.ch &lt; curSpaceString.length) {
            var pos = Pos(n, curSpaceString.length);
            replaceOneSelection(doc, i, new Range(pos, pos));
            break;
          }
        }
      }
    }
  
    // Utility for applying a change to a line by handle or number,
    // returning the number and optionally registering the line as
    // changed.
    function changeLine(doc, handle, changeType, op) {
      var no = handle, line = handle;
      if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
      else no = lineNo(handle);
      if (no == null) return null;
      if (op(line, no) &amp;&amp; doc.cm) regLineChange(doc.cm, no, changeType);
      return line;
    }
  
    // Helper for deleting text near the selection(s), used to implement
    // backspace, delete, and similar functionality.
    function deleteNearSelection(cm, compute) {
      var ranges = cm.doc.sel.ranges, kill = [];
      // Build up a set of ranges to kill first, merging overlapping
      // ranges.
      for (var i = 0; i &lt; ranges.length; i++) {
        var toKill = compute(ranges[i]);
        while (kill.length &amp;&amp; cmp(toKill.from, lst(kill).to) &lt;= 0) {
          var replaced = kill.pop();
          if (cmp(replaced.from, toKill.from) &lt; 0) {
            toKill.from = replaced.from;
            break;
          }
        }
        kill.push(toKill);
      }
      // Next, remove those actual ranges.
      runInOp(cm, function() {
        for (var i = kill.length - 1; i &gt;= 0; i--)
          replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
        ensureCursorVisible(cm);
      });
    }
  
    // Used for horizontal relative motion. Dir is -1 or 1 (left or
    // right), unit can be "char", "column" (like char, but doesn't
    // cross line boundaries), "word" (across next word), or "group" (to
    // the start of next group of word or non-word-non-whitespace
    // chars). The visually param controls whether, in right-to-left
    // text, direction 1 means to move towards the next index in the
    // string, or towards the character to the right of the current
    // position. The resulting position will have a hitSide=true
    // property if it reached the end of the document.
    function findPosH(doc, pos, dir, unit, visually) {
      var line = pos.line, ch = pos.ch, origDir = dir;
      var lineObj = getLine(doc, line);
      function findNextLine() {
        var l = line + dir;
        if (l &lt; doc.first || l &gt;= doc.first + doc.size) return false
        line = l;
        return lineObj = getLine(doc, l);
      }
      function moveOnce(boundToLine) {
        var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
        if (next == null) {
          if (!boundToLine &amp;&amp; findNextLine()) {
            if (visually) ch = (dir &lt; 0 ? lineRight : lineLeft)(lineObj);
            else ch = dir &lt; 0 ? lineObj.text.length : 0;
          } else return false
        } else ch = next;
        return true;
      }
  
      if (unit == "char") {
        moveOnce()
      } else if (unit == "column") {
        moveOnce(true)
      } else if (unit == "word" || unit == "group") {
        var sawType = null, group = unit == "group";
        var helper = doc.cm &amp;&amp; doc.cm.getHelper(pos, "wordChars");
        for (var first = true;; first = false) {
          if (dir &lt; 0 &amp;&amp; !moveOnce(!first)) break;
          var cur = lineObj.text.charAt(ch) || "\n";
          var type = isWordChar(cur, helper) ? "w"
            : group &amp;&amp; cur == "\n" ? "n"
            : !group || /\s/.test(cur) ? null
            : "p";
          if (group &amp;&amp; !first &amp;&amp; !type) type = "s";
          if (sawType &amp;&amp; sawType != type) {
            if (dir &lt; 0) {dir = 1; moveOnce();}
            break;
          }
  
          if (type) sawType = type;
          if (dir &gt; 0 &amp;&amp; !moveOnce(!first)) break;
        }
      }
      var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
      if (!cmp(pos, result)) result.hitSide = true;
      return result;
    }
  
    // For relative vertical movement. Dir may be -1 or 1. Unit can be
    // "page" or "line". The resulting position will have a hitSide=true
    // property if it reached the end of the document.
    function findPosV(cm, pos, dir, unit) {
      var doc = cm.doc, x = pos.left, y;
      if (unit == "page") {
        var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
        y = pos.top + dir * (pageSize - (dir &lt; 0 ? 1.5 : .5) * textHeight(cm.display));
      } else if (unit == "line") {
        y = dir &gt; 0 ? pos.bottom + 3 : pos.top - 3;
      }
      for (;;) {
        var target = coordsChar(cm, x, y);
        if (!target.outside) break;
        if (dir &lt; 0 ? y &lt;= 0 : y &gt;= doc.height) { target.hitSide = true; break; }
        y += dir * 5;
      }
      return target;
    }
  
    // EDITOR METHODS
  
    // The publicly visible API. Note that methodOp(f) means
    // 'wrap f in an operation, performed on its `this` parameter'.
  
    // This is not the complete set of editor methods. Most of the
    // methods defined on the Doc type are also injected into
    // CodeMirror.prototype, for backwards compatibility and
    // convenience.
  
    CodeMirror.prototype = {
      constructor: CodeMirror,
      focus: function(){window.focus(); this.display.input.focus();},
  
      setOption: function(option, value) {
        var options = this.options, old = options[option];
        if (options[option] == value &amp;&amp; option != "mode") return;
        options[option] = value;
        if (optionHandlers.hasOwnProperty(option))
          operation(this, optionHandlers[option])(this, value, old);
      },
  
      getOption: function(option) {return this.options[option];},
      getDoc: function() {return this.doc;},
  
      addKeyMap: function(map, bottom) {
        this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
      },
      removeKeyMap: function(map) {
        var maps = this.state.keyMaps;
        for (var i = 0; i &lt; maps.length; ++i)
          if (maps[i] == map || maps[i].name == map) {
            maps.splice(i, 1);
            return true;
          }
      },
  
      addOverlay: methodOp(function(spec, options) {
        var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
        if (mode.startState) throw new Error("Overlays may not be stateful.");
        this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options &amp;&amp; options.opaque});
        this.state.modeGen++;
        regChange(this);
      }),
      removeOverlay: methodOp(function(spec) {
        var overlays = this.state.overlays;
        for (var i = 0; i &lt; overlays.length; ++i) {
          var cur = overlays[i].modeSpec;
          if (cur == spec || typeof spec == "string" &amp;&amp; cur.name == spec) {
            overlays.splice(i, 1);
            this.state.modeGen++;
            regChange(this);
            return;
          }
        }
      }),
  
      indentLine: methodOp(function(n, dir, aggressive) {
        if (typeof dir != "string" &amp;&amp; typeof dir != "number") {
          if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
          else dir = dir ? "add" : "subtract";
        }
        if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
      }),
      indentSelection: methodOp(function(how) {
        var ranges = this.doc.sel.ranges, end = -1;
        for (var i = 0; i &lt; ranges.length; i++) {
          var range = ranges[i];
          if (!range.empty()) {
            var from = range.from(), to = range.to();
            var start = Math.max(end, from.line);
            end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
            for (var j = start; j &lt; end; ++j)
              indentLine(this, j, how);
            var newRanges = this.doc.sel.ranges;
            if (from.ch == 0 &amp;&amp; ranges.length == newRanges.length &amp;&amp; newRanges[i].from().ch &gt; 0)
              replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
          } else if (range.head.line &gt; end) {
            indentLine(this, range.head.line, how, true);
            end = range.head.line;
            if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
          }
        }
      }),
  
      // Fetch the parser token for a given character. Useful for hacks
      // that want to inspect the mode state (say, for completion).
      getTokenAt: function(pos, precise) {
        return takeToken(this, pos, precise);
      },
  
      getLineTokens: function(line, precise) {
        return takeToken(this, Pos(line), precise, true);
      },
  
      getTokenTypeAt: function(pos) {
        pos = clipPos(this.doc, pos);
        var styles = getLineStyles(this, getLine(this.doc, pos.line));
        var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
        var type;
        if (ch == 0) type = styles[2];
        else for (;;) {
          var mid = (before + after) &gt;&gt; 1;
          if ((mid ? styles[mid * 2 - 1] : 0) &gt;= ch) after = mid;
          else if (styles[mid * 2 + 1] &lt; ch) before = mid + 1;
          else { type = styles[mid * 2 + 2]; break; }
        }
        var cut = type ? type.indexOf("cm-overlay ") : -1;
        return cut &lt; 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
      },
  
      getModeAt: function(pos) {
        var mode = this.doc.mode;
        if (!mode.innerMode) return mode;
        return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
      },
  
      getHelper: function(pos, type) {
        return this.getHelpers(pos, type)[0];
      },
  
      getHelpers: function(pos, type) {
        var found = [];
        if (!helpers.hasOwnProperty(type)) return found;
        var help = helpers[type], mode = this.getModeAt(pos);
        if (typeof mode[type] == "string") {
          if (help[mode[type]]) found.push(help[mode[type]]);
        } else if (mode[type]) {
          for (var i = 0; i &lt; mode[type].length; i++) {
            var val = help[mode[type][i]];
            if (val) found.push(val);
          }
        } else if (mode.helperType &amp;&amp; help[mode.helperType]) {
          found.push(help[mode.helperType]);
        } else if (help[mode.name]) {
          found.push(help[mode.name]);
        }
        for (var i = 0; i &lt; help._global.length; i++) {
          var cur = help._global[i];
          if (cur.pred(mode, this) &amp;&amp; indexOf(found, cur.val) == -1)
            found.push(cur.val);
        }
        return found;
      },
  
      getStateAfter: function(line, precise) {
        var doc = this.doc;
        line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
        return getStateBefore(this, line + 1, precise);
      },
  
      cursorCoords: function(start, mode) {
        var pos, range = this.doc.sel.primary();
        if (start == null) pos = range.head;
        else if (typeof start == "object") pos = clipPos(this.doc, start);
        else pos = start ? range.from() : range.to();
        return cursorCoords(this, pos, mode || "page");
      },
  
      charCoords: function(pos, mode) {
        return charCoords(this, clipPos(this.doc, pos), mode || "page");
      },
  
      coordsChar: function(coords, mode) {
        coords = fromCoordSystem(this, coords, mode || "page");
        return coordsChar(this, coords.left, coords.top);
      },
  
      lineAtHeight: function(height, mode) {
        height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
        return lineAtHeight(this.doc, height + this.display.viewOffset);
      },
      heightAtLine: function(line, mode) {
        var end = false, lineObj;
        if (typeof line == "number") {
          var last = this.doc.first + this.doc.size - 1;
          if (line &lt; this.doc.first) line = this.doc.first;
          else if (line &gt; last) { line = last; end = true; }
          lineObj = getLine(this.doc, line);
        } else {
          lineObj = line;
        }
        return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
          (end ? this.doc.height - heightAtLine(lineObj) : 0);
      },
  
      defaultTextHeight: function() { return textHeight(this.display); },
      defaultCharWidth: function() { return charWidth(this.display); },
  
      setGutterMarker: methodOp(function(line, gutterID, value) {
        return changeLine(this.doc, line, "gutter", function(line) {
          var markers = line.gutterMarkers || (line.gutterMarkers = {});
          markers[gutterID] = value;
          if (!value &amp;&amp; isEmpty(markers)) line.gutterMarkers = null;
          return true;
        });
      }),
  
      clearGutter: methodOp(function(gutterID) {
        var cm = this, doc = cm.doc, i = doc.first;
        doc.iter(function(line) {
          if (line.gutterMarkers &amp;&amp; line.gutterMarkers[gutterID]) {
            line.gutterMarkers[gutterID] = null;
            regLineChange(cm, i, "gutter");
            if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
          }
          ++i;
        });
      }),
  
      lineInfo: function(line) {
        if (typeof line == "number") {
          if (!isLine(this.doc, line)) return null;
          var n = line;
          line = getLine(this.doc, line);
          if (!line) return null;
        } else {
          var n = lineNo(line);
          if (n == null) return null;
        }
        return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
                textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
                widgets: line.widgets};
      },
  
      getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  
      addWidget: function(pos, node, scroll, vert, horiz) {
        var display = this.display;
        pos = cursorCoords(this, clipPos(this.doc, pos));
        var top = pos.bottom, left = pos.left;
        node.style.position = "absolute";
        node.setAttribute("cm-ignore-events", "true");
        this.display.input.setUneditable(node);
        display.sizer.appendChild(node);
        if (vert == "over") {
          top = pos.top;
        } else if (vert == "above" || vert == "near") {
          var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
          hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
          // Default to positioning above (if specified and possible); otherwise default to positioning below
          if ((vert == 'above' || pos.bottom + node.offsetHeight &gt; vspace) &amp;&amp; pos.top &gt; node.offsetHeight)
            top = pos.top - node.offsetHeight;
          else if (pos.bottom + node.offsetHeight &lt;= vspace)
            top = pos.bottom;
          if (left + node.offsetWidth &gt; hspace)
            left = hspace - node.offsetWidth;
        }
        node.style.top = top + "px";
        node.style.left = node.style.right = "";
        if (horiz == "right") {
          left = display.sizer.clientWidth - node.offsetWidth;
          node.style.right = "0px";
        } else {
          if (horiz == "left") left = 0;
          else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
          node.style.left = left + "px";
        }
        if (scroll)
          scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
      },
  
      triggerOnKeyDown: methodOp(onKeyDown),
      triggerOnKeyPress: methodOp(onKeyPress),
      triggerOnKeyUp: onKeyUp,
  
      execCommand: function(cmd) {
        if (commands.hasOwnProperty(cmd))
          return commands[cmd].call(null, this);
      },
  
      triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  
      findPosH: function(from, amount, unit, visually) {
        var dir = 1;
        if (amount &lt; 0) { dir = -1; amount = -amount; }
        for (var i = 0, cur = clipPos(this.doc, from); i &lt; amount; ++i) {
          cur = findPosH(this.doc, cur, dir, unit, visually);
          if (cur.hitSide) break;
        }
        return cur;
      },
  
      moveH: methodOp(function(dir, unit) {
        var cm = this;
        cm.extendSelectionsBy(function(range) {
          if (cm.display.shift || cm.doc.extend || range.empty())
            return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
          else
            return dir &lt; 0 ? range.from() : range.to();
        }, sel_move);
      }),
  
      deleteH: methodOp(function(dir, unit) {
        var sel = this.doc.sel, doc = this.doc;
        if (sel.somethingSelected())
          doc.replaceSelection("", null, "+delete");
        else
          deleteNearSelection(this, function(range) {
            var other = findPosH(doc, range.head, dir, unit, false);
            return dir &lt; 0 ? {from: other, to: range.head} : {from: range.head, to: other};
          });
      }),
  
      findPosV: function(from, amount, unit, goalColumn) {
        var dir = 1, x = goalColumn;
        if (amount &lt; 0) { dir = -1; amount = -amount; }
        for (var i = 0, cur = clipPos(this.doc, from); i &lt; amount; ++i) {
          var coords = cursorCoords(this, cur, "div");
          if (x == null) x = coords.left;
          else coords.left = x;
          cur = findPosV(this, coords, dir, unit);
          if (cur.hitSide) break;
        }
        return cur;
      },
  
      moveV: methodOp(function(dir, unit) {
        var cm = this, doc = this.doc, goals = [];
        var collapse = !cm.display.shift &amp;&amp; !doc.extend &amp;&amp; doc.sel.somethingSelected();
        doc.extendSelectionsBy(function(range) {
          if (collapse)
            return dir &lt; 0 ? range.from() : range.to();
          var headPos = cursorCoords(cm, range.head, "div");
          if (range.goalColumn != null) headPos.left = range.goalColumn;
          goals.push(headPos.left);
          var pos = findPosV(cm, headPos, dir, unit);
          if (unit == "page" &amp;&amp; range == doc.sel.primary())
            addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
          return pos;
        }, sel_move);
        if (goals.length) for (var i = 0; i &lt; doc.sel.ranges.length; i++)
          doc.sel.ranges[i].goalColumn = goals[i];
      }),
  
      // Find the word at the given position (as returned by coordsChar).
      findWordAt: function(pos) {
        var doc = this.doc, line = getLine(doc, pos.line).text;
        var start = pos.ch, end = pos.ch;
        if (line) {
          var helper = this.getHelper(pos, "wordChars");
          if ((pos.xRel &lt; 0 || end == line.length) &amp;&amp; start) --start; else ++end;
          var startChar = line.charAt(start);
          var check = isWordChar(startChar, helper)
            ? function(ch) { return isWordChar(ch, helper); }
            : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
            : function(ch) {return !/\s/.test(ch) &amp;&amp; !isWordChar(ch);};
          while (start &gt; 0 &amp;&amp; check(line.charAt(start - 1))) --start;
          while (end &lt; line.length &amp;&amp; check(line.charAt(end))) ++end;
        }
        return new Range(Pos(pos.line, start), Pos(pos.line, end));
      },
  
      toggleOverwrite: function(value) {
        if (value != null &amp;&amp; value == this.state.overwrite) return;
        if (this.state.overwrite = !this.state.overwrite)
          addClass(this.display.cursorDiv, "CodeMirror-overwrite");
        else
          rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  
        signal(this, "overwriteToggle", this, this.state.overwrite);
      },
      hasFocus: function() { return this.display.input.getField() == activeElt(); },
      isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  
      scrollTo: methodOp(function(x, y) {
        if (x != null || y != null) resolveScrollToPos(this);
        if (x != null) this.curOp.scrollLeft = x;
        if (y != null) this.curOp.scrollTop = y;
      }),
      getScrollInfo: function() {
        var scroller = this.display.scroller;
        return {left: scroller.scrollLeft, top: scroller.scrollTop,
                height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
                width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
                clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
      },
  
      scrollIntoView: methodOp(function(range, margin) {
        if (range == null) {
          range = {from: this.doc.sel.primary().head, to: null};
          if (margin == null) margin = this.options.cursorScrollMargin;
        } else if (typeof range == "number") {
          range = {from: Pos(range, 0), to: null};
        } else if (range.from == null) {
          range = {from: range, to: null};
        }
        if (!range.to) range.to = range.from;
        range.margin = margin || 0;
  
        if (range.from.line != null) {
          resolveScrollToPos(this);
          this.curOp.scrollToPos = range;
        } else {
          var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
                                        Math.min(range.from.top, range.to.top) - range.margin,
                                        Math.max(range.from.right, range.to.right),
                                        Math.max(range.from.bottom, range.to.bottom) + range.margin);
          this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
        }
      }),
  
      setSize: methodOp(function(width, height) {
        var cm = this;
        function interpret(val) {
          return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
        }
        if (width != null) cm.display.wrapper.style.width = interpret(width);
        if (height != null) cm.display.wrapper.style.height = interpret(height);
        if (cm.options.lineWrapping) clearLineMeasurementCache(this);
        var lineNo = cm.display.viewFrom;
        cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
          if (line.widgets) for (var i = 0; i &lt; line.widgets.length; i++)
            if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
          ++lineNo;
        });
        cm.curOp.forceUpdate = true;
        signal(cm, "refresh", this);
      }),
  
      operation: function(f){return runInOp(this, f);},
  
      refresh: methodOp(function() {
        var oldHeight = this.display.cachedTextHeight;
        regChange(this);
        this.curOp.forceUpdate = true;
        clearCaches(this);
        this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
        updateGutterSpace(this);
        if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) &gt; .5)
          estimateLineHeights(this);
        signal(this, "refresh", this);
      }),
  
      swapDoc: methodOp(function(doc) {
        var old = this.doc;
        old.cm = null;
        attachDoc(this, doc);
        clearCaches(this);
        this.display.input.reset();
        this.scrollTo(doc.scrollLeft, doc.scrollTop);
        this.curOp.forceScroll = true;
        signalLater(this, "swapDoc", this, old);
        return old;
      }),
  
      getInputField: function(){return this.display.input.getField();},
      getWrapperElement: function(){return this.display.wrapper;},
      getScrollerElement: function(){return this.display.scroller;},
      getGutterElement: function(){return this.display.gutters;}
    };
    eventMixin(CodeMirror);
  
    // OPTION DEFAULTS
  
    // The default configuration options.
    var defaults = CodeMirror.defaults = {};
    // Functions to run when options are changed.
    var optionHandlers = CodeMirror.optionHandlers = {};
  
    function option(name, deflt, handle, notOnInit) {
      CodeMirror.defaults[name] = deflt;
      if (handle) optionHandlers[name] =
        notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
    }
  
    // Passed to option handlers when there is no old value.
    var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  
    // These two are, on init, called from the constructor because they
    // have to be initialized before the editor can start at all.
    option("value", "", function(cm, val) {
      cm.setValue(val);
    }, true);
    option("mode", null, function(cm, val) {
      cm.doc.modeOption = val;
      loadMode(cm);
    }, true);
  
    option("indentUnit", 2, loadMode, true);
    option("indentWithTabs", false);
    option("smartIndent", true);
    option("tabSize", 4, function(cm) {
      resetModeState(cm);
      clearCaches(cm);
      regChange(cm);
    }, true);
    option("lineSeparator", null, function(cm, val) {
      cm.doc.lineSep = val;
      if (!val) return;
      var newBreaks = [], lineNo = cm.doc.first;
      cm.doc.iter(function(line) {
        for (var pos = 0;;) {
          var found = line.text.indexOf(val, pos);
          if (found == -1) break;
          pos = found + val.length;
          newBreaks.push(Pos(lineNo, found));
        }
        lineNo++;
      });
      for (var i = newBreaks.length - 1; i &gt;= 0; i--)
        replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
    });
    option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
      cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
      if (old != CodeMirror.Init) cm.refresh();
    });
    option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
    option("electricChars", true);
    option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
      throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
    }, true);
    option("rtlMoveVisually", !windows);
    option("wholeLineUpdateBefore", true);
  
    option("theme", "default", function(cm) {
      themeChanged(cm);
      guttersChanged(cm);
    }, true);
    option("keyMap", "default", function(cm, val, old) {
      var next = getKeyMap(val);
      var prev = old != CodeMirror.Init &amp;&amp; getKeyMap(old);
      if (prev &amp;&amp; prev.detach) prev.detach(cm, next);
      if (next.attach) next.attach(cm, prev || null);
    });
    option("extraKeys", null);
  
    option("lineWrapping", false, wrappingChanged, true);
    option("gutters", [], function(cm) {
      setGuttersForLineNumbers(cm.options);
      guttersChanged(cm);
    }, true);
    option("fixedGutter", true, function(cm, val) {
      cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
      cm.refresh();
    }, true);
    option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
    option("scrollbarStyle", "native", function(cm) {
      initScrollbars(cm);
      updateScrollbars(cm);
      cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
      cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
    }, true);
    option("lineNumbers", false, function(cm) {
      setGuttersForLineNumbers(cm.options);
      guttersChanged(cm);
    }, true);
    option("firstLineNumber", 1, guttersChanged, true);
    option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
    option("showCursorWhenSelecting", false, updateSelection, true);
  
    option("resetSelectionOnContextMenu", true);
    option("lineWiseCopyCut", true);
  
    option("readOnly", false, function(cm, val) {
      if (val == "nocursor") {
        onBlur(cm);
        cm.display.input.blur();
        cm.display.disabled = true;
      } else {
        cm.display.disabled = false;
      }
      cm.display.input.readOnlyChanged(val)
    });
    option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
    option("dragDrop", true, dragDropChanged);
    option("allowDropFileTypes", null);
  
    option("cursorBlinkRate", 530);
    option("cursorScrollMargin", 0);
    option("cursorHeight", 1, updateSelection, true);
    option("singleCursorHeightPerLine", true, updateSelection, true);
    option("workTime", 100);
    option("workDelay", 100);
    option("flattenSpans", true, resetModeState, true);
    option("addModeClass", false, resetModeState, true);
    option("pollInterval", 100);
    option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
    option("historyEventDelay", 1250);
    option("viewportMargin", 10, function(cm){cm.refresh();}, true);
    option("maxHighlightLength", 10000, resetModeState, true);
    option("moveInputWithCursor", true, function(cm, val) {
      if (!val) cm.display.input.resetPosition();
    });
  
    option("tabindex", null, function(cm, val) {
      cm.display.input.getField().tabIndex = val || "";
    });
    option("autofocus", null);
  
    // MODE DEFINITION AND QUERYING
  
    // Known modes, by name and by MIME
    var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  
    // Extra arguments are stored as the mode's dependencies, which is
    // used by (legacy) mechanisms like loadmode.js to automatically
    // load a mode. (Preferred mechanism is the require/define calls.)
    CodeMirror.defineMode = function(name, mode) {
      if (!CodeMirror.defaults.mode &amp;&amp; name != "null") CodeMirror.defaults.mode = name;
      if (arguments.length &gt; 2)
        mode.dependencies = Array.prototype.slice.call(arguments, 2);
      modes[name] = mode;
    };
  
    CodeMirror.defineMIME = function(mime, spec) {
      mimeModes[mime] = spec;
    };
  
    // Given a MIME type, a {name, ...options} config object, or a name
    // string, return a mode config object.
    CodeMirror.resolveMode = function(spec) {
      if (typeof spec == "string" &amp;&amp; mimeModes.hasOwnProperty(spec)) {
        spec = mimeModes[spec];
      } else if (spec &amp;&amp; typeof spec.name == "string" &amp;&amp; mimeModes.hasOwnProperty(spec.name)) {
        var found = mimeModes[spec.name];
        if (typeof found == "string") found = {name: found};
        spec = createObj(found, spec);
        spec.name = found.name;
      } else if (typeof spec == "string" &amp;&amp; /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
        return CodeMirror.resolveMode("application/xml");
      }
      if (typeof spec == "string") return {name: spec};
      else return spec || {name: "null"};
    };
  
    // Given a mode spec (anything that resolveMode accepts), find and
    // initialize an actual mode object.
    CodeMirror.getMode = function(options, spec) {
      var spec = CodeMirror.resolveMode(spec);
      var mfactory = modes[spec.name];
      if (!mfactory) return CodeMirror.getMode(options, "text/plain");
      var modeObj = mfactory(options, spec);
      if (modeExtensions.hasOwnProperty(spec.name)) {
        var exts = modeExtensions[spec.name];
        for (var prop in exts) {
          if (!exts.hasOwnProperty(prop)) continue;
          if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
          modeObj[prop] = exts[prop];
        }
      }
      modeObj.name = spec.name;
      if (spec.helperType) modeObj.helperType = spec.helperType;
      if (spec.modeProps) for (var prop in spec.modeProps)
        modeObj[prop] = spec.modeProps[prop];
  
      return modeObj;
    };
  
    // Minimal default mode.
    CodeMirror.defineMode("null", function() {
      return {token: function(stream) {stream.skipToEnd();}};
    });
    CodeMirror.defineMIME("text/plain", "null");
  
    // This can be used to attach properties to mode objects from
    // outside the actual mode definition.
    var modeExtensions = CodeMirror.modeExtensions = {};
    CodeMirror.extendMode = function(mode, properties) {
      var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
      copyObj(properties, exts);
    };
  
    // EXTENSIONS
  
    CodeMirror.defineExtension = function(name, func) {
      CodeMirror.prototype[name] = func;
    };
    CodeMirror.defineDocExtension = function(name, func) {
      Doc.prototype[name] = func;
    };
    CodeMirror.defineOption = option;
  
    var initHooks = [];
    CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  
    var helpers = CodeMirror.helpers = {};
    CodeMirror.registerHelper = function(type, name, value) {
      if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
      helpers[type][name] = value;
    };
    CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
      CodeMirror.registerHelper(type, name, value);
      helpers[type]._global.push({pred: predicate, val: value});
    };
  
    // MODE STATE HANDLING
  
    // Utility functions for working with state. Exported because nested
    // modes need to do this for their inner modes.
  
    var copyState = CodeMirror.copyState = function(mode, state) {
      if (state === true) return state;
      if (mode.copyState) return mode.copyState(state);
      var nstate = {};
      for (var n in state) {
        var val = state[n];
        if (val instanceof Array) val = val.concat([]);
        nstate[n] = val;
      }
      return nstate;
    };
  
    var startState = CodeMirror.startState = function(mode, a1, a2) {
      return mode.startState ? mode.startState(a1, a2) : true;
    };
  
    // Given a mode and a state (for that mode), find the inner mode and
    // state at the position that the state refers to.
    CodeMirror.innerMode = function(mode, state) {
      while (mode.innerMode) {
        var info = mode.innerMode(state);
        if (!info || info.mode == mode) break;
        state = info.state;
        mode = info.mode;
      }
      return info || {mode: mode, state: state};
    };
  
    // STANDARD COMMANDS
  
    // Commands are parameter-less actions that can be performed on an
    // editor, mostly used for keybindings.
    var commands = CodeMirror.commands = {
      selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
      singleSelection: function(cm) {
        cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
      },
      killLine: function(cm) {
        deleteNearSelection(cm, function(range) {
          if (range.empty()) {
            var len = getLine(cm.doc, range.head.line).text.length;
            if (range.head.ch == len &amp;&amp; range.head.line &lt; cm.lastLine())
              return {from: range.head, to: Pos(range.head.line + 1, 0)};
            else
              return {from: range.head, to: Pos(range.head.line, len)};
          } else {
            return {from: range.from(), to: range.to()};
          }
        });
      },
      deleteLine: function(cm) {
        deleteNearSelection(cm, function(range) {
          return {from: Pos(range.from().line, 0),
                  to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
        });
      },
      delLineLeft: function(cm) {
        deleteNearSelection(cm, function(range) {
          return {from: Pos(range.from().line, 0), to: range.from()};
        });
      },
      delWrappedLineLeft: function(cm) {
        deleteNearSelection(cm, function(range) {
          var top = cm.charCoords(range.head, "div").top + 5;
          var leftPos = cm.coordsChar({left: 0, top: top}, "div");
          return {from: leftPos, to: range.from()};
        });
      },
      delWrappedLineRight: function(cm) {
        deleteNearSelection(cm, function(range) {
          var top = cm.charCoords(range.head, "div").top + 5;
          var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
          return {from: range.from(), to: rightPos };
        });
      },
      undo: function(cm) {cm.undo();},
      redo: function(cm) {cm.redo();},
      undoSelection: function(cm) {cm.undoSelection();},
      redoSelection: function(cm) {cm.redoSelection();},
      goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
      goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
      goLineStart: function(cm) {
        cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
                              {origin: "+move", bias: 1});
      },
      goLineStartSmart: function(cm) {
        cm.extendSelectionsBy(function(range) {
          return lineStartSmart(cm, range.head);
        }, {origin: "+move", bias: 1});
      },
      goLineEnd: function(cm) {
        cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
                              {origin: "+move", bias: -1});
      },
      goLineRight: function(cm) {
        cm.extendSelectionsBy(function(range) {
          var top = cm.charCoords(range.head, "div").top + 5;
          return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
        }, sel_move);
      },
      goLineLeft: function(cm) {
        cm.extendSelectionsBy(function(range) {
          var top = cm.charCoords(range.head, "div").top + 5;
          return cm.coordsChar({left: 0, top: top}, "div");
        }, sel_move);
      },
      goLineLeftSmart: function(cm) {
        cm.extendSelectionsBy(function(range) {
          var top = cm.charCoords(range.head, "div").top + 5;
          var pos = cm.coordsChar({left: 0, top: top}, "div");
          if (pos.ch &lt; cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
          return pos;
        }, sel_move);
      },
      goLineUp: function(cm) {cm.moveV(-1, "line");},
      goLineDown: function(cm) {cm.moveV(1, "line");},
      goPageUp: function(cm) {cm.moveV(-1, "page");},
      goPageDown: function(cm) {cm.moveV(1, "page");},
      goCharLeft: function(cm) {cm.moveH(-1, "char");},
      goCharRight: function(cm) {cm.moveH(1, "char");},
      goColumnLeft: function(cm) {cm.moveH(-1, "column");},
      goColumnRight: function(cm) {cm.moveH(1, "column");},
      goWordLeft: function(cm) {cm.moveH(-1, "word");},
      goGroupRight: function(cm) {cm.moveH(1, "group");},
      goGroupLeft: function(cm) {cm.moveH(-1, "group");},
      goWordRight: function(cm) {cm.moveH(1, "word");},
      delCharBefore: function(cm) {cm.deleteH(-1, "char");},
      delCharAfter: function(cm) {cm.deleteH(1, "char");},
      delWordBefore: function(cm) {cm.deleteH(-1, "word");},
      delWordAfter: function(cm) {cm.deleteH(1, "word");},
      delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
      delGroupAfter: function(cm) {cm.deleteH(1, "group");},
      indentAuto: function(cm) {cm.indentSelection("smart");},
      indentMore: function(cm) {cm.indentSelection("add");},
      indentLess: function(cm) {cm.indentSelection("subtract");},
      insertTab: function(cm) {cm.replaceSelection("\t");},
      insertSoftTab: function(cm) {
        var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
        for (var i = 0; i &lt; ranges.length; i++) {
          var pos = ranges[i].from();
          var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
          spaces.push(spaceStr(tabSize - col % tabSize));
        }
        cm.replaceSelections(spaces);
      },
      defaultTab: function(cm) {
        if (cm.somethingSelected()) cm.indentSelection("add");
        else cm.execCommand("insertTab");
      },
      transposeChars: function(cm) {
        runInOp(cm, function() {
          var ranges = cm.listSelections(), newSel = [];
          for (var i = 0; i &lt; ranges.length; i++) {
            var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
            if (line) {
              if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
              if (cur.ch &gt; 0) {
                cur = new Pos(cur.line, cur.ch + 1);
                cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
                                Pos(cur.line, cur.ch - 2), cur, "+transpose");
              } else if (cur.line &gt; cm.doc.first) {
                var prev = getLine(cm.doc, cur.line - 1).text;
                if (prev)
                  cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
                                  prev.charAt(prev.length - 1),
                                  Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
              }
            }
            newSel.push(new Range(cur, cur));
          }
          cm.setSelections(newSel);
        });
      },
      newlineAndIndent: function(cm) {
        runInOp(cm, function() {
          var len = cm.listSelections().length;
          for (var i = 0; i &lt; len; i++) {
            var range = cm.listSelections()[i];
            cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
            cm.indentLine(range.from().line + 1, null, true);
          }
          ensureCursorVisible(cm);
        });
      },
      openLine: function(cm) {cm.replaceSelection("\n", "start")},
      toggleOverwrite: function(cm) {cm.toggleOverwrite();}
    };
  
  
    // STANDARD KEYMAPS
  
    var keyMap = CodeMirror.keyMap = {};
  
    keyMap.basic = {
      "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
      "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
      "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
      "Tab": "defaultTab", "Shift-Tab": "indentAuto",
      "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
      "Esc": "singleSelection"
    };
    // Note that the save and find-related commands aren't defined by
    // default. User code or addons can define them. Unknown commands
    // are simply ignored.
    keyMap.pcDefault = {
      "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
      "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
      "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
      "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
      "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
      "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
      "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
      fallthrough: "basic"
    };
    // Very basic readline/emacs-style bindings, which are standard on Mac.
    keyMap.emacsy = {
      "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
      "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
      "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
      "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
      "Ctrl-O": "openLine"
    };
    keyMap.macDefault = {
      "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
      "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
      "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
      "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
      "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
      "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
      "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
      fallthrough: ["basic", "emacsy"]
    };
    keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  
    // KEYMAP DISPATCH
  
    function normalizeKeyName(name) {
      var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
      var alt, ctrl, shift, cmd;
      for (var i = 0; i &lt; parts.length - 1; i++) {
        var mod = parts[i];
        if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
        else if (/^a(lt)?$/i.test(mod)) alt = true;
        else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
        else if (/^s(hift)$/i.test(mod)) shift = true;
        else throw new Error("Unrecognized modifier name: " + mod);
      }
      if (alt) name = "Alt-" + name;
      if (ctrl) name = "Ctrl-" + name;
      if (cmd) name = "Cmd-" + name;
      if (shift) name = "Shift-" + name;
      return name;
    }
  
    // This is a kludge to keep keymaps mostly working as raw objects
    // (backwards compatibility) while at the same time support features
    // like normalization and multi-stroke key bindings. It compiles a
    // new normalized keymap, and then updates the old object to reflect
    // this.
    CodeMirror.normalizeKeyMap = function(keymap) {
      var copy = {};
      for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
        var value = keymap[keyname];
        if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
        if (value == "...") { delete keymap[keyname]; continue; }
  
        var keys = map(keyname.split(" "), normalizeKeyName);
        for (var i = 0; i &lt; keys.length; i++) {
          var val, name;
          if (i == keys.length - 1) {
            name = keys.join(" ");
            val = value;
          } else {
            name = keys.slice(0, i + 1).join(" ");
            val = "...";
          }
          var prev = copy[name];
          if (!prev) copy[name] = val;
          else if (prev != val) throw new Error("Inconsistent bindings for " + name);
        }
        delete keymap[keyname];
      }
      for (var prop in copy) keymap[prop] = copy[prop];
      return keymap;
    };
  
    var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
      map = getKeyMap(map);
      var found = map.call ? map.call(key, context) : map[key];
      if (found === false) return "nothing";
      if (found === "...") return "multi";
      if (found != null &amp;&amp; handle(found)) return "handled";
  
      if (map.fallthrough) {
        if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
          return lookupKey(key, map.fallthrough, handle, context);
        for (var i = 0; i &lt; map.fallthrough.length; i++) {
          var result = lookupKey(key, map.fallthrough[i], handle, context);
          if (result) return result;
        }
      }
    };
  
    // Modifier key presses don't count as 'real' key presses for the
    // purpose of keymap fallthrough.
    var isModifierKey = CodeMirror.isModifierKey = function(value) {
      var name = typeof value == "string" ? value : keyNames[value.keyCode];
      return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
    };
  
    // Look up the name of a key as indicated by an event object.
    var keyName = CodeMirror.keyName = function(event, noShift) {
      if (presto &amp;&amp; event.keyCode == 34 &amp;&amp; event["char"]) return false;
      var base = keyNames[event.keyCode], name = base;
      if (name == null || event.altGraphKey) return false;
      if (event.altKey &amp;&amp; base != "Alt") name = "Alt-" + name;
      if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) &amp;&amp; base != "Ctrl") name = "Ctrl-" + name;
      if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) &amp;&amp; base != "Cmd") name = "Cmd-" + name;
      if (!noShift &amp;&amp; event.shiftKey &amp;&amp; base != "Shift") name = "Shift-" + name;
      return name;
    };
  
    function getKeyMap(val) {
      return typeof val == "string" ? keyMap[val] : val;
    }
  
    // FROMTEXTAREA
  
    CodeMirror.fromTextArea = function(textarea, options) {
      options = options ? copyObj(options) : {};
      options.value = textarea.value;
      if (!options.tabindex &amp;&amp; textarea.tabIndex)
        options.tabindex = textarea.tabIndex;
      if (!options.placeholder &amp;&amp; textarea.placeholder)
        options.placeholder = textarea.placeholder;
      // Set autofocus to true if this textarea is focused, or if it has
      // autofocus and no other element is focused.
      if (options.autofocus == null) {
        var hasFocus = activeElt();
        options.autofocus = hasFocus == textarea ||
          textarea.getAttribute("autofocus") != null &amp;&amp; hasFocus == document.body;
      }
  
      function save() {textarea.value = cm.getValue();}
      if (textarea.form) {
        on(textarea.form, "submit", save);
        // Deplorable hack to make the submit method do the right thing.
        if (!options.leaveSubmitMethodAlone) {
          var form = textarea.form, realSubmit = form.submit;
          try {
            var wrappedSubmit = form.submit = function() {
              save();
              form.submit = realSubmit;
              form.submit();
              form.submit = wrappedSubmit;
            };
          } catch(e) {}
        }
      }
  
      options.finishInit = function(cm) {
        cm.save = save;
        cm.getTextArea = function() { return textarea; };
        cm.toTextArea = function() {
          cm.toTextArea = isNaN; // Prevent this from being ran twice
          save();
          textarea.parentNode.removeChild(cm.getWrapperElement());
          textarea.style.display = "";
          if (textarea.form) {
            off(textarea.form, "submit", save);
            if (typeof textarea.form.submit == "function")
              textarea.form.submit = realSubmit;
          }
        };
      };
  
      textarea.style.display = "none";
      var cm = CodeMirror(function(node) {
        textarea.parentNode.insertBefore(node, textarea.nextSibling);
      }, options);
      return cm;
    };
  
    // STRING STREAM
  
    // Fed to the mode parsers, provides helper functions to make
    // parsers more succinct.
  
    var StringStream = CodeMirror.StringStream = function(string, tabSize) {
      this.pos = this.start = 0;
      this.string = string;
      this.tabSize = tabSize || 8;
      this.lastColumnPos = this.lastColumnValue = 0;
      this.lineStart = 0;
    };
  
    StringStream.prototype = {
      eol: function() {return this.pos &gt;= this.string.length;},
      sol: function() {return this.pos == this.lineStart;},
      peek: function() {return this.string.charAt(this.pos) || undefined;},
      next: function() {
        if (this.pos &lt; this.string.length)
          return this.string.charAt(this.pos++);
      },
      eat: function(match) {
        var ch = this.string.charAt(this.pos);
        if (typeof match == "string") var ok = ch == match;
        else var ok = ch &amp;&amp; (match.test ? match.test(ch) : match(ch));
        if (ok) {++this.pos; return ch;}
      },
      eatWhile: function(match) {
        var start = this.pos;
        while (this.eat(match)){}
        return this.pos &gt; start;
      },
      eatSpace: function() {
        var start = this.pos;
        while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
        return this.pos &gt; start;
      },
      skipToEnd: function() {this.pos = this.string.length;},
      skipTo: function(ch) {
        var found = this.string.indexOf(ch, this.pos);
        if (found &gt; -1) {this.pos = found; return true;}
      },
      backUp: function(n) {this.pos -= n;},
      column: function() {
        if (this.lastColumnPos &lt; this.start) {
          this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
          this.lastColumnPos = this.start;
        }
        return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
      },
      indentation: function() {
        return countColumn(this.string, null, this.tabSize) -
          (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
      },
      match: function(pattern, consume, caseInsensitive) {
        if (typeof pattern == "string") {
          var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
          var substr = this.string.substr(this.pos, pattern.length);
          if (cased(substr) == cased(pattern)) {
            if (consume !== false) this.pos += pattern.length;
            return true;
          }
        } else {
          var match = this.string.slice(this.pos).match(pattern);
          if (match &amp;&amp; match.index &gt; 0) return null;
          if (match &amp;&amp; consume !== false) this.pos += match[0].length;
          return match;
        }
      },
      current: function(){return this.string.slice(this.start, this.pos);},
      hideFirstChars: function(n, inner) {
        this.lineStart += n;
        try { return inner(); }
        finally { this.lineStart -= n; }
      }
    };
  
    // TEXTMARKERS
  
    // Created with markText and setBookmark methods. A TextMarker is a
    // handle that can be used to clear or find a marked position in the
    // document. Line objects hold arrays (markedSpans) containing
    // {from, to, marker} object pointing to such marker objects, and
    // indicating that such a marker is present on that line. Multiple
    // lines may point to the same marker when it spans across lines.
    // The spans will have null for their from/to properties when the
    // marker continues beyond the start/end of the line. Markers have
    // links back to the lines they currently touch.
  
    var nextMarkerId = 0;
  
    var TextMarker = CodeMirror.TextMarker = function(doc, type) {
      this.lines = [];
      this.type = type;
      this.doc = doc;
      this.id = ++nextMarkerId;
    };
    eventMixin(TextMarker);
  
    // Clear the marker.
    TextMarker.prototype.clear = function() {
      if (this.explicitlyCleared) return;
      var cm = this.doc.cm, withOp = cm &amp;&amp; !cm.curOp;
      if (withOp) startOperation(cm);
      if (hasHandler(this, "clear")) {
        var found = this.find();
        if (found) signalLater(this, "clear", found.from, found.to);
      }
      var min = null, max = null;
      for (var i = 0; i &lt; this.lines.length; ++i) {
        var line = this.lines[i];
        var span = getMarkedSpanFor(line.markedSpans, this);
        if (cm &amp;&amp; !this.collapsed) regLineChange(cm, lineNo(line), "text");
        else if (cm) {
          if (span.to != null) max = lineNo(line);
          if (span.from != null) min = lineNo(line);
        }
        line.markedSpans = removeMarkedSpan(line.markedSpans, span);
        if (span.from == null &amp;&amp; this.collapsed &amp;&amp; !lineIsHidden(this.doc, line) &amp;&amp; cm)
          updateLineHeight(line, textHeight(cm.display));
      }
      if (cm &amp;&amp; this.collapsed &amp;&amp; !cm.options.lineWrapping) for (var i = 0; i &lt; this.lines.length; ++i) {
        var visual = visualLine(this.lines[i]), len = lineLength(visual);
        if (len &gt; cm.display.maxLineLength) {
          cm.display.maxLine = visual;
          cm.display.maxLineLength = len;
          cm.display.maxLineChanged = true;
        }
      }
  
      if (min != null &amp;&amp; cm &amp;&amp; this.collapsed) regChange(cm, min, max + 1);
      this.lines.length = 0;
      this.explicitlyCleared = true;
      if (this.atomic &amp;&amp; this.doc.cantEdit) {
        this.doc.cantEdit = false;
        if (cm) reCheckSelection(cm.doc);
      }
      if (cm) signalLater(cm, "markerCleared", cm, this);
      if (withOp) endOperation(cm);
      if (this.parent) this.parent.clear();
    };
  
    // Find the position of the marker in the document. Returns a {from,
    // to} object by default. Side can be passed to get a specific side
    // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
    // Pos objects returned contain a line object, rather than a line
    // number (used to prevent looking up the same line twice).
    TextMarker.prototype.find = function(side, lineObj) {
      if (side == null &amp;&amp; this.type == "bookmark") side = 1;
      var from, to;
      for (var i = 0; i &lt; this.lines.length; ++i) {
        var line = this.lines[i];
        var span = getMarkedSpanFor(line.markedSpans, this);
        if (span.from != null) {
          from = Pos(lineObj ? line : lineNo(line), span.from);
          if (side == -1) return from;
        }
        if (span.to != null) {
          to = Pos(lineObj ? line : lineNo(line), span.to);
          if (side == 1) return to;
        }
      }
      return from &amp;&amp; {from: from, to: to};
    };
  
    // Signals that the marker's widget changed, and surrounding layout
    // should be recomputed.
    TextMarker.prototype.changed = function() {
      var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
      if (!pos || !cm) return;
      runInOp(cm, function() {
        var line = pos.line, lineN = lineNo(pos.line);
        var view = findViewForLine(cm, lineN);
        if (view) {
          clearLineMeasurementCacheFor(view);
          cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
        }
        cm.curOp.updateMaxLine = true;
        if (!lineIsHidden(widget.doc, line) &amp;&amp; widget.height != null) {
          var oldHeight = widget.height;
          widget.height = null;
          var dHeight = widgetHeight(widget) - oldHeight;
          if (dHeight)
            updateLineHeight(line, line.height + dHeight);
        }
      });
    };
  
    TextMarker.prototype.attachLine = function(line) {
      if (!this.lines.length &amp;&amp; this.doc.cm) {
        var op = this.doc.cm.curOp;
        if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
          (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
      }
      this.lines.push(line);
    };
    TextMarker.prototype.detachLine = function(line) {
      this.lines.splice(indexOf(this.lines, line), 1);
      if (!this.lines.length &amp;&amp; this.doc.cm) {
        var op = this.doc.cm.curOp;
        (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
      }
    };
  
    // Collapsed markers have unique ids, in order to be able to order
    // them, which is needed for uniquely determining an outer marker
    // when they overlap (they may nest, but not partially overlap).
    var nextMarkerId = 0;
  
    // Create a marker, wire it up to the right lines, and
    function markText(doc, from, to, options, type) {
      // Shared markers (across linked documents) are handled separately
      // (markTextShared will call out to this again, once per
      // document).
      if (options &amp;&amp; options.shared) return markTextShared(doc, from, to, options, type);
      // Ensure we are in an operation.
      if (doc.cm &amp;&amp; !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  
      var marker = new TextMarker(doc, type), diff = cmp(from, to);
      if (options) copyObj(options, marker, false);
      // Don't connect empty markers unless clearWhenEmpty is false
      if (diff &gt; 0 || diff == 0 &amp;&amp; marker.clearWhenEmpty !== false)
        return marker;
      if (marker.replacedWith) {
        // Showing up as a widget implies collapsed (widget replaces text)
        marker.collapsed = true;
        marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
        if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
        if (options.insertLeft) marker.widgetNode.insertLeft = true;
      }
      if (marker.collapsed) {
        if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
            from.line != to.line &amp;&amp; conflictingCollapsedRange(doc, to.line, from, to, marker))
          throw new Error("Inserting collapsed marker partially overlapping an existing one");
        sawCollapsedSpans = true;
      }
  
      if (marker.addToHistory)
        addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  
      var curLine = from.line, cm = doc.cm, updateMaxLine;
      doc.iter(curLine, to.line + 1, function(line) {
        if (cm &amp;&amp; marker.collapsed &amp;&amp; !cm.options.lineWrapping &amp;&amp; visualLine(line) == cm.display.maxLine)
          updateMaxLine = true;
        if (marker.collapsed &amp;&amp; curLine != from.line) updateLineHeight(line, 0);
        addMarkedSpan(line, new MarkedSpan(marker,
                                           curLine == from.line ? from.ch : null,
                                           curLine == to.line ? to.ch : null));
        ++curLine;
      });
      // lineIsHidden depends on the presence of the spans, so needs a second pass
      if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
        if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
      });
  
      if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  
      if (marker.readOnly) {
        sawReadOnlySpans = true;
        if (doc.history.done.length || doc.history.undone.length)
          doc.clearHistory();
      }
      if (marker.collapsed) {
        marker.id = ++nextMarkerId;
        marker.atomic = true;
      }
      if (cm) {
        // Sync editor state
        if (updateMaxLine) cm.curOp.updateMaxLine = true;
        if (marker.collapsed)
          regChange(cm, from.line, to.line + 1);
        else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
          for (var i = from.line; i &lt;= to.line; i++) regLineChange(cm, i, "text");
        if (marker.atomic) reCheckSelection(cm.doc);
        signalLater(cm, "markerAdded", cm, marker);
      }
      return marker;
    }
  
    // SHARED TEXTMARKERS
  
    // A shared marker spans multiple linked documents. It is
    // implemented as a meta-marker-object controlling multiple normal
    // markers.
    var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
      this.markers = markers;
      this.primary = primary;
      for (var i = 0; i &lt; markers.length; ++i)
        markers[i].parent = this;
    };
    eventMixin(SharedTextMarker);
  
    SharedTextMarker.prototype.clear = function() {
      if (this.explicitlyCleared) return;
      this.explicitlyCleared = true;
      for (var i = 0; i &lt; this.markers.length; ++i)
        this.markers[i].clear();
      signalLater(this, "clear");
    };
    SharedTextMarker.prototype.find = function(side, lineObj) {
      return this.primary.find(side, lineObj);
    };
  
    function markTextShared(doc, from, to, options, type) {
      options = copyObj(options);
      options.shared = false;
      var markers = [markText(doc, from, to, options, type)], primary = markers[0];
      var widget = options.widgetNode;
      linkedDocs(doc, function(doc) {
        if (widget) options.widgetNode = widget.cloneNode(true);
        markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
        for (var i = 0; i &lt; doc.linked.length; ++i)
          if (doc.linked[i].isParent) return;
        primary = lst(markers);
      });
      return new SharedTextMarker(markers, primary);
    }
  
    function findSharedMarkers(doc) {
      return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
                           function(m) { return m.parent; });
    }
  
    function copySharedMarkers(doc, markers) {
      for (var i = 0; i &lt; markers.length; i++) {
        var marker = markers[i], pos = marker.find();
        var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
        if (cmp(mFrom, mTo)) {
          var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
          marker.markers.push(subMark);
          subMark.parent = marker;
        }
      }
    }
  
    function detachSharedMarkers(markers) {
      for (var i = 0; i &lt; markers.length; i++) {
        var marker = markers[i], linked = [marker.primary.doc];;
        linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
        for (var j = 0; j &lt; marker.markers.length; j++) {
          var subMarker = marker.markers[j];
          if (indexOf(linked, subMarker.doc) == -1) {
            subMarker.parent = null;
            marker.markers.splice(j--, 1);
          }
        }
      }
    }
  
    // TEXTMARKER SPANS
  
    function MarkedSpan(marker, from, to) {
      this.marker = marker;
      this.from = from; this.to = to;
    }
  
    // Search an array of spans for a span matching the given marker.
    function getMarkedSpanFor(spans, marker) {
      if (spans) for (var i = 0; i &lt; spans.length; ++i) {
        var span = spans[i];
        if (span.marker == marker) return span;
      }
    }
    // Remove a span from an array, returning undefined if no spans are
    // left (we don't store arrays for lines without spans).
    function removeMarkedSpan(spans, span) {
      for (var r, i = 0; i &lt; spans.length; ++i)
        if (spans[i] != span) (r || (r = [])).push(spans[i]);
      return r;
    }
    // Add a span to a line.
    function addMarkedSpan(line, span) {
      line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
      span.marker.attachLine(line);
    }
  
    // Used for the algorithm that adjusts markers for a change in the
    // document. These functions cut an array of spans at a given
    // character position, returning an array of remaining chunks (or
    // undefined if nothing remains).
    function markedSpansBefore(old, startCh, isInsert) {
      if (old) for (var i = 0, nw; i &lt; old.length; ++i) {
        var span = old[i], marker = span.marker;
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from &lt;= startCh : span.from &lt; startCh);
        if (startsBefore || span.from == startCh &amp;&amp; marker.type == "bookmark" &amp;&amp; (!isInsert || !span.marker.insertLeft)) {
          var endsAfter = span.to == null || (marker.inclusiveRight ? span.to &gt;= startCh : span.to &gt; startCh);
          (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
        }
      }
      return nw;
    }
    function markedSpansAfter(old, endCh, isInsert) {
      if (old) for (var i = 0, nw; i &lt; old.length; ++i) {
        var span = old[i], marker = span.marker;
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to &gt;= endCh : span.to &gt; endCh);
        if (endsAfter || span.from == endCh &amp;&amp; marker.type == "bookmark" &amp;&amp; (!isInsert || span.marker.insertLeft)) {
          var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from &lt;= endCh : span.from &lt; endCh);
          (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
                                                span.to == null ? null : span.to - endCh));
        }
      }
      return nw;
    }
  
    // Given a change object, compute the new set of marker spans that
    // cover the line in which the change took place. Removes spans
    // entirely within the change, reconnects spans belonging to the
    // same marker that appear on both sides of the change, and cuts off
    // spans partially within the change. Returns an array of span
    // arrays with one element for each line in (after) the change.
    function stretchSpansOverChange(doc, change) {
      if (change.full) return null;
      var oldFirst = isLine(doc, change.from.line) &amp;&amp; getLine(doc, change.from.line).markedSpans;
      var oldLast = isLine(doc, change.to.line) &amp;&amp; getLine(doc, change.to.line).markedSpans;
      if (!oldFirst &amp;&amp; !oldLast) return null;
  
      var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
      // Get the spans that 'stick out' on both sides
      var first = markedSpansBefore(oldFirst, startCh, isInsert);
      var last = markedSpansAfter(oldLast, endCh, isInsert);
  
      // Next, merge those two ends
      var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
      if (first) {
        // Fix up .to properties of first
        for (var i = 0; i &lt; first.length; ++i) {
          var span = first[i];
          if (span.to == null) {
            var found = getMarkedSpanFor(last, span.marker);
            if (!found) span.to = startCh;
            else if (sameLine) span.to = found.to == null ? null : found.to + offset;
          }
        }
      }
      if (last) {
        // Fix up .from in last (or move them into first in case of sameLine)
        for (var i = 0; i &lt; last.length; ++i) {
          var span = last[i];
          if (span.to != null) span.to += offset;
          if (span.from == null) {
            var found = getMarkedSpanFor(first, span.marker);
            if (!found) {
              span.from = offset;
              if (sameLine) (first || (first = [])).push(span);
            }
          } else {
            span.from += offset;
            if (sameLine) (first || (first = [])).push(span);
          }
        }
      }
      // Make sure we didn't create any zero-length spans
      if (first) first = clearEmptySpans(first);
      if (last &amp;&amp; last != first) last = clearEmptySpans(last);
  
      var newMarkers = [first];
      if (!sameLine) {
        // Fill gap with whole-line-spans
        var gap = change.text.length - 2, gapMarkers;
        if (gap &gt; 0 &amp;&amp; first)
          for (var i = 0; i &lt; first.length; ++i)
            if (first[i].to == null)
              (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
        for (var i = 0; i &lt; gap; ++i)
          newMarkers.push(gapMarkers);
        newMarkers.push(last);
      }
      return newMarkers;
    }
  
    // Remove spans that are empty and don't have a clearWhenEmpty
    // option of false.
    function clearEmptySpans(spans) {
      for (var i = 0; i &lt; spans.length; ++i) {
        var span = spans[i];
        if (span.from != null &amp;&amp; span.from == span.to &amp;&amp; span.marker.clearWhenEmpty !== false)
          spans.splice(i--, 1);
      }
      if (!spans.length) return null;
      return spans;
    }
  
    // Used for un/re-doing changes from the history. Combines the
    // result of computing the existing spans with the set of spans that
    // existed in the history (so that deleting around a span and then
    // undoing brings back the span).
    function mergeOldSpans(doc, change) {
      var old = getOldSpans(doc, change);
      var stretched = stretchSpansOverChange(doc, change);
      if (!old) return stretched;
      if (!stretched) return old;
  
      for (var i = 0; i &lt; old.length; ++i) {
        var oldCur = old[i], stretchCur = stretched[i];
        if (oldCur &amp;&amp; stretchCur) {
          spans: for (var j = 0; j &lt; stretchCur.length; ++j) {
            var span = stretchCur[j];
            for (var k = 0; k &lt; oldCur.length; ++k)
              if (oldCur[k].marker == span.marker) continue spans;
            oldCur.push(span);
          }
        } else if (stretchCur) {
          old[i] = stretchCur;
        }
      }
      return old;
    }
  
    // Used to 'clip' out readOnly ranges when making a change.
    function removeReadOnlyRanges(doc, from, to) {
      var markers = null;
      doc.iter(from.line, to.line + 1, function(line) {
        if (line.markedSpans) for (var i = 0; i &lt; line.markedSpans.length; ++i) {
          var mark = line.markedSpans[i].marker;
          if (mark.readOnly &amp;&amp; (!markers || indexOf(markers, mark) == -1))
            (markers || (markers = [])).push(mark);
        }
      });
      if (!markers) return null;
      var parts = [{from: from, to: to}];
      for (var i = 0; i &lt; markers.length; ++i) {
        var mk = markers[i], m = mk.find(0);
        for (var j = 0; j &lt; parts.length; ++j) {
          var p = parts[j];
          if (cmp(p.to, m.from) &lt; 0 || cmp(p.from, m.to) &gt; 0) continue;
          var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
          if (dfrom &lt; 0 || !mk.inclusiveLeft &amp;&amp; !dfrom)
            newParts.push({from: p.from, to: m.from});
          if (dto &gt; 0 || !mk.inclusiveRight &amp;&amp; !dto)
            newParts.push({from: m.to, to: p.to});
          parts.splice.apply(parts, newParts);
          j += newParts.length - 1;
        }
      }
      return parts;
    }
  
    // Connect or disconnect spans from a line.
    function detachMarkedSpans(line) {
      var spans = line.markedSpans;
      if (!spans) return;
      for (var i = 0; i &lt; spans.length; ++i)
        spans[i].marker.detachLine(line);
      line.markedSpans = null;
    }
    function attachMarkedSpans(line, spans) {
      if (!spans) return;
      for (var i = 0; i &lt; spans.length; ++i)
        spans[i].marker.attachLine(line);
      line.markedSpans = spans;
    }
  
    // Helpers used when computing which overlapping collapsed span
    // counts as the larger one.
    function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
    function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  
    // Returns a number indicating which of two overlapping collapsed
    // spans is larger (and thus includes the other). Falls back to
    // comparing ids when the spans cover exactly the same range.
    function compareCollapsedMarkers(a, b) {
      var lenDiff = a.lines.length - b.lines.length;
      if (lenDiff != 0) return lenDiff;
      var aPos = a.find(), bPos = b.find();
      var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
      if (fromCmp) return -fromCmp;
      var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
      if (toCmp) return toCmp;
      return b.id - a.id;
    }
  
    // Find out whether a line ends or starts in a collapsed span. If
    // so, return the marker for that span.
    function collapsedSpanAtSide(line, start) {
      var sps = sawCollapsedSpans &amp;&amp; line.markedSpans, found;
      if (sps) for (var sp, i = 0; i &lt; sps.length; ++i) {
        sp = sps[i];
        if (sp.marker.collapsed &amp;&amp; (start ? sp.from : sp.to) == null &amp;&amp;
            (!found || compareCollapsedMarkers(found, sp.marker) &lt; 0))
          found = sp.marker;
      }
      return found;
    }
    function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
    function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  
    // Test whether there exists a collapsed span that partially
    // overlaps (covers the start or end, but not both) of a new span.
    // Such overlap is not allowed.
    function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
      var line = getLine(doc, lineNo);
      var sps = sawCollapsedSpans &amp;&amp; line.markedSpans;
      if (sps) for (var i = 0; i &lt; sps.length; ++i) {
        var sp = sps[i];
        if (!sp.marker.collapsed) continue;
        var found = sp.marker.find(0);
        var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
        var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
        if (fromCmp &gt;= 0 &amp;&amp; toCmp &lt;= 0 || fromCmp &lt;= 0 &amp;&amp; toCmp &gt;= 0) continue;
        if (fromCmp &lt;= 0 &amp;&amp; (sp.marker.inclusiveRight &amp;&amp; marker.inclusiveLeft ? cmp(found.to, from) &gt;= 0 : cmp(found.to, from) &gt; 0) ||
            fromCmp &gt;= 0 &amp;&amp; (sp.marker.inclusiveRight &amp;&amp; marker.inclusiveLeft ? cmp(found.from, to) &lt;= 0 : cmp(found.from, to) &lt; 0))
          return true;
      }
    }
  
    // A visual line is a line as drawn on the screen. Folding, for
    // example, can cause multiple logical lines to appear on the same
    // visual line. This finds the start of the visual line that the
    // given line is part of (usually that is the line itself).
    function visualLine(line) {
      var merged;
      while (merged = collapsedSpanAtStart(line))
        line = merged.find(-1, true).line;
      return line;
    }
  
    // Returns an array of logical lines that continue the visual line
    // started by the argument, or undefined if there are no such lines.
    function visualLineContinued(line) {
      var merged, lines;
      while (merged = collapsedSpanAtEnd(line)) {
        line = merged.find(1, true).line;
        (lines || (lines = [])).push(line);
      }
      return lines;
    }
  
    // Get the line number of the start of the visual line that the
    // given line number is part of.
    function visualLineNo(doc, lineN) {
      var line = getLine(doc, lineN), vis = visualLine(line);
      if (line == vis) return lineN;
      return lineNo(vis);
    }
    // Get the line number of the start of the next visual line after
    // the given line.
    function visualLineEndNo(doc, lineN) {
      if (lineN &gt; doc.lastLine()) return lineN;
      var line = getLine(doc, lineN), merged;
      if (!lineIsHidden(doc, line)) return lineN;
      while (merged = collapsedSpanAtEnd(line))
        line = merged.find(1, true).line;
      return lineNo(line) + 1;
    }
  
    // Compute whether a line is hidden. Lines count as hidden when they
    // are part of a visual line that starts with another line, or when
    // they are entirely covered by collapsed, non-widget span.
    function lineIsHidden(doc, line) {
      var sps = sawCollapsedSpans &amp;&amp; line.markedSpans;
      if (sps) for (var sp, i = 0; i &lt; sps.length; ++i) {
        sp = sps[i];
        if (!sp.marker.collapsed) continue;
        if (sp.from == null) return true;
        if (sp.marker.widgetNode) continue;
        if (sp.from == 0 &amp;&amp; sp.marker.inclusiveLeft &amp;&amp; lineIsHiddenInner(doc, line, sp))
          return true;
      }
    }
    function lineIsHiddenInner(doc, line, span) {
      if (span.to == null) {
        var end = span.marker.find(1, true);
        return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
      }
      if (span.marker.inclusiveRight &amp;&amp; span.to == line.text.length)
        return true;
      for (var sp, i = 0; i &lt; line.markedSpans.length; ++i) {
        sp = line.markedSpans[i];
        if (sp.marker.collapsed &amp;&amp; !sp.marker.widgetNode &amp;&amp; sp.from == span.to &amp;&amp;
            (sp.to == null || sp.to != span.from) &amp;&amp;
            (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &amp;&amp;
            lineIsHiddenInner(doc, line, sp)) return true;
      }
    }
  
    // LINE WIDGETS
  
    // Line widgets are block elements displayed above or below a line.
  
    var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
      if (options) for (var opt in options) if (options.hasOwnProperty(opt))
        this[opt] = options[opt];
      this.doc = doc;
      this.node = node;
    };
    eventMixin(LineWidget);
  
    function adjustScrollWhenAboveVisible(cm, line, diff) {
      if (heightAtLine(line) &lt; ((cm.curOp &amp;&amp; cm.curOp.scrollTop) || cm.doc.scrollTop))
        addToScrollPos(cm, null, diff);
    }
  
    LineWidget.prototype.clear = function() {
      var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
      if (no == null || !ws) return;
      for (var i = 0; i &lt; ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
      if (!ws.length) line.widgets = null;
      var height = widgetHeight(this);
      updateLineHeight(line, Math.max(0, line.height - height));
      if (cm) runInOp(cm, function() {
        adjustScrollWhenAboveVisible(cm, line, -height);
        regLineChange(cm, no, "widget");
      });
    };
    LineWidget.prototype.changed = function() {
      var oldH = this.height, cm = this.doc.cm, line = this.line;
      this.height = null;
      var diff = widgetHeight(this) - oldH;
      if (!diff) return;
      updateLineHeight(line, line.height + diff);
      if (cm) runInOp(cm, function() {
        cm.curOp.forceUpdate = true;
        adjustScrollWhenAboveVisible(cm, line, diff);
      });
    };
  
    function widgetHeight(widget) {
      if (widget.height != null) return widget.height;
      var cm = widget.doc.cm;
      if (!cm) return 0;
      if (!contains(document.body, widget.node)) {
        var parentStyle = "position: relative;";
        if (widget.coverGutter)
          parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
        if (widget.noHScroll)
          parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
        removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
      }
      return widget.height = widget.node.parentNode.offsetHeight;
    }
  
    function addLineWidget(doc, handle, node, options) {
      var widget = new LineWidget(doc, node, options);
      var cm = doc.cm;
      if (cm &amp;&amp; widget.noHScroll) cm.display.alignWidgets = true;
      changeLine(doc, handle, "widget", function(line) {
        var widgets = line.widgets || (line.widgets = []);
        if (widget.insertAt == null) widgets.push(widget);
        else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
        widget.line = line;
        if (cm &amp;&amp; !lineIsHidden(doc, line)) {
          var aboveVisible = heightAtLine(line) &lt; doc.scrollTop;
          updateLineHeight(line, line.height + widgetHeight(widget));
          if (aboveVisible) addToScrollPos(cm, null, widget.height);
          cm.curOp.forceUpdate = true;
        }
        return true;
      });
      return widget;
    }
  
    // LINE DATA STRUCTURE
  
    // Line objects. These hold state related to a line, including
    // highlighting info (the styles array).
    var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
      this.text = text;
      attachMarkedSpans(this, markedSpans);
      this.height = estimateHeight ? estimateHeight(this) : 1;
    };
    eventMixin(Line);
    Line.prototype.lineNo = function() { return lineNo(this); };
  
    // Change the content (text, markers) of a line. Automatically
    // invalidates cached information and tries to re-estimate the
    // line's height.
    function updateLine(line, text, markedSpans, estimateHeight) {
      line.text = text;
      if (line.stateAfter) line.stateAfter = null;
      if (line.styles) line.styles = null;
      if (line.order != null) line.order = null;
      detachMarkedSpans(line);
      attachMarkedSpans(line, markedSpans);
      var estHeight = estimateHeight ? estimateHeight(line) : 1;
      if (estHeight != line.height) updateLineHeight(line, estHeight);
    }
  
    // Detach a line from the document tree and its markers.
    function cleanUpLine(line) {
      line.parent = null;
      detachMarkedSpans(line);
    }
  
    function extractLineClasses(type, output) {
      if (type) for (;;) {
        var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
        if (!lineClass) break;
        type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
        var prop = lineClass[1] ? "bgClass" : "textClass";
        if (output[prop] == null)
          output[prop] = lineClass[2];
        else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
          output[prop] += " " + lineClass[2];
      }
      return type;
    }
  
    function callBlankLine(mode, state) {
      if (mode.blankLine) return mode.blankLine(state);
      if (!mode.innerMode) return;
      var inner = CodeMirror.innerMode(mode, state);
      if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
    }
  
    function readToken(mode, stream, state, inner) {
      for (var i = 0; i &lt; 10; i++) {
        if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
        var style = mode.token(stream, state);
        if (stream.pos &gt; stream.start) return style;
      }
      throw new Error("Mode " + mode.name + " failed to advance stream.");
    }
  
    // Utility for getTokenAt and getLineTokens
    function takeToken(cm, pos, precise, asArray) {
      function getObj(copy) {
        return {start: stream.start, end: stream.pos,
                string: stream.current(),
                type: style || null,
                state: copy ? copyState(doc.mode, state) : state};
      }
  
      var doc = cm.doc, mode = doc.mode, style;
      pos = clipPos(doc, pos);
      var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
      var stream = new StringStream(line.text, cm.options.tabSize), tokens;
      if (asArray) tokens = [];
      while ((asArray || stream.pos &lt; pos.ch) &amp;&amp; !stream.eol()) {
        stream.start = stream.pos;
        style = readToken(mode, stream, state);
        if (asArray) tokens.push(getObj(true));
      }
      return asArray ? tokens : getObj();
    }
  
    // Run the given mode's parser over a line, calling f for each token.
    function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
      var flattenSpans = mode.flattenSpans;
      if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
      var curStart = 0, curStyle = null;
      var stream = new StringStream(text, cm.options.tabSize), style;
      var inner = cm.options.addModeClass &amp;&amp; [null];
      if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
      while (!stream.eol()) {
        if (stream.pos &gt; cm.options.maxHighlightLength) {
          flattenSpans = false;
          if (forceToEnd) processLine(cm, text, state, stream.pos);
          stream.pos = text.length;
          style = null;
        } else {
          style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
        }
        if (inner) {
          var mName = inner[0].name;
          if (mName) style = "m-" + (style ? mName + " " + style : mName);
        }
        if (!flattenSpans || curStyle != style) {
          while (curStart &lt; stream.start) {
            curStart = Math.min(stream.start, curStart + 50000);
            f(curStart, curStyle);
          }
          curStyle = style;
        }
        stream.start = stream.pos;
      }
      while (curStart &lt; stream.pos) {
        // Webkit seems to refuse to render text nodes longer than 57444 characters
        var pos = Math.min(stream.pos, curStart + 50000);
        f(pos, curStyle);
        curStart = pos;
      }
    }
  
    // Compute a style array (an array starting with a mode generation
    // -- for invalidation -- followed by pairs of end positions and
    // style strings), which is used to highlight the tokens on the
    // line.
    function highlightLine(cm, line, state, forceToEnd) {
      // A styles array always starts with a number identifying the
      // mode/overlays that it is based on (for easy invalidation).
      var st = [cm.state.modeGen], lineClasses = {};
      // Compute the base array of styles
      runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
        st.push(end, style);
      }, lineClasses, forceToEnd);
  
      // Run overlays, adjust style array.
      for (var o = 0; o &lt; cm.state.overlays.length; ++o) {
        var overlay = cm.state.overlays[o], i = 1, at = 0;
        runMode(cm, line.text, overlay.mode, true, function(end, style) {
          var start = i;
          // Ensure there's a token end at the current position, and that i points at it
          while (at &lt; end) {
            var i_end = st[i];
            if (i_end &gt; end)
              st.splice(i, 1, end, st[i+1], i_end);
            i += 2;
            at = Math.min(end, i_end);
          }
          if (!style) return;
          if (overlay.opaque) {
            st.splice(start, i - start, end, "cm-overlay " + style);
            i = start + 2;
          } else {
            for (; start &lt; i; start += 2) {
              var cur = st[start+1];
              st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
            }
          }
        }, lineClasses);
      }
  
      return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
    }
  
    function getLineStyles(cm, line, updateFrontier) {
      if (!line.styles || line.styles[0] != cm.state.modeGen) {
        var state = getStateBefore(cm, lineNo(line));
        var result = highlightLine(cm, line, line.text.length &gt; cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
        line.stateAfter = state;
        line.styles = result.styles;
        if (result.classes) line.styleClasses = result.classes;
        else if (line.styleClasses) line.styleClasses = null;
        if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
      }
      return line.styles;
    }
  
    // Lightweight form of highlight -- proceed over this line and
    // update state, but don't save a style array. Used for lines that
    // aren't currently visible.
    function processLine(cm, text, state, startAt) {
      var mode = cm.doc.mode;
      var stream = new StringStream(text, cm.options.tabSize);
      stream.start = stream.pos = startAt || 0;
      if (text == "") callBlankLine(mode, state);
      while (!stream.eol()) {
        readToken(mode, stream, state);
        stream.start = stream.pos;
      }
    }
  
    // Convert a style as returned by a mode (either null, or a string
    // containing one or more styles) to a CSS style. This is cached,
    // and also looks for line-wide styles.
    var styleToClassCache = {}, styleToClassCacheWithMode = {};
    function interpretTokenStyle(style, options) {
      if (!style || /^\s*$/.test(style)) return null;
      var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
      return cache[style] ||
        (cache[style] = style.replace(/\S+/g, "cm-$&amp;"));
    }
  
    // Render the DOM representation of the text of a line. Also builds
    // up a 'line map', which points at the DOM nodes that represent
    // specific stretches of text, and is used by the measuring code.
    // The returned object contains the DOM node, this map, and
    // information about line-wide styles that were set by the mode.
    function buildLineContent(cm, lineView) {
      // The padding-right forces the element to have a 'border', which
      // is needed on Webkit to be able to get line-level bounding
      // rectangles for it (in measureChar).
      var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
      var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
                     col: 0, pos: 0, cm: cm,
                     splitSpaces: (ie || webkit) &amp;&amp; cm.getOption("lineWrapping")};
      lineView.measure = {};
  
      // Iterate over the logical lines that make up this visual line.
      for (var i = 0; i &lt;= (lineView.rest ? lineView.rest.length : 0); i++) {
        var line = i ? lineView.rest[i - 1] : lineView.line, order;
        builder.pos = 0;
        builder.addToken = buildToken;
        // Optionally wire in some hacks into the token-rendering
        // algorithm, to deal with browser quirks.
        if (hasBadBidiRects(cm.display.measure) &amp;&amp; (order = getOrder(line)))
          builder.addToken = buildTokenBadBidi(builder.addToken, order);
        builder.map = [];
        var allowFrontierUpdate = lineView != cm.display.externalMeasured &amp;&amp; lineNo(line);
        insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
        if (line.styleClasses) {
          if (line.styleClasses.bgClass)
            builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
          if (line.styleClasses.textClass)
            builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
        }
  
        // Ensure at least a single node is present, for measuring.
        if (builder.map.length == 0)
          builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  
        // Store the map and a cache object for the current logical line
        if (i == 0) {
          lineView.measure.map = builder.map;
          lineView.measure.cache = {};
        } else {
          (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
          (lineView.measure.caches || (lineView.measure.caches = [])).push({});
        }
      }
  
      // See issue #2901
      if (webkit) {
        var last = builder.content.lastChild
        if (/\bcm-tab\b/.test(last.className) || (last.querySelector &amp;&amp; last.querySelector(".cm-tab")))
          builder.content.className = "cm-tab-wrap-hack";
      }
  
      signal(cm, "renderLine", cm, lineView.line, builder.pre);
      if (builder.pre.className)
        builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  
      return builder;
    }
  
    function defaultSpecialCharPlaceholder(ch) {
      var token = elt("span", "\u2022", "cm-invalidchar");
      token.title = "\\u" + ch.charCodeAt(0).toString(16);
      token.setAttribute("aria-label", token.title);
      return token;
    }
  
    // Build up the DOM representation for a single token, and add it to
    // the line map. Takes care to render special characters separately.
    function buildToken(builder, text, style, startStyle, endStyle, title, css) {
      if (!text) return;
      var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
      var special = builder.cm.state.specialChars, mustWrap = false;
      if (!special.test(text)) {
        builder.col += text.length;
        var content = document.createTextNode(displayText);
        builder.map.push(builder.pos, builder.pos + text.length, content);
        if (ie &amp;&amp; ie_version &lt; 9) mustWrap = true;
        builder.pos += text.length;
      } else {
        var content = document.createDocumentFragment(), pos = 0;
        while (true) {
          special.lastIndex = pos;
          var m = special.exec(text);
          var skipped = m ? m.index - pos : text.length - pos;
          if (skipped) {
            var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
            if (ie &amp;&amp; ie_version &lt; 9) content.appendChild(elt("span", [txt]));
            else content.appendChild(txt);
            builder.map.push(builder.pos, builder.pos + skipped, txt);
            builder.col += skipped;
            builder.pos += skipped;
          }
          if (!m) break;
          pos += skipped + 1;
          if (m[0] == "\t") {
            var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
            var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
            txt.setAttribute("role", "presentation");
            txt.setAttribute("cm-text", "\t");
            builder.col += tabWidth;
          } else if (m[0] == "\r" || m[0] == "\n") {
            var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
            txt.setAttribute("cm-text", m[0]);
            builder.col += 1;
          } else {
            var txt = builder.cm.options.specialCharPlaceholder(m[0]);
            txt.setAttribute("cm-text", m[0]);
            if (ie &amp;&amp; ie_version &lt; 9) content.appendChild(elt("span", [txt]));
            else content.appendChild(txt);
            builder.col += 1;
          }
          builder.map.push(builder.pos, builder.pos + 1, txt);
          builder.pos++;
        }
      }
      if (style || startStyle || endStyle || mustWrap || css) {
        var fullStyle = style || "";
        if (startStyle) fullStyle += startStyle;
        if (endStyle) fullStyle += endStyle;
        var token = elt("span", [content], fullStyle, css);
        if (title) token.title = title;
        return builder.content.appendChild(token);
      }
      builder.content.appendChild(content);
    }
  
    function splitSpaces(old) {
      var out = " ";
      for (var i = 0; i &lt; old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
      out += " ";
      return out;
    }
  
    // Work around nonsense dimensions being reported for stretches of
    // right-to-left text.
    function buildTokenBadBidi(inner, order) {
      return function(builder, text, style, startStyle, endStyle, title, css) {
        style = style ? style + " cm-force-border" : "cm-force-border";
        var start = builder.pos, end = start + text.length;
        for (;;) {
          // Find the part that overlaps with the start of this text
          for (var i = 0; i &lt; order.length; i++) {
            var part = order[i];
            if (part.to &gt; start &amp;&amp; part.from &lt;= start) break;
          }
          if (part.to &gt;= end) return inner(builder, text, style, startStyle, endStyle, title, css);
          inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
          startStyle = null;
          text = text.slice(part.to - start);
          start = part.to;
        }
      };
    }
  
    function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
      var widget = !ignoreWidget &amp;&amp; marker.widgetNode;
      if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
      if (!ignoreWidget &amp;&amp; builder.cm.display.input.needsContentAttribute) {
        if (!widget)
          widget = builder.content.appendChild(document.createElement("span"));
        widget.setAttribute("cm-marker", marker.id);
      }
      if (widget) {
        builder.cm.display.input.setUneditable(widget);
        builder.content.appendChild(widget);
      }
      builder.pos += size;
    }
  
    // Outputs a number of spans to make up a line, taking highlighting
    // and marked text into account.
    function insertLineContent(line, builder, styles) {
      var spans = line.markedSpans, allText = line.text, at = 0;
      if (!spans) {
        for (var i = 1; i &lt; styles.length; i+=2)
          builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
        return;
      }
  
      var len = allText.length, pos = 0, i = 1, text = "", style, css;
      var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
      for (;;) {
        if (nextChange == pos) { // Update current marker set
          spanStyle = spanEndStyle = spanStartStyle = title = css = "";
          collapsed = null; nextChange = Infinity;
          var foundBookmarks = [], endStyles
          for (var j = 0; j &lt; spans.length; ++j) {
            var sp = spans[j], m = sp.marker;
            if (m.type == "bookmark" &amp;&amp; sp.from == pos &amp;&amp; m.widgetNode) {
              foundBookmarks.push(m);
            } else if (sp.from &lt;= pos &amp;&amp; (sp.to == null || sp.to &gt; pos || m.collapsed &amp;&amp; sp.to == pos &amp;&amp; sp.from == pos)) {
              if (sp.to != null &amp;&amp; sp.to != pos &amp;&amp; nextChange &gt; sp.to) {
                nextChange = sp.to;
                spanEndStyle = "";
              }
              if (m.className) spanStyle += " " + m.className;
              if (m.css) css = (css ? css + ";" : "") + m.css;
              if (m.startStyle &amp;&amp; sp.from == pos) spanStartStyle += " " + m.startStyle;
              if (m.endStyle &amp;&amp; sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
              if (m.title &amp;&amp; !title) title = m.title;
              if (m.collapsed &amp;&amp; (!collapsed || compareCollapsedMarkers(collapsed.marker, m) &lt; 0))
                collapsed = sp;
            } else if (sp.from &gt; pos &amp;&amp; nextChange &gt; sp.from) {
              nextChange = sp.from;
            }
          }
          if (endStyles) for (var j = 0; j &lt; endStyles.length; j += 2)
            if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  
          if (!collapsed || collapsed.from == pos) for (var j = 0; j &lt; foundBookmarks.length; ++j)
            buildCollapsedSpan(builder, 0, foundBookmarks[j]);
          if (collapsed &amp;&amp; (collapsed.from || 0) == pos) {
            buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
                               collapsed.marker, collapsed.from == null);
            if (collapsed.to == null) return;
            if (collapsed.to == pos) collapsed = false;
          }
        }
        if (pos &gt;= len) break;
  
        var upto = Math.min(len, nextChange);
        while (true) {
          if (text) {
            var end = pos + text.length;
            if (!collapsed) {
              var tokenText = end &gt; upto ? text.slice(0, upto - pos) : text;
              builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
                               spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
            }
            if (end &gt;= upto) {text = text.slice(upto - pos); pos = upto; break;}
            pos = end;
            spanStartStyle = "";
          }
          text = allText.slice(at, at = styles[i++]);
          style = interpretTokenStyle(styles[i++], builder.cm.options);
        }
      }
    }
  
    // DOCUMENT DATA STRUCTURE
  
    // By default, updates that start and end at the beginning of a line
    // are treated specially, in order to make the association of line
    // widgets and marker elements with the text behave more intuitive.
    function isWholeLineUpdate(doc, change) {
      return change.from.ch == 0 &amp;&amp; change.to.ch == 0 &amp;&amp; lst(change.text) == "" &amp;&amp;
        (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
    }
  
    // Perform a change on the document data structure.
    function updateDoc(doc, change, markedSpans, estimateHeight) {
      function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
      function update(line, text, spans) {
        updateLine(line, text, spans, estimateHeight);
        signalLater(line, "change", line, change);
      }
      function linesFor(start, end) {
        for (var i = start, result = []; i &lt; end; ++i)
          result.push(new Line(text[i], spansFor(i), estimateHeight));
        return result;
      }
  
      var from = change.from, to = change.to, text = change.text;
      var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
      var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  
      // Adjust the line structure
      if (change.full) {
        doc.insert(0, linesFor(0, text.length));
        doc.remove(text.length, doc.size - text.length);
      } else if (isWholeLineUpdate(doc, change)) {
        // This is a whole-line replace. Treated specially to make
        // sure line objects move the way they are supposed to.
        var added = linesFor(0, text.length - 1);
        update(lastLine, lastLine.text, lastSpans);
        if (nlines) doc.remove(from.line, nlines);
        if (added.length) doc.insert(from.line, added);
      } else if (firstLine == lastLine) {
        if (text.length == 1) {
          update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
        } else {
          var added = linesFor(1, text.length - 1);
          added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
          update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
          doc.insert(from.line + 1, added);
        }
      } else if (text.length == 1) {
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
        doc.remove(from.line + 1, nlines);
      } else {
        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
        update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
        var added = linesFor(1, text.length - 1);
        if (nlines &gt; 1) doc.remove(from.line + 1, nlines - 1);
        doc.insert(from.line + 1, added);
      }
  
      signalLater(doc, "change", doc, change);
    }
  
    // The document is represented as a BTree consisting of leaves, with
    // chunk of lines in them, and branches, with up to ten leaves or
    // other branch nodes below them. The top node is always a branch
    // node, and is the document object itself (meaning it has
    // additional methods and properties).
    //
    // All nodes have parent links. The tree is used both to go from
    // line numbers to line objects, and to go from objects to numbers.
    // It also indexes by height, and is used to convert between height
    // and line object, and to find the total height of the document.
    //
    // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  
    function LeafChunk(lines) {
      this.lines = lines;
      this.parent = null;
      for (var i = 0, height = 0; i &lt; lines.length; ++i) {
        lines[i].parent = this;
        height += lines[i].height;
      }
      this.height = height;
    }
  
    LeafChunk.prototype = {
      chunkSize: function() { return this.lines.length; },
      // Remove the n lines at offset 'at'.
      removeInner: function(at, n) {
        for (var i = at, e = at + n; i &lt; e; ++i) {
          var line = this.lines[i];
          this.height -= line.height;
          cleanUpLine(line);
          signalLater(line, "delete");
        }
        this.lines.splice(at, n);
      },
      // Helper used to collapse a small branch into a single leaf.
      collapse: function(lines) {
        lines.push.apply(lines, this.lines);
      },
      // Insert the given array of lines at offset 'at', count them as
      // having the given height.
      insertInner: function(at, lines, height) {
        this.height += height;
        this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
        for (var i = 0; i &lt; lines.length; ++i) lines[i].parent = this;
      },
      // Used to iterate over a part of the tree.
      iterN: function(at, n, op) {
        for (var e = at + n; at &lt; e; ++at)
          if (op(this.lines[at])) return true;
      }
    };
  
    function BranchChunk(children) {
      this.children = children;
      var size = 0, height = 0;
      for (var i = 0; i &lt; children.length; ++i) {
        var ch = children[i];
        size += ch.chunkSize(); height += ch.height;
        ch.parent = this;
      }
      this.size = size;
      this.height = height;
      this.parent = null;
    }
  
    BranchChunk.prototype = {
      chunkSize: function() { return this.size; },
      removeInner: function(at, n) {
        this.size -= n;
        for (var i = 0; i &lt; this.children.length; ++i) {
          var child = this.children[i], sz = child.chunkSize();
          if (at &lt; sz) {
            var rm = Math.min(n, sz - at), oldHeight = child.height;
            child.removeInner(at, rm);
            this.height -= oldHeight - child.height;
            if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
            if ((n -= rm) == 0) break;
            at = 0;
          } else at -= sz;
        }
        // If the result is smaller than 25 lines, ensure that it is a
        // single leaf node.
        if (this.size - n &lt; 25 &amp;&amp;
            (this.children.length &gt; 1 || !(this.children[0] instanceof LeafChunk))) {
          var lines = [];
          this.collapse(lines);
          this.children = [new LeafChunk(lines)];
          this.children[0].parent = this;
        }
      },
      collapse: function(lines) {
        for (var i = 0; i &lt; this.children.length; ++i) this.children[i].collapse(lines);
      },
      insertInner: function(at, lines, height) {
        this.size += lines.length;
        this.height += height;
        for (var i = 0; i &lt; this.children.length; ++i) {
          var child = this.children[i], sz = child.chunkSize();
          if (at &lt;= sz) {
            child.insertInner(at, lines, height);
            if (child.lines &amp;&amp; child.lines.length &gt; 50) {
              // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
              // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
              var remaining = child.lines.length % 25 + 25
              for (var pos = remaining; pos &lt; child.lines.length;) {
                var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
                child.height -= leaf.height;
                this.children.splice(++i, 0, leaf);
                leaf.parent = this;
              }
              child.lines = child.lines.slice(0, remaining);
              this.maybeSpill();
            }
            break;
          }
          at -= sz;
        }
      },
      // When a node has grown, check whether it should be split.
      maybeSpill: function() {
        if (this.children.length &lt;= 10) return;
        var me = this;
        do {
          var spilled = me.children.splice(me.children.length - 5, 5);
          var sibling = new BranchChunk(spilled);
          if (!me.parent) { // Become the parent node
            var copy = new BranchChunk(me.children);
            copy.parent = me;
            me.children = [copy, sibling];
            me = copy;
         } else {
            me.size -= sibling.size;
            me.height -= sibling.height;
            var myIndex = indexOf(me.parent.children, me);
            me.parent.children.splice(myIndex + 1, 0, sibling);
          }
          sibling.parent = me.parent;
        } while (me.children.length &gt; 10);
        me.parent.maybeSpill();
      },
      iterN: function(at, n, op) {
        for (var i = 0; i &lt; this.children.length; ++i) {
          var child = this.children[i], sz = child.chunkSize();
          if (at &lt; sz) {
            var used = Math.min(n, sz - at);
            if (child.iterN(at, used, op)) return true;
            if ((n -= used) == 0) break;
            at = 0;
          } else at -= sz;
        }
      }
    };
  
    var nextDocId = 0;
    var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
      if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
      if (firstLine == null) firstLine = 0;
  
      BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
      this.first = firstLine;
      this.scrollTop = this.scrollLeft = 0;
      this.cantEdit = false;
      this.cleanGeneration = 1;
      this.frontier = firstLine;
      var start = Pos(firstLine, 0);
      this.sel = simpleSelection(start);
      this.history = new History(null);
      this.id = ++nextDocId;
      this.modeOption = mode;
      this.lineSep = lineSep;
      this.extend = false;
  
      if (typeof text == "string") text = this.splitLines(text);
      updateDoc(this, {from: start, to: start, text: text});
      setSelection(this, simpleSelection(start), sel_dontScroll);
    };
  
    Doc.prototype = createObj(BranchChunk.prototype, {
      constructor: Doc,
      // Iterate over the document. Supports two forms -- with only one
      // argument, it calls that for each line in the document. With
      // three, it iterates over the range given by the first two (with
      // the second being non-inclusive).
      iter: function(from, to, op) {
        if (op) this.iterN(from - this.first, to - from, op);
        else this.iterN(this.first, this.first + this.size, from);
      },
  
      // Non-public interface for adding and removing lines.
      insert: function(at, lines) {
        var height = 0;
        for (var i = 0; i &lt; lines.length; ++i) height += lines[i].height;
        this.insertInner(at - this.first, lines, height);
      },
      remove: function(at, n) { this.removeInner(at - this.first, n); },
  
      // From here, the methods are part of the public interface. Most
      // are also available from CodeMirror (editor) instances.
  
      getValue: function(lineSep) {
        var lines = getLines(this, this.first, this.first + this.size);
        if (lineSep === false) return lines;
        return lines.join(lineSep || this.lineSeparator());
      },
      setValue: docMethodOp(function(code) {
        var top = Pos(this.first, 0), last = this.first + this.size - 1;
        makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
                          text: this.splitLines(code), origin: "setValue", full: true}, true);
        setSelection(this, simpleSelection(top));
      }),
      replaceRange: function(code, from, to, origin) {
        from = clipPos(this, from);
        to = to ? clipPos(this, to) : from;
        replaceRange(this, code, from, to, origin);
      },
      getRange: function(from, to, lineSep) {
        var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
        if (lineSep === false) return lines;
        return lines.join(lineSep || this.lineSeparator());
      },
  
      getLine: function(line) {var l = this.getLineHandle(line); return l &amp;&amp; l.text;},
  
      getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
      getLineNumber: function(line) {return lineNo(line);},
  
      getLineHandleVisualStart: function(line) {
        if (typeof line == "number") line = getLine(this, line);
        return visualLine(line);
      },
  
      lineCount: function() {return this.size;},
      firstLine: function() {return this.first;},
      lastLine: function() {return this.first + this.size - 1;},
  
      clipPos: function(pos) {return clipPos(this, pos);},
  
      getCursor: function(start) {
        var range = this.sel.primary(), pos;
        if (start == null || start == "head") pos = range.head;
        else if (start == "anchor") pos = range.anchor;
        else if (start == "end" || start == "to" || start === false) pos = range.to();
        else pos = range.from();
        return pos;
      },
      listSelections: function() { return this.sel.ranges; },
      somethingSelected: function() {return this.sel.somethingSelected();},
  
      setCursor: docMethodOp(function(line, ch, options) {
        setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
      }),
      setSelection: docMethodOp(function(anchor, head, options) {
        setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
      }),
      extendSelection: docMethodOp(function(head, other, options) {
        extendSelection(this, clipPos(this, head), other &amp;&amp; clipPos(this, other), options);
      }),
      extendSelections: docMethodOp(function(heads, options) {
        extendSelections(this, clipPosArray(this, heads), options);
      }),
      extendSelectionsBy: docMethodOp(function(f, options) {
        var heads = map(this.sel.ranges, f);
        extendSelections(this, clipPosArray(this, heads), options);
      }),
      setSelections: docMethodOp(function(ranges, primary, options) {
        if (!ranges.length) return;
        for (var i = 0, out = []; i &lt; ranges.length; i++)
          out[i] = new Range(clipPos(this, ranges[i].anchor),
                             clipPos(this, ranges[i].head));
        if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
        setSelection(this, normalizeSelection(out, primary), options);
      }),
      addSelection: docMethodOp(function(anchor, head, options) {
        var ranges = this.sel.ranges.slice(0);
        ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
        setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
      }),
  
      getSelection: function(lineSep) {
        var ranges = this.sel.ranges, lines;
        for (var i = 0; i &lt; ranges.length; i++) {
          var sel = getBetween(this, ranges[i].from(), ranges[i].to());
          lines = lines ? lines.concat(sel) : sel;
        }
        if (lineSep === false) return lines;
        else return lines.join(lineSep || this.lineSeparator());
      },
      getSelections: function(lineSep) {
        var parts = [], ranges = this.sel.ranges;
        for (var i = 0; i &lt; ranges.length; i++) {
          var sel = getBetween(this, ranges[i].from(), ranges[i].to());
          if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
          parts[i] = sel;
        }
        return parts;
      },
      replaceSelection: function(code, collapse, origin) {
        var dup = [];
        for (var i = 0; i &lt; this.sel.ranges.length; i++)
          dup[i] = code;
        this.replaceSelections(dup, collapse, origin || "+input");
      },
      replaceSelections: docMethodOp(function(code, collapse, origin) {
        var changes = [], sel = this.sel;
        for (var i = 0; i &lt; sel.ranges.length; i++) {
          var range = sel.ranges[i];
          changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
        }
        var newSel = collapse &amp;&amp; collapse != "end" &amp;&amp; computeReplacedSel(this, changes, collapse);
        for (var i = changes.length - 1; i &gt;= 0; i--)
          makeChange(this, changes[i]);
        if (newSel) setSelectionReplaceHistory(this, newSel);
        else if (this.cm) ensureCursorVisible(this.cm);
      }),
      undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
      redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
      undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
      redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  
      setExtending: function(val) {this.extend = val;},
      getExtending: function() {return this.extend;},
  
      historySize: function() {
        var hist = this.history, done = 0, undone = 0;
        for (var i = 0; i &lt; hist.done.length; i++) if (!hist.done[i].ranges) ++done;
        for (var i = 0; i &lt; hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
        return {undo: done, redo: undone};
      },
      clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  
      markClean: function() {
        this.cleanGeneration = this.changeGeneration(true);
      },
      changeGeneration: function(forceSplit) {
        if (forceSplit)
          this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
        return this.history.generation;
      },
      isClean: function (gen) {
        return this.history.generation == (gen || this.cleanGeneration);
      },
  
      getHistory: function() {
        return {done: copyHistoryArray(this.history.done),
                undone: copyHistoryArray(this.history.undone)};
      },
      setHistory: function(histData) {
        var hist = this.history = new History(this.history.maxGeneration);
        hist.done = copyHistoryArray(histData.done.slice(0), null, true);
        hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
      },
  
      addLineClass: docMethodOp(function(handle, where, cls) {
        return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
          var prop = where == "text" ? "textClass"
                   : where == "background" ? "bgClass"
                   : where == "gutter" ? "gutterClass" : "wrapClass";
          if (!line[prop]) line[prop] = cls;
          else if (classTest(cls).test(line[prop])) return false;
          else line[prop] += " " + cls;
          return true;
        });
      }),
      removeLineClass: docMethodOp(function(handle, where, cls) {
        return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
          var prop = where == "text" ? "textClass"
                   : where == "background" ? "bgClass"
                   : where == "gutter" ? "gutterClass" : "wrapClass";
          var cur = line[prop];
          if (!cur) return false;
          else if (cls == null) line[prop] = null;
          else {
            var found = cur.match(classTest(cls));
            if (!found) return false;
            var end = found.index + found[0].length;
            line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
          }
          return true;
        });
      }),
  
      addLineWidget: docMethodOp(function(handle, node, options) {
        return addLineWidget(this, handle, node, options);
      }),
      removeLineWidget: function(widget) { widget.clear(); },
  
      markText: function(from, to, options) {
        return markText(this, clipPos(this, from), clipPos(this, to), options, options &amp;&amp; options.type || "range");
      },
      setBookmark: function(pos, options) {
        var realOpts = {replacedWith: options &amp;&amp; (options.nodeType == null ? options.widget : options),
                        insertLeft: options &amp;&amp; options.insertLeft,
                        clearWhenEmpty: false, shared: options &amp;&amp; options.shared,
                        handleMouseEvents: options &amp;&amp; options.handleMouseEvents};
        pos = clipPos(this, pos);
        return markText(this, pos, pos, realOpts, "bookmark");
      },
      findMarksAt: function(pos) {
        pos = clipPos(this, pos);
        var markers = [], spans = getLine(this, pos.line).markedSpans;
        if (spans) for (var i = 0; i &lt; spans.length; ++i) {
          var span = spans[i];
          if ((span.from == null || span.from &lt;= pos.ch) &amp;&amp;
              (span.to == null || span.to &gt;= pos.ch))
            markers.push(span.marker.parent || span.marker);
        }
        return markers;
      },
      findMarks: function(from, to, filter) {
        from = clipPos(this, from); to = clipPos(this, to);
        var found = [], lineNo = from.line;
        this.iter(from.line, to.line + 1, function(line) {
          var spans = line.markedSpans;
          if (spans) for (var i = 0; i &lt; spans.length; i++) {
            var span = spans[i];
            if (!(span.to != null &amp;&amp; lineNo == from.line &amp;&amp; from.ch &gt;= span.to ||
                  span.from == null &amp;&amp; lineNo != from.line ||
                  span.from != null &amp;&amp; lineNo == to.line &amp;&amp; span.from &gt;= to.ch) &amp;&amp;
                (!filter || filter(span.marker)))
              found.push(span.marker.parent || span.marker);
          }
          ++lineNo;
        });
        return found;
      },
      getAllMarks: function() {
        var markers = [];
        this.iter(function(line) {
          var sps = line.markedSpans;
          if (sps) for (var i = 0; i &lt; sps.length; ++i)
            if (sps[i].from != null) markers.push(sps[i].marker);
        });
        return markers;
      },
  
      posFromIndex: function(off) {
        var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
        this.iter(function(line) {
          var sz = line.text.length + sepSize;
          if (sz &gt; off) { ch = off; return true; }
          off -= sz;
          ++lineNo;
        });
        return clipPos(this, Pos(lineNo, ch));
      },
      indexFromPos: function (coords) {
        coords = clipPos(this, coords);
        var index = coords.ch;
        if (coords.line &lt; this.first || coords.ch &lt; 0) return 0;
        var sepSize = this.lineSeparator().length;
        this.iter(this.first, coords.line, function (line) {
          index += line.text.length + sepSize;
        });
        return index;
      },
  
      copy: function(copyHistory) {
        var doc = new Doc(getLines(this, this.first, this.first + this.size),
                          this.modeOption, this.first, this.lineSep);
        doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
        doc.sel = this.sel;
        doc.extend = false;
        if (copyHistory) {
          doc.history.undoDepth = this.history.undoDepth;
          doc.setHistory(this.getHistory());
        }
        return doc;
      },
  
      linkedDoc: function(options) {
        if (!options) options = {};
        var from = this.first, to = this.first + this.size;
        if (options.from != null &amp;&amp; options.from &gt; from) from = options.from;
        if (options.to != null &amp;&amp; options.to &lt; to) to = options.to;
        var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
        if (options.sharedHist) copy.history = this.history;
        (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
        copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
        copySharedMarkers(copy, findSharedMarkers(this));
        return copy;
      },
      unlinkDoc: function(other) {
        if (other instanceof CodeMirror) other = other.doc;
        if (this.linked) for (var i = 0; i &lt; this.linked.length; ++i) {
          var link = this.linked[i];
          if (link.doc != other) continue;
          this.linked.splice(i, 1);
          other.unlinkDoc(this);
          detachSharedMarkers(findSharedMarkers(this));
          break;
        }
        // If the histories were shared, split them again
        if (other.history == this.history) {
          var splitIds = [other.id];
          linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
          other.history = new History(null);
          other.history.done = copyHistoryArray(this.history.done, splitIds);
          other.history.undone = copyHistoryArray(this.history.undone, splitIds);
        }
      },
      iterLinkedDocs: function(f) {linkedDocs(this, f);},
  
      getMode: function() {return this.mode;},
      getEditor: function() {return this.cm;},
  
      splitLines: function(str) {
        if (this.lineSep) return str.split(this.lineSep);
        return splitLinesAuto(str);
      },
      lineSeparator: function() { return this.lineSep || "\n"; }
    });
  
    // Public alias.
    Doc.prototype.eachLine = Doc.prototype.iter;
  
    // Set up methods on CodeMirror's prototype to redirect to the editor's document.
    var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
    for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) &amp;&amp; indexOf(dontDelegate, prop) &lt; 0)
      CodeMirror.prototype[prop] = (function(method) {
        return function() {return method.apply(this.doc, arguments);};
      })(Doc.prototype[prop]);
  
    eventMixin(Doc);
  
    // Call f for all linked documents.
    function linkedDocs(doc, f, sharedHistOnly) {
      function propagate(doc, skip, sharedHist) {
        if (doc.linked) for (var i = 0; i &lt; doc.linked.length; ++i) {
          var rel = doc.linked[i];
          if (rel.doc == skip) continue;
          var shared = sharedHist &amp;&amp; rel.sharedHist;
          if (sharedHistOnly &amp;&amp; !shared) continue;
          f(rel.doc, shared);
          propagate(rel.doc, doc, shared);
        }
      }
      propagate(doc, null, true);
    }
  
    // Attach a document to an editor.
    function attachDoc(cm, doc) {
      if (doc.cm) throw new Error("This document is already in use.");
      cm.doc = doc;
      doc.cm = cm;
      estimateLineHeights(cm);
      loadMode(cm);
      if (!cm.options.lineWrapping) findMaxLine(cm);
      cm.options.mode = doc.modeOption;
      regChange(cm);
    }
  
    // LINE UTILITIES
  
    // Find the line object corresponding to the given line number.
    function getLine(doc, n) {
      n -= doc.first;
      if (n &lt; 0 || n &gt;= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
      for (var chunk = doc; !chunk.lines;) {
        for (var i = 0;; ++i) {
          var child = chunk.children[i], sz = child.chunkSize();
          if (n &lt; sz) { chunk = child; break; }
          n -= sz;
        }
      }
      return chunk.lines[n];
    }
  
    // Get the part of a document between two positions, as an array of
    // strings.
    function getBetween(doc, start, end) {
      var out = [], n = start.line;
      doc.iter(start.line, end.line + 1, function(line) {
        var text = line.text;
        if (n == end.line) text = text.slice(0, end.ch);
        if (n == start.line) text = text.slice(start.ch);
        out.push(text);
        ++n;
      });
      return out;
    }
    // Get the lines between from and to, as array of strings.
    function getLines(doc, from, to) {
      var out = [];
      doc.iter(from, to, function(line) { out.push(line.text); });
      return out;
    }
  
    // Update the height of a line, propagating the height change
    // upwards to parent nodes.
    function updateLineHeight(line, height) {
      var diff = height - line.height;
      if (diff) for (var n = line; n; n = n.parent) n.height += diff;
    }
  
    // Given a line object, find its line number by walking up through
    // its parent links.
    function lineNo(line) {
      if (line.parent == null) return null;
      var cur = line.parent, no = indexOf(cur.lines, line);
      for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
        for (var i = 0;; ++i) {
          if (chunk.children[i] == cur) break;
          no += chunk.children[i].chunkSize();
        }
      }
      return no + cur.first;
    }
  
    // Find the line at the given vertical position, using the height
    // information in the document tree.
    function lineAtHeight(chunk, h) {
      var n = chunk.first;
      outer: do {
        for (var i = 0; i &lt; chunk.children.length; ++i) {
          var child = chunk.children[i], ch = child.height;
          if (h &lt; ch) { chunk = child; continue outer; }
          h -= ch;
          n += child.chunkSize();
        }
        return n;
      } while (!chunk.lines);
      for (var i = 0; i &lt; chunk.lines.length; ++i) {
        var line = chunk.lines[i], lh = line.height;
        if (h &lt; lh) break;
        h -= lh;
      }
      return n + i;
    }
  
  
    // Find the height above the given line.
    function heightAtLine(lineObj) {
      lineObj = visualLine(lineObj);
  
      var h = 0, chunk = lineObj.parent;
      for (var i = 0; i &lt; chunk.lines.length; ++i) {
        var line = chunk.lines[i];
        if (line == lineObj) break;
        else h += line.height;
      }
      for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
        for (var i = 0; i &lt; p.children.length; ++i) {
          var cur = p.children[i];
          if (cur == chunk) break;
          else h += cur.height;
        }
      }
      return h;
    }
  
    // Get the bidi ordering for the given line (and cache it). Returns
    // false for lines that are fully left-to-right, and an array of
    // BidiSpan objects otherwise.
    function getOrder(line) {
      var order = line.order;
      if (order == null) order = line.order = bidiOrdering(line.text);
      return order;
    }
  
    // HISTORY
  
    function History(startGen) {
      // Arrays of change events and selections. Doing something adds an
      // event to done and clears undo. Undoing moves events from done
      // to undone, redoing moves them in the other direction.
      this.done = []; this.undone = [];
      this.undoDepth = Infinity;
      // Used to track when changes can be merged into a single undo
      // event
      this.lastModTime = this.lastSelTime = 0;
      this.lastOp = this.lastSelOp = null;
      this.lastOrigin = this.lastSelOrigin = null;
      // Used by the isClean() method
      this.generation = this.maxGeneration = startGen || 1;
    }
  
    // Create a history change event from an updateDoc-style change
    // object.
    function historyChangeFromChange(doc, change) {
      var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
      attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
      linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
      return histChange;
    }
  
    // Pop all selection events off the end of a history array. Stop at
    // a change event.
    function clearSelectionEvents(array) {
      while (array.length) {
        var last = lst(array);
        if (last.ranges) array.pop();
        else break;
      }
    }
  
    // Find the top change event in the history. Pop off selection
    // events that are in the way.
    function lastChangeEvent(hist, force) {
      if (force) {
        clearSelectionEvents(hist.done);
        return lst(hist.done);
      } else if (hist.done.length &amp;&amp; !lst(hist.done).ranges) {
        return lst(hist.done);
      } else if (hist.done.length &gt; 1 &amp;&amp; !hist.done[hist.done.length - 2].ranges) {
        hist.done.pop();
        return lst(hist.done);
      }
    }
  
    // Register a change in the history. Merges changes that are within
    // a single operation, ore are close together with an origin that
    // allows merging (starting with "+") into a single event.
    function addChangeToHistory(doc, change, selAfter, opId) {
      var hist = doc.history;
      hist.undone.length = 0;
      var time = +new Date, cur;
  
      if ((hist.lastOp == opId ||
           hist.lastOrigin == change.origin &amp;&amp; change.origin &amp;&amp;
           ((change.origin.charAt(0) == "+" &amp;&amp; doc.cm &amp;&amp; hist.lastModTime &gt; time - doc.cm.options.historyEventDelay) ||
            change.origin.charAt(0) == "*")) &amp;&amp;
          (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
        // Merge this change into the last event
        var last = lst(cur.changes);
        if (cmp(change.from, change.to) == 0 &amp;&amp; cmp(change.from, last.to) == 0) {
          // Optimized case for simple insertion -- don't want to add
          // new changesets for every character typed
          last.to = changeEnd(change);
        } else {
          // Add new sub-event
          cur.changes.push(historyChangeFromChange(doc, change));
        }
      } else {
        // Can not be merged, start a new event.
        var before = lst(hist.done);
        if (!before || !before.ranges)
          pushSelectionToHistory(doc.sel, hist.done);
        cur = {changes: [historyChangeFromChange(doc, change)],
               generation: hist.generation};
        hist.done.push(cur);
        while (hist.done.length &gt; hist.undoDepth) {
          hist.done.shift();
          if (!hist.done[0].ranges) hist.done.shift();
        }
      }
      hist.done.push(selAfter);
      hist.generation = ++hist.maxGeneration;
      hist.lastModTime = hist.lastSelTime = time;
      hist.lastOp = hist.lastSelOp = opId;
      hist.lastOrigin = hist.lastSelOrigin = change.origin;
  
      if (!last) signal(doc, "historyAdded");
    }
  
    function selectionEventCanBeMerged(doc, origin, prev, sel) {
      var ch = origin.charAt(0);
      return ch == "*" ||
        ch == "+" &amp;&amp;
        prev.ranges.length == sel.ranges.length &amp;&amp;
        prev.somethingSelected() == sel.somethingSelected() &amp;&amp;
        new Date - doc.history.lastSelTime &lt;= (doc.cm ? doc.cm.options.historyEventDelay : 500);
    }
  
    // Called whenever the selection changes, sets the new selection as
    // the pending selection in the history, and pushes the old pending
    // selection into the 'done' array when it was significantly
    // different (in number of selected ranges, emptiness, or time).
    function addSelectionToHistory(doc, sel, opId, options) {
      var hist = doc.history, origin = options &amp;&amp; options.origin;
  
      // A new event is started when the previous origin does not match
      // the current, or the origins don't allow matching. Origins
      // starting with * are always merged, those starting with + are
      // merged when similar and close together in time.
      if (opId == hist.lastSelOp ||
          (origin &amp;&amp; hist.lastSelOrigin == origin &amp;&amp;
           (hist.lastModTime == hist.lastSelTime &amp;&amp; hist.lastOrigin == origin ||
            selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
        hist.done[hist.done.length - 1] = sel;
      else
        pushSelectionToHistory(sel, hist.done);
  
      hist.lastSelTime = +new Date;
      hist.lastSelOrigin = origin;
      hist.lastSelOp = opId;
      if (options &amp;&amp; options.clearRedo !== false)
        clearSelectionEvents(hist.undone);
    }
  
    function pushSelectionToHistory(sel, dest) {
      var top = lst(dest);
      if (!(top &amp;&amp; top.ranges &amp;&amp; top.equals(sel)))
        dest.push(sel);
    }
  
    // Used to store marked span information in the history.
    function attachLocalSpans(doc, change, from, to) {
      var existing = change["spans_" + doc.id], n = 0;
      doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
        if (line.markedSpans)
          (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
        ++n;
      });
    }
  
    // When un/re-doing restores text containing marked spans, those
    // that have been explicitly cleared should not be restored.
    function removeClearedSpans(spans) {
      if (!spans) return null;
      for (var i = 0, out; i &lt; spans.length; ++i) {
        if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
        else if (out) out.push(spans[i]);
      }
      return !out ? spans : out.length ? out : null;
    }
  
    // Retrieve and filter the old marked spans stored in a change event.
    function getOldSpans(doc, change) {
      var found = change["spans_" + doc.id];
      if (!found) return null;
      for (var i = 0, nw = []; i &lt; change.text.length; ++i)
        nw.push(removeClearedSpans(found[i]));
      return nw;
    }
  
    // Used both to provide a JSON-safe object in .getHistory, and, when
    // detaching a document, to split the history in two
    function copyHistoryArray(events, newGroup, instantiateSel) {
      for (var i = 0, copy = []; i &lt; events.length; ++i) {
        var event = events[i];
        if (event.ranges) {
          copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
          continue;
        }
        var changes = event.changes, newChanges = [];
        copy.push({changes: newChanges});
        for (var j = 0; j &lt; changes.length; ++j) {
          var change = changes[j], m;
          newChanges.push({from: change.from, to: change.to, text: change.text});
          if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
            if (indexOf(newGroup, Number(m[1])) &gt; -1) {
              lst(newChanges)[prop] = change[prop];
              delete change[prop];
            }
          }
        }
      }
      return copy;
    }
  
    // Rebasing/resetting history to deal with externally-sourced changes
  
    function rebaseHistSelSingle(pos, from, to, diff) {
      if (to &lt; pos.line) {
        pos.line += diff;
      } else if (from &lt; pos.line) {
        pos.line = from;
        pos.ch = 0;
      }
    }
  
    // Tries to rebase an array of history events given a change in the
    // document. If the change touches the same lines as the event, the
    // event, and everything 'behind' it, is discarded. If the change is
    // before the event, the event's positions are updated. Uses a
    // copy-on-write scheme for the positions, to avoid having to
    // reallocate them all on every rebase, but also avoid problems with
    // shared position objects being unsafely updated.
    function rebaseHistArray(array, from, to, diff) {
      for (var i = 0; i &lt; array.length; ++i) {
        var sub = array[i], ok = true;
        if (sub.ranges) {
          if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
          for (var j = 0; j &lt; sub.ranges.length; j++) {
            rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
            rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
          }
          continue;
        }
        for (var j = 0; j &lt; sub.changes.length; ++j) {
          var cur = sub.changes[j];
          if (to &lt; cur.from.line) {
            cur.from = Pos(cur.from.line + diff, cur.from.ch);
            cur.to = Pos(cur.to.line + diff, cur.to.ch);
          } else if (from &lt;= cur.to.line) {
            ok = false;
            break;
          }
        }
        if (!ok) {
          array.splice(0, i + 1);
          i = 0;
        }
      }
    }
  
    function rebaseHist(hist, change) {
      var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
      rebaseHistArray(hist.done, from, to, diff);
      rebaseHistArray(hist.undone, from, to, diff);
    }
  
    // EVENT UTILITIES
  
    // Due to the fact that we still support jurassic IE versions, some
    // compatibility wrappers are needed.
  
    var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
      if (e.preventDefault) e.preventDefault();
      else e.returnValue = false;
    };
    var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
      if (e.stopPropagation) e.stopPropagation();
      else e.cancelBubble = true;
    };
    function e_defaultPrevented(e) {
      return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
    }
    var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  
    function e_target(e) {return e.target || e.srcElement;}
    function e_button(e) {
      var b = e.which;
      if (b == null) {
        if (e.button &amp; 1) b = 1;
        else if (e.button &amp; 2) b = 3;
        else if (e.button &amp; 4) b = 2;
      }
      if (mac &amp;&amp; e.ctrlKey &amp;&amp; b == 1) b = 3;
      return b;
    }
  
    // EVENT HANDLING
  
    // Lightweight event framework. on/off also work on DOM nodes,
    // registering native DOM handlers.
  
    var on = CodeMirror.on = function(emitter, type, f) {
      if (emitter.addEventListener)
        emitter.addEventListener(type, f, false);
      else if (emitter.attachEvent)
        emitter.attachEvent("on" + type, f);
      else {
        var map = emitter._handlers || (emitter._handlers = {});
        var arr = map[type] || (map[type] = []);
        arr.push(f);
      }
    };
  
    var noHandlers = []
    function getHandlers(emitter, type, copy) {
      var arr = emitter._handlers &amp;&amp; emitter._handlers[type]
      if (copy) return arr &amp;&amp; arr.length &gt; 0 ? arr.slice() : noHandlers
      else return arr || noHandlers
    }
  
    var off = CodeMirror.off = function(emitter, type, f) {
      if (emitter.removeEventListener)
        emitter.removeEventListener(type, f, false);
      else if (emitter.detachEvent)
        emitter.detachEvent("on" + type, f);
      else {
        var handlers = getHandlers(emitter, type, false)
        for (var i = 0; i &lt; handlers.length; ++i)
          if (handlers[i] == f) { handlers.splice(i, 1); break; }
      }
    };
  
    var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
      var handlers = getHandlers(emitter, type, true)
      if (!handlers.length) return;
      var args = Array.prototype.slice.call(arguments, 2);
      for (var i = 0; i &lt; handlers.length; ++i) handlers[i].apply(null, args);
    };
  
    var orphanDelayedCallbacks = null;
  
    // Often, we want to signal events at a point where we are in the
    // middle of some work, but don't want the handler to start calling
    // other methods on the editor, which might be in an inconsistent
    // state or simply not expect any other events to happen.
    // signalLater looks whether there are any handlers, and schedules
    // them to be executed when the last operation ends, or, if no
    // operation is active, when a timeout fires.
    function signalLater(emitter, type /*, values...*/) {
      var arr = getHandlers(emitter, type, false)
      if (!arr.length) return;
      var args = Array.prototype.slice.call(arguments, 2), list;
      if (operationGroup) {
        list = operationGroup.delayedCallbacks;
      } else if (orphanDelayedCallbacks) {
        list = orphanDelayedCallbacks;
      } else {
        list = orphanDelayedCallbacks = [];
        setTimeout(fireOrphanDelayed, 0);
      }
      function bnd(f) {return function(){f.apply(null, args);};};
      for (var i = 0; i &lt; arr.length; ++i)
        list.push(bnd(arr[i]));
    }
  
    function fireOrphanDelayed() {
      var delayed = orphanDelayedCallbacks;
      orphanDelayedCallbacks = null;
      for (var i = 0; i &lt; delayed.length; ++i) delayed[i]();
    }
  
    // The DOM events that CodeMirror handles can be overridden by
    // registering a (non-DOM) handler on the editor for the event name,
    // and preventDefault-ing the event in that handler.
    function signalDOMEvent(cm, e, override) {
      if (typeof e == "string")
        e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
      signal(cm, override || e.type, cm, e);
      return e_defaultPrevented(e) || e.codemirrorIgnore;
    }
  
    function signalCursorActivity(cm) {
      var arr = cm._handlers &amp;&amp; cm._handlers.cursorActivity;
      if (!arr) return;
      var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
      for (var i = 0; i &lt; arr.length; ++i) if (indexOf(set, arr[i]) == -1)
        set.push(arr[i]);
    }
  
    function hasHandler(emitter, type) {
      return getHandlers(emitter, type).length &gt; 0
    }
  
    // Add on and off methods to a constructor's prototype, to make
    // registering events on such objects more convenient.
    function eventMixin(ctor) {
      ctor.prototype.on = function(type, f) {on(this, type, f);};
      ctor.prototype.off = function(type, f) {off(this, type, f);};
    }
  
    // MISC UTILITIES
  
    // Number of pixels added to scroller and sizer to hide scrollbar
    var scrollerGap = 30;
  
    // Returned or thrown by various protocols to signal 'I'm not
    // handling this'.
    var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  
    // Reused option objects for setSelection &amp; friends
    var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  
    function Delayed() {this.id = null;}
    Delayed.prototype.set = function(ms, f) {
      clearTimeout(this.id);
      this.id = setTimeout(f, ms);
    };
  
    // Counts the column offset in a string, taking tabs into account.
    // Used mostly to find indentation.
    var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
      if (end == null) {
        end = string.search(/[^\s\u00a0]/);
        if (end == -1) end = string.length;
      }
      for (var i = startIndex || 0, n = startValue || 0;;) {
        var nextTab = string.indexOf("\t", i);
        if (nextTab &lt; 0 || nextTab &gt;= end)
          return n + (end - i);
        n += nextTab - i;
        n += tabSize - (n % tabSize);
        i = nextTab + 1;
      }
    };
  
    // The inverse of countColumn -- find the offset that corresponds to
    // a particular column.
    var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
      for (var pos = 0, col = 0;;) {
        var nextTab = string.indexOf("\t", pos);
        if (nextTab == -1) nextTab = string.length;
        var skipped = nextTab - pos;
        if (nextTab == string.length || col + skipped &gt;= goal)
          return pos + Math.min(skipped, goal - col);
        col += nextTab - pos;
        col += tabSize - (col % tabSize);
        pos = nextTab + 1;
        if (col &gt;= goal) return pos;
      }
    }
  
    var spaceStrs = [""];
    function spaceStr(n) {
      while (spaceStrs.length &lt;= n)
        spaceStrs.push(lst(spaceStrs) + " ");
      return spaceStrs[n];
    }
  
    function lst(arr) { return arr[arr.length-1]; }
  
    var selectInput = function(node) { node.select(); };
    if (ios) // Mobile Safari apparently has a bug where select() is broken.
      selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
    else if (ie) // Suppress mysterious IE10 errors
      selectInput = function(node) { try { node.select(); } catch(_e) {} };
  
    function indexOf(array, elt) {
      for (var i = 0; i &lt; array.length; ++i)
        if (array[i] == elt) return i;
      return -1;
    }
    function map(array, f) {
      var out = [];
      for (var i = 0; i &lt; array.length; i++) out[i] = f(array[i], i);
      return out;
    }
  
    function nothing() {}
  
    function createObj(base, props) {
      var inst;
      if (Object.create) {
        inst = Object.create(base);
      } else {
        nothing.prototype = base;
        inst = new nothing();
      }
      if (props) copyObj(props, inst);
      return inst;
    };
  
    function copyObj(obj, target, overwrite) {
      if (!target) target = {};
      for (var prop in obj)
        if (obj.hasOwnProperty(prop) &amp;&amp; (overwrite !== false || !target.hasOwnProperty(prop)))
          target[prop] = obj[prop];
      return target;
    }
  
    function bind(f) {
      var args = Array.prototype.slice.call(arguments, 1);
      return function(){return f.apply(null, args);};
    }
  
    var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
    var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
      return /\w/.test(ch) || ch &gt; "\x80" &amp;&amp;
        (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
    };
    function isWordChar(ch, helper) {
      if (!helper) return isWordCharBasic(ch);
      if (helper.source.indexOf("\\w") &gt; -1 &amp;&amp; isWordCharBasic(ch)) return true;
      return helper.test(ch);
    }
  
    function isEmpty(obj) {
      for (var n in obj) if (obj.hasOwnProperty(n) &amp;&amp; obj[n]) return false;
      return true;
    }
  
    // Extending unicode characters. A series of a non-extending char +
    // any number of extending chars is treated as a single unit as far
    // as editing and measuring is concerned. This is not fully correct,
    // since some scripts/fonts/browsers also treat other configurations
    // of code points as a group.
    var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
    function isExtendingChar(ch) { return ch.charCodeAt(0) &gt;= 768 &amp;&amp; extendingChars.test(ch); }
  
    // DOM UTILITIES
  
    function elt(tag, content, className, style) {
      var e = document.createElement(tag);
      if (className) e.className = className;
      if (style) e.style.cssText = style;
      if (typeof content == "string") e.appendChild(document.createTextNode(content));
      else if (content) for (var i = 0; i &lt; content.length; ++i) e.appendChild(content[i]);
      return e;
    }
  
    var range;
    if (document.createRange) range = function(node, start, end, endNode) {
      var r = document.createRange();
      r.setEnd(endNode || node, end);
      r.setStart(node, start);
      return r;
    };
    else range = function(node, start, end) {
      var r = document.body.createTextRange();
      try { r.moveToElementText(node.parentNode); }
      catch(e) { return r; }
      r.collapse(true);
      r.moveEnd("character", end);
      r.moveStart("character", start);
      return r;
    };
  
    function removeChildren(e) {
      for (var count = e.childNodes.length; count &gt; 0; --count)
        e.removeChild(e.firstChild);
      return e;
    }
  
    function removeChildrenAndAdd(parent, e) {
      return removeChildren(parent).appendChild(e);
    }
  
    var contains = CodeMirror.contains = function(parent, child) {
      if (child.nodeType == 3) // Android browser always returns false when child is a textnode
        child = child.parentNode;
      if (parent.contains)
        return parent.contains(child);
      do {
        if (child.nodeType == 11) child = child.host;
        if (child == parent) return true;
      } while (child = child.parentNode);
    };
  
    function activeElt() {
      var activeElement = document.activeElement;
      while (activeElement &amp;&amp; activeElement.root &amp;&amp; activeElement.root.activeElement)
        activeElement = activeElement.root.activeElement;
      return activeElement;
    }
    // Older versions of IE throws unspecified error when touching
    // document.activeElement in some cases (during loading, in iframe)
    if (ie &amp;&amp; ie_version &lt; 11) activeElt = function() {
      try { return document.activeElement; }
      catch(e) { return document.body; }
    };
  
    function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
    var rmClass = CodeMirror.rmClass = function(node, cls) {
      var current = node.className;
      var match = classTest(cls).exec(current);
      if (match) {
        var after = current.slice(match.index + match[0].length);
        node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
      }
    };
    var addClass = CodeMirror.addClass = function(node, cls) {
      var current = node.className;
      if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
    };
    function joinClasses(a, b) {
      var as = a.split(" ");
      for (var i = 0; i &lt; as.length; i++)
        if (as[i] &amp;&amp; !classTest(as[i]).test(b)) b += " " + as[i];
      return b;
    }
  
    // WINDOW-WIDE EVENTS
  
    // These must be handled carefully, because naively registering a
    // handler for each editor will cause the editors to never be
    // garbage collected.
  
    function forEachCodeMirror(f) {
      if (!document.body.getElementsByClassName) return;
      var byClass = document.body.getElementsByClassName("CodeMirror");
      for (var i = 0; i &lt; byClass.length; i++) {
        var cm = byClass[i].CodeMirror;
        if (cm) f(cm);
      }
    }
  
    var globalsRegistered = false;
    function ensureGlobalHandlers() {
      if (globalsRegistered) return;
      registerGlobalHandlers();
      globalsRegistered = true;
    }
    function registerGlobalHandlers() {
      // When the window resizes, we need to refresh active editors.
      var resizeTimer;
      on(window, "resize", function() {
        if (resizeTimer == null) resizeTimer = setTimeout(function() {
          resizeTimer = null;
          forEachCodeMirror(onResize);
        }, 100);
      });
      // When the window loses focus, we want to show the editor as blurred
      on(window, "blur", function() {
        forEachCodeMirror(onBlur);
      });
    }
  
    // FEATURE DETECTION
  
    // Detect drag-and-drop
    var dragAndDrop = function() {
      // There is *some* kind of drag-and-drop support in IE6-8, but I
      // couldn't get it to work yet.
      if (ie &amp;&amp; ie_version &lt; 9) return false;
      var div = elt('div');
      return "draggable" in div || "dragDrop" in div;
    }();
  
    var zwspSupported;
    function zeroWidthElement(measure) {
      if (zwspSupported == null) {
        var test = elt("span", "\u200b");
        removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
        if (measure.firstChild.offsetHeight != 0)
          zwspSupported = test.offsetWidth &lt;= 1 &amp;&amp; test.offsetHeight &gt; 2 &amp;&amp; !(ie &amp;&amp; ie_version &lt; 8);
      }
      var node = zwspSupported ? elt("span", "\u200b") :
        elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
      node.setAttribute("cm-text", "");
      return node;
    }
  
    // Feature-detect IE's crummy client rect reporting for bidi text
    var badBidiRects;
    function hasBadBidiRects(measure) {
      if (badBidiRects != null) return badBidiRects;
      var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
      var r0 = range(txt, 0, 1).getBoundingClientRect();
      if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
      var r1 = range(txt, 1, 2).getBoundingClientRect();
      return badBidiRects = (r1.right - r0.right &lt; 3);
    }
  
    // See if "".split is the broken IE version, if so, provide an
    // alternative way to split lines.
    var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
      var pos = 0, result = [], l = string.length;
      while (pos &lt;= l) {
        var nl = string.indexOf("\n", pos);
        if (nl == -1) nl = string.length;
        var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
        var rt = line.indexOf("\r");
        if (rt != -1) {
          result.push(line.slice(0, rt));
          pos += rt + 1;
        } else {
          result.push(line);
          pos = nl + 1;
        }
      }
      return result;
    } : function(string){return string.split(/\r\n?|\n/);};
  
    var hasSelection = window.getSelection ? function(te) {
      try { return te.selectionStart != te.selectionEnd; }
      catch(e) { return false; }
    } : function(te) {
      try {var range = te.ownerDocument.selection.createRange();}
      catch(e) {}
      if (!range || range.parentElement() != te) return false;
      return range.compareEndPoints("StartToEnd", range) != 0;
    };
  
    var hasCopyEvent = (function() {
      var e = elt("div");
      if ("oncopy" in e) return true;
      e.setAttribute("oncopy", "return;");
      return typeof e.oncopy == "function";
    })();
  
    var badZoomedRects = null;
    function hasBadZoomedRects(measure) {
      if (badZoomedRects != null) return badZoomedRects;
      var node = removeChildrenAndAdd(measure, elt("span", "x"));
      var normal = node.getBoundingClientRect();
      var fromRange = range(node, 0, 1).getBoundingClientRect();
      return badZoomedRects = Math.abs(normal.left - fromRange.left) &gt; 1;
    }
  
    // KEY NAMES
  
    var keyNames = CodeMirror.keyNames = {
      3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
      19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
      36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
      46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
      106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
      173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
      221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
      63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
    };
    (function() {
      // Number keys
      for (var i = 0; i &lt; 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
      // Alphabetic keys
      for (var i = 65; i &lt;= 90; i++) keyNames[i] = String.fromCharCode(i);
      // Function keys
      for (var i = 1; i &lt;= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
    })();
  
    // BIDI HELPERS
  
    function iterateBidiSections(order, from, to, f) {
      if (!order) return f(from, to, "ltr");
      var found = false;
      for (var i = 0; i &lt; order.length; ++i) {
        var part = order[i];
        if (part.from &lt; to &amp;&amp; part.to &gt; from || from == to &amp;&amp; part.to == from) {
          f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
          found = true;
        }
      }
      if (!found) f(from, to, "ltr");
    }
  
    function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
    function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  
    function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
    function lineRight(line) {
      var order = getOrder(line);
      if (!order) return line.text.length;
      return bidiRight(lst(order));
    }
  
    function lineStart(cm, lineN) {
      var line = getLine(cm.doc, lineN);
      var visual = visualLine(line);
      if (visual != line) lineN = lineNo(visual);
      var order = getOrder(visual);
      var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
      return Pos(lineN, ch);
    }
    function lineEnd(cm, lineN) {
      var merged, line = getLine(cm.doc, lineN);
      while (merged = collapsedSpanAtEnd(line)) {
        line = merged.find(1, true).line;
        lineN = null;
      }
      var order = getOrder(line);
      var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
      return Pos(lineN == null ? lineNo(line) : lineN, ch);
    }
    function lineStartSmart(cm, pos) {
      var start = lineStart(cm, pos.line);
      var line = getLine(cm.doc, start.line);
      var order = getOrder(line);
      if (!order || order[0].level == 0) {
        var firstNonWS = Math.max(0, line.text.search(/\S/));
        var inWS = pos.line == start.line &amp;&amp; pos.ch &lt;= firstNonWS &amp;&amp; pos.ch;
        return Pos(start.line, inWS ? 0 : firstNonWS);
      }
      return start;
    }
  
    function compareBidiLevel(order, a, b) {
      var linedir = order[0].level;
      if (a == linedir) return true;
      if (b == linedir) return false;
      return a &lt; b;
    }
    var bidiOther;
    function getBidiPartAt(order, pos) {
      bidiOther = null;
      for (var i = 0, found; i &lt; order.length; ++i) {
        var cur = order[i];
        if (cur.from &lt; pos &amp;&amp; cur.to &gt; pos) return i;
        if ((cur.from == pos || cur.to == pos)) {
          if (found == null) {
            found = i;
          } else if (compareBidiLevel(order, cur.level, order[found].level)) {
            if (cur.from != cur.to) bidiOther = found;
            return i;
          } else {
            if (cur.from != cur.to) bidiOther = i;
            return found;
          }
        }
      }
      return found;
    }
  
    function moveInLine(line, pos, dir, byUnit) {
      if (!byUnit) return pos + dir;
      do pos += dir;
      while (pos &gt; 0 &amp;&amp; isExtendingChar(line.text.charAt(pos)));
      return pos;
    }
  
    // This is needed in order to move 'visually' through bi-directional
    // text -- i.e., pressing left should make the cursor go left, even
    // when in RTL text. The tricky part is the 'jumps', where RTL and
    // LTR text touch each other. This often requires the cursor offset
    // to move more than one unit, in order to visually move one unit.
    function moveVisually(line, start, dir, byUnit) {
      var bidi = getOrder(line);
      if (!bidi) return moveLogically(line, start, dir, byUnit);
      var pos = getBidiPartAt(bidi, start), part = bidi[pos];
      var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  
      for (;;) {
        if (target &gt; part.from &amp;&amp; target &lt; part.to) return target;
        if (target == part.from || target == part.to) {
          if (getBidiPartAt(bidi, target) == pos) return target;
          part = bidi[pos += dir];
          return (dir &gt; 0) == part.level % 2 ? part.to : part.from;
        } else {
          part = bidi[pos += dir];
          if (!part) return null;
          if ((dir &gt; 0) == part.level % 2)
            target = moveInLine(line, part.to, -1, byUnit);
          else
            target = moveInLine(line, part.from, 1, byUnit);
        }
      }
    }
  
    function moveLogically(line, start, dir, byUnit) {
      var target = start + dir;
      if (byUnit) while (target &gt; 0 &amp;&amp; isExtendingChar(line.text.charAt(target))) target += dir;
      return target &lt; 0 || target &gt; line.text.length ? null : target;
    }
  
    // Bidirectional ordering algorithm
    // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
    // that this (partially) implements.
  
    // One-char codes used for character types:
    // L (L):   Left-to-Right
    // R (R):   Right-to-Left
    // r (AL):  Right-to-Left Arabic
    // 1 (EN):  European Number
    // + (ES):  European Number Separator
    // % (ET):  European Number Terminator
    // n (AN):  Arabic Number
    // , (CS):  Common Number Separator
    // m (NSM): Non-Spacing Mark
    // b (BN):  Boundary Neutral
    // s (B):   Paragraph Separator
    // t (S):   Segment Separator
    // w (WS):  Whitespace
    // N (ON):  Other Neutrals
  
    // Returns null if characters are ordered as they appear
    // (left-to-right), or an array of sections ({from, to, level}
    // objects) in the order in which they occur visually.
    var bidiOrdering = (function() {
      // Character types for codepoints 0 to 0xff
      var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
      // Character types for codepoints 0x600 to 0x6ff
      var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
      function charType(code) {
        if (code &lt;= 0xf7) return lowTypes.charAt(code);
        else if (0x590 &lt;= code &amp;&amp; code &lt;= 0x5f4) return "R";
        else if (0x600 &lt;= code &amp;&amp; code &lt;= 0x6ed) return arabicTypes.charAt(code - 0x600);
        else if (0x6ee &lt;= code &amp;&amp; code &lt;= 0x8ac) return "r";
        else if (0x2000 &lt;= code &amp;&amp; code &lt;= 0x200b) return "w";
        else if (code == 0x200c) return "b";
        else return "L";
      }
  
      var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
      var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
      // Browsers seem to always treat the boundaries of block elements as being L.
      var outerType = "L";
  
      function BidiSpan(level, from, to) {
        this.level = level;
        this.from = from; this.to = to;
      }
  
      return function(str) {
        if (!bidiRE.test(str)) return false;
        var len = str.length, types = [];
        for (var i = 0, type; i &lt; len; ++i)
          types.push(type = charType(str.charCodeAt(i)));
  
        // W1. Examine each non-spacing mark (NSM) in the level run, and
        // change the type of the NSM to the type of the previous
        // character. If the NSM is at the start of the level run, it will
        // get the type of sor.
        for (var i = 0, prev = outerType; i &lt; len; ++i) {
          var type = types[i];
          if (type == "m") types[i] = prev;
          else prev = type;
        }
  
        // W2. Search backwards from each instance of a European number
        // until the first strong type (R, L, AL, or sor) is found. If an
        // AL is found, change the type of the European number to Arabic
        // number.
        // W3. Change all ALs to R.
        for (var i = 0, cur = outerType; i &lt; len; ++i) {
          var type = types[i];
          if (type == "1" &amp;&amp; cur == "r") types[i] = "n";
          else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
        }
  
        // W4. A single European separator between two European numbers
        // changes to a European number. A single common separator between
        // two numbers of the same type changes to that type.
        for (var i = 1, prev = types[0]; i &lt; len - 1; ++i) {
          var type = types[i];
          if (type == "+" &amp;&amp; prev == "1" &amp;&amp; types[i+1] == "1") types[i] = "1";
          else if (type == "," &amp;&amp; prev == types[i+1] &amp;&amp;
                   (prev == "1" || prev == "n")) types[i] = prev;
          prev = type;
        }
  
        // W5. A sequence of European terminators adjacent to European
        // numbers changes to all European numbers.
        // W6. Otherwise, separators and terminators change to Other
        // Neutral.
        for (var i = 0; i &lt; len; ++i) {
          var type = types[i];
          if (type == ",") types[i] = "N";
          else if (type == "%") {
            for (var end = i + 1; end &lt; len &amp;&amp; types[end] == "%"; ++end) {}
            var replace = (i &amp;&amp; types[i-1] == "!") || (end &lt; len &amp;&amp; types[end] == "1") ? "1" : "N";
            for (var j = i; j &lt; end; ++j) types[j] = replace;
            i = end - 1;
          }
        }
  
        // W7. Search backwards from each instance of a European number
        // until the first strong type (R, L, or sor) is found. If an L is
        // found, then change the type of the European number to L.
        for (var i = 0, cur = outerType; i &lt; len; ++i) {
          var type = types[i];
          if (cur == "L" &amp;&amp; type == "1") types[i] = "L";
          else if (isStrong.test(type)) cur = type;
        }
  
        // N1. A sequence of neutrals takes the direction of the
        // surrounding strong text if the text on both sides has the same
        // direction. European and Arabic numbers act as if they were R in
        // terms of their influence on neutrals. Start-of-level-run (sor)
        // and end-of-level-run (eor) are used at level run boundaries.
        // N2. Any remaining neutrals take the embedding direction.
        for (var i = 0; i &lt; len; ++i) {
          if (isNeutral.test(types[i])) {
            for (var end = i + 1; end &lt; len &amp;&amp; isNeutral.test(types[end]); ++end) {}
            var before = (i ? types[i-1] : outerType) == "L";
            var after = (end &lt; len ? types[end] : outerType) == "L";
            var replace = before || after ? "L" : "R";
            for (var j = i; j &lt; end; ++j) types[j] = replace;
            i = end - 1;
          }
        }
  
        // Here we depart from the documented algorithm, in order to avoid
        // building up an actual levels array. Since there are only three
        // levels (0, 1, 2) in an implementation that doesn't take
        // explicit embedding into account, we can build up the order on
        // the fly, without following the level-based algorithm.
        var order = [], m;
        for (var i = 0; i &lt; len;) {
          if (countsAsLeft.test(types[i])) {
            var start = i;
            for (++i; i &lt; len &amp;&amp; countsAsLeft.test(types[i]); ++i) {}
            order.push(new BidiSpan(0, start, i));
          } else {
            var pos = i, at = order.length;
            for (++i; i &lt; len &amp;&amp; types[i] != "L"; ++i) {}
            for (var j = pos; j &lt; i;) {
              if (countsAsNum.test(types[j])) {
                if (pos &lt; j) order.splice(at, 0, new BidiSpan(1, pos, j));
                var nstart = j;
                for (++j; j &lt; i &amp;&amp; countsAsNum.test(types[j]); ++j) {}
                order.splice(at, 0, new BidiSpan(2, nstart, j));
                pos = j;
              } else ++j;
            }
            if (pos &lt; i) order.splice(at, 0, new BidiSpan(1, pos, i));
          }
        }
        if (order[0].level == 1 &amp;&amp; (m = str.match(/^\s+/))) {
          order[0].from = m[0].length;
          order.unshift(new BidiSpan(0, 0, m[0].length));
        }
        if (lst(order).level == 1 &amp;&amp; (m = str.match(/\s+$/))) {
          lst(order).to -= m[0].length;
          order.push(new BidiSpan(0, len - m[0].length, len));
        }
        if (order[0].level == 2)
          order.unshift(new BidiSpan(1, order[0].to, order[0].to));
        if (order[0].level != lst(order).level)
          order.push(new BidiSpan(order[0].level, len, len));
  
        return order;
      };
    })();
  
    // THE END
  
    CodeMirror.version = "5.16.0";
  
    return CodeMirror;
  });
document.addEventListener("spree:load", function () {
  var menuItemType = $('#menu_item_item_type').select2();

  updateContainerMessage();

  menuItemType.on('change', function () {
    updateContainerMessage();
  });

  function updateContainerMessage() {
    var linkSettingsPanel = document.getElementById('LinkSettings');

    if (!linkSettingsPanel) return;

    var selectedLinkType = $('#menu_item_item_type').val();
    var usingConainerMessage = document.getElementById('usingContainerInfo');

    if (selectedLinkType === 'Container') {
      linkSettingsPanel.classList.add('d-none');
      usingConainerMessage.classList.remove('d-none');
    } else {
      linkSettingsPanel.classList.remove('d-none');
      usingConainerMessage.classList.add('d-none');
    }
  }
});
document.addEventListener("spree:load", function() {
  $(document).on('change', '.return-items-table .return-item-exchange-selection', function () {
    $('.expedited-exchanges-warning').fadeIn()
  })
});
document.addEventListener("spree:load", function() {
  var formFields = $("[data-hook='admin_customer_return_form_fields'], [data-hook='admin_return_authorization_form_fields']")

  function checkAddItemBox () {
    $(this).closest('tr').find('input.add-item').attr('checked', 'checked')
    updateSuggestedAmount()
  }

  function updateSuggestedAmount () {
    var totalPretaxRefund = 0
    var checkedItems = formFields.find('input.add-item:checked')
    $.each(checkedItems, function (i, checkbox) {
      var returnItemRow = $(checkbox).parents('tr')
      var returnQuantity = parseInt(returnItemRow.find('.refund-quantity-input').val(), 10)
      var purchasedQuantity = parseInt(returnItemRow.find('.purchased-quantity').text(), 10)
      var amount = (returnQuantity / purchasedQuantity) * parseFloat(returnItemRow.find('.charged-amount').data('chargedAmount'))
      returnItemRow.find('.refund-amount-input').val(amount.toFixed(2))
      totalPretaxRefund += amount
    })

    var displayTotal = isNaN(totalPretaxRefund) ? '' : totalPretaxRefund.toFixed(2)
    formFields.find('span#total_pre_tax_refund').html(displayTotal)
  }

  if (formFields.length &gt; 0) {
    updateSuggestedAmount()

    formFields.find('input#select-all').on('change', function (ev) {
      var checkBoxes = $(ev.currentTarget).parents('table:first').find('input.add-item')
      checkBoxes.prop('checked', this.checked)
      updateSuggestedAmount()
    })

    formFields.find('input.add-item').on('change', updateSuggestedAmount)
    formFields.find('.refund-amount-input').on('keyup', updateSuggestedAmount)
    formFields.find('.refund-quantity-input').on('keyup mouseup', updateSuggestedAmount)

    formFields.find('input, select').not('.add-item').on('change', checkAddItemBox)
  }
});
/* global shipments, variantStockTemplate, order_number, order_id */
// Shipments AJAX API
document.addEventListener("spree:load", function() {
  'use strict'

  // handle variant selection, show stock level.
  $('#add_variant_id').change(function () {
    var variantId = $(this).val().toString()
    var variant = _.find(window.variants, function (variant) {
      return variant.id.toString() === variantId
    })

    $('#stock_details').html(variantStockTemplate({ variant: variant }))
    $('#stock_details').show()

    $('button.add_variant').click(addVariantFromStockLocation)
  })

  // handle edit click
  $('a.edit-item').click(toggleItemEdit)

  // handle cancel click
  $('a.cancel-item').click(toggleItemEdit)

  // handle split click
  $('a.split-item').click(startItemSplit)

  // handle save click
  $('a.save-item').click(function () {
    var save = $(this)
    var shipmentNumber = save.data('shipment-number')
    var variantId = save.data('variant-id')

    var quantity = parseInt(save.parents('tr').find('input.line_item_quantity').val())

    toggleItemEdit()
    adjustShipmentItems(shipmentNumber, variantId, quantity)
    return false
  })

  // handle delete click
  $('a.delete-item').click(function (event) {
    if (confirm(Spree.translations.are_you_sure_delete)) {
      var del = $(this)
      var shipmentNumber = del.data('shipment-number')
      var variantId = del.data('variant-id')
      // eslint-disable-next-line
      var url = Spree.routes.shipments_api_v2 + '/' + shipmentNumber + '/remove_item'

      toggleItemEdit()

      $.ajax({
        type: 'PATCH',
        url: Spree.url(url),
        data: {
          shipment: {
            variant_id: variantId
          }
        },
        headers: Spree.apiV2Authentication()
      }).done(function (msg) {
        window.location.reload()
      }).fail(function (msg) {
        alert(msg.responseJSON.error)
      })
    }
    return false
  })

  // handle ship click
  $('[data-hook=admin_shipment_form] a.ship').on('click', function () {
    var link = $(this)
    var url = Spree.url(Spree.routes.shipments_api_v2 + '/' + link.data('shipment-number') + '/ship')
    $.ajax({
      type: 'PATCH',
      url: url,
      headers: Spree.apiV2Authentication()
    }).done(function () {
      window.location.reload()
    }).fail(function (msg) {
      alert(msg.responseJSON.error)
    })
  })

  // handle shipping method edit click
  $('a.edit-method').click(toggleMethodEdit)
  $('a.cancel-method').click(toggleMethodEdit)

  // handle shipping method save
  $('[data-hook=admin_shipment_form] a.save-method').on('click', function (event) {
    event.preventDefault()

    var link = $(this)
    var shipmentNumber = link.data('shipment-number')
    var selectedShippingRateId = link.parents('tbody').find("select#selected_shipping_rate_id[data-shipment-number='" + shipmentNumber + "']").val()
    var unlock = link.parents('tbody').find("input[name='open_adjustment'][data-shipment-number='" + shipmentNumber + "']:checked").val()
    var url = Spree.url(Spree.routes.shipments_api_v2 + '/' + shipmentNumber + '.json')

    $.ajax({
      type: 'PATCH',
      url: url,
      data: {
        shipment: {
          selected_shipping_rate_id: selectedShippingRateId,
          unlock: unlock
        },
      },
      headers: Spree.apiV2Authentication()
    }).done(function () {
      window.location.reload()
    }).fail(function (msg) {
      alert(msg.responseJSON.error)
    })
  })

  function toggleTrackingEdit(event) {
    event.preventDefault()

    var link = $(this)
    link.parents('tbody').find('tr.edit-tracking').toggle()
    link.parents('tbody').find('tr.show-tracking').toggle()
  }

  // handle tracking edit click
  $('a.edit-tracking').click(toggleTrackingEdit)
  $('a.cancel-tracking').click(toggleTrackingEdit)

  function createTrackingValueContent(data) {
    if (data.attributes.tracking_url &amp;&amp; data.attributes.tracking) {
      return '&lt;a target="_blank" href="' + data.attributes.tracking_url + '"&gt;' + data.attributes.tracking + '&lt;a&gt;'
    }

    return data.attributes.tracking
  }

  // handle tracking save
  $('[data-hook=admin_shipment_form] a.save-tracking').on('click', function (event) {
    event.preventDefault()

    var link = $(this)
    var shipmentNumber = link.data('shipment-number')
    var tracking = link.parents('tbody').find('input#tracking').val()
    var url = Spree.url(Spree.routes.shipments_api_v2 + '/' + shipmentNumber + '.json')

    $.ajax({
      type: 'PATCH',
      url: url,
      data: {
        shipment: {
          tracking: tracking
        }
      },
      headers: Spree.apiV2Authentication()
    }).done(function (json) {
      link.parents('tbody').find('tr.edit-tracking').toggle()

      var show = link.parents('tbody').find('tr.show-tracking')
      show.toggle()

      if (json.data.attributes.tracking) {
        show.find('.tracking-value').html($('&lt;strong&gt;').html(Spree.translations.tracking + ': ')).append(createTrackingValueContent(json.data))
      } else {
        show.find('.tracking-value').html(Spree.translations.no_tracking_present)
      }
    })
  })
})

function adjustShipmentItems(shipmentNumber, variantId, quantity) {
  var shipment = _.findWhere(shipments, { number: shipmentNumber + '' })
  var inventoryUnits = _.where(shipment.inventory_units, { variant_id: variantId })
  var url = Spree.routes.shipments_api_v2 + '/' + shipmentNumber
  var previousQuantity = inventoryUnits.reduce(function (accumulator, currentUnit, _index, _array) {
    return accumulator + currentUnit.quantity
  }, 0)
  var newQuantity = 0

  if (previousQuantity &lt; quantity) {
    url += '/add_item'
    newQuantity = (quantity - previousQuantity)
  } else if (previousQuantity &gt; quantity) {
    url += '/remove_item'
    newQuantity = (previousQuantity - quantity)
  }
  url += '.json'

  if (newQuantity !== 0) {
    $.ajax({
      type: 'PATCH',
      url: Spree.url(url),
      data: {
        shipment: {
          variant_id: variantId,
          quantity: newQuantity,
        }
      },
      headers: Spree.apiV2Authentication()
    }).done(function (msg) {
      window.location.reload()
    }).fail(function (msg) {
      alert(msg.responseJSON.error)
    })
  }
}

function toggleMethodEdit() {
  var link = $(this)
  link.parents('tbody').find('tr.edit-method').toggle()
  link.parents('tbody').find('tr.show-method').toggle()

  return false
}

function toggleItemEdit() {
  var link = $(this)
  var linkParent = link.parent()
  linkParent.find('a.edit-item').toggle()
  linkParent.find('a.cancel-item').toggle()
  linkParent.find('a.split-item').toggle()
  linkParent.find('a.save-item').toggle()
  linkParent.find('a.delete-item').toggle()
  link.parents('tr').find('td.item-qty-show').toggle()
  link.parents('tr').find('td.item-qty-edit').toggle()

  return false
}

function startItemSplit(event) {
  event.preventDefault()
  $('.cancel-split').each(function () {
    $(this).click()
  })
  var link = $(this)
  link.parent().find('a.edit-item').toggle()
  link.parent().find('a.split-item').toggle()
  link.parent().find('a.delete-item').toggle()
  var variantId = link.data('variant-id')

  var variant = {}
  $.ajax({
    type: 'GET',
    async: false,
    url: Spree.routes.variants_api_v2 + '/' + variantId,
    data: {
      include: 'stock_items.stock_location'
    },
    headers: Spree.apiV2Authentication()
  }).done(function (json) {
    var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer
    new JSONAPIDeserializer({ keyForAttribute: 'snake_case' }).deserialize(json, function (_err, deserializedJson) {
      variant = deserializedJson

      var maxQuantity = link.closest('tr').data('item-quantity')
      var splitItemTemplate = Handlebars.compile($('#variant_split_template').text())

      link.closest('tr').after(splitItemTemplate({ variant: variant, shipments: shipments, max_quantity: maxQuantity }))
      $('a.cancel-split').click(cancelItemSplit)
      $('a.save-split').click(completeItemSplit)

      $('#item_stock_location').select2({ width: 'resolve', placeholder: Spree.translations.item_stock_placeholder })
    })
  }).fail(function (msg) {
    alert(msg.responseJSON.error)
  })
}

function completeItemSplit(event) {
  event.preventDefault()

  if ($('#item_stock_location').val() === '') {
    alert('Please select the split destination.')
    return false
  }

  var link = $(this)
  var stockItemRow = link.closest('tr')
  var variantId = stockItemRow.data('variant-id')
  var quantity = stockItemRow.find('#item_quantity').val()

  var stockLocationId = stockItemRow.find('#item_stock_location').val()
  var originalShipmentNumber = link.closest('tbody').data('shipment-number')

  var selectedShipment = stockItemRow.find('#item_stock_location option:selected')
  var targetShipmentNumber = selectedShipment.data('shipment-number')
  var newShipment = selectedShipment.data('new-shipment')

  // eslint-disable-next-line eqeqeq
  if (stockLocationId != 'new_shipment') {
    var path, additionalData
    if (newShipment !== undefined) {
      // transfer to a new location data
      path = '/transfer_to_location'
      additionalData = { stock_location_id: stockLocationId }
    } else {
      // transfer to an existing shipment data
      path = '/transfer_to_shipment'
      additionalData = { target_shipment_number: targetShipmentNumber }
    }

    var data = {
      variant_id: variantId,
      quantity: quantity
    }

    $.ajax({
      type: 'PATCH',
      async: false,
      url: Spree.url(Spree.routes.shipments_api_v2 + '/' + originalShipmentNumber + path),
      data: {
        shipment: $.extend(data, additionalData)
      },
      headers: Spree.apiV2Authentication()
    }).fail(function (msg) {
      alert(msg.responseJSON.error)
    }).done(function (msg) {
      window.location.reload()
    })
  }
}

function cancelItemSplit(event) {
  event.preventDefault()
  var link = $(this)
  var prevRow = link.closest('tr').prev()
  link.closest('tr').remove()
  prevRow.find('a.edit-item').toggle()
  prevRow.find('a.split-item').toggle()
  prevRow.find('a.delete-item').toggle()
}

function addVariantFromStockLocation(event) {
  event.preventDefault()

  $('#stock_details').hide()

  var variantId = $('select.variant_autocomplete').val()
  var stockLocationId = $(this).data('stock-location-id')
  var quantity = $("input.quantity[data-stock-location-id='" + stockLocationId + "']").val()

  var shipment = _.find(shipments, function (shipment) {
    return shipment.stock_location_id === stockLocationId &amp;&amp; (shipment.state === 'ready' || shipment.state === 'pending')
  })

  if (shipment === undefined) {
    $.ajax({
      type: 'POST',
      // eslint-disable-next-line camelcase
      url: Spree.routes.shipments_api_v2,
      data: {
        shipment: {
          order_id: order_id,
          variant_id: variantId,
          quantity: quantity,
          stock_location_id: stockLocationId
        }
      },
      headers: Spree.apiV2Authentication()
    }).done(function (msg) {
      window.location.reload()
    }).fail(function (msg) {
      alert(msg.responseJSON.error)
    })
  } else {
    // add to existing shipment
    adjustShipmentItems(shipment.number, variantId, quantity)
  }
  return 1
};
document.addEventListener("spree:load", function() {
  'use strict'

  if ($('#new_state_link').length) {
    $('#country').on('change', function () {
      var newStateLinkHref = $('#new_state_link').prop('href')
      var selectedCountryId = $('#country option:selected').prop('value')
      var newLink = newStateLinkHref.replace(/countries\/(\d+)/,
        'countries/' + selectedCountryId)
      $('#new_state_link').attr('href', newLink)
    })
  };
});
document.addEventListener("spree:load", function() {
  $('[data-hook=stock_location_country] span#country .select2').on('change', function () { updateAddressState('') })
});
document.addEventListener("spree:load", function() {
  $('.stock_item_backorderable').on('click', function () {
    $(this).parent('form').submit()
  })
  $('.toggle_stock_item_backorderable').on('submit', function () {
    $.ajax({
      type: this.method,
      url: this.action,
      data: $(this).serialize(),
      dataType: 'json'
    })
    return false
  })
});
/* global variantTemplate */
document.addEventListener("spree:load", function() {
  var el = $('#stock_movement_stock_item_id')
  var jsonApiVariants = {}
  el.select2({
    placeholder: 'Find a stock item', // translate
    minimumInputLength: 3,
    quietMillis: 200,
    ajax: {
      url: Spree.routes.stock_items_api_v2,
      data: function (params, page) {
        return {
          filter: {
            variant_product_name_cont: params.term,
            stock_location_id_eq: el.data('stock-location-id')
          },
          include: 'variant',
          image_transformation: {
            size: '100x100'
          },
          fields: {
            'variant': 'name,sku,options_text,images'
          },
          per_page: 50,
          page: page
        }
      },
      headers: Spree.apiV2Authentication(),
      success: function(data) {
        var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer
        new JSONAPIDeserializer({ keyForAttribute: 'snake_case' }).deserialize(data, function (_err, variants) {
          jsonApiVariants = variants
        })
      },
      processResults: function (json) {
        var res = jsonApiVariants.map(function (stockItem) {
          return {
            id: stockItem.id,
            text: stockItem.variant.name,
            variant: stockItem.variant
          }
        })

        return {
          results: res
        }
      },
      results: function (data, page) {
        var more = (page * 50) &lt; data.count
        return {
          results: data.stock_items,
          more: more
        }
      }
    },
    templateResult: function (stockItem) {
      if (stockItem.loading) {
        return stockItem.text
      }

      let variant = stockItem.variant
      if (variant['images'][0] !== undefined &amp;&amp; variant['images'][0].transformed_url !== undefined) {
        variant.image = variant.images[0].transformed_url
      }
      return $(variantTemplate({
        variant: variant
      }))
    },
    templateSelection: function(stockItem) {
      const variant = stockItem.variant
      if (variant === undefined) {
        return stockItem.text
      } else if (!!variant.options_text &amp;&amp; variant.options_text !== '') {
        return variant.name + '(' + variant.options_text + ')'
      } else {
        return variant.name
      }
    }
  })
});
document.addEventListener("spree:load", function() {
  function TransferVariant (variant1) {
    // refactor variant1
    this.variant = variant1
    this.id = this.variant[0].variant.id
    this.name = this.variant[0].variant.name + ' - ' + this.variant[0].variant.sku
    this.quantity = 0
  }
  TransferVariant.prototype.add = function (quantity) {
    this.quantity += quantity
    return this.quantity
  }

  function TransferLocations () {
    this.source = $('#transfer_source_location_id')
    this.destination = $('#transfer_destination_location_id')
    this.source.change(this.populate_destination.bind(this))
    $('#transfer_receive_stock').change(this.receive_stock_change.bind(this))

    $.ajax({
      url: Spree.routes.stock_locations_api_v2 + '?per_page=1000',
      type: 'GET',
      data: {
        fields: {
          stock_location: 'name'
        }
      },
      headers: Spree.apiV2Authentication()
    }).then(function (json) {
      this.locations = (function () {
        var ref = json.data
        var results = []
        var i, len
        for (i = 0, len = ref.length; i &lt; len; i++) {
          results.push({
            id: ref[i].id,
            name: ref[i].attributes.name
          })
        }
        return results
      })()
      if (this.locations.length &lt; 2) {
        this.force_receive_stock()
      }
      this.populate_source()
      this.populate_destination()
    }.bind(this))
  }

  TransferLocations.prototype.force_receive_stock = function () {
    $('#receive_stock_field').hide()
    $('#transfer_receive_stock').prop('checked', true)
    this.toggle_source_location(true)
  }

  TransferLocations.prototype.is_source_location_hidden = function () {
    return $('#transfer_source_location_id_field').css('visibility') === 'hidden'
  }

  TransferLocations.prototype.toggle_source_location = function (hide) {
    if (hide == null) {
      hide = false
    }
    this.source.trigger('change')
    var transferSourceLocationIdField = $('#transfer_source_location_id_field')
    if (this.is_source_location_hidden() &amp;&amp; !hide) {
      transferSourceLocationIdField.css('visibility', 'visible')
      transferSourceLocationIdField.show()
    } else {
      transferSourceLocationIdField.css('visibility', 'hidden')
      transferSourceLocationIdField.hide()
    }
  }

  TransferLocations.prototype.receive_stock_change = function (event) {
    this.toggle_source_location(event.target.checked)
    this.populate_destination(!event.target.checked)
  }

  TransferLocations.prototype.populate_source = function () {
    this.populate_select(this.source)
    this.source.trigger('change')
  }

  TransferLocations.prototype.populate_destination = function () {
    if (this.is_source_location_hidden()) {
      return this.populate_select(this.destination)
    } else {
      return this.populate_select(this.destination, this.source.val())
    }
  }

  TransferLocations.prototype.populate_select = function (select, except) {
    var i, len, location, ref
    if (except == null) {
      except = 0
    }
    select.children('option').remove()
    ref = this.locations
    for (i = 0, len = ref.length; i &lt; len; i++) {
      location = ref[i]
      if (location.id !== except) {
        select.append($('&lt;option&gt;&lt;/option&gt;').text(location.name).attr('value', location.id))
      }
    }
    return select.select2()
  }

  function TransferVariants () {
    $('#transfer_source_location_id').change(this.refresh_variants.bind(this))
  }

  TransferVariants.prototype.receiving_stock = function () {
    return $('#transfer_receive_stock:checked').length &gt; 0
  }

  TransferVariants.prototype.refresh_variants = function () {
    if (this.receiving_stock()) {
      return this._search_transfer_variants()
    } else {
      return this._search_transfer_stock_items()
    }
  }

  TransferVariants.prototype._search_transfer_variants = function () {
    return this.build_select(Spree.url(Spree.routes.variants_api_v2), 'product_name_or_sku_cont')
  }

  TransferVariants.prototype._search_transfer_stock_items = function () {
    var stockLocationId = $('#transfer_source_location_id').val()
    return this.build_select(Spree.routes.stock_items_api_v2 + '?filter[stock_location_id_eq]=' + stockLocationId + '&amp;include=variant', 'variant_product_name_or_variant_sku_cont')
  }

  TransferVariants.prototype.format_variant_result = function (result) {
    // eslint-disable-next-line no-extra-boolean-cast
    if (!!result.options_text) {
      return result.name + ' - ' + result.sku + ' (' + result.options_text + ')'
    } else {
      return result.name + ' - ' + result.sku
    }
  }

  function formattedVariantList(obj) {
    return {
     id: obj.id,
     text: obj.name,
     name: obj.name,
     sku: obj.sku,
     options_text: obj.options_text,
     variant: obj
    }
  }

  TransferVariants.prototype.build_select = function (url, query) {
    return $('#transfer_variant').select2({
      minimumInputLength: 3,
      ajax: {
        url: url,
        datatype: 'json',
        data: function (params) {
          var filter = {}
          filter[query] = params.term

          return {
            filter: filter,
            fields: {
              'variant': 'name,sku,options_text'
            }
          }
        },
        headers: Spree.apiV2Authentication(),
        success: function(data) {
          var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer
          new JSONAPIDeserializer({ keyForAttribute: 'snake_case' }).deserialize(data, function (_err, variants) {
            jsonApiVariants = variants
          })
        },
        processResults: function (json) {
          if (json &amp;&amp; json.data &amp;&amp; jsonApiVariants) {
            var res = {}

            if (json.links.self.match(/platform\/variants/)) {
              res = jsonApiVariants.map(function (variant) {
                return formattedVariantList(variant)
              })
            } else {
              res = jsonApiVariants.map(function (variant) {
                return formattedVariantList(variant.variant)
              })
            }

            return {
              results: res
            }
          }
        }
      },
      templateResult: function(variant) {
        if (variant.options_text !== "") {
          return variant.name + ' - ' + variant.sku + ' (' + variant.options_text + ')'
        } else {
          return variant.name + ' - ' + variant.sku
        }
      },
      templateSelection: function (variant) {
        // eslint-disable-next-line no-extra-boolean-cast
        if (!!variant.options_text) {
          return variant.name + (' (' + variant.options_text + ')') + (' - ' + variant.sku)
        } else {
          return variant.name + (' - ' + variant.sku)
        }
      }
    })
  }

  function TransferAddVariants () {
    this.variants = []
    this.template = Handlebars.compile($('#transfer_variant_template').html())
    $('#transfer_source_location_id').change(this.clear_variants.bind(this))
    $('button.transfer_add_variant').click(function (event) {
      event.preventDefault()
      if ($('#transfer_variant').select2('data') != null) {
        this.add_variant()
      } else {
        alert('Please select a variant first')
      }
    }.bind(this))
    $('#transfer-variants-table').on('click', '.transfer_remove_variant', function (event) {
      event.preventDefault()
      this.remove_variant($(event.target))
    }.bind(this))
    $('button.transfer_transfer').click(function () {
      if (!(this.variants.length &gt; 0)) {
        alert('no variants to transfer')
        return false
      }
    }.bind(this))
  }

  TransferAddVariants.prototype.add_variant = function () {
    var variant = $('#transfer_variant').select2('data')
    var quantity = parseInt($('#transfer_variant_quantity').val())
    variant = this.find_or_add(variant)
    variant.add(quantity)
    return this.render()
  }

  TransferAddVariants.prototype.find_or_add = function (variant) {
    var existing = _.find(this.variants, function (v) {
      return v.id.toString() === variant[0].id
    })
    if (existing) {
      return existing
    } else {
      variant = new TransferVariant($.extend({}, variant))
      this.variants.push(variant)
      return variant
    }
  }

  TransferAddVariants.prototype.remove_variant = function (target) {
    var v
    var variantId = target.data('variantId').toString()

    this.variants = (function () {
      var ref = this.variants
      var results = []
      var i, len
      for (i = 0, len = ref.length; i &lt; len; i++) {
        v = ref[i]
        if (v.id.toString() !== variantId) {
          results.push(v)
        }
      }
      return results
    }.call(this))
    return this.render()
  }

  TransferAddVariants.prototype.clear_variants = function () {
    this.variants = []
    return this.render()
  }

  TransferAddVariants.prototype.contains = function (id) {
    return _.contains(_.pluck(this.variants, 'id'), id)
  }

  TransferAddVariants.prototype.render = function () {
    if (this.variants.length === 0) {
      $('#transfer-variants-table').hide()
      return $('.no-objects-found').show()
    } else {
      $('#transfer-variants-table').show()
      $('.no-objects-found').hide()
      return $('#transfer_variants_tbody').html(this.template({
        variants: this.variants
      }))
    }
  }

  if ($('#transfer_source_location_id').length &gt; 0) {
    /* eslint-disable no-new */
    new TransferLocations()
    new TransferVariants()
    new TransferAddVariants()
    /* eslint-enable no-new */
  }
});
$.fn.taxonAutocomplete = function() {
  'use strict'

  function formatTaxonList(values) {
    return values.map(function (obj) {
      return {
        id: obj.id,
        text: obj.attributes.pretty_name
      }
    })
  }

  this.select2({
    multiple: true,
    placeholder: Spree.translations.taxon_placeholder,
    minimumInputLength: 2,
    ajax: {
      url: Spree.routes.taxons_api_v2,
      dataType: 'json',
      data: function (params) {
        return {
          filter: {
            name_cont: params.term
          },
          fields: {
            taxon: 'pretty_name'
          }
        }
      },
      headers: Spree.apiV2Authentication(),
      processResults: function(data) {
        return {
          results: formatTaxonList(data.data)
        }
      }
    }
  })
}

document.addEventListener("spree:load", function() {
  var productTaxonSelector = document.getElementById('product_taxon_ids')
  if (productTaxonSelector == null) return
  if (productTaxonSelector.hasAttribute('data-autocomplete-url-value')) return

  $('#product_taxon_ids').taxonAutocomplete()
});
/* global productTemplate */
document.addEventListener("spree:load", function() {
  window.productTemplate = Handlebars.compile($('#product_template').text())
  var taxonProducts = $('#taxon_products')
  var taxonId = $('#taxon_id')

  var el = document.getElementById('taxon_products')
  if (el) {
    Sortable.create(el, {
      handle: '.sort-handle',
      ghostClass: 'moving-this',
      animation: 550,
      easing: 'cubic-bezier(1, 0, 0, 1)',
      swapThreshold: 0.9,
      forceFallback: true,
      onEnd: function (evt) {
        handleClassificationReposition(evt)
      }
    })
  }

  function handleClassificationReposition(evt) {
    var classificationId = evt.item.getAttribute('data-classification-id')
    var data = {
      classification: {
        position: parseInt(evt.newIndex, 10) + 1
      }
    }
    var requestData = {
       uri: Spree.routes.classifications_api_v2 + '/' + classificationId,
       method: 'PATCH',
       dataBody: data,
    }
    spreeFetchRequest(requestData)
  }

  if (taxonId.length &gt; 0) {
    taxonId.select2({
      placeholder: Spree.translations.find_a_taxon,
      minimumInputLength: 3,
      multiple: false,
      ajax: {
        url: Spree.routes.taxons_api_v2,
        datatype: 'json',
        headers: Spree.apiV2Authentication(),
        data: function (params, page) {
          return {
            per_page: 50,
            page: page,
            filter: {
              name_cont: params.term
            }
          }
        },
        processResults: function (data, page) {
          var more = page &lt; data.meta.total_pages

          var results = data.data.map(function (obj) {
            return {
              id: obj.id,
              text: obj.attributes.pretty_name
            }
          })

          return {
            results: results,
            pagination: {
              more: more
            }
          }
        }
      }
    }).on('select2:select', function (e) {
      $.ajax({
        url: Spree.routes.classifications_api_v2,
        headers: Spree.apiV2Authentication(),
        data: {
          filter: {
            taxon_id_eq: e.params.data.id
          },
          include: 'product.images',
          per_page: 150,
          sort: 'position'
        }
      }).done(function (json) {
        taxonProducts.empty()

        if (json.meta.total_count === 0) {
          return taxonProducts.html('&lt;p class="text-center w-100 p-4"&gt;' + Spree.translations.no_results + '&lt;/p&gt;')
        } else {
          var results = []

          json.data.forEach(function (classification) {
            var productId = classification.relationships.product.data.id.toString()

            var product = json.included.find(function(included) {
              if (included.type === 'product' &amp;&amp; included.id === productId) {
                return included
              }
            })

            if (product &amp;&amp; classification) {
              var imageUrl = null

              if (product.relationships.images.data.length &gt; 0) {
                var imageId = product.relationships.images.data[0].id

                var image = json.included.find(function(included) {
                  if (included.type === 'image' &amp;&amp; included.id === imageId) {
                    return included
                  }
                })

                if (image &amp;&amp; image.attributes &amp;&amp; image.attributes.styles) {
                  imageUrl = image.attributes.styles[2].url
                }
              }

              results.push(taxonProducts.append(productTemplate({
                product: product,
                classification: classification,
                image: imageUrl
              })))
            }
          })

          return results
        }
      })
    })
  }

  taxonProducts.on('click', '.js-delete-product', function (e) {
    var product = $(this).parents('.product')
    var classificationId = product.data('classification-id')
    $.ajax({
      url: Spree.routes.classifications_api_v2 + '/' + classificationId.toString(),
      headers: Spree.apiV2Authentication(),
      type: 'DELETE'
    }).done(function () {
      product.fadeOut(400, function (e) {
        product.remove()
      })
    })
  })

  $('.variant_autocomplete').variantAutocomplete()
});
document.addEventListener("spree:load", function() {
  var useBilling = $('#user_use_billing')

  if (useBilling.is(':checked')) {
    $('#shipping').hide()
  }

  useBilling.change(function () {
    if (this.checked) {
      $('#shipping').hide()
      return $('#shipping input, #shipping select').prop('disabled', true)
    } else {
      $('#shipping').show()
      $('#shipping input, #shipping select').prop('disabled', false)
    }
  })
});
$.fn.userAutocomplete = function () {
  'use strict'

  function formatUserList(values) {
    return values.map(function (obj) {
      return {
        id: obj.id,
        text: obj.attributes.email
      }
    })
  }

  this.select2({
    multiple: true,
    minimumInputLength: 1,
    ajax: {
      url: Spree.routes.users_api_v2,
      dataType: 'json',
      headers: Spree.apiV2Authentication(),
      data: function (params) {
        return {
          filter: {
            email_i_cont: params.term
          }
        }
      },
      processResults: function(data) {
        return {
          results: formatUserList(data.data)
        }
      }
    }
  })
}

document.addEventListener("spree:load", function() {
  $('.user_picker').userAutocomplete()
});
/* global variantTemplate */
// variant autocompletion
document.addEventListener("spree:load", function() {
  var variantAutocompleteTemplate = $('#variant_autocomplete_template')
  if (variantAutocompleteTemplate.length &gt; 0) {
    window.variantTemplate = Handlebars.compile(variantAutocompleteTemplate.text())
    window.variantStockTemplate = Handlebars.compile($('#variant_autocomplete_stock_template').text())
    window.variantLineItemTemplate = Handlebars.compile($('#variant_line_items_autocomplete_stock_template').text())
  }
})

function formatVariantResult(variant) {
  if (variant.loading) {
    return variant.text
  }

  if (variant['images'][0] !== undefined &amp;&amp; variant['images'][0].transformed_url !== undefined) {
    variant.image = variant.images[0].transformed_url
  }
  return $(variantTemplate({
    variant: variant
  }))
}

$.fn.variantAutocomplete = function () {

  // deal with initSelection
  return this.select2({
    placeholder: Spree.translations.variant_placeholder,
    minimumInputLength: 3,
    quietMillis: 200,
    ajax: {
      url: Spree.url(Spree.routes.variants_api_v2),
      dataType: 'json',
      data: function (params) {
        var query = {
          filter: {
            search_by_product_name_or_sku: params.term
          },
          include: 'images,stock_items.stock_location',
          image_transformation: {
            size: '100x100'
          }
        }

        return query;
      },
      headers: Spree.apiV2Authentication(),
      success: function(data) {
        var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer
        new JSONAPIDeserializer({ keyForAttribute: 'snake_case' }).deserialize(data, function (_err, variants) {
          jsonApiVariants = variants
          window.variants = variants
        })
      },
      processResults: function (_data) {
        return { results: jsonApiVariants } // we need to return deserialized json api data
      }
    },
    templateResult: formatVariantResult,
    templateSelection: function(variant) {
      if (!!variant.options_text) {
        return variant.name + '(' + variant.options_text + ')'
      } else {
        return variant.name
      }
    }
  })

};
document.addEventListener("spree:load", function() {
  $('.track_inventory_checkbox').on('click', function () {
    $(this).siblings('.variant_track_inventory').val($(this).is(':checked'))
    $(this).parents('form').submit()
  })
  $('.toggle_variant_track_inventory').on('submit', function () {
    $.ajax({
      type: this.method,
      url: this.action,
      data: $(this).serialize(),
      dataType: 'json'
    })
    return false
  })
});
document.addEventListener("spree:load", function() {
  var countryBased = $('#country_based')
  var stateBased = $('#state_based')
  countryBased.click(show_country)
  stateBased.click(show_state)
  if (countryBased.is(':checked')) {
    show_country()
  } else if (stateBased.is(':checked')) {
    show_state()
  } else {
    show_state()
    stateBased.click()
  }
})
// eslint-disable-next-line camelcase
function show_country () {
  $('#state_members :input').each(function () {
    $(this).prop('disabled', true)
  })
  $('#state_members').hide()
  $('#zone_members :input').each(function () {
    $(this).prop('disabled', true)
  })
  $('#zone_members').hide()
  $('#country_members :input').each(function () {
    $(this).prop('disabled', false)
  })
  $('#country_members').show()
}
// eslint-disable-next-line camelcase
function show_state () {
  $('#country_members :input').each(function () {
    $(this).prop('disabled', true)
  })
  $('#country_members').hide()
  $('#zone_members :input').each(function () {
    $(this).prop('disabled', true)
  })
  $('#zone_members').hide()
  $('#state_members :input').each(function () {
    $(this).prop('disabled', false)
  })
  $('#state_members').show()
};
$(function() {
  var storage_path_field;
  storage_path_field = $('#storage_path');
  return $('#store_pdf').click(function() {
    return storage_path_field.prop('disabled', !$(this).prop('checked'));
  });
});


// Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js';
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//





;
</pre></body></html>