/*eslint-disable no-unused-vars*/
/*!
 * jQuery JavaScript Library v3.1.0
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2016-07-07T21:44Z
 */

(function (global, factory) {

	"use strict";

	if (typeof module === "object" && 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 #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 <= 12 - 13+, Firefox <=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 document = window.document;

	var getProto = Object.getPrototypeOf;

	var slice = arr.slice;

	var concat = arr.concat;

	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 = {};



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

		var script = doc.createElement("script");

		script.text = code;
		doc.head.appendChild(script).parentNode.removeChild(script);
	}
	/* global Symbol */
	// Defining this global in .eslintrc 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.1.0",

		// 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);
		},

		// Support: Android <=4.0 only
		// Make sure we trim BOM and NBSP
		rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

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

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

	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 num != null ?

				// Return just the one element from the set
				(num < 0 ? this[num + this.length] : this[num]) :

				// Return all the elements in a clean array
				slice.call(this);
		},

		// 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);
		},

		eq: function (i) {
			var len = this.length,
				j = +i + (i < 0 ? len : 0);
			return this.pushStack(j >= 0 && j < 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" && !jQuery.isFunction(target)) {
			target = {};
		}

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

		for (; i < length; i++) {

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

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

					// Prevent never-ending loop
					if (target === copy) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (jQuery.isPlainObject(copy) ||
						(copyIsArray = jQuery.isArray(copy)))) {

						if (copyIsArray) {
							copyIsArray = false;
							clone = src && jQuery.isArray(src) ? src : [];

						} else {
							clone = src && jQuery.isPlainObject(src) ? src : {};
						}

						// 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 () { },

		isFunction: function (obj) {
			return jQuery.type(obj) === "function";
		},

		isArray: Array.isArray,

		isWindow: function (obj) {
			return obj != null && obj === obj.window;
		},

		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") &&

				// parseFloat NaNs numeric-cast false positives ("")
				// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
				// subtraction forces infinities to NaN
				!isNaN(obj - parseFloat(obj));
		},

		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") && proto.constructor;
			return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
		},

		isEmptyObject: function (obj) {

			/* eslint-disable no-unused-vars */
			// See https://github.com/eslint/eslint/issues/6125
			var name;

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

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

			// Support: Android <=2.3 only (functionish RegExp)
			return typeof obj === "object" || typeof obj === "function" ?
				class2type[toString.call(obj)] || "object" :
				typeof obj;
		},

		// Evaluates a script in a global context
		globalEval: function (code) {
			DOMEval(code);
		},

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

		nodeName: function (elem, name) {
			return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
		},

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

			if (isArrayLike(obj)) {
				length = obj.length;
				for (; i < 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;
		},

		// Support: Android <=4.0 only
		trim: function (text) {
			return text == null ?
				"" :
				(text + "").replace(rtrim, "");
		},

		// 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 <=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 < 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 < 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 < 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 concat.apply([], ret);
		},

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

		// Bind a function to a context, optionally partially applying any
		// arguments.
		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 (!jQuery.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;
		},

		now: Date.now,

		// 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 && "length" in obj && obj.length,
			type = jQuery.type(obj);

		if (type === "function" || jQuery.isWindow(obj)) {
			return false;
		}

		return type === "array" || length === 0 ||
			typeof length === "number" && length > 0 && (length - 1) in obj;
	}
	var Sizzle =
	/*!
	 * Sizzle CSS Selector Engine v2.3.0
	 * https://sizzlejs.com/
	 *
	 * Copyright jQuery Foundation and other contributors
	 * Released under the MIT license
	 * http://jquery.org/license
	 *
	 * Date: 2016-01-04
	 */
	(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(),
			sortOrder = function (a, b) {
				if (a === b) {
					hasDuplicate = true;
				}
				return 0;
			},

			// Instance methods
			hasOwn = ({}).hasOwnProperty,
			arr = [],
			pop = arr.pop,
			push_native = 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 < 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]",

			// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
			identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",

			// 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 + "*([>+~]|" + 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"),
				// For use in libraries implementing .is()
				// We use this for POS matching in `select`
				"needsContext": new RegExp("^" + whitespace + "*[>+~]|:(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/,

			// 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-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"),
			funescape = function (_, escaped, escapedWhitespace) {
				var high = "0x" + escaped - 0x10000;
				// NaN means non-codepoint
				// Support: Firefox<24
				// Workaround erroneous numeric interpretation of +"0x"
				return high !== high || escapedWhitespace ?
					escaped :
					high < 0 ?
						// BMP codepoint
						String.fromCharCode(high + 0x10000) :
						// Supplemental Plane codepoint (surrogate pair)
						String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
			},

			// CSS string/identifier serialization
			// https://drafts.csswg.org/cssom/#common-serializing-idioms
			rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\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();
			},

			disabledAncestor = addCombinator(
				function (elem) {
					return elem.disabled === true;
				},
				{ dir: "parentNode", next: "legend" }
			);

		// Optimize for push.apply( _, NodeList )
		try {
			push.apply(
				(arr = slice.call(preferredDoc.childNodes)),
				preferredDoc.childNodes
			);
			// Support: Android<4.0
			// Detect silently failing push.apply
			arr[preferredDoc.childNodes.length].nodeType;
		} catch (e) {
			push = {
				apply: arr.length ?

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

					// Support: IE<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 && 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 && nodeType !== 9 && nodeType !== 11) {

				return results;
			}

			// Try to shortcut find operations (as opposed to filters) in HTML documents
			if (!seed) {

				if ((context ? context.ownerDocument || context : preferredDoc) !== document) {
					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 && (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 && (elem = newContext.getElementById(m)) &&
									contains(context, elem) &&
									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]) && support.getElementsByClassName &&
							context.getElementsByClassName) {

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

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

						if (nodeType !== 1) {
							newContext = context;
							newSelector = selector;

							// qSA looks outside Element context, which is not what we want
							// Thanks to Andrew Dupont for this workaround technique
							// Support: IE <=8
							// Exclude object elements
						} else if (context.nodeName.toLowerCase() !== "object") {

							// 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 + " " + toSelector(groups[i]);
							}
							newSelector = groups.join(",");

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

						if (newSelector) {
							try {
								push.apply(results,
									newContext.querySelectorAll(newSelector)
								);
								return results;
							} catch (qsaError) {
							} 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 + " ") > 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 && a,
				diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
					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" && 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") && 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:
			// IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset)
			// not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
			return function (elem) {

				// Check form elements and option elements for explicit disabling
				return "label" in elem && elem.disabled === disabled ||
					"form" in elem && elem.disabled === disabled ||

					// Check non-disabled form elements for fieldset[disabled] ancestors
					"form" in elem && elem.disabled === false && (
						// Support: IE6-11+
						// Ancestry is covered for us
						elem.isDisabled === disabled ||

						// Otherwise, assume any non-<option> under fieldset[disabled] is disabled
						/* jshint -W018 */
						elem.isDisabled !== !disabled &&
							("label" in elem || !disabledAncestor(elem)) !== disabled
					);
			};
		}

		/**
		 * 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 && typeof context.getElementsByTagName !== "undefined" && 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) {
			// documentElement is verified for cases where it doesn't yet exist
			// (such as loading iframes in IE - #4833)
			var documentElement = elem && (elem.ownerDocument || elem).documentElement;
			return documentElement ? documentElement.nodeName !== "HTML" : false;
		};

		/**
		 * 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
			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
			// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
			if (preferredDoc !== document &&
				(subWindow = document.defaultView) && 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);
				}
			}

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

			// Support: IE<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<9
			support.getElementsByClassName = rnative.test(document.getElementsByClassName);

			// Support: IE<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 find and filter
			if (support.getById) {
				Expr.find["ID"] = function (id, context) {
					if (typeof context.getElementById !== "undefined" && documentIsHTML) {
						var m = context.getElementById(id);
						return m ? [m] : [];
					}
				};
				Expr.filter["ID"] = function (id) {
					var attrId = id.replace(runescape, funescape);
					return function (elem) {
						return elem.getAttribute("id") === attrId;
					};
				};
			} else {
				// Support: IE6/7
				// getElementById is not reliable as a find shortcut
				delete Expr.find["ID"];

				Expr.filter["ID"] = function (id) {
					var attrId = id.replace(runescape, funescape);
					return function (elem) {
						var node = typeof elem.getAttributeNode !== "undefined" &&
							elem.getAttributeNode("id");
						return node && node.value === attrId;
					};
				};
			}

			// 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 && function (className, context) {
				if (typeof context.getElementsByClassName !== "undefined" && 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) {
					// 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 = "<a id='" + expando + "'></a>" +
						"<select id='" + expando + "-\r\\' msallowcapture=''>" +
						"<option selected=''></option></select>";

					// 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<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
					if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
						rbuggyQSA.push("~=");
					}

					// 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(".#.+[+~]");
					}
				});

				assert(function (el) {
					el.innerHTML = "<a href='' disabled='disabled'></a>" +
						"<select disabled='disabled'><option/></select>";

					// 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");
					}

					// 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 && new RegExp(rbuggyQSA.join("|"));
			rbuggyMatches = rbuggyMatches.length && 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 && b.parentNode;
					return a === bup || !!(bup && bup.nodeType === 1 && (
						adown.contains ?
							adown.contains(bup) :
							a.compareDocumentPosition && a.compareDocumentPosition(bup) & 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
				compare = (a.ownerDocument || a) === (b.ownerDocument || b) ?
					a.compareDocumentPosition(b) :

					// Otherwise we know they are disconnected
					1;

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

					// Choose the first element that is related to our preferred document
					if (a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
						return -1;
					}
					if (b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
						return 1;
					}

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

				return compare & 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) {
					return a === document ? -1 :
						b === document ? 1 :
						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
					ap[i] === preferredDoc ? -1 :
					bp[i] === preferredDoc ? 1 :
					0;
			};

			return document;
		};

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

		Sizzle.matchesSelector = function (elem, expr) {
			// Set document vars if needed
			if ((elem.ownerDocument || elem) !== document) {
				setDocument(elem);
			}

			// Make sure that attribute selectors are quoted
			expr = expr.replace(rattributeQuotes, "='$1']");

			if (support.matchesSelector && documentIsHTML &&
				!compilerCache[expr + " "] &&
				(!rbuggyMatches || !rbuggyMatches.test(expr)) &&
				(!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 && elem.document.nodeType !== 11) {
						return ret;
					}
				} catch (e) { }
			}

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

		Sizzle.contains = function (context, elem) {
			// Set document vars if needed
			if ((context.ownerDocument || context) !== document) {
				setDocument(context);
			}
			return contains(context, elem);
		};

		Sizzle.attr = function (elem, name) {
			// Set document vars if needed
			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 && 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)) && 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 && 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: {
				">": { 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] && 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 && rpseudo.test(unquoted) &&
						// Get excess from tokenize (recursively)
						(excess = tokenize(unquoted, true)) &&
						// 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 && elem.nodeName.toLowerCase() === nodeName;
						};
				},

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

					return pattern ||
						(pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) &&
						classCache(className, function (elem) {
							return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && 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 && result.indexOf(check) === 0 :
							operator === "*=" ? check && result.indexOf(check) > -1 :
							operator === "$=" ? check && result.slice(-check.length) === check :
							operator === "~=" ? (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -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 && 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 && elem.nodeName.toLowerCase(),
								useCache = !xml && !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" && !start && "nextSibling";
									}
									return true;
								}

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

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

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

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

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

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

									while ((node = ++nodeIndex && node && 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 && ++diff && 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 <9 only
										// Defend against cloned attroperties (jQuery gh-1709)
										uniqueCache = outerCache[node.uniqueID] ||
											(outerCache[node.uniqueID] = {});

										cache = uniqueCache[type] || [];
										nodeIndex = cache[0] === dirruns && 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 && node && node[dir] ||
											(diff = nodeIndex = 0) || start.pop())) {

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

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

													// Support: IE <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 && diff / first >= 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 > 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 > 0;
					};
				}),

				"contains": markFunction(function (text) {
					text = text.replace(runescape, funescape);
					return function (elem) {
						return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -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) && elem.nodeType === 1);
						return false;
					};
				}),

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

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

				"focus": function (elem) {
					return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(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" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
				},

				"selected": function (elem) {
					// Accessing this property makes selected-by-default
					// options in Safari work properly
					if (elem.parentNode) {
						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 < 6 works because attributes (2) do not appear as children
					for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
						if (elem.nodeType < 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" && elem.type === "button" || name === "button";
				},

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

						// Support: IE<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 < 0 ? argument + length : argument];
				}),

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

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

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

				"gt": createPositionalPseudo(function (matchIndexes, length, argument) {
					var i = argument < 0 ? argument + length : argument;
					for (; ++i < 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)) && (!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 < 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 && 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);
						}
					}
				} :

				// 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 <9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});

								if (skip && skip === elem.nodeName.toLowerCase()) {
									elem = elem[dir] || elem;
								} else if ((oldCache = uniqueCache[key]) &&
									oldCache[0] === dirruns && 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;
									}
								}
							}
						}
					}
				};
		}

		function elementMatcher(matchers) {
			return matchers.length > 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 < 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 < 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 && !postFilter[expando]) {
				postFilter = setMatcher(postFilter);
			}
			if (postFinder && !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 && (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]) &&
								(temp = postFinder ? indexOf(seed, elem) : preMap[i]) > -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) > -1;
				}, implicitRelative, true),
				matchers = [function (elem, context, xml) {
					var ret = (!leadingRelative && (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 < 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 < len; j++) {
							if (Expr.relative[tokens[j].type]) {
								break;
							}
						}
						return setMatcher(
							i > 1 && elementMatcher(matchers),
							i > 1 && 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 < j && matcherFromTokens(tokens.slice(i, j)),
							j < len && matcherFromTokens((tokens = tokens.slice(j))),
							j < len && toSelector(tokens)
						);
					}
					matchers.push(matcher);
				}
			}

			return elementMatcher(matchers);
		}

		function matcherFromGroupMatchers(elementMatchers, setMatchers) {
			var bySet = setMatchers.length > 0,
				byElement = elementMatchers.length > 0,
				superMatcher = function (seed, context, xml, results, outermost) {
					var elem, j, matcher,
						matchedCount = 0,
						i = "0",
						unmatched = seed && [],
						setMatched = [],
						contextBackup = outermostContext,
						// We must always have either seed elements or outermost context
						elems = seed || byElement && 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) {
						outermostContext = context === document || context || outermost;
					}

					// Add elements passing elementMatchers directly to results
					// Support: IE<9, Safari
					// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
					for (; i !== len && (elem = elems[i]) != null; i++) {
						if (byElement && elem) {
							j = 0;
							if (!context && 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 && 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 && 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 > 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 && !seed && setMatched.length > 0 &&
							(matchedCount + setMatchers.length) > 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" && selector,
				match = !seed && 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 > 2 && (token = tokens[0]).type === "ID" &&
						support.getById && context.nodeType === 9 && documentIsHTML &&
						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) && testContext(context.parentNode) || context
						))) {

							// If seed is empty or no tokens remain, we can return early
							tokens.splice(i, 1);
							selector = seed.length && 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) && 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<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")) & 1;
		});

		// Support: IE<8
		// Prevent attribute/property "interpolation"
		// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
		if (!assert(function (el) {
			el.innerHTML = "<a href='#'></a>";
			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<9
		// Use defaultValue in place of getAttribute("value")
		if (!support.attributes || !assert(function (el) {
			el.innerHTML = "<input/>";
			el.firstChild.setAttribute("value", "");
			return el.firstChild.getAttribute("value") === "";
		})) {
			addHandle("value", function (elem, name, isXML) {
				if (!isXML && elem.nodeName.toLowerCase() === "input") {
					return elem.defaultValue;
				}
			});
		}

		// Support: IE<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)) && 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]) && elem.nodeType !== 9) {
			if (elem.nodeType === 1) {
				if (truncate && 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 && n !== elem) {
				matched.push(n);
			}
		}

		return matched;
	};


	var rneedsContext = jQuery.expr.match.needsContext;

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



	var risSimple = /^.[^:#\[\.,]*$/;

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

		}

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

		}

		if (typeof qualifier === "string") {
			if (risSimple.test(qualifier)) {
				return jQuery.filter(qualifier, elements, not);
			}

			qualifier = jQuery.filter(qualifier, elements);
		}

		return jQuery.grep(elements, function (elem) {
			return (indexOf.call(qualifier, elem) > -1) !== not && elem.nodeType === 1;
		});
	}

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

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

		return elems.length === 1 && elem.nodeType === 1 ?
			jQuery.find.matchesSelector(elem, expr) ? [elem] : [] :
			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 < len; i++) {
						if (jQuery.contains(self[i], this)) {
							return true;
						}
					}
				}));
			}

			ret = this.pushStack([]);

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

			return len > 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" && 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 <tag> to avoid XSS via location.hash (#9521)
		// Strict HTML recognition (#11290: must start with <)
		// Shortcut simple #id case for speed
		rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\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] === "<" &&
					selector[selector.length - 1] === ">" &&
					selector.length >= 3) {

					// Assume that strings that start and end with <> 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 && (match[1] || !context)) {

					// HANDLE: $(html) -> $(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 && context.nodeType ? context.ownerDocument || context : document,
							true
						));

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

								// Properties of context are called as methods if possible
								if (jQuery.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 (jQuery.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 < 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" && jQuery(selectors);

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

						// Always skip document fragments
						if (cur.nodeType < 11 && (targets ?
							targets.index(cur) > -1 :

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

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

			return this.pushStack(matched.length > 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] && 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]) && cur.nodeType !== 1) { }
		return cur;
	}

	jQuery.each({
		parent: function (elem) {
			var parent = elem.parentNode;
			return parent && 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) {
			return elem.contentDocument || 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 && typeof selector === "string") {
				matched = jQuery.filter(selector, matched);
			}

			if (this.length > 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 rnotwhite = (/\S+/g);



	// Convert String-formatted options into Object-formatted ones
	function createOptions(options) {
		var object = {};
		jQuery.each(options.match(rnotwhite) || [], 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 = 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 < list.length) {

						// Run callback and check for early termination
						if (list[firingIndex].apply(memory[0], memory[1]) === false &&
							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 && !firing) {
							firingIndex = list.length - 1;
							queue.push(memory);
						}

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

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

						if (memory && !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)) > -1) {
							list.splice(index, 1);

							// Handle firing indexes
							if (index <= 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) > -1 :
						list.length > 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 && !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) {
		var method;

		try {

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

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

				// Other non-thenables
			} else {

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

			// 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.call(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 = jQuery.isFunction(fns[tuple[4]]) && 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 && fn.apply(this, arguments);
									if (returned && jQuery.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 < 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 &&

											// 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") &&
											returned.then;

										// Handle a returned thenable
										if (jQuery.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 >= 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,
									jQuery.isFunction(onProgress) ?
								onProgress :
										Identity,
									newDefer.notifyWith
								)
							);

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

							// rejected_handlers.add( ... )
							tuples[2][3].add(
								resolve(
									0,
									newDefer,
									jQuery.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,

						// progress_callbacks.lock
						tuples[0][2].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 master Deferred
				master = jQuery.Deferred(),

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

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

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

					return master.then();
				}
			}

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

			return master.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 && window.console.warn && error && 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 #6781
		readyWait: 1,

		// Hold (or release) the ready event
		holdReady: function (hold) {
			if (hold) {
				jQuery.readyWait++;
			} else {
				jQuery.ready(true);
			}
		},

		// 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 && --jQuery.readyWait > 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 <=9 - 10 only
	// Older IE sometimes signals "interactive" too soon
	if (document.readyState === "complete" ||
		(document.readyState !== "loading" && !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 (jQuery.type(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 (!jQuery.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 < len; i++) {
					fn(
						elems[i], key, raw ?
						value :
						value.call(elems[i], i, fn(elems[i], key))
					);
				}
			}
		}

		return chainable ?
			elems :

			// Gets
			bulk ?
				fn.call(elems) :
				len ? fn(elems[0], key) : emptyGet;
	};
	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 #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[jQuery.camelCase(data)] = value;

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

				// Copy the properties one-by-one to the cache object
				for (prop in data) {
					cache[jQuery.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] && owner[this.expando][jQuery.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 && typeof key === "string") && 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 (jQuery.isArray(key)) {

					// If key is an array of keys...
					// We always set camelCase keys, so remove that.
					key = key.map(jQuery.camelCase);
				} else {
					key = jQuery.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(rnotwhite) || []);
				}

				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 <=35 - 45
				// Webkit & 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 && !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 dataAttr(elem, key, data) {
		var name;

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

			if (typeof data === "string") {
				try {
					data = data === "true" ? true :
						data === "false" ? false :
						data === "null" ? null :

						// Only convert to a number if it doesn't change the string
						+data + "" === data ? +data :
						rbrace.test(data) ? JSON.parse(data) :
						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 && elem.attributes;

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

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

							// Support: IE 11 only
							// The attrs elements can be null (#14894)
							if (attrs[i]) {
								name = attrs[i].name;
								if (name.indexOf("data-") === 0) {
									name = jQuery.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 && 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 > 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 || jQuery.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 && 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 < 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" && 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 && 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 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 === "" &&

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

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

	var swap = function (elem, options, callback, args) {
		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.apply(elem, args || []);

		// Revert the old values
		for (name in options) {
			elem.style[name] = old[name];
		}

		return ret;
	};




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

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

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

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

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

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

			do {

				// If previous iteration zeroed out, double until we get *something*.
				// Use string for doubling so we don't accidentally see scale as unchanged below
				scale = scale || ".5";

				// Adjust and apply
				initialInUnit = initialInUnit / scale;
				jQuery.style(elem, prop, initialInUnit + unit);

				// Update scale, tolerating zero or NaN from tween.cur()
				// Break the loop if scale is unchanged or perfect, or if we've just had enough.
			} while (
				scale !== (scale = currentValue() / initial) && scale !== 1 && --maxIterations
			);
		}

		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 < 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 === "" && 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 < 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 = (/<([a-z][^\/\0>\x20\t\r\n\f]+)/i);

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



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

		// Support: IE <=9 only
		option: [1, "<select multiple='multiple'>", "</select>"],

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

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

	// Support: IE <=9 only
	wrapMap.optgroup = wrapMap.option;

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


	function getAll(context, tag) {

		// Support: IE <=9 - 11 only
		// Use typeof to avoid zero-argument method invocation on host objects (#15151)
		var ret = typeof context.getElementsByTagName !== "undefined" ?
				context.getElementsByTagName(tag || "*") :
				typeof context.querySelectorAll !== "undefined" ?
					context.querySelectorAll(tag || "*") :
				[];

		return tag === undefined || tag && jQuery.nodeName(context, tag) ?
			jQuery.merge([context], ret) :
			ret;
	}


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

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


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

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

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

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

				// Add nodes directly
				if (jQuery.type(elem) === "object") {

					// Support: Android <=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 <=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 (#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 && jQuery.inArray(elem, selection) > -1) {
				if (ignored) {
					ignored.push(elem);
				}
				continue;
			}

			contains = jQuery.contains(elem.ownerDocument, elem);

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

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

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

		return fragment;
	}


	(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 (#11217)
		// Support: Windows Web Apps (WWA)
		// `name` and `type` must use .setAttribute for WWA (#14901)
		input.setAttribute("type", "radio");
		input.setAttribute("checked", "checked");
		input.setAttribute("name", "t");

		div.appendChild(input);

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

		// Support: IE <=11 only
		// Make sure textarea (and checkbox) defaultValue is properly cloned
		div.innerHTML = "<textarea>x</textarea>";
		support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;
	})();
	var documentElement = document.documentElement;



	var
		rkeyEvent = /^key/,
		rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
		rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

	function returnTrue() {
		return true;
	}

	function returnFalse() {
		return false;
	}

	// Support: IE <=9 only
	// See #13393 for more info
	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 && 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);

			// Don't attach events to noData or text/comment nodes (but allow plain objects)
			if (!elemData) {
				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 = {};
			}
			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" && jQuery.event.triggered !== e.type ?
						jQuery.event.dispatch.apply(elem, arguments) : undefined;
				};
			}

			// Handle multiple events separated by a space
			types = (types || "").match(rnotwhite) || [""];
			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 && 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) && dataPriv.get(elem);

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

			// Once for each type.namespace in types; type may be omitted
			types = (types || "").match(rnotwhite) || [""];
			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] &&
					new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");

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

					if ((mappedTypes || origType === handleObj.origType) &&
						(!handler || handler.guid === handleObj.guid) &&
						(!tmp || tmp.test(handleObj.namespace)) &&
						(!selector || selector === handleObj.selector ||
							selector === "**" && 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 && !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) {

			// Make a writable jQuery.Event from the native event object
			var event = jQuery.event.fix(nativeEvent);

			var i, j, ret, matched, handleObj, handlerQueue,
				args = new Array(arguments.length),
				handlers = (dataPriv.get(this, "events") || {})[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 < 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 && 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++]) && !event.isPropagationStopped()) {
				event.currentTarget = matched.elem;

				j = 0;
				while ((handleObj = matched.handlers[j++]) &&
					!event.isImmediatePropagationStopped()) {

					// Triggered event must either 1) have no namespace, or 2) have namespace(s)
					// a subset or equal to those in the bound event (both can have no namespace).
					if (!event.rnamespace || 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, matches, sel, handleObj,
				handlerQueue = [],
				delegateCount = handlers.delegateCount,
				cur = event.target;

			// Support: IE <=9
			// Find delegate handlers
			// Black-hole SVG <use> instance trees (#13180)
			//
			// Support: Firefox <=42
			// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
			if (delegateCount && cur.nodeType &&
				(event.type !== "click" || isNaN(event.button) || event.button < 1)) {

				for (; cur !== this; cur = cur.parentNode || this) {

					// Don't check non-elements (#13208)
					// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
					if (cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click")) {
						matches = [];
						for (i = 0; i < delegateCount; i++) {
							handleObj = handlers[i];

							// Don't conflict with Object.prototype properties (#13203)
							sel = handleObj.selector + " ";

							if (matches[sel] === undefined) {
								matches[sel] = handleObj.needsContext ?
									jQuery(sel, this).index(cur) > -1 :
									jQuery.find(sel, this, null, [cur]).length;
							}
							if (matches[sel]) {
								matches.push(handleObj);
							}
						}
						if (matches.length) {
							handlerQueue.push({ elem: cur, handlers: matches });
						}
					}
				}
			}

			// Add the remaining (directly-bound) handlers
			if (delegateCount < handlers.length) {
				handlerQueue.push({ elem: this, handlers: handlers.slice(delegateCount) });
			}

			return handlerQueue;
		},

		addProp: function (name, hook) {
			Object.defineProperty(jQuery.Event.prototype, name, {
				enumerable: true,
				configurable: true,

				get: jQuery.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
			},
			focus: {

				// Fire native event if possible so blur/focus sequence is correct
				trigger: function () {
					if (this !== safeActiveElement() && this.focus) {
						this.focus();
						return false;
					}
				},
				delegateType: "focusin"
			},
			blur: {
				trigger: function () {
					if (this === safeActiveElement() && this.blur) {
						this.blur();
						return false;
					}
				},
				delegateType: "focusout"
			},
			click: {

				// For checkbox, fire native event so checked state will be right
				trigger: function () {
					if (this.type === "checkbox" && this.click && jQuery.nodeName(this, "input")) {
						this.click();
						return false;
					}
				},

				// For cross-browser consistency, don't fire native .click() on links
				_default: function (event) {
					return jQuery.nodeName(event.target, "a");
				}
			},

			beforeunload: {
				postDispatch: function (event) {

					// Support: Firefox 20+
					// Firefox doesn't alert if the returnValue field is not set.
					if (event.result !== undefined && event.originalEvent) {
						event.originalEvent.returnValue = event.result;
					}
				}
			}
		}
	};

	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 && 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 &&

					// Support: Android <=2.3 only
					src.returnValue === false ?
				returnTrue :
				returnFalse;

			// Create target properties
			// Support: Safari <=6 - 7 only
			// Target should not be a text node (#504, #13143)
			this.target = (src.target && 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 && src.timeStamp || jQuery.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 && !this.isSimulated) {
				e.preventDefault();
			}
		},
		stopPropagation: function () {
			var e = this.originalEvent;

			this.isPropagationStopped = returnTrue;

			if (e && !this.isSimulated) {
				e.stopPropagation();
			}
		},
		stopImmediatePropagation: function () {
			var e = this.originalEvent;

			this.isImmediatePropagationStopped = returnTrue;

			if (e && !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,
		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: function (event) {
			var button = event.button;

			// Add which for key events
			if (event.which == null && rkeyEvent.test(event.type)) {
				return event.charCode != null ? event.charCode : event.keyCode;
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			if (!event.which && button !== undefined && rmouseEvent.test(event.type)) {
				return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
			}

			return event.which;
		}
	}, jQuery.event.addProp);

	// 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 && !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 && types.preventDefault && 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

		/* eslint-disable max-len */

		// See https://github.com/eslint/eslint/issues/3229
		rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,

		/* eslint-enable */

		// Support: IE <=10 - 11, Edge 12 - 13
		// In IE/Edge using regex groups here causes severe slowdowns.
		// See https://connect.microsoft.com/IE/feedback/details/1736512/
		rnoInnerhtml = /<script|<style|<link/i,

		// checked="checked" or checked
		rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
		rscriptTypeMasked = /^true\/(.*)/,
		rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;

	function manipulationTarget(elem, content) {
		if (jQuery.nodeName(elem, "table") &&
			jQuery.nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr")) {

			return elem.getElementsByTagName("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) {
		var match = rscriptTypeMasked.exec(elem.type);

		if (match) {
			elem.type = match[1];
		} else {
			elem.removeAttribute("type");
		}

		return elem;
	}

	function cloneCopyEvent(src, dest) {
		var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;

		if (dest.nodeType !== 1) {
			return;
		}

		// 1. Copy private data: events, handlers, etc.
		if (dataPriv.hasData(src)) {
			pdataOld = dataPriv.access(src);
			pdataCur = dataPriv.set(dest, pdataOld);
			events = pdataOld.events;

			if (events) {
				delete pdataCur.handle;
				pdataCur.events = {};

				for (type in events) {
					for (i = 0, l = events[type].length; i < 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" && 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 = concat.apply([], args);

		var fragment, first, scripts, hasScripts, node, doc,
			i = 0,
			l = collection.length,
			iNoClone = l - 1,
			value = args[0],
			isFunction = jQuery.isFunction(value);

		// We can't cloneNode fragments that contain checked, in WebKit
		if (isFunction ||
				(l > 1 && typeof value === "string" &&
					!support.checkClone && rchecked.test(value))) {
			return collection.each(function (index) {
				var self = collection.eq(index);
				if (isFunction) {
					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 (#8070).
				for (; i < 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 <=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 < hasScripts; i++) {
						node = scripts[i];
						if (rscriptType.test(node.type || "") &&
							!dataPriv.access(node, "globalEval") &&
							jQuery.contains(doc, node)) {

							if (node.src) {

								// Optional AJAX dependency, but won't run scripts if not present
								if (jQuery._evalUrl) {
									jQuery._evalUrl(node.src);
								}
							} else {
								DOMEval(node.textContent.replace(rcleanScript, ""), 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 && node.nodeType === 1) {
				jQuery.cleanData(getAll(node));
			}

			if (node.parentNode) {
				if (keepData && jQuery.contains(node.ownerDocument, node)) {
					setGlobalEval(getAll(node, "script"));
				}
				node.parentNode.removeChild(node);
			}
		}

		return elem;
	}

	jQuery.extend({
		htmlPrefilter: function (html) {
			return html.replace(rxhtmlTag, "<$1></$2>");
		},

		clone: function (elem, dataAndEvents, deepDataAndEvents) {
			var i, l, srcElements, destElements,
				clone = elem.cloneNode(true),
				inPage = jQuery.contains(elem.ownerDocument, elem);

			// Fix IE cloning issues
			if (!support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) &&
					!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 < 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 < l; i++) {
						cloneCopyEvent(srcElements[i], destElements[i]);
					}
				} else {
					cloneCopyEvent(elem, clone);
				}
			}

			// Preserve script evaluation history
			destElements = getAll(clone, "script");
			if (destElements.length > 0) {
				setGlobalEval(destElements, !inPage && 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 <=35 - 45+
						// Assign undefined instead of using delete, see Data#remove
						elem[dataPriv.expando] = undefined;
					}
					if (elem[dataUser.expando]) {

						// Support: Chrome <=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 && elem.nodeType === 1) {
					return elem.innerHTML;
				}

				// See if we can take a shortcut and just use innerHTML
				if (typeof value === "string" && !rnoInnerhtml.test(value) &&
					!wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {

					value = jQuery.htmlPrefilter(value);

					try {
						for (; i < 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) < 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 <= last; i++) {
				elems = i === last ? this : this.clone(true);
				jQuery(insert[i])[original](elems);

				// Support: Android <=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 rmargin = (/^margin/);

	var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");

	var getStyles = function (elem) {

		// Support: IE <=11 only, Firefox <=30 (#15098, #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);
	};



	(function () {

		// Executing both pixelPosition & 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;
			}

			div.style.cssText =
				"box-sizing:border-box;" +
				"position:relative;display:block;" +
				"margin:auto;border:1px;padding:1px;" +
				"top:1%;width:50%";
			div.innerHTML = "";
			documentElement.appendChild(container);

			var divStyle = window.getComputedStyle(div);
			pixelPositionVal = divStyle.top !== "1%";

			// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
			reliableMarginLeftVal = divStyle.marginLeft === "2px";
			boxSizingReliableVal = divStyle.width === "4px";

			// Support: Android 4.0 - 4.3 only
			// Some styles come back with percentage values, even though they shouldn't
			div.style.marginRight = "50%";
			pixelMarginRightVal = divStyle.marginRight === "4px";

			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;
		}

		var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
			container = document.createElement("div"),
			div = document.createElement("div");

		// Finish early in limited (non-browser) environments
		if (!div.style) {
			return;
		}

		// Support: IE <=9 - 11 only
		// Style of cloned element affects source element cloned (#8908)
		div.style.backgroundClip = "content-box";
		div.cloneNode(true).style.backgroundClip = "";
		support.clearCloneStyle = div.style.backgroundClip === "content-box";

		container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
			"padding:0;margin-top:1px;position:absolute";
		container.appendChild(div);

		jQuery.extend(support, {
			pixelPosition: function () {
				computeStyleTests();
				return pixelPositionVal;
			},
			boxSizingReliable: function () {
				computeStyleTests();
				return boxSizingReliableVal;
			},
			pixelMarginRight: function () {
				computeStyleTests();
				return pixelMarginRightVal;
			},
			reliableMarginLeft: function () {
				computeStyleTests();
				return reliableMarginLeftVal;
			}
		});
	})();


	function curCSS(elem, name, computed) {
		var width, minWidth, maxWidth, ret,
			style = elem.style;

		computed = computed || getStyles(elem);

		// Support: IE <=9 only
		// getPropertyValue is only needed for .css('filter') (#12537)
		if (computed) {
			ret = computed.getPropertyValue(name) || computed[name];

			if (ret === "" && !jQuery.contains(elem.ownerDocument, 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.pixelMarginRight() && rnumnonpx.test(ret) && rmargin.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 <=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

		// 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"
		},

		cssPrefixes = ["Webkit", "Moz", "ms"],
		emptyStyle = document.createElement("div").style;

	// Return a css property mapped to a potentially vendor prefixed property
	function vendorPropName(name) {

		// Shortcut for names that are not vendor prefixed
		if (name in emptyStyle) {
			return 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;
			}
		}
	}

	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 augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) {
		var i = extra === (isBorderBox ? "border" : "content") ?

			// If we already have the right measurement, avoid augmentation
			4 :

			// Otherwise initialize for horizontal or vertical properties
			name === "width" ? 1 : 0,

			val = 0;

		for (; i < 4; i += 2) {

			// Both box models exclude margin, so add it if we want it
			if (extra === "margin") {
				val += jQuery.css(elem, extra + cssExpand[i], true, styles);
			}

			if (isBorderBox) {

				// border-box includes padding, so remove it if we want content
				if (extra === "content") {
					val -= jQuery.css(elem, "padding" + cssExpand[i], true, styles);
				}

				// At this point, extra isn't border nor margin, so remove border
				if (extra !== "margin") {
					val -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
				}
			} else {

				// At this point, extra isn't content, so add padding
				val += jQuery.css(elem, "padding" + cssExpand[i], true, styles);

				// At this point, extra isn't content nor padding, so add border
				if (extra !== "padding") {
					val += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
				}
			}
		}

		return val;
	}

	function getWidthOrHeight(elem, name, extra) {

		// Start with offset property, which is equivalent to the border-box value
		var val,
			valueIsBorderBox = true,
			styles = getStyles(elem),
			isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box";

		// Support: IE <=11 only
		// Running getBoundingClientRect on a disconnected node
		// in IE throws an error.
		if (elem.getClientRects().length) {
			val = elem.getBoundingClientRect()[name];
		}

		// Some non-html elements return undefined for offsetWidth, so check for null/undefined
		// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
		// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
		if (val <= 0 || val == null) {

			// Fall back to computed then uncomputed css if necessary
			val = curCSS(elem, name, styles);
			if (val < 0 || val == null) {
				val = elem.style[name];
			}

			// Computed unit is not pixels. Stop here and return.
			if (rnumnonpx.test(val)) {
				return val;
			}

			// Check for style in case a browser which returns unreliable values
			// for getComputedStyle silently falls back to the reliable elem.style
			valueIsBorderBox = isBorderBox &&
				(support.boxSizingReliable() || val === elem.style[name]);

			// Normalize "", auto, and prepare for extra
			val = parseFloat(val) || 0;
		}

		// Use the active box-sizing model to add/subtract irrelevant styles
		return (val +
			augmentWidthOrHeight(
				elem,
				name,
				extra || (isBorderBox ? "border" : "content"),
				valueIsBorderBox,
				styles
			)
		) + "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,
			"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: {
			"float": "cssFloat"
		},

		// 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 = jQuery.camelCase(name),
				style = elem.style;

			name = jQuery.cssProps[origName] ||
				(jQuery.cssProps[origName] = vendorPropName(origName) || 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 (#7345)
				if (type === "string" && (ret = rcssNum.exec(value)) && ret[1]) {
					value = adjustCSS(elem, name, ret);

					// Fixes bug #9237
					type = "number";
				}

				// Make sure that null and NaN values aren't set (#7116)
				if (value == null || value !== value) {
					return;
				}

				// If a number was passed in, add the unit (except for certain CSS properties)
				if (type === "number") {
					value += ret && ret[3] || (jQuery.cssNumber[origName] ? "" : "px");
				}

				// background-* props affect original clone's values
				if (!support.clearCloneStyle && value === "" && 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) {

					style[name] = value;
				}

			} else {

				// If a hook was provided get the non-computed value from there
				if (hooks && "get" in hooks &&
					(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 = jQuery.camelCase(name);

			// Make sure that we're working with the right name
			name = jQuery.cssProps[origName] ||
				(jQuery.cssProps[origName] = vendorPropName(origName) || 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 && "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" && 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, name) {
		jQuery.cssHooks[name] = {
			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")) &&

						// Support: Safari 8+
						// Table columns in Safari have non-zero offsetWidth & zero
						// getBoundingClientRect().width unless display is changed.
						// Support: IE <=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, name, extra);
							}) :
							getWidthOrHeight(elem, name, extra);
				}
			},

			set: function (elem, value, extra) {
				var matches,
					styles = extra && getStyles(elem),
					subtract = extra && augmentWidthOrHeight(
						elem,
						name,
						extra,
						jQuery.css(elem, "boxSizing", false, styles) === "border-box",
						styles
					);

				// Convert to pixels if value adjustment is needed
				if (subtract && (matches = rcssNum.exec(value)) &&
					(matches[3] || "px") !== "px") {

					elem.style[name] = value;
					value = jQuery.css(elem, name);
				}

				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 < 4; i++) {
					expanded[prefix + cssExpand[i] + suffix] =
						parts[i] || parts[i - 2] || parts[0];
				}

				return expanded;
			}
		};

		if (!rmargin.test(prefix)) {
			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 (jQuery.isArray(name)) {
					styles = getStyles(elem);
					len = name.length;

					for (; i < 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 > 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 && 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 && 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 && 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 &&
					(tween.elem.style[jQuery.cssProps[tween.prop]] != null ||
						jQuery.cssHooks[tween.prop])) {
					jQuery.style(tween.elem, tween.prop, tween.now + tween.unit);
				} else {
					tween.elem[tween.prop] = tween.now;
				}
			}
		}
	};

	// Support: IE <=9 only
	// Panic based approach to setting things on disconnected nodes
	Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
		set: function (tween) {
			if (tween.elem.nodeType && 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 <1.8 extension point
	jQuery.fx.step = {};




	var
		fxNow, timerId,
		rfxtypes = /^(?:toggle|show|hide)$/,
		rrun = /queueHooks$/;

	function raf() {
		if (timerId) {
			window.requestAnimationFrame(raf);
			jQuery.fx.tick();
		}
	}

	// Animations created synchronously will run synchronously
	function createFxNow() {
		window.setTimeout(function () {
			fxNow = undefined;
		});
		return (fxNow = jQuery.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 < 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 < 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 && 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" && dataShow && dataShow[prop] !== undefined) {
						hidden = true;

						// Ignore all other no-op show/hide data
					} else {
						continue;
					}
				}
				orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop);
			}
		}

		// Bail out if this is a no-op like .hide().hide()
		propTween = !jQuery.isEmptyObject(props);
		if (!propTween && jQuery.isEmptyObject(orig)) {
			return;
		}

		// Restrict "overflow" and "display" styles during box animations
		if (isBox && elem.nodeType === 1) {

			// Support: IE <=9 - 11, Edge 12 - 13
			// Record all 3 overflow attributes because IE does not infer the shorthand
			// from identically-valued overflowX and overflowY
			opts.overflow = [style.overflow, style.overflowX, style.overflowY];

			// Identify a display type, preferring old show/hide data over the CSS cascade
			restoreDisplay = dataShow && 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" && 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 = jQuery.camelCase(index);
			easing = specialEasing[name];
			value = props[index];
			if (jQuery.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 && "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 )` (#12497)
					temp = remaining / animation.duration || 0,
					percent = 1 - temp,
					index = 0,
					length = animation.tweens.length;

				for (; index < length; index++) {
					animation.tweens[index].run(percent);
				}

				deferred.notifyWith(elem, [animation, percent, remaining]);

				if (percent < 1 && length) {
					return remaining;
				} else {
					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 < 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 < length; index++) {
			result = Animation.prefilters[index].call(animation, elem, props, animation.opts);
			if (result) {
				if (jQuery.isFunction(result.stop)) {
					jQuery._queueHooks(animation.elem, animation.opts.queue).stop =
						jQuery.proxy(result.stop, result);
				}
				return result;
			}
		}

		jQuery.map(props, createTween, animation);

		if (jQuery.isFunction(animation.opts.start)) {
			animation.opts.start.call(elem, animation);
		}

		jQuery.fx.timer(
			jQuery.extend(tick, {
				elem: elem,
				anim: animation,
				queue: animation.opts.queue
			})
		);

		// attach callbacks from options
		return animation.progress(animation.opts.progress)
			.done(animation.opts.done, animation.opts.complete)
			.fail(animation.opts.fail)
			.always(animation.opts.always);
	}

	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 (jQuery.isFunction(props)) {
				callback = props;
				props = ["*"];
			} else {
				props = props.match(rnotwhite);
			}

			var prop,
				index = 0,
				length = props.length;

			for (; index < 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 && typeof speed === "object" ? jQuery.extend({}, speed) : {
			complete: fn || !fn && easing ||
				jQuery.isFunction(speed) && speed,
			duration: speed,
			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
		};

		// Go to the end state if fx are off or if document is hidden
		if (jQuery.fx.off || document.hidden) {
			opt.duration = 0;

		} else {
			opt.duration = typeof opt.duration === "number" ?
				opt.duration : opt.duration in jQuery.fx.speeds ?
					jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
		}

		// Normalize opt.queue - true/undefined/null -> "fx"
		if (opt.queue == null || opt.queue === true) {
			opt.queue = "fx";
		}

		// Queueing
		opt.old = opt.complete;

		opt.complete = function () {
			if (jQuery.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 && type !== false) {
				this.queue(type || "fx", []);
			}

			return this.each(function () {
				var dequeue = true,
					index = type != null && type + "queueHooks",
					timers = jQuery.timers,
					data = dataPriv.get(this);

				if (index) {
					if (data[index] && data[index].stop) {
						stopQueue(data[index]);
					}
				} else {
					for (index in data) {
						if (data[index] && data[index].stop && rrun.test(index)) {
							stopQueue(data[index]);
						}
					}
				}

				for (index = timers.length; index--;) {
					if (timers[index].elem === this &&
						(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 && 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 && 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 < length; index++) {
					if (queue[index] && 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 = jQuery.now();

		for (; i < timers.length; i++) {
			timer = timers[i];

			// Checks the timer has not already been removed
			if (!timer() && timers[i] === timer) {
				timers.splice(i--, 1);
			}
		}

		if (!timers.length) {
			jQuery.fx.stop();
		}
		fxNow = undefined;
	};

	jQuery.fx.timer = function (timer) {
		jQuery.timers.push(timer);
		if (timer()) {
			jQuery.fx.start();
		} else {
			jQuery.timers.pop();
		}
	};

	jQuery.fx.interval = 13;
	jQuery.fx.start = function () {
		if (!timerId) {
			timerId = window.requestAnimationFrame ?
				window.requestAnimationFrame(raf) :
				window.setInterval(jQuery.fx.tick, jQuery.fx.interval);
		}
	};

	jQuery.fx.stop = function () {
		if (window.cancelAnimationFrame) {
			window.cancelAnimationFrame(timerId);
		} else {
			window.clearInterval(timerId);
		}

		timerId = null;
	};

	jQuery.fx.speeds = {
		slow: 600,
		fast: 200,

		// Default speed
		_default: 400
	};


	// Based off of the plugin by Clint Helfers, with permission.
	// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
	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 <=4.3 only
		// Default value for a checkbox should be "on"
		support.checkOn = input.value !== "";

		// Support: IE <=11 only
		// Must access selectedIndex to make default options select
		support.optSelected = opt.selected;

		// Support: IE <=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 > 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 && "set" in hooks &&
					(ret = hooks.set(elem, value, name)) !== undefined) {
					return ret;
				}

				elem.setAttribute(name, value + "");
				return value;
			}

			if (hooks && "get" in hooks && (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 && value === "radio" &&
						jQuery.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,
				attrNames = value && value.match(rnotwhite);

			if (attrNames && 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 > 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 && "set" in hooks &&
					(ret = hooks.set(elem, value, name)) !== undefined) {
					return ret;
				}

				return (elem[name] = value);
			}

			if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
				return ret;
			}

			return elem[name];
		},

		propHooks: {
			tabIndex: {
				get: function (elem) {

					// Support: IE <=9 - 11 only
					// elem.tabIndex doesn't always return the
					// correct value when it hasn't been explicitly set
					// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
					// Use proper attribute retrieval(#12072)
					var tabindex = jQuery.find.attr(elem, "tabindex");

					return tabindex ?
						parseInt(tabindex, 10) :
						rfocusable.test(elem.nodeName) ||
							rclickable.test(elem.nodeName) && elem.href ?
								0 :
								-1;
				}
			}
		},

		propFix: {
			"for": "htmlFor",
			"class": "className"
		}
	});

	// Support: IE <=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
	if (!support.optSelected) {
		jQuery.propHooks.selected = {
			get: function (elem) {
				var parent = elem.parentNode;
				if (parent && parent.parentNode) {
					parent.parentNode.selectedIndex;
				}
				return null;
			},
			set: function (elem) {
				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;
	});




	var rclass = /[\t\r\n\f]/g;

	function getClass(elem) {
		return elem.getAttribute && elem.getAttribute("class") || "";
	}

	jQuery.fn.extend({
		addClass: function (value) {
			var classes, elem, cur, curValue, clazz, j, finalValue,
				i = 0;

			if (jQuery.isFunction(value)) {
				return this.each(function (j) {
					jQuery(this).addClass(value.call(this, j, getClass(this)));
				});
			}

			if (typeof value === "string" && value) {
				classes = value.match(rnotwhite) || [];

				while ((elem = this[i++])) {
					curValue = getClass(elem);
					cur = elem.nodeType === 1 &&
						(" " + curValue + " ").replace(rclass, " ");

					if (cur) {
						j = 0;
						while ((clazz = classes[j++])) {
							if (cur.indexOf(" " + clazz + " ") < 0) {
								cur += clazz + " ";
							}
						}

						// Only assign if different to avoid unneeded rendering.
						finalValue = jQuery.trim(cur);
						if (curValue !== finalValue) {
							elem.setAttribute("class", finalValue);
						}
					}
				}
			}

			return this;
		},

		removeClass: function (value) {
			var classes, elem, cur, curValue, clazz, j, finalValue,
				i = 0;

			if (jQuery.isFunction(value)) {
				return this.each(function (j) {
					jQuery(this).removeClass(value.call(this, j, getClass(this)));
				});
			}

			if (!arguments.length) {
				return this.attr("class", "");
			}

			if (typeof value === "string" && value) {
				classes = value.match(rnotwhite) || [];

				while ((elem = this[i++])) {
					curValue = getClass(elem);

					// This expression is here for better compressibility (see addClass)
					cur = elem.nodeType === 1 &&
						(" " + curValue + " ").replace(rclass, " ");

					if (cur) {
						j = 0;
						while ((clazz = classes[j++])) {

							// Remove *all* instances
							while (cur.indexOf(" " + clazz + " ") > -1) {
								cur = cur.replace(" " + clazz + " ", " ");
							}
						}

						// Only assign if different to avoid unneeded rendering.
						finalValue = jQuery.trim(cur);
						if (curValue !== finalValue) {
							elem.setAttribute("class", finalValue);
						}
					}
				}
			}

			return this;
		},

		toggleClass: function (value, stateVal) {
			var type = typeof value;

			if (typeof stateVal === "boolean" && type === "string") {
				return stateVal ? this.addClass(value) : this.removeClass(value);
			}

			if (jQuery.isFunction(value)) {
				return this.each(function (i) {
					jQuery(this).toggleClass(
						value.call(this, i, getClass(this), stateVal),
						stateVal
					);
				});
			}

			return this.each(function () {
				var className, i, self, classNames;

				if (type === "string") {

					// Toggle individual class names
					i = 0;
					self = jQuery(this);
					classNames = value.match(rnotwhite) || [];

					while ((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 &&
					(" " + getClass(elem) + " ").replace(rclass, " ")
						.indexOf(className) > -1
				) {
					return true;
				}
			}

			return false;
		}
	});




	var rreturn = /\r/g,
		rspaces = /[\x20\t\r\n\f]+/g;

	jQuery.fn.extend({
		val: function (value) {
			var hooks, ret, isFunction,
				elem = this[0];

			if (!arguments.length) {
				if (elem) {
					hooks = jQuery.valHooks[elem.type] ||
						jQuery.valHooks[elem.nodeName.toLowerCase()];

					if (hooks &&
						"get" in hooks &&
						(ret = hooks.get(elem, "value")) !== undefined
					) {
						return ret;
					}

					ret = elem.value;

					return typeof ret === "string" ?

						// Handle most common string cases
						ret.replace(rreturn, "") :

						// Handle cases where value is null/undef or number
						ret == null ? "" : ret;
				}

				return;
			}

			isFunction = jQuery.isFunction(value);

			return this.each(function (i) {
				var val;

				if (this.nodeType !== 1) {
					return;
				}

				if (isFunction) {
					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 (jQuery.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 <=10 - 11 only
						// option.text throws exceptions (#14686, #14858)
						// Strip and collapse whitespace
						// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
						jQuery.trim(jQuery.text(elem)).replace(rspaces, " ");
				}
			},
			select: {
				get: function (elem) {
					var value, option,
						options = elem.options,
						index = elem.selectedIndex,
						one = elem.type === "select-one",
						values = one ? null : [],
						max = one ? index + 1 : options.length,
						i = index < 0 ?
						max :
							one ? index : 0;

					// Loop through all the selected options
					for (; i < max; i++) {
						option = options[i];

						// Support: IE <=9 only
						// IE8-9 doesn't update selected after form reset (#2551)
						if ((option.selected || i === index) &&

							// Don't return options that are disabled or in a disabled optgroup
								!option.disabled &&
								(!option.parentNode.disabled ||
									!jQuery.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) > -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 (jQuery.isArray(value)) {
					return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) > -1);
				}
			}
		};
		if (!support.checkOn) {
			jQuery.valHooks[this].get = function (elem) {
				return elem.getAttribute("value") === null ? "on" : elem.value;
			};
		}
	});




	// Return jQuery for attributes-only inclusion


	var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;

	jQuery.extend(jQuery.event, {

		trigger: function (event, data, elem, onlyHandlers) {

			var i, cur, tmp, bubbleType, ontype, handle, special,
				eventPath = [elem || document],
				type = hasOwn.call(event, "type") ? event.type : event,
				namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];

			cur = 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(".") > -1) {

				// Namespaced trigger; create a regexp to match event type in handle()
				namespaces = type.split(".");
				type = namespaces.shift();
				namespaces.sort();
			}
			ontype = type.indexOf(":") < 0 && "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" && event);

			// Trigger bitmask: & 1 for native handlers; & 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 && special.trigger && special.trigger.apply(elem, data) === false) {
				return;
			}

			// Determine event propagation path in advance, per W3C events spec (#9951)
			// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
			if (!onlyHandlers && !special.noBubble && !jQuery.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++]) && !event.isPropagationStopped()) {

				event.type = i > 1 ?
					bubbleType :
					special.bindType || type;

				// jQuery handler
				handle = (dataPriv.get(cur, "events") || {})[event.type] &&
					dataPriv.get(cur, "handle");
				if (handle) {
					handle.apply(cur, data);
				}

				// Native handler
				handle = ontype && cur[ontype];
				if (handle && handle.apply && 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 && !event.isDefaultPrevented()) {

				if ((!special._default ||
					special._default.apply(eventPath.pop(), data) === false) &&
					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 (#6170)
					if (ontype && jQuery.isFunction(elem[type]) && !jQuery.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;
						elem[type]();
						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);
			}
		}
	});


	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 > 0 ?
					this.on(name, null, data, fn) :
					this.trigger(name);
			};
		});

	jQuery.fn.extend({
		hover: function (fnOver, fnOut) {
			return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
		}
	});




	support.focusin = "onfocusin" in window;


	// Support: Firefox <=44
	// Firefox doesn't have focus(in | out) events
	// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
	//
	// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
	// focus(in | out) events fire after focus & 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 () {
					var doc = this.ownerDocument || 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,
						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 = jQuery.now();

	var rquery = (/\?/);



	// Cross-browser xml parsing
	jQuery.parseXML = function (data) {
		var xml;
		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) {
			xml = undefined;
		}

		if (!xml || xml.getElementsByTagName("parsererror").length) {
			jQuery.error("Invalid XML: " + 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 (jQuery.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" && v != null ? i : "") + "]",
						v,
						traditional,
						add
					);
				}
			});

		} else if (!traditional && jQuery.type(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 = jQuery.isFunction(valueOrFunction) ?
					valueOrFunction() :
					valueOrFunction;

				s[s.length] = encodeURIComponent(key) + "=" +
					encodeURIComponent(value == null ? "" : value);
			};

		// If an array was passed in, assume that it is an array of form elements.
		if (jQuery.isArray(a) || (a.jquery && !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("&");
	};

	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 && !jQuery(this).is(":disabled") &&
					rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
					(this.checked || !rcheckableType.test(type));
			})
			.map(function (i, elem) {
				var val = jQuery(this).val();

				return val == null ?
					null :
					jQuery.isArray(val) ?
						jQuery.map(val, function (val) {
							return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
						}) :
					{ name: elem.name, value: val.replace(rCRLF, "\r\n") };
			}).get();
		}
	});


	var
		r20 = /%20/g,
		rhash = /#.*$/,
		rts = /([?&])_=[^&]*/,
		rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

		// #7653, #8125, #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 (#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(rnotwhite) || [];

			if (jQuery.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" &&
					!seekingTransport && !inspected[dataTypeOrTransport]) {

					options.dataTypes.unshift(dataTypeOrTransport);
					inspect(dataTypeOrTransport);
					return false;
				} else if (seekingTransport) {
					return !(selected = dataTypeOrTransport);
				}
			});
			return selected;
		}

		return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
	}

	// A special extend for ajax options
	// that takes "flat" options (not to be deep extended)
	// Fixes #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] && 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 && isSuccess && 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 !== "*" && 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 && 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 &&
					(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()] = match[2];
								}
							}
							match = responseHeaders[key.toLowerCase()];
						}
						return match == null ? null : match;
					},

					// 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 (#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 #12004
			s.type = options.method || options.type || s.method || s.type;

			// Extract dataTypes list
			s.dataTypes = (s.dataType || "*").toLowerCase().match(rnotwhite) || [""];

			// 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 <=8 - 11, Edge 12 - 13
				// 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 <=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 && s.processData && 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 (#15118)
			fireGlobals = jQuery.event && s.global;

			// Watch for a new set of requests
			if (fireGlobals && 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, append data to url
				if (s.data) {
					cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s.data;

					// #9682: remove data so that it's not used in an eventual retry
					delete s.data;
				}

				// Add anti-cache in uncached url if needed
				if (s.cache === false) {
					cacheURL = cacheURL.replace(rts, "");
					uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + (nonce++) + 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 && s.processData &&
				(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 && s.hasContent && 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] && 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 &&
				(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 && s.timeout > 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 > 0 ? 4 : 0;

				// Determine if successful
				isSuccess = status >= 200 && status < 300 || status === 304;

				// Get response data
				if (responses) {
					response = ajaxHandleResponses(s, jqXHR, responses);
				}

				// 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 < 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 (jQuery.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) && url));
		};
	});


	jQuery._evalUrl = function (url) {
		return jQuery.ajax({
			url: url,

			// Make this explicit, since user can override this through ajaxSetup (#11264)
			type: "GET",
			dataType: "script",
			cache: true,
			async: false,
			global: false,
			"throws": true
		});
	};


	jQuery.fn.extend({
		wrapAll: function (html) {
			var wrap;

			if (this[0]) {
				if (jQuery.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 (jQuery.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 isFunction = jQuery.isFunction(html);

			return this.each(function (i) {
				jQuery(this).wrapAll(isFunction ? 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 <=9 only
		// #1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
		xhrSupported = jQuery.ajaxSettings.xhr();

	support.cors = !!xhrSupported && ("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 && !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 && 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 && !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.onreadystatechange = null;

								if (type === "abort") {
									xhr.abort();
								} else if (type === "error") {

									// Support: IE <=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 #8605, #14207
											xhr.status,
											xhr.statusText
										);
									}
								} else {
									complete(
										xhrSuccessStatus[xhr.status] || xhr.status,
										xhr.statusText,

										// Support: IE <=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 = 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 && options.data || null);
					} catch (e) {

						// #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 requests
		if (s.crossDomain) {
			var script, callback;
			return {
				send: function (_, complete) {
					script = jQuery("<script>").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 = /(=)\?(?=&|$)|\?\?/;

	// Default jsonp settings
	jQuery.ajaxSetup({
		jsonp: "callback",
		jsonpCallback: function () {
			var callback = oldCallbacks.pop() || (jQuery.expando + "_" + (nonce++));
			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 && (rjsonp.test(s.url) ?
				"url" :
				typeof s.data === "string" &&
					(s.contentType || "")
						.indexOf("application/x-www-form-urlencoded") === 0 &&
					rjsonp.test(s.data) && "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 = jQuery.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) ? "&" : "?") + 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 && jQuery.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 = "<form></form><form></form>";
		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 && [];

		// Single tag
		if (parsed) {
			return [context.createElement(parsed[1])];
		}

		parsed = buildFragment([data], context, scripts);

		if (scripts && 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 > -1) {
			selector = jQuery.trim(url.slice(off));
			url = url.slice(0, off);
		}

		// If it's a function
		if (jQuery.isFunction(params)) {

			// We assume that it's the callback
			callback = params;
			params = undefined;

			// Otherwise, build a param string
		} else if (params && typeof params === "object") {
			type = "POST";
		}

		// If we have elements to modify, make the request
		if (self.length > 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("<div>").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 && function (jqXHR, status) {
				self.each(function () {
					callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
				});
			});
		}

		return this;
	};




	// Attach a bunch of functions for handling common AJAX events
	jQuery.each([
		"ajaxStart",
		"ajaxStop",
		"ajaxComplete",
		"ajaxError",
		"ajaxSuccess",
		"ajaxSend"
	], function (i, type) {
		jQuery.fn[type] = function (fn) {
			return this.on(type, fn);
		};
	});




	jQuery.expr.pseudos.animated = function (elem) {
		return jQuery.grep(jQuery.timers, function (fn) {
			return elem === fn.elem;
		}).length;
	};




	/**
	 * Gets a window from an element
	 */
	function getWindow(elem) {
		return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
	}

	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") &&
				(curCSSTop + curCSSLeft).indexOf("auto") > -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 (jQuery.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: function (options) {

			// Preserve chaining for setter
			if (arguments.length) {
				return options === undefined ?
					this :
					this.each(function (i) {
						jQuery.offset.setOffset(this, options, i);
					});
			}

			var docElem, win, rect, doc,
				elem = this[0];

			if (!elem) {
				return;
			}

			// Support: IE <=11 only
			// Running getBoundingClientRect on a
			// disconnected node in IE throws an error
			if (!elem.getClientRects().length) {
				return { top: 0, left: 0 };
			}

			rect = elem.getBoundingClientRect();

			// Make sure element is not hidden (display: none)
			if (rect.width || rect.height) {
				doc = elem.ownerDocument;
				win = getWindow(doc);
				docElem = doc.documentElement;

				return {
					top: rect.top + win.pageYOffset - docElem.clientTop,
					left: rect.left + win.pageXOffset - docElem.clientLeft
				};
			}

			// Return zeros for disconnected and hidden elements (gh-2310)
			return rect;
		},

		position: function () {
			if (!this[0]) {
				return;
			}

			var offsetParent, offset,
				elem = this[0],
				parentOffset = { top: 0, left: 0 };

			// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
			// because it is its only offset parent
			if (jQuery.css(elem, "position") === "fixed") {

				// Assume getBoundingClientRect is there when computed position is fixed
				offset = elem.getBoundingClientRect();

			} else {

				// Get *real* offsetParent
				offsetParent = this.offsetParent();

				// Get correct offsets
				offset = this.offset();
				if (!jQuery.nodeName(offsetParent[0], "html")) {
					parentOffset = offsetParent.offset();
				}

				// Add offsetParent borders
				parentOffset = {
					top: parentOffset.top + jQuery.css(offsetParent[0], "borderTopWidth", true),
					left: parentOffset.left + jQuery.css(offsetParent[0], "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 && 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) {
				var win = getWindow(elem);

				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 <=7 - 9.1, Chrome <=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 && (defaultExtra || typeof margin !== "boolean"),
						extra = defaultExtra || (margin === true || value === true ? "margin" : "border");

					return access(this, function (elem, type, value) {
						var doc;

						if (jQuery.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.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);
		}
	});

	jQuery.parseJSON = JSON.parse;




	// 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" && 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 && window.jQuery === jQuery) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	};

	// Expose jQuery and $ identifiers, even in AMD
	// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
	// and CommonJS for browser emulators (#13566)
	if (!noGlobal) {
		window.jQuery = window.$ = jQuery;
	}


	return jQuery;
});
/*! jQuery UI - v1.12.1 - 2017-03-15
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/menu.js, widgets/mouse.js, widgets/selectmenu.js, widgets/slider.js, widgets/tooltip.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */


(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

$.ui = $.ui || {};

var version = $.ui.version = "1.12.1";


/*!
 * jQuery UI Widget 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/



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 && 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 < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && 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 && 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 && methodValue !== undefined ) {
						returnValue = methodValue && 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: "<div>",

	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" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < 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 < 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 && 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 &&
						( 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 ) &&
			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 && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

var widget = $.widget;


/*!
 * 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/
 */

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/


( 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 = $( "<div " +
				"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
				"<div style='height:100px;width:auto;'></div></div>" ),
			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" && within.width < within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < 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 ] && withinElement[ 0 ].nodeType === 9,
			hasOffset = !isWindow && !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 < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > 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 > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 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 > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 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 < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < 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 < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < 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 );
		}
	}
};

} )();

var position = $.ui.position;


/*!
 * jQuery UI :data 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/


var data = $.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo( function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		} ) :

		// Support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		}
} );

/*!
 * jQuery UI Disable Selection 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/

// This file is deprecated


var disableSelection = $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );


/*!
 * jQuery UI Focusable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/



// Selectors
$.ui.focusable = function( element, hasTabindex ) {
	var map, mapName, img, focusableIfVisible, fieldset,
		nodeName = element.nodeName.toLowerCase();

	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" );
		return img.length > 0 && img.is( ":visible" );
	}

	if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
		focusableIfVisible = !element.disabled;

		if ( focusableIfVisible ) {

			// Form controls within a disabled fieldset are disabled.
			// However, controls within the fieldset's legend do not get disabled.
			// Since controls generally aren't placed inside legends, we skip
			// this portion of the check.
			fieldset = $( element ).closest( "fieldset" )[ 0 ];
			if ( fieldset ) {
				focusableIfVisible = !fieldset.disabled;
			}
		}
	} else if ( "a" === nodeName ) {
		focusableIfVisible = element.href || hasTabindex;
	} else {
		focusableIfVisible = hasTabindex;
	}

	return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};

// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
	var visibility = element.css( "visibility" );
	while ( visibility === "inherit" ) {
		element = element.parent();
		visibility = element.css( "visibility" );
	}
	return visibility !== "hidden";
}

$.extend( $.expr[ ":" ], {
	focusable: function( element ) {
		return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
	}
} );

var focusable = $.ui.focusable;




// Support: IE8 Only
// IE8 does not support the form attribute and when it is supplied. It overwrites the form prop
// with a string, so we need to find the proper form.
var form = $.fn.form = function() {
	return typeof this[ 0 ].form === "string" ? this.closest( "form" ) : $( this[ 0 ].form );
};


/*!
 * jQuery UI Form Reset Mixin 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Form Reset Mixin
//>>group: Core
//>>description: Refresh input widgets when their form is reset
//>>docs: http://api.jqueryui.com/form-reset-mixin/



var formResetMixin = $.ui.formResetMixin = {
	_formResetHandler: function() {
		var form = $( this );

		// Wait for the form reset to actually happen before refreshing
		setTimeout( function() {
			var instances = form.data( "ui-form-reset-instances" );
			$.each( instances, function() {
				this.refresh();
			} );
		} );
	},

	_bindFormResetHandler: function() {
		this.form = this.element.form();
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" ) || [];
		if ( !instances.length ) {

			// We don't use _on() here because we use a single event handler per form
			this.form.on( "reset.ui-form-reset", this._formResetHandler );
		}
		instances.push( this );
		this.form.data( "ui-form-reset-instances", instances );
	},

	_unbindFormResetHandler: function() {
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" );
		instances.splice( $.inArray( this, instances ), 1 );
		if ( instances.length ) {
			this.form.data( "ui-form-reset-instances", instances );
		} else {
			this.form
				.removeData( "ui-form-reset-instances" )
				.off( "reset.ui-form-reset" );
		}
	}
};


/*!
 * jQuery UI Support for jQuery core 1.7.x 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 */

//>>label: jQuery 1.7 Support
//>>group: Core
//>>description: Support version 1.7.x of jQuery core



// Support: jQuery 1.7 only
// Not a great way to check versions, but since we only support 1.7+ and only
// need to detect <1.8, this is a simple check that should suffice. Checking
// for "1.7." would be a bit safer, but the version string is 1.7, not 1.7.0
// and we'll never reach 1.70.0 (if we do, we certainly won't be supporting
// 1.7 anymore). See #11197 for why we're not using feature detection.
if ( $.fn.jquery.substring( 0, 3 ) === "1.7" ) {

	// Setters for .innerWidth(), .innerHeight(), .outerWidth(), .outerHeight()
	// Unlike jQuery Core 1.8+, these only support numeric values to set the
	// dimensions in pixels
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

		function reduce( elem, size, border, margin ) {
			$.each( side, function() {
				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
				if ( border ) {
					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
				}
				if ( margin ) {
					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
				}
			} );
			return size;
		}

		$.fn[ "inner" + name ] = function( size ) {
			if ( size === undefined ) {
				return orig[ "inner" + name ].call( this );
			}

			return this.each( function() {
				$( this ).css( type, reduce( this, size ) + "px" );
			} );
		};

		$.fn[ "outer" + name ] = function( size, margin ) {
			if ( typeof size !== "number" ) {
				return orig[ "outer" + name ].call( this, size );
			}

			return this.each( function() {
				$( this ).css( type, reduce( this, size, true, margin ) + "px" );
			} );
		};
	} );

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

;
/*!
 * jQuery UI Keycode 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/


var keycode = $.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
};




// Internal use only
var escapeSelector = $.ui.escapeSelector = ( function() {
	var selectorEscape = /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;
	return function( selector ) {
		return selector.replace( selectorEscape, "\\$1" );
	};
} )();


/*!
 * jQuery UI Labels 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: labels
//>>group: Core
//>>description: Find all the labels associated with a given input
//>>docs: http://api.jqueryui.com/labels/



var labels = $.fn.labels = function() {
	var ancestor, selector, id, labels, ancestors;

	// Check control.labels first
	if ( this[ 0 ].labels && this[ 0 ].labels.length ) {
		return this.pushStack( this[ 0 ].labels );
	}

	// Support: IE <= 11, FF <= 37, Android <= 2.3 only
	// Above browsers do not support control.labels. Everything below is to support them
	// as well as document fragments. control.labels does not work on document fragments
	labels = this.eq( 0 ).parents( "label" );

	// Look for the label based on the id
	id = this.attr( "id" );
	if ( id ) {

		// We don't search against the document in case the element
		// is disconnected from the DOM
		ancestor = this.eq( 0 ).parents().last();

		// Get a full set of top level ancestors
		ancestors = ancestor.add( ancestor.length ? ancestor.siblings() : this.siblings() );

		// Create a selector for the label based on the id
		selector = "label[for='" + $.ui.escapeSelector( id ) + "']";

		labels = labels.add( ancestors.find( selector ).addBack( selector ) );

	}

	// Return whatever we have found for labels
	return this.pushStack( labels );
};


/*!
 * jQuery UI Scroll Parent 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/



var scrollParent = $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};


/*!
 * jQuery UI Tabbable 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :tabbable Selector
//>>group: Core
//>>description: Selects elements which can be tabbed to.
//>>docs: http://api.jqueryui.com/tabbable-selector/



var tabbable = $.extend( $.expr[ ":" ], {
	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			hasTabindex = tabIndex != null;
		return ( !hasTabindex || tabIndex >= 0 ) && $.ui.focusable( element, hasTabindex );
	}
} );


/*!
 * 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
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/



var uniqueId = $.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" );
			}
		} );
	}
} );



var safeActiveElement = $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	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 <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};


/*!
 * jQuery UI Menu 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: http://api.jqueryui.com/menu/
//>>demos: http://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css



var widgetsMenu = $.widget( "ui.menu", {
	version: "1.12.1",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-caret-1-e"
		},
		items: "> *",
		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 && 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" ) &&
							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 && 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 && !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 >= 96 && event.keyCode <= 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 && 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 && !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 = $( "<span>" ).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 && !$.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 && 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 && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay( function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^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 < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > 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 && 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 &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".ui-menu " )
					.find( this.options.items )
						.first();

		if ( newItem && 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 && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !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 < 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 > 0;
			} );

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < 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, "\\$&" ),
			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() ) );
					} );
	}
} );




// This file is deprecated
var ie = $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

/*!
 * jQuery UI Mouse 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/



var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

var widgetsMouse = $.widget( "ui.mouse", {
	version: "1.12.1",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		( this._mouseStarted && this._mouseUp( event ) );

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
				$( event.target ).closest( this.options.cancel ).length : false );
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) );
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) { return true; }
} );


/*!
 * jQuery UI Selectmenu 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Selectmenu
//>>group: Widgets
// jscs:disable maximumLineLength
//>>description: Duplicates and extends the functionality of a native HTML select element, allowing it to be customizable in behavior and appearance far beyond the limitations of a native select.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/selectmenu/
//>>demos: http://jqueryui.com/selectmenu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/selectmenu.css, ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css



var widgetsSelectmenu = $.widget( "ui.selectmenu", [ $.ui.formResetMixin, {
	version: "1.12.1",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		classes: {
			"ui-selectmenu-button-open": "ui-corner-top",
			"ui-selectmenu-button-closed": "ui-corner-all"
		},
		disabled: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		width: false,

		// Callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();
		this._bindFormResetHandler();

		this._rendered = false;
		this.menuItems = $();
	},

	_drawButton: function() {
		var icon,
			that = this,
			item = this._parseOption(
				this.element.find( "option:selected" ),
				this.element[ 0 ].selectedIndex
			);

		// Associate existing label with the new button
		this.labels = this.element.labels().attr( "for", this.ids.button );
		this._on( this.labels, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		} );

		// Hide original select element
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			tabindex: this.options.disabled ? -1 : 0,
			id: this.ids.button,
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true",
			title: this.element.attr( "title" )
		} )
			.insertAfter( this.element );

		this._addClass( this.button, "ui-selectmenu-button ui-selectmenu-button-closed",
			"ui-button ui-widget" );

		icon = $( "<span>" ).appendTo( this.button );
		this._addClass( icon, "ui-selectmenu-icon", "ui-icon " + this.options.icons.button );
		this.buttonItem = this._renderButtonItem( item )
			.appendTo( this.button );

		if ( this.options.width !== false ) {
			this._resizeButton();
		}

		this._on( this.button, this._buttonEvents );
		this.button.one( "focusin", function() {

			// Delay rendering the menu items until the button receives focus.
			// The menu may have already been rendered via a programmatic open.
			if ( !that._rendered ) {
				that._refreshMenu();
			}
		} );
	},

	_drawMenu: function() {
		var that = this;

		// Create menu
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		} );

		// Wrap menu
		this.menuWrap = $( "<div>" ).append( this.menu );
		this._addClass( this.menuWrap, "ui-selectmenu-menu", "ui-front" );
		this.menuWrap.appendTo( this._appendTo() );

		// Initialize menu widget
		this.menuInstance = this.menu
			.menu( {
				classes: {
					"ui-menu": "ui-corner-bottom"
				},
				role: "listbox",
				select: function( event, ui ) {
					event.preventDefault();

					// Support: IE8
					// If the item was selected via a click, the text selection
					// will be destroyed in IE
					that._setSelection();

					that._select( ui.item.data( "ui-selectmenu-item" ), event );
				},
				focus: function( event, ui ) {
					var item = ui.item.data( "ui-selectmenu-item" );

					// Prevent inital focus from firing and check if its a newly focused item
					if ( that.focusIndex != null && item.index !== that.focusIndex ) {
						that._trigger( "focus", event, { item: item } );
						if ( !that.isOpen ) {
							that._select( item, event );
						}
					}
					that.focusIndex = item.index;

					that.button.attr( "aria-activedescendant",
						that.menuItems.eq( item.index ).attr( "id" ) );
				}
			} )
			.menu( "instance" );

		// Don't close the menu on mouseleave
		this.menuInstance._off( this.menu, "mouseleave" );

		// Cancel the menu's collapseAll on document click
		this.menuInstance._closeOnDocumentClick = function() {
			return false;
		};

		// Selects often contain empty items, but never contain dividers
		this.menuInstance._isDivider = function() {
			return false;
		};
	},

	refresh: function() {
		this._refreshMenu();
		this.buttonItem.replaceWith(
			this.buttonItem = this._renderButtonItem(

				// Fall back to an empty object in case there are no options
				this._getSelectedItem().data( "ui-selectmenu-item" ) || {}
			)
		);
		if ( this.options.width === null ) {
			this._resizeButton();
		}
	},

	_refreshMenu: function() {
		var item,
			options = this.element.find( "option" );

		this.menu.empty();

		this._parseOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menuInstance.refresh();
		this.menuItems = this.menu.find( "li" )
			.not( ".ui-selectmenu-optgroup" )
				.find( ".ui-menu-item-wrapper" );

		this._rendered = true;

		if ( !options.length ) {
			return;
		}

		item = this._getSelectedItem();

		// Update the menu to have the correct item focused
		this.menuInstance.focus( null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}

		// If this is the first time the menu is being opened, render the items
		if ( !this._rendered ) {
			this._refreshMenu();
		} else {

			// Menu clears focus on close, reset focus to selected item
			this._removeClass( this.menu.find( ".ui-state-active" ), null, "ui-state-active" );
			this.menuInstance.focus( null, this._getSelectedItem() );
		}

		// If there are no options, don't open the menu
		if ( !this.menuItems.length ) {
			return;
		}

		this.isOpen = true;
		this._toggleAttr();
		this._resizeMenu();
		this._position();

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	_position: function() {
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		this.range = null;
		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderButtonItem: function( item ) {
		var buttonItem = $( "<span>" );

		this._setText( buttonItem, item.label );
		this._addClass( buttonItem, "ui-selectmenu-text" );

		return buttonItem;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			var li;

			if ( item.optgroup !== currentOptgroup ) {
				li = $( "<li>", {
					text: item.optgroup
				} );
				that._addClass( li, "ui-selectmenu-optgroup", "ui-menu-divider" +
					( item.element.parent( "optgroup" ).prop( "disabled" ) ?
						" ui-state-disabled" :
						"" ) );

				li.appendTo( ul );

				currentOptgroup = item.optgroup;
			}

			that._renderItemData( ul, item );
		} );
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ),
			wrapper = $( "<div>", {
				title: item.element.attr( "title" )
			} );

		if ( item.disabled ) {
			this._addClass( li, null, "ui-state-disabled" );
		}
		this._setText( wrapper, item.label );

		return li.append( wrapper ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( "&#160;" );
		}
	},

	_move: function( direction, event ) {
		var item, next,
			filter = ".ui-menu-item";

		if ( this.isOpen ) {
			item = this.menuItems.eq( this.focusIndex ).parent( "li" );
		} else {
			item = this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
			filter += ":not(.ui-state-disabled)";
		}

		if ( direction === "first" || direction === "last" ) {
			next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 );
		} else {
			next = item[ direction + "All" ]( filter ).eq( 0 );
		}

		if ( next.length ) {
			this.menuInstance.focus( event, next );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		this[ this.isOpen ? "close" : "open" ]( event );
	},

	_setSelection: function() {
		var selection;

		if ( !this.range ) {
			return;
		}

		if ( window.getSelection ) {
			selection = window.getSelection();
			selection.removeAllRanges();
			selection.addRange( this.range );

		// Support: IE8
		} else {
			this.range.select();
		}

		// Support: IE
		// Setting the text selection kills the button focus in IE, but
		// restoring the focus doesn't kill the selection.
		this.button.focus();
	},

	_documentClick: {
		mousedown: function( event ) {
			if ( !this.isOpen ) {
				return;
			}

			if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" +
					$.ui.escapeSelector( this.ids.button ) ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {

		// Prevent text selection from being reset when interacting with the selectmenu (#10144)
		mousedown: function() {
			var selection;

			if ( window.getSelection ) {
				selection = window.getSelection();
				if ( selection.rangeCount ) {
					this.range = selection.getRangeAt( 0 );
				}

			// Support: IE8
			} else {
				this.range = document.selection.createRange();
			}
		},

		click: function( event ) {
			this._setSelection();
			this._toggle( event );
		},

		keydown: function( event ) {
			var preventDefault = true;
			switch ( event.keyCode ) {
			case $.ui.keyCode.TAB:
			case $.ui.keyCode.ESCAPE:
				this.close( event );
				preventDefault = false;
				break;
			case $.ui.keyCode.ENTER:
				if ( this.isOpen ) {
					this._selectFocusedItem( event );
				}
				break;
			case $.ui.keyCode.UP:
				if ( event.altKey ) {
					this._toggle( event );
				} else {
					this._move( "prev", event );
				}
				break;
			case $.ui.keyCode.DOWN:
				if ( event.altKey ) {
					this._toggle( event );
				} else {
					this._move( "next", event );
				}
				break;
			case $.ui.keyCode.SPACE:
				if ( this.isOpen ) {
					this._selectFocusedItem( event );
				} else {
					this._toggle( event );
				}
				break;
			case $.ui.keyCode.LEFT:
				this._move( "prev", event );
				break;
			case $.ui.keyCode.RIGHT:
				this._move( "next", event );
				break;
			case $.ui.keyCode.HOME:
			case $.ui.keyCode.PAGE_UP:
				this._move( "first", event );
				break;
			case $.ui.keyCode.END:
			case $.ui.keyCode.PAGE_DOWN:
				this._move( "last", event );
				break;
			default:
				this.menu.trigger( event );
				preventDefault = false;
			}

			if ( preventDefault ) {
				event.preventDefault();
			}
		}
	},

	_selectFocusedItem: function( event ) {
		var item = this.menuItems.eq( this.focusIndex ).parent( "li" );
		if ( !item.hasClass( "ui-state-disabled" ) ) {
			this._select( item.data( "ui-selectmenu-item" ), event );
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;

		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this.buttonItem.replaceWith( this.buttonItem = this._renderButtonItem( item ) );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}

		this.close( event );
	},

	_setAria: function( item ) {
		var id = this.menuItems.eq( item.index ).attr( "id" );

		this.button.attr( {
			"aria-labelledby": id,
			"aria-activedescendant": id
		} );
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icon = this.button.find( "span.ui-icon" );
			this._removeClass( icon, null, this.options.icons.button )
				._addClass( icon, null, value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}

		if ( key === "width" ) {
			this._resizeButton();
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.menuInstance.option( "disabled", value );
		this.button.attr( "aria-disabled", value );
		this._toggleClass( this.button, null, "ui-state-disabled", value );

		this.element.prop( "disabled", value );
		if ( value ) {
			this.button.attr( "tabindex", -1 );
			this.close();
		} else {
			this.button.attr( "tabindex", 0 );
		}
	},

	_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;
	},

	_toggleAttr: function() {
		this.button.attr( "aria-expanded", this.isOpen );

		// We can't use two _toggleClass() calls here, because we need to make sure
		// we always remove classes first and add them second, otherwise if both classes have the
		// same theme class, it will be removed after we add it.
		this._removeClass( this.button, "ui-selectmenu-button-" +
			( this.isOpen ? "closed" : "open" ) )
			._addClass( this.button, "ui-selectmenu-button-" +
				( this.isOpen ? "open" : "closed" ) )
			._toggleClass( this.menuWrap, "ui-selectmenu-open", null, this.isOpen );

		this.menu.attr( "aria-hidden", !this.isOpen );
	},

	_resizeButton: function() {
		var width = this.options.width;

		// For `width: false`, just remove inline style and stop
		if ( width === false ) {
			this.button.css( "width", "" );
			return;
		}

		// For `width: null`, match the width of the original element
		if ( width === null ) {
			width = this.element.show().outerWidth();
			this.element.hide();
		}

		this.button.outerWidth( width );
	},

	_resizeMenu: function() {
		this.menu.outerWidth( Math.max(
			this.button.outerWidth(),

			// Support: IE10
			// IE10 wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping
			this.menu.width( "" ).outerWidth() + 1
		) );
	},

	_getCreateOptions: function() {
		var options = this._super();

		options.disabled = this.element.prop( "disabled" );

		return options;
	},

	_parseOptions: function( options ) {
		var that = this,
			data = [];
		options.each( function( index, item ) {
			data.push( that._parseOption( $( item ), index ) );
		} );
		this.items = data;
	},

	_parseOption: function( option, index ) {
		var optgroup = option.parent( "optgroup" );

		return {
			element: option,
			index: index,
			value: option.val(),
			label: option.text(),
			optgroup: optgroup.attr( "label" ) || "",
			disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" )
		};
	},

	_destroy: function() {
		this._unbindFormResetHandler();
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.labels.attr( "for", this.ids.element );
	}
} ] );


/*!
 * jQuery UI Slider 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slider
//>>group: Widgets
//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
//>>docs: http://api.jqueryui.com/slider/
//>>demos: http://jqueryui.com/slider/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/slider.css
//>>css.theme: ../../themes/base/theme.css



var widgetsSlider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.12.1",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		classes: {
			"ui-slider": "ui-corner-all",
			"ui-slider-handle": "ui-corner-all",

			// Note: ui-widget-header isn't the most fittingly semantic framework class for this
			// element, but worked best visually with a variety of themes
			"ui-slider-range": "ui-corner-all ui-widget-header"
		},
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// Callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// Number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this._addClass( "ui-slider ui-slider-" + this.orientation,
			"ui-widget ui-widget-content" );

		this._refresh();

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ),
			handle = "<span tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this._addClass( this.handles, "ui-slider-handle", "ui-state-default" );

		this.handle = this.handles.eq( 0 );

		this.handles.each( function( i ) {
			$( this )
				.data( "ui-slider-handle-index", i )
				.attr( "tabIndex", 0 );
		} );
	},

	_createRange: function() {
		var options = this.options;

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[ 0 ], options.values[ 0 ] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice( 0 );
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div>" )
					.appendTo( this.element );

				this._addClass( this.range, "ui-slider-range" );
			} else {
				this._removeClass( this.range, "ui-slider-range-min ui-slider-range-max" );

				// Handle range switching from true to min/max
				this.range.css( {
					"left": "",
					"bottom": ""
				} );
			}
			if ( options.range === "min" || options.range === "max" ) {
				this._addClass( this.range, "ui-slider-range-" + options.range );
			}
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each( function( i ) {
			var thisDistance = Math.abs( normValue - that.values( i ) );
			if ( ( distance > thisDistance ) ||
				( distance === thisDistance &&
					( i === that._lastChangedValue || that.values( i ) === o.min ) ) ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		} );

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		this._addClass( closestHandle, null, "ui-state-active" );
		closestHandle.trigger( "focus" );

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
				( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
				( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this._removeClass( this.handles, null, "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left -
				( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top -
				( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_uiHash: function( index, value, values ) {
		var uiHash = {
			handle: this.handles[ index ],
			handleIndex: index,
			value: value !== undefined ? value : this.value()
		};

		if ( this._hasMultipleValues() ) {
			uiHash.value = value !== undefined ? value : this.values( index );
			uiHash.values = values || this.values();
		}

		return uiHash;
	},

	_hasMultipleValues: function() {
		return this.options.values && this.options.values.length;
	},

	_start: function( event, index ) {
		return this._trigger( "start", event, this._uiHash( index ) );
	},

	_slide: function( event, index, newVal ) {
		var allowed, otherVal,
			currentValue = this.value(),
			newValues = this.values();

		if ( this._hasMultipleValues() ) {
			otherVal = this.values( index ? 0 : 1 );
			currentValue = this.values( index );

			if ( this.options.values.length === 2 && this.options.range === true ) {
				newVal =  index === 0 ? Math.min( otherVal, newVal ) : Math.max( otherVal, newVal );
			}

			newValues[ index ] = newVal;
		}

		if ( newVal === currentValue ) {
			return;
		}

		allowed = this._trigger( "slide", event, this._uiHash( index, newVal, newValues ) );

		// A slide can be canceled by returning false from the slide callback
		if ( allowed === false ) {
			return;
		}

		if ( this._hasMultipleValues() ) {
			this.values( index, newVal );
		} else {
			this.value( newVal );
		}
	},

	_stop: function( event, index ) {
		this._trigger( "stop", event, this._uiHash( index ) );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;
			this._trigger( "change", event, this._uiHash( index ) );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this._hasMultipleValues() ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this._removeClass( "ui-slider-horizontal ui-slider-vertical" )
					._addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				if ( this.options.range ) {
					this._refreshRange( value );
				}

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();

				// Start from the last handle to prevent unreachable handles (#9046)
				for ( i = valsLength - 1; i >= 0; i-- ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// Returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = ( val - this._valueMin() ) % step,
			alignValue = val - valModStep;

		if ( Math.abs( valModStep ) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed( 5 ) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.round( ( max - min ) / step ) * step;
		max = aboveMin + min;
		if ( max > this.options.max ) {

			//If max is not divisible by step, rounding off may increase its value
			max -= step;
		}
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshRange: function( orientation ) {
		if ( orientation === "vertical" ) {
			this.range.css( { "width": "", "left": "" } );
		}
		if ( orientation === "horizontal" ) {
			this.range.css( { "height": "", "bottom": "" } );
		}
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this._hasMultipleValues() ) {
			this.handles.each( function( i ) {
				valPercent = ( that.values( i ) - that._valueMin() ) / ( that._valueMax() -
					that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								left: valPercent + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								width: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								bottom: ( valPercent ) + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								height: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					}
				}
				lastValPercent = valPercent;
			} );
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						this._addClass( $( event.target ), null, "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this._hasMultipleValues() ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( ( this._valueMax() - this._valueMin() ) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				this._removeClass( $( event.target ), null, "ui-state-active" );
			}
		}
	}
} );


/*!
 * jQuery UI Tooltip 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Tooltip
//>>group: Widgets
//>>description: Shows additional information for any element on hover or focus.
//>>docs: http://api.jqueryui.com/tooltip/
//>>demos: http://jqueryui.com/tooltip/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tooltip.css
//>>css.theme: ../../themes/base/theme.css



$.widget( "ui.tooltip", {
	version: "1.12.1",
	options: {
		classes: {
			"ui-tooltip": "ui-corner-all ui-widget-shadow"
		},
		content: function() {

			// support: IE<9, Opera in jQuery <1.7
			// .text() can't accept undefined, so coerce to a string
			var title = $( this ).attr( "title" ) || "";

			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,

		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		track: false,

		// Callbacks
		close: null,
		open: null
	},

	_addDescribedBy: function( elem, id ) {
		var describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ );
		describedby.push( id );
		elem
			.data( "ui-tooltip-id", id )
			.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
	},

	_removeDescribedBy: function( elem ) {
		var id = elem.data( "ui-tooltip-id" ),
			describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ ),
			index = $.inArray( id, describedby );

		if ( index !== -1 ) {
			describedby.splice( index, 1 );
		}

		elem.removeData( "ui-tooltip-id" );
		describedby = $.trim( describedby.join( " " ) );
		if ( describedby ) {
			elem.attr( "aria-describedby", describedby );
		} else {
			elem.removeAttr( "aria-describedby" );
		}
	},

	_create: function() {
		this._on( {
			mouseover: "open",
			focusin: "open"
		} );

		// IDs of generated tooltips, needed for destroy
		this.tooltips = {};

		// IDs of parent tooltips where we removed the title attribute
		this.parents = {};

		// Append the aria-live region so tooltips announce correctly
		this.liveRegion = $( "<div>" )
			.attr( {
				role: "log",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			} )
			.appendTo( this.document[ 0 ].body );
		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

		this.disabledTitles = $( [] );
	},

	_setOption: function( key, value ) {
		var that = this;

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, tooltipData ) {
				that._updateContent( tooltipData.element );
			} );
		}
	},

	_setOptionDisabled: function( value ) {
		this[ value ? "_disable" : "_enable" ]();
	},

	_disable: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = tooltipData.element[ 0 ];
			that.close( event, true );
		} );

		// Remove title attributes to prevent native tooltips
		this.disabledTitles = this.disabledTitles.add(
			this.element.find( this.options.items ).addBack()
				.filter( function() {
					var element = $( this );
					if ( element.is( "[title]" ) ) {
						return element
							.data( "ui-tooltip-title", element.attr( "title" ) )
							.removeAttr( "title" );
					}
				} )
		);
	},

	_enable: function() {

		// restore title attributes
		this.disabledTitles.each( function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		} );
		this.disabledTitles = $( [] );
	},

	open: function( event ) {
		var that = this,
			target = $( event ? event.target : this.element )

				// we need closest here due to mouseover bubbling,
				// but always pointing at the same event target
				.closest( this.options.items );

		// No element to show a tooltip for or the tooltip is already open
		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
			return;
		}

		if ( target.attr( "title" ) ) {
			target.data( "ui-tooltip-title", target.attr( "title" ) );
		}

		target.data( "ui-tooltip-open", true );

		// Kill parent tooltips, custom or native, for hover
		if ( event && event.type === "mouseover" ) {
			target.parents().each( function() {
				var parent = $( this ),
					blurEvent;
				if ( parent.data( "ui-tooltip-open" ) ) {
					blurEvent = $.Event( "blur" );
					blurEvent.target = blurEvent.currentTarget = this;
					that.close( blurEvent, true );
				}
				if ( parent.attr( "title" ) ) {
					parent.uniqueId();
					that.parents[ this.id ] = {
						element: this,
						title: parent.attr( "title" )
					};
					parent.attr( "title", "" );
				}
			} );
		}

		this._registerCloseHandlers( event, target );
		this._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" || contentOption.nodeType ||
				contentOption.jquery ) {
			return this._open( event, target, contentOption );
		}

		content = contentOption.call( target[ 0 ], function( response ) {

			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			that._delay( function() {

				// Ignore async response if tooltip was closed already
				if ( !target.data( "ui-tooltip-open" ) ) {
					return;
				}

				// JQuery creates a special event for focusin when it doesn't
				// exist natively. To improve performance, the native event
				// object is reused and the type is changed. Therefore, we can't
				// rely on the type being correct after the event finished
				// bubbling, so we set it back to the previous value. (#8740)
				if ( event ) {
					event.type = eventType;
				}
				this._open( event, target, response );
			} );
		} );
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltipData, tooltip, delayedShow, a11yContent,
			positionOption = $.extend( {}, this.options.position );

		if ( !content ) {
			return;
		}

		// Content can be updated multiple times. If the tooltip already
		// exists, then just update the content and bail.
		tooltipData = this._find( target );
		if ( tooltipData ) {
			tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
			return;
		}

		// If we have a title, clear it to prevent the native tooltip
		// we have to check first to avoid defining a title if none exists
		// (we don't want to cause an element to start matching [title])
		//
		// We use removeAttr only for key events, to allow IE to export the correct
		// accessible attributes. For mouse events, set to empty string to avoid
		// native tooltip showing up (happens only when removing inside mouseover).
		if ( target.is( "[title]" ) ) {
			if ( event && event.type === "mouseover" ) {
				target.attr( "title", "" );
			} else {
				target.removeAttr( "title" );
			}
		}

		tooltipData = this._tooltip( target );
		tooltip = tooltipData.tooltip;
		this._addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		// Support: Voiceover on OS X, JAWS on IE <= 9
		// JAWS announces deletions even when aria-relevant="additions"
		// Voiceover will sometimes re-read the entire log region's contents from the beginning
		this.liveRegion.children().hide();
		a11yContent = $( "<div>" ).html( tooltip.find( ".ui-tooltip-content" ).html() );
		a11yContent.removeAttr( "name" ).find( "[name]" ).removeAttr( "name" );
		a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
		a11yContent.appendTo( this.liveRegion );

		function position( event ) {
			positionOption.of = event;
			if ( tooltip.is( ":hidden" ) ) {
				return;
			}
			tooltip.position( positionOption );
		}
		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
			this._on( this.document, {
				mousemove: position
			} );

			// trigger once to override element-relative positioning
			position( event );
		} else {
			tooltip.position( $.extend( {
				of: target
			}, this.options.position ) );
		}

		tooltip.hide();

		this._show( tooltip, this.options.show );

		// Handle tracking tooltips that are shown with a delay (#8644). As soon
		// as the tooltip is visible, position the tooltip using the most recent
		// event.
		// Adds the check to add the timers only when both delay and track options are set (#14682)
		if ( this.options.track && this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval( function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, $.fx.interval );
		}

		this._trigger( "open", event, { tooltip: tooltip } );
	},

	_registerCloseHandlers: function( event, target ) {
		var events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event( event );
					fakeEvent.currentTarget = target[ 0 ];
					this.close( fakeEvent, true );
				}
			}
		};

		// Only bind remove handler for delegated targets. Non-delegated
		// tooltips will handle this in destroy.
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			events.remove = function() {
				this._removeTooltip( this._find( target ).tooltip );
			};
		}

		if ( !event || event.type === "mouseover" ) {
			events.mouseleave = "close";
		}
		if ( !event || event.type === "focusin" ) {
			events.focusout = "close";
		}
		this._on( true, target, events );
	},

	close: function( event ) {
		var tooltip,
			that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltipData = this._find( target );

		// The tooltip may already be closed
		if ( !tooltipData ) {

			// We set ui-tooltip-open immediately upon open (in open()), but only set the
			// additional data once there's actually content to show (in _open()). So even if the
			// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
			// the period between open() and _open().
			target.removeData( "ui-tooltip-open" );
			return;
		}

		tooltip = tooltipData.tooltip;

		// Disabling closes the tooltip, so we need to track when we're closing
		// to avoid an infinite loop in case the tooltip becomes disabled on close
		if ( tooltipData.closing ) {
			return;
		}

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		// Only set title if we had one before (see comment in _open())
		// If the title attribute has changed since open(), don't restore
		if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		this._removeDescribedBy( target );

		tooltipData.hiding = true;
		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			that._removeTooltip( $( this ) );
		} );

		target.removeData( "ui-tooltip-open" );
		this._off( target, "mouseleave focusout keyup" );

		// Remove 'remove' binding only on delegated targets
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			this._off( target, "remove" );
		}
		this._off( this.document, "mousemove" );

		if ( event && event.type === "mouseleave" ) {
			$.each( this.parents, function( id, parent ) {
				$( parent.element ).attr( "title", parent.title );
				delete that.parents[ id ];
			} );
		}

		tooltipData.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		if ( !tooltipData.hiding ) {
			tooltipData.closing = false;
		}
	},

	_tooltip: function( element ) {
		var tooltip = $( "<div>" ).attr( "role", "tooltip" ),
			content = $( "<div>" ).appendTo( tooltip ),
			id = tooltip.uniqueId().attr( "id" );

		this._addClass( content, "ui-tooltip-content" );
		this._addClass( tooltip, "ui-tooltip", "ui-widget ui-widget-content" );

		tooltip.appendTo( this._appendTo( element ) );

		return this.tooltips[ id ] = {
			element: element,
			tooltip: tooltip
		};
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? this.tooltips[ id ] : null;
	},

	_removeTooltip: function( tooltip ) {
		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_appendTo: function( target ) {
		var element = target.closest( ".ui-front, dialog" );

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_destroy: function() {
		var that = this;

		// Close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {

			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" ),
				element = tooltipData.element;
			event.target = event.currentTarget = element[ 0 ];
			that.close( event, true );

			// Remove immediately; destroying an open tooltip doesn't use the
			// hide animation
			$( "#" + id ).remove();

			// Restore the title
			if ( element.data( "ui-tooltip-title" ) ) {

				// If the title attribute has changed since open(), don't restore
				if ( !element.attr( "title" ) ) {
					element.attr( "title", element.data( "ui-tooltip-title" ) );
				}
				element.removeData( "ui-tooltip-title" );
			}
		} );
		this.liveRegion.remove();
	}
} );

// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for tooltipClass option
	$.widget( "ui.tooltip", $.ui.tooltip, {
		options: {
			tooltipClass: null
		},
		_tooltip: function() {
			var tooltipData = this._superApply( arguments );
			if ( this.options.tooltipClass ) {
				tooltipData.tooltip.addClass( this.options.tooltipClass );
			}
			return tooltipData;
		}
	} );
}

var widgetsTooltip = $.ui.tooltip;


/*!
 * jQuery UI Effects 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Effects Core
//>>group: Effects
// jscs:disable maximumLineLength
//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/category/effects-core/
//>>demos: http://jqueryui.com/effect/



var dataSpace = "ui-effects-",
	dataSpaceStyle = "ui-effects-style",
	dataSpaceAnimated = "ui-effects-animated",

	// Create a local jQuery because jQuery Color relies on it and the
	// global may not exist with AMD and a custom build (#10199)
	jQuery = $;

$.effects = {
	effect: {}
};

/*!
 * jQuery Color Animations v2.1.2
 * https://github.com/jquery/jquery-color
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Wed Jan 16 08:47:09 2013 -0600
 */
( function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
		"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	// Plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,

	// A set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {

			// This regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 )
				];
			}
		}, {

			// This regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// JQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	support = color.support = {},

	// Element for support tests
	supportElem = jQuery( "<p>" )[ 0 ],

	// Colors = jQuery.Color.names
	colors,

	// Local aliases of functions called often
	each = jQuery.each;

// Determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;

// Define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
} );

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return ( allowEmpty || !prop.def ) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// IE will pass in empty strings as value for alpha,
	// which will hit this case
	if ( isNaN( value ) ) {
		return prop.def;
	}

	if ( type.mod ) {

		// We add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return ( value + type.mod ) % type.mod;
	}

	// For now all property types without mod have min and max
	return 0 > value ? 0 : type.max < value ? type.max : value;
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// If this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// Exit each( stringParsers ) here because we matched
			return false;
		}
	} );

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// If this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// Named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = jQuery.type( red ),
			rgba = this._rgba = [];

		// More than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			} );
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				} );
			} else {
				each( spaces, function( spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// If the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// If the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// This is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					} );

					// Everything defined but alpha?
					if ( inst[ cache ] &&
							jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {

						// Use the default of 1
						inst[ cache ][ 3 ] = 1;
						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				} );
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if ( isCache ) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				} );
			}
			return same;
		} );
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		} );
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// If null, don't override start value
			if ( endValue === null ) {
				return;
			}

			// If null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		} );
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {

		// If we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		} ) );
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				return v == null ? ( i > 2 ? 1 : 0 ) : v;
			} );

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// Catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			} );

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// Default to 0 when nulls exist
			v = ( v || 0 ).toString( 16 );
			return v.length === 1 ? "0" + v : v;
		} ).join( "" );
	},
	toString: function() {
		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
	}
} );
color.fn.parse.prototype = color.fn;

// Hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + ( q - p ) * h * 6;
	}
	if ( h * 2 < 1 ) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
	}
	return p;
}

spaces.hsla.to = function( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// Chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};

each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// Makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// Generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = jQuery.type( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		} );

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// Makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {

		// Alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var vtype = jQuery.type( value ),
				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
				local = this[ fn ](),
				cur = local[ prop.idx ],
				match;

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = jQuery.type( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	} );
} );

// Add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( jQuery.type( value ) !== "string" ||
						( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
						curElem = hook === "backgroundColor" ? elem.parentNode : elem;
						while (
							( backgroundColor === "" || backgroundColor === "transparent" ) &&
							curElem && curElem.style
						) {
							try {
								backgroundColor = jQuery.css( curElem, "backgroundColor" );
								curElem = curElem.parentNode;
							} catch ( e ) {
							}
						}

						value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
							backgroundColor :
							"_default" );
					}

					value = value.toRgbaString();
				}
				try {
					elem.style[ hook ] = value;
				} catch ( e ) {

					// Wrapped to prevent IE from throwing errors on "invalid" values like
					// 'auto' or 'inherit'
				}
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	} );

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		} );
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {

	// 4.1. Basic color keywords
	aqua: "#00ffff",
	black: "#000000",
	blue: "#0000ff",
	fuchsia: "#ff00ff",
	gray: "#808080",
	green: "#008000",
	lime: "#00ff00",
	maroon: "#800000",
	navy: "#000080",
	olive: "#808000",
	purple: "#800080",
	red: "#ff0000",
	silver: "#c0c0c0",
	teal: "#008080",
	white: "#ffffff",
	yellow: "#ffff00",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};

} )( jQuery );

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
( function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each(
	[ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
	function( _, prop ) {
		$.fx.step[ prop ] = function( fx ) {
			if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
				jQuery.style( fx.elem, prop, fx.end );
				fx.setAttr = true;
			}
		};
	}
);

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ $.camelCase( key ) ] = style[ key ];
			}
		}

	// Support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

// Support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// Map the animated objects to store the original styles.
		allAnimations = allAnimations.map( function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		} );

		// Apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function( i, action ) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			} );
		};
		applyClassChange();

		// Map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map( function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		} );

		// Apply original class
		animated.attr( "class", baseClass );

		// Map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map( function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend( {}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				} );

			this.el.animate( this.diff, opts );
			return dfd.promise();
		} );

		// Once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done( function() {

			// Set the final class
			applyClassChange();

			// For each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function( key ) {
					el.css( key, "" );
				} );
			} );

			// This is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		} );
	} );
};

$.fn.extend( {
	addClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.addClass ),

	removeClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.removeClass ),

	toggleClass: ( function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {

					// Without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						( force ? { add: classNames } : { remove: classNames } ),
						speed, easing, callback );
				}
			} else {

				// Without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	} )( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback ) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
} );

} )();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

( function() {

if ( $.expr && $.expr.filters && $.expr.filters.animated ) {
	$.expr.filters.animated = ( function( orig ) {
		return function( elem ) {
			return !!$( elem ).data( dataSpaceAnimated ) || orig( elem );
		};
	} )( $.expr.filters.animated );
}

if ( $.uiBackCompat !== false ) {
	$.extend( $.effects, {

		// Saves a set of properties in a data storage
		save: function( element, set ) {
			var i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
				}
			}
		},

		// Restores a set of previously saved properties from a data storage
		restore: function( element, set ) {
			var val, i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					val = element.data( dataSpace + set[ i ] );
					element.css( set[ i ], val );
				}
			}
		},

		setMode: function( el, mode ) {
			if ( mode === "toggle" ) {
				mode = el.is( ":hidden" ) ? "show" : "hide";
			}
			return mode;
		},

		// Wraps the element around a wrapper that copies position properties
		createWrapper: function( element ) {

			// If the element is already wrapped, return it
			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				return element.parent();
			}

			// Wrap the element
			var props = {
					width: element.outerWidth( true ),
					height: element.outerHeight( true ),
					"float": element.css( "float" )
				},
				wrapper = $( "<div></div>" )
					.addClass( "ui-effects-wrapper" )
					.css( {
						fontSize: "100%",
						background: "transparent",
						border: "none",
						margin: 0,
						padding: 0
					} ),

				// Store the size in case width/height are defined in % - Fixes #5245
				size = {
					width: element.width(),
					height: element.height()
				},
				active = document.activeElement;

			// Support: Firefox
			// Firefox incorrectly exposes anonymous content
			// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
			try {
				active.id;
			} catch ( e ) {
				active = document.body;
			}

			element.wrap( wrapper );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).trigger( "focus" );
			}

			// Hotfix for jQuery 1.4 since some change in wrap() seems to actually
			// lose the reference to the wrapped element
			wrapper = element.parent();

			// Transfer positioning properties to the wrapper
			if ( element.css( "position" ) === "static" ) {
				wrapper.css( { position: "relative" } );
				element.css( { position: "relative" } );
			} else {
				$.extend( props, {
					position: element.css( "position" ),
					zIndex: element.css( "z-index" )
				} );
				$.each( [ "top", "left", "bottom", "right" ], function( i, pos ) {
					props[ pos ] = element.css( pos );
					if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
						props[ pos ] = "auto";
					}
				} );
				element.css( {
					position: "relative",
					top: 0,
					left: 0,
					right: "auto",
					bottom: "auto"
				} );
			}
			element.css( size );

			return wrapper.css( props ).show();
		},

		removeWrapper: function( element ) {
			var active = document.activeElement;

			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				element.parent().replaceWith( element );

				// Fixes #7595 - Elements lose focus when wrapped.
				if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
					$( active ).trigger( "focus" );
				}
			}

			return element;
		}
	} );
}

$.extend( $.effects, {
	version: "1.12.1",

	define: function( name, mode, effect ) {
		if ( !effect ) {
			effect = mode;
			mode = "effect";
		}

		$.effects.effect[ name ] = effect;
		$.effects.effect[ name ].mode = mode;

		return effect;
	},

	scaledDimensions: function( element, percent, direction ) {
		if ( percent === 0 ) {
			return {
				height: 0,
				width: 0,
				outerHeight: 0,
				outerWidth: 0
			};
		}

		var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1,
			y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1;

		return {
			height: element.height() * y,
			width: element.width() * x,
			outerHeight: element.outerHeight() * y,
			outerWidth: element.outerWidth() * x
		};

	},

	clipToBox: function( animation ) {
		return {
			width: animation.clip.right - animation.clip.left,
			height: animation.clip.bottom - animation.clip.top,
			left: animation.clip.left,
			top: animation.clip.top
		};
	},

	// Injects recently queued functions to be first in line (after "inprogress")
	unshift: function( element, queueLength, count ) {
		var queue = element.queue();

		if ( queueLength > 1 ) {
			queue.splice.apply( queue,
				[ 1, 0 ].concat( queue.splice( queueLength, count ) ) );
		}
		element.dequeue();
	},

	saveStyle: function( element ) {
		element.data( dataSpaceStyle, element[ 0 ].style.cssText );
	},

	restoreStyle: function( element ) {
		element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || "";
		element.removeData( dataSpaceStyle );
	},

	mode: function( element, mode ) {
		var hidden = element.is( ":hidden" );

		if ( mode === "toggle" ) {
			mode = hidden ? "show" : "hide";
		}
		if ( hidden ? mode === "hide" : mode === "show" ) {
			mode = "none";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	getBaseline: function( origin, original ) {
		var y, x;

		switch ( origin[ 0 ] ) {
		case "top":
			y = 0;
			break;
		case "middle":
			y = 0.5;
			break;
		case "bottom":
			y = 1;
			break;
		default:
			y = origin[ 0 ] / original.height;
		}

		switch ( origin[ 1 ] ) {
		case "left":
			x = 0;
			break;
		case "center":
			x = 0.5;
			break;
		case "right":
			x = 1;
			break;
		default:
			x = origin[ 1 ] / original.width;
		}

		return {
			x: x,
			y: y
		};
	},

	// Creates a placeholder element so that the original element can be made absolute
	createPlaceholder: function( element ) {
		var placeholder,
			cssPosition = element.css( "position" ),
			position = element.position();

		// Lock in margins first to account for form elements, which
		// will change margin if you explicitly set height
		// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
		// Support: Safari
		element.css( {
			marginTop: element.css( "marginTop" ),
			marginBottom: element.css( "marginBottom" ),
			marginLeft: element.css( "marginLeft" ),
			marginRight: element.css( "marginRight" )
		} )
		.outerWidth( element.outerWidth() )
		.outerHeight( element.outerHeight() );

		if ( /^(static|relative)/.test( cssPosition ) ) {
			cssPosition = "absolute";

			placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {

				// Convert inline to inline block to account for inline elements
				// that turn to inline block based on content (like img)
				display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
					"inline-block" :
					"block",
				visibility: "hidden",

				// Margins need to be set to account for margin collapse
				marginTop: element.css( "marginTop" ),
				marginBottom: element.css( "marginBottom" ),
				marginLeft: element.css( "marginLeft" ),
				marginRight: element.css( "marginRight" ),
				"float": element.css( "float" )
			} )
			.outerWidth( element.outerWidth() )
			.outerHeight( element.outerHeight() )
			.addClass( "ui-effects-placeholder" );

			element.data( dataSpace + "placeholder", placeholder );
		}

		element.css( {
			position: cssPosition,
			left: position.left,
			top: position.top
		} );

		return placeholder;
	},

	removePlaceholder: function( element ) {
		var dataKey = dataSpace + "placeholder",
				placeholder = element.data( dataKey );

		if ( placeholder ) {
			placeholder.remove();
			element.removeData( dataKey );
		}
	},

	// Removes a placeholder if it exists and restores
	// properties that were modified during placeholder creation
	cleanUp: function( element ) {
		$.effects.restoreStyle( element );
		$.effects.removePlaceholder( element );
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		} );
		return value;
	}
} );

// Return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// Allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// Convert to an object
	effect = { effect: effect };

	// Catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// Catch (effect, callback)
	if ( $.isFunction( options ) ) {
		callback = options;
		speed = null;
		options = {};
	}

	// Catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// Catch (effect, options, callback)
	if ( $.isFunction( speed ) ) {
		callback = speed;
		speed = null;
	}

	// Add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {

	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( $.isFunction( option ) ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend( {
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			effectMethod = $.effects.effect[ args.effect ],
			defaultMode = effectMethod.mode,
			queue = args.queue,
			queueName = queue || "fx",
			complete = args.complete,
			mode = args.mode,
			modes = [],
			prefilter = function( next ) {
				var el = $( this ),
					normalizedMode = $.effects.mode( el, mode ) || defaultMode;

				// Sentinel for duck-punching the :animated psuedo-selector
				el.data( dataSpaceAnimated, true );

				// Save effect mode for later use,
				// we can't just call $.effects.mode again later,
				// as the .show() below destroys the initial state
				modes.push( normalizedMode );

				// See $.uiBackCompat inside of run() for removal of defaultMode in 1.13
				if ( defaultMode && ( normalizedMode === "show" ||
						( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) {
					el.show();
				}

				if ( !defaultMode || normalizedMode !== "none" ) {
					$.effects.saveStyle( el );
				}

				if ( $.isFunction( next ) ) {
					next();
				}
			};

		if ( $.fx.off || !effectMethod ) {

			// Delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, complete );
			} else {
				return this.each( function() {
					if ( complete ) {
						complete.call( this );
					}
				} );
			}
		}

		function run( next ) {
			var elem = $( this );

			function cleanup() {
				elem.removeData( dataSpaceAnimated );

				$.effects.cleanUp( elem );

				if ( args.mode === "hide" ) {
					elem.hide();
				}

				done();
			}

			function done() {
				if ( $.isFunction( complete ) ) {
					complete.call( elem[ 0 ] );
				}

				if ( $.isFunction( next ) ) {
					next();
				}
			}

			// Override mode option on a per element basis,
			// as toggle can be either show or hide depending on element state
			args.mode = modes.shift();

			if ( $.uiBackCompat !== false && !defaultMode ) {
				if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, done );
				}
			} else {
				if ( args.mode === "none" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, cleanup );
				}
			}
		}

		// Run prefilter on all elements first to ensure that
		// any showing or hiding happens before placeholder creation,
		// which ensures that any layout changes are correctly captured.
		return queue === false ?
			this.each( prefilter ).each( run ) :
			this.queue( queueName, prefilter ).queue( queueName, run );
	},

	show: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.show ),

	hide: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.hide ),

	toggle: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.toggle ),

	cssUnit: function( key ) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		} );
		return val;
	},

	cssClip: function( clipObj ) {
		if ( clipObj ) {
			return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
				clipObj.bottom + "px " + clipObj.left + "px)" );
		}
		return parseClip( this.css( "clip" ), this );
	},

	transfer: function( options, done ) {
		var element = $( this ),
			target = $( options.to ),
			targetFixed = target.css( "position" ) === "fixed",
			body = $( "body" ),
			fixTop = targetFixed ? body.scrollTop() : 0,
			fixLeft = targetFixed ? body.scrollLeft() : 0,
			endPosition = target.offset(),
			animation = {
				top: endPosition.top - fixTop,
				left: endPosition.left - fixLeft,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = element.offset(),
			transfer = $( "<div class='ui-effects-transfer'></div>" )
				.appendTo( "body" )
				.addClass( options.className )
				.css( {
					top: startPosition.top - fixTop,
					left: startPosition.left - fixLeft,
					height: element.innerHeight(),
					width: element.innerWidth(),
					position: targetFixed ? "fixed" : "absolute"
				} )
				.animate( animation, options.duration, options.easing, function() {
					transfer.remove();
					if ( $.isFunction( done ) ) {
						done();
					}
				} );
	}
} );

function parseClip( str, element ) {
		var outerWidth = element.outerWidth(),
			outerHeight = element.outerHeight(),
			clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
			values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ];

		return {
			top: parseFloat( values[ 1 ] ) || 0,
			right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ),
			bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ),
			left: parseFloat( values[ 4 ] ) || 0
		};
}

$.fx.step.clip = function( fx ) {
	if ( !fx.clipInit ) {
		fx.start = $( fx.elem ).cssClip();
		if ( typeof fx.end === "string" ) {
			fx.end = parseClip( fx.end, fx.elem );
		}
		fx.clipInit = true;
	}

	$( fx.elem ).cssClip( {
		top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top,
		right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right,
		bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom,
		left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left
	} );
};

} )();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

( function() {

// Based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
} );

$.extend( baseEasings, {
	Sine: function( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * ( p - 1 ) ) * Math.sin( ( ( p - 1 ) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
} );

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
} );

} )();

var effect = $.effects;


/*!
 * jQuery UI Effects Blind 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Blind Effect
//>>group: Effects
//>>description: Blinds the element.
//>>docs: http://api.jqueryui.com/blind-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectBlind = $.effects.define( "blind", "hide", function( options, done ) {
	var map = {
			up: [ "bottom", "top" ],
			vertical: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			horizontal: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		element = $( this ),
		direction = options.direction || "up",
		start = element.cssClip(),
		animate = { clip: $.extend( {}, start ) },
		placeholder = $.effects.createPlaceholder( element );

	animate.clip[ map[ direction ][ 0 ] ] = animate.clip[ map[ direction ][ 1 ] ];

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animate ) );
		}

		animate.clip = start;
	}

	if ( placeholder ) {
		placeholder.animate( $.effects.clipToBox( animate ), options.duration, options.easing );
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Bounce 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Bounce Effect
//>>group: Effects
//>>description: Bounces an element horizontally or vertically n times.
//>>docs: http://api.jqueryui.com/bounce-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectBounce = $.effects.define( "bounce", function( options, done ) {
	var upAnim, downAnim, refValue,
		element = $( this ),

		// Defaults:
		mode = options.mode,
		hide = mode === "hide",
		show = mode === "show",
		direction = options.direction || "up",
		distance = options.distance,
		times = options.times || 5,

		// Number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = options.duration / anims,
		easing = options.easing,

		// Utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i = 0,

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	refValue = element.css( ref );

	// Default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = element[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = refValue;

		// If we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		element
			.css( "opacity", 0 )
			.css( ref, motion ? -distance * 2 : distance * 2 )
			.animate( downAnim, speed, easing );
	}

	// Start at the smallest distance if we are hiding
	if ( hide ) {
		distance = distance / Math.pow( 2, times - 1 );
	}

	downAnim = {};
	downAnim[ ref ] = refValue;

	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( ; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element
			.animate( upAnim, speed, easing )
			.animate( downAnim, speed, easing );

		distance = hide ? distance * 2 : distance / 2;
	}

	// Last Bounce when Hiding
	if ( hide ) {
		upAnim = { opacity: 0 };
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element.animate( upAnim, speed, easing );
	}

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Clip 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Clip Effect
//>>group: Effects
//>>description: Clips the element on and off like an old TV.
//>>docs: http://api.jqueryui.com/clip-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectClip = $.effects.define( "clip", "hide", function( options, done ) {
	var start,
		animate = {},
		element = $( this ),
		direction = options.direction || "vertical",
		both = direction === "both",
		horizontal = both || direction === "horizontal",
		vertical = both || direction === "vertical";

	start = element.cssClip();
	animate.clip = {
		top: vertical ? ( start.bottom - start.top ) / 2 : start.top,
		right: horizontal ? ( start.right - start.left ) / 2 : start.right,
		bottom: vertical ? ( start.bottom - start.top ) / 2 : start.bottom,
		left: horizontal ? ( start.right - start.left ) / 2 : start.left
	};

	$.effects.createPlaceholder( element );

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		animate.clip = start;
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );

} );


/*!
 * jQuery UI Effects Drop 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Drop Effect
//>>group: Effects
//>>description: Moves an element in one direction and hides it at the same time.
//>>docs: http://api.jqueryui.com/drop-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectDrop = $.effects.define( "drop", "hide", function( options, done ) {

	var distance,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "-=" : "+=",
		oppositeMotion = ( motion === "+=" ) ? "-=" : "+=",
		animation = {
			opacity: 0
		};

	$.effects.createPlaceholder( element );

	distance = options.distance ||
		element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;

	animation[ ref ] = motion + distance;

	if ( show ) {
		element.css( animation );

		animation[ ref ] = oppositeMotion + distance;
		animation.opacity = 1;
	}

	// Animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Explode 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Explode Effect
//>>group: Effects
// jscs:disable maximumLineLength
//>>description: Explodes an element in all directions into n pieces. Implodes an element to its original wholeness.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/explode-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectExplode = $.effects.define( "explode", "hide", function( options, done ) {

	var i, j, left, top, mx, my,
		rows = options.pieces ? Math.round( Math.sqrt( options.pieces ) ) : 3,
		cells = rows,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",

		// Show and then visibility:hidden the element before calculating offset
		offset = element.show().css( "visibility", "hidden" ).offset(),

		// Width and height of a piece
		width = Math.ceil( element.outerWidth() / cells ),
		height = Math.ceil( element.outerHeight() / rows ),
		pieces = [];

	// Children animate complete:
	function childComplete() {
		pieces.push( this );
		if ( pieces.length === rows * cells ) {
			animComplete();
		}
	}

	// Clone the element for each row and cell.
	for ( i = 0; i < rows; i++ ) { // ===>
		top = offset.top + i * height;
		my = i - ( rows - 1 ) / 2;

		for ( j = 0; j < cells; j++ ) { // |||
			left = offset.left + j * width;
			mx = j - ( cells - 1 ) / 2;

			// Create a clone of the now hidden main element that will be absolute positioned
			// within a wrapper div off the -left and -top equal to size of our pieces
			element
				.clone()
				.appendTo( "body" )
				.wrap( "<div></div>" )
				.css( {
					position: "absolute",
					visibility: "visible",
					left: -j * width,
					top: -i * height
				} )

				// Select the wrapper - make it overflow: hidden and absolute positioned based on
				// where the original was located +left and +top equal to the size of pieces
				.parent()
					.addClass( "ui-effects-explode" )
					.css( {
						position: "absolute",
						overflow: "hidden",
						width: width,
						height: height,
						left: left + ( show ? mx * width : 0 ),
						top: top + ( show ? my * height : 0 ),
						opacity: show ? 0 : 1
					} )
					.animate( {
						left: left + ( show ? 0 : mx * width ),
						top: top + ( show ? 0 : my * height ),
						opacity: show ? 1 : 0
					}, options.duration || 500, options.easing, childComplete );
		}
	}

	function animComplete() {
		element.css( {
			visibility: "visible"
		} );
		$( pieces ).remove();
		done();
	}
} );


/*!
 * jQuery UI Effects Fade 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Fade Effect
//>>group: Effects
//>>description: Fades the element.
//>>docs: http://api.jqueryui.com/fade-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectFade = $.effects.define( "fade", "toggle", function( options, done ) {
	var show = options.mode === "show";

	$( this )
		.css( "opacity", show ? 0 : 1 )
		.animate( {
			opacity: show ? 1 : 0
		}, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );


/*!
 * jQuery UI Effects Fold 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Fold Effect
//>>group: Effects
//>>description: Folds an element first horizontally and then vertically.
//>>docs: http://api.jqueryui.com/fold-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectFold = $.effects.define( "fold", "hide", function( options, done ) {

	// Create element
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		size = options.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!options.horizFirst,
		ref = horizFirst ? [ "right", "bottom" ] : [ "bottom", "right" ],
		duration = options.duration / 2,

		placeholder = $.effects.createPlaceholder( element ),

		start = element.cssClip(),
		animation1 = { clip: $.extend( {}, start ) },
		animation2 = { clip: $.extend( {}, start ) },

		distance = [ start[ ref[ 0 ] ], start[ ref[ 1 ] ] ],

		queuelen = element.queue().length;

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	animation1.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 1 ] ] = 0;

	if ( show ) {
		element.cssClip( animation2.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animation2 ) );
		}

		animation2.clip = start;
	}

	// Animate
	element
		.queue( function( next ) {
			if ( placeholder ) {
				placeholder
					.animate( $.effects.clipToBox( animation1 ), duration, options.easing )
					.animate( $.effects.clipToBox( animation2 ), duration, options.easing );
			}

			next();
		} )
		.animate( animation1, duration, options.easing )
		.animate( animation2, duration, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, 4 );
} );


/*!
 * jQuery UI Effects Highlight 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Highlight Effect
//>>group: Effects
//>>description: Highlights the background of an element in a defined color for a custom duration.
//>>docs: http://api.jqueryui.com/highlight-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectHighlight = $.effects.define( "highlight", "show", function( options, done ) {
	var element = $( this ),
		animation = {
			backgroundColor: element.css( "backgroundColor" )
		};

	if ( options.mode === "hide" ) {
		animation.opacity = 0;
	}

	$.effects.saveStyle( element );

	element
		.css( {
			backgroundImage: "none",
			backgroundColor: options.color || "#ffff99"
		} )
		.animate( animation, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );


/*!
 * jQuery UI Effects Size 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Size Effect
//>>group: Effects
//>>description: Resize an element to a specified width and height.
//>>docs: http://api.jqueryui.com/size-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectSize = $.effects.define( "size", function( options, done ) {

	// Create element
	var baseline, factor, temp,
		element = $( this ),

		// Copy for children
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = options.mode,
		restore = mode !== "effect",
		scale = options.scale || "both",
		origin = options.origin || [ "middle", "center" ],
		position = element.css( "position" ),
		pos = element.position(),
		original = $.effects.scaledDimensions( element ),
		from = options.from || original,
		to = options.to || $.effects.scaledDimensions( element, 0 );

	$.effects.createPlaceholder( element );

	if ( mode === "show" ) {
		temp = from;
		from = to;
		to = temp;
	}

	// Set scaling factor
	factor = {
		from: {
			y: from.height / original.height,
			x: from.width / original.width
		},
		to: {
			y: to.height / original.height,
			x: to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, vProps, factor.from.y, from );
			to = $.effects.setTransition( element, vProps, factor.to.y, to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			from = $.effects.setTransition( element, hProps, factor.from.x, from );
			to = $.effects.setTransition( element, hProps, factor.to.x, to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, cProps, factor.from.y, from );
			to = $.effects.setTransition( element, cProps, factor.to.y, to );
		}
	}

	// Adjust the position properties based on the provided origin points
	if ( origin ) {
		baseline = $.effects.getBaseline( origin, original );
		from.top = ( original.outerHeight - from.outerHeight ) * baseline.y + pos.top;
		from.left = ( original.outerWidth - from.outerWidth ) * baseline.x + pos.left;
		to.top = ( original.outerHeight - to.outerHeight ) * baseline.y + pos.top;
		to.left = ( original.outerWidth - to.outerWidth ) * baseline.x + pos.left;
	}
	element.css( from );

	// Animate the children if desired
	if ( scale === "content" || scale === "both" ) {

		vProps = vProps.concat( [ "marginTop", "marginBottom" ] ).concat( cProps );
		hProps = hProps.concat( [ "marginLeft", "marginRight" ] );

		// Only animate children with width attributes specified
		// TODO: is this right? should we include anything with css width specified as well
		element.find( "*[width]" ).each( function() {
			var child = $( this ),
				childOriginal = $.effects.scaledDimensions( child ),
				childFrom = {
					height: childOriginal.height * factor.from.y,
					width: childOriginal.width * factor.from.x,
					outerHeight: childOriginal.outerHeight * factor.from.y,
					outerWidth: childOriginal.outerWidth * factor.from.x
				},
				childTo = {
					height: childOriginal.height * factor.to.y,
					width: childOriginal.width * factor.to.x,
					outerHeight: childOriginal.height * factor.to.y,
					outerWidth: childOriginal.width * factor.to.x
				};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				childFrom = $.effects.setTransition( child, vProps, factor.from.y, childFrom );
				childTo = $.effects.setTransition( child, vProps, factor.to.y, childTo );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				childFrom = $.effects.setTransition( child, hProps, factor.from.x, childFrom );
				childTo = $.effects.setTransition( child, hProps, factor.to.x, childTo );
			}

			if ( restore ) {
				$.effects.saveStyle( child );
			}

			// Animate children
			child.css( childFrom );
			child.animate( childTo, options.duration, options.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restoreStyle( child );
				}
			} );
		} );
	}

	// Animate
	element.animate( to, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: function() {

			var offset = element.offset();

			if ( to.opacity === 0 ) {
				element.css( "opacity", from.opacity );
			}

			if ( !restore ) {
				element
					.css( "position", position === "static" ? "relative" : position )
					.offset( offset );

				// Need to save style here so that automatic style restoration
				// doesn't restore to the original styles from before the animation.
				$.effects.saveStyle( element );
			}

			done();
		}
	} );

} );


/*!
 * jQuery UI Effects Scale 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Scale Effect
//>>group: Effects
//>>description: Grows or shrinks an element and its content.
//>>docs: http://api.jqueryui.com/scale-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectScale = $.effects.define( "scale", function( options, done ) {

	// Create element
	var el = $( this ),
		mode = options.mode,
		percent = parseInt( options.percent, 10 ) ||
			( parseInt( options.percent, 10 ) === 0 ? 0 : ( mode !== "effect" ? 0 : 100 ) ),

		newOptions = $.extend( true, {
			from: $.effects.scaledDimensions( el ),
			to: $.effects.scaledDimensions( el, percent, options.direction || "both" ),
			origin: options.origin || [ "middle", "center" ]
		}, options );

	// Fade option to support puff
	if ( options.fade ) {
		newOptions.from.opacity = 1;
		newOptions.to.opacity = 0;
	}

	$.effects.effect.size.call( this, newOptions, done );
} );


/*!
 * jQuery UI Effects Puff 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Puff Effect
//>>group: Effects
//>>description: Creates a puff effect by scaling the element up and hiding it at the same time.
//>>docs: http://api.jqueryui.com/puff-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectPuff = $.effects.define( "puff", "hide", function( options, done ) {
	var newOptions = $.extend( true, {}, options, {
		fade: true,
		percent: parseInt( options.percent, 10 ) || 150
	} );

	$.effects.effect.scale.call( this, newOptions, done );
} );


/*!
 * jQuery UI Effects Pulsate 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Pulsate Effect
//>>group: Effects
//>>description: Pulsates an element n times by changing the opacity to zero and back.
//>>docs: http://api.jqueryui.com/pulsate-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectPulsate = $.effects.define( "pulsate", "show", function( options, done ) {
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		showhide = show || hide,

		// Showing or hiding leaves off the "last" animation
		anims = ( ( options.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = options.duration / anims,
		animateTo = 0,
		i = 1,
		queuelen = element.queue().length;

	if ( show || !element.is( ":visible" ) ) {
		element.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// Anims - 1 opacity "toggles"
	for ( ; i < anims; i++ ) {
		element.animate( { opacity: animateTo }, duration, options.easing );
		animateTo = 1 - animateTo;
	}

	element.animate( { opacity: animateTo }, duration, options.easing );

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Shake 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Shake Effect
//>>group: Effects
//>>description: Shakes an element horizontally or vertically n times.
//>>docs: http://api.jqueryui.com/shake-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectShake = $.effects.define( "shake", function( options, done ) {

	var i = 1,
		element = $( this ),
		direction = options.direction || "left",
		distance = options.distance || 20,
		times = options.times || 3,
		anims = times * 2 + 1,
		speed = Math.round( options.duration / anims ),
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		animation = {},
		animation1 = {},
		animation2 = {},

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	element.animate( animation, speed, options.easing );

	// Shakes
	for ( ; i < times; i++ ) {
		element
			.animate( animation1, speed, options.easing )
			.animate( animation2, speed, options.easing );
	}

	element
		.animate( animation1, speed, options.easing )
		.animate( animation, speed / 2, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Slide 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slide Effect
//>>group: Effects
//>>description: Slides an element in and out of the viewport.
//>>docs: http://api.jqueryui.com/slide-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectSlide = $.effects.define( "slide", "show", function( options, done ) {
	var startClip, startRef,
		element = $( this ),
		map = {
			up: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		mode = options.mode,
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		distance = options.distance ||
			element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ),
		animation = {};

	$.effects.createPlaceholder( element );

	startClip = element.cssClip();
	startRef = element.position()[ ref ];

	// Define hide animation
	animation[ ref ] = ( positiveMotion ? -1 : 1 ) * distance + startRef;
	animation.clip = element.cssClip();
	animation.clip[ map[ direction ][ 1 ] ] = animation.clip[ map[ direction ][ 0 ] ];

	// Reverse the animation if we're showing
	if ( mode === "show" ) {
		element.cssClip( animation.clip );
		element.css( ref, animation[ ref ] );
		animation.clip = startClip;
		animation[ ref ] = startRef;
	}

	// Actually animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Transfer 1.12.1
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: http://api.jqueryui.com/transfer-effect/
//>>demos: http://jqueryui.com/effect/



var effect;
if ( $.uiBackCompat !== false ) {
	effect = $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}
var effectsEffectTransfer = effect;




}));
var DropdownDecorator = function (node, options) {
	options = options || {};

	var ractive = node._ractive.root;
	var keypath = node._ractive.binding.keypath;
	var isSetting = false;
	var dropdown$ = $(node);

	dropdown$
		.selectmenu({
			appendTo: (ractive.el.id.length > 0 ? "#" + ractive.el.id : "") + ractive.el.className.split(" ").join("."),
			change: function (event, data) {
				if (!isSetting) {
					isSetting = false;
					ractive.set(keypath.str, data.item.value);
				}
			}
		})
		.selectmenu("menuWidget")
		.addClass(node.className);


	var observer = ractive.observe(keypath.str, function (newvalue, oldvalue) {
		if (!isSetting) {
			isSetting = true;
			dropdown$.val(newvalue);
			dropdown$.selectmenu("refresh");
			isSetting = false;
		}
	});

	return {
		update: function (newOptions) {
			options = newOptions;

		},
		teardown: function () {
			if (dropdown$) {
				dropdown$.remove();
				dropdown$ = null;
			}

			if (observer) {
				observer.cancel();
			}
		}
	};
};
/*
	Ractive.js v0.7.3
	Sat Apr 25 2015 13:52:38 GMT-0400 (EDT) - commit da40f81c660ba2f09c45a09a9c20fdd34ee36d80

	http://ractivejs.org
	http://twitter.com/RactiveJS

	Released under the MIT License.
*/


(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	global.Ractive = factory()
}(this, function () {
	'use strict';

	var TEMPLATE_VERSION = 3;

	var defaultOptions = {

		// render placement:
		el: void 0,
		append: false,

		// template:
		template: { v: TEMPLATE_VERSION, t: [] },

		// parse:     // TODO static delimiters?
		preserveWhitespace: false,
		sanitize: false,
		stripComments: true,
		delimiters: ["{{", "}}"],
		tripleDelimiters: ["{{{", "}}}"],
		interpolate: false,

		// data & binding:
		data: {},
		computed: {},
		magic: false,
		modifyArrays: true,
		adapt: [],
		isolated: false,
		twoway: true,
		lazy: false,

		// transitions:
		noIntro: false,
		transitionsEnabled: true,
		complete: void 0,

		// css:
		css: null,
		noCssTransform: false
	};

	var config_defaults = defaultOptions;

	// These are a subset of the easing equations found at
	// https://raw.github.com/danro/easing-js - license info
	// follows:

	// --------------------------------------------------
	// easing.js v0.5.4
	// Generic set of easing functions with AMD support
	// https://github.com/danro/easing-js
	// This code may be freely distributed under the MIT license
	// http://danro.mit-license.org/
	// --------------------------------------------------
	// All functions adapted from Thomas Fuchs & Jeremy Kahn
	// Easing Equations (c) 2003 Robert Penner, BSD license
	// https://raw.github.com/danro/easing-js/master/LICENSE
	// --------------------------------------------------

	// In that library, the functions named easeIn, easeOut, and
	// easeInOut below are named easeInCubic, easeOutCubic, and
	// (you guessed it) easeInOutCubic.
	//
	// You can add additional easing functions to this list, and they
	// will be globally available.

	var static_easing = {
		linear: function (pos) {
			return pos;
		},
		easeIn: function (pos) {
			return Math.pow(pos, 3);
		},
		easeOut: function (pos) {
			return Math.pow(pos - 1, 3) + 1;
		},
		easeInOut: function (pos) {
			if ((pos /= 0.5) < 1) {
				return 0.5 * Math.pow(pos, 3);
			}
			return 0.5 * (Math.pow(pos - 2, 3) + 2);
		}
	};

	/*global console, navigator */
	var isClient, isJsdom, hasConsole, environment__magic, namespaces, svg, vendors;

	isClient = typeof document === "object";

	isJsdom = typeof navigator !== "undefined" && /jsDom/.test(navigator.appName);

	hasConsole = typeof console !== "undefined" && typeof console.warn === "function" && typeof console.warn.apply === "function";

	try {
		Object.defineProperty({}, "test", { value: 0 });
		environment__magic = true;
	} catch (e) {
		environment__magic = false;
	}

	namespaces = {
		html: "http://www.w3.org/1999/xhtml",
		mathml: "http://www.w3.org/1998/Math/MathML",
		svg: "http://www.w3.org/2000/svg",
		xlink: "http://www.w3.org/1999/xlink",
		xml: "http://www.w3.org/XML/1998/namespace",
		xmlns: "http://www.w3.org/2000/xmlns/"
	};

	if (typeof document === "undefined") {
		svg = false;
	} else {
		svg = document && document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
	}

	vendors = ["o", "ms", "moz", "webkit"];

	var createElement, matches, dom__div, methodNames, unprefixed, prefixed, dom__i, j, makeFunction;

	// Test for SVG support
	if (!svg) {
		createElement = function (type, ns) {
			if (ns && ns !== namespaces.html) {
				throw "This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you're trying to render SVG in an older browser. See http://docs.ractivejs.org/latest/svg-and-older-browsers for more information";
			}

			return document.createElement(type);
		};
	} else {
		createElement = function (type, ns) {
			if (!ns || ns === namespaces.html) {
				return document.createElement(type);
			}

			return document.createElementNS(ns, type);
		};
	}

	function getElement(input) {
		var output;

		if (!input || typeof input === "boolean") {
			return;
		}

		if (typeof window === "undefined" || !document || !input) {
			return null;
		}

		// We already have a DOM node - no work to do. (Duck typing alert!)
		if (input.nodeType) {
			return input;
		}

		// Get node from string
		if (typeof input === "string") {
			// try ID first
			output = document.getElementById(input);

			// then as selector, if possible
			if (!output && document.querySelector) {
				output = document.querySelector(input);
			}

			// did it work?
			if (output && output.nodeType) {
				return output;
			}
		}

		// If we've been given a collection (jQuery, Zepto etc), extract the first item
		if (input[0] && input[0].nodeType) {
			return input[0];
		}

		return null;
	}

	if (!isClient) {
		matches = null;
	} else {
		dom__div = createElement("div");
		methodNames = ["matches", "matchesSelector"];

		makeFunction = function (methodName) {
			return function (node, selector) {
				return node[methodName](selector);
			};
		};

		dom__i = methodNames.length;

		while (dom__i-- && !matches) {
			unprefixed = methodNames[dom__i];

			if (dom__div[unprefixed]) {
				matches = makeFunction(unprefixed);
			} else {
				j = vendors.length;
				while (j--) {
					prefixed = vendors[dom__i] + unprefixed.substr(0, 1).toUpperCase() + unprefixed.substring(1);

					if (dom__div[prefixed]) {
						matches = makeFunction(prefixed);
						break;
					}
				}
			}
		}

		// IE8...
		if (!matches) {
			matches = function (node, selector) {
				var nodes, parentNode, i;

				parentNode = node.parentNode;

				if (!parentNode) {
					// empty dummy <div>
					dom__div.innerHTML = "";

					parentNode = dom__div;
					node = node.cloneNode();

					dom__div.appendChild(node);
				}

				nodes = parentNode.querySelectorAll(selector);

				i = nodes.length;
				while (i--) {
					if (nodes[i] === node) {
						return true;
					}
				}

				return false;
			};
		}
	}

	function detachNode(node) {
		if (node && typeof node.parentNode !== "unknown" && node.parentNode) {
			node.parentNode.removeChild(node);
		}

		return node;
	}

	function safeToStringValue(value) {
		return value == null || !value.toString ? "" : value;
	}

	var legacy = null;

	var create, defineProperty, defineProperties;

	try {
		Object.defineProperty({}, "test", { value: 0 });

		if (isClient) {
			Object.defineProperty(document.createElement("div"), "test", { value: 0 });
		}

		defineProperty = Object.defineProperty;
	} catch (err) {
		// Object.defineProperty doesn't exist, or we're in IE8 where you can
		// only use it with DOM objects (what were you smoking, MSFT?)
		defineProperty = function (obj, prop, desc) {
			obj[prop] = desc.value;
		};
	}

	try {
		try {
			Object.defineProperties({}, { test: { value: 0 } });
		} catch (err) {
			// TODO how do we account for this? noMagic = true;
			throw err;
		}

		if (isClient) {
			Object.defineProperties(createElement("div"), { test: { value: 0 } });
		}

		defineProperties = Object.defineProperties;
	} catch (err) {
		defineProperties = function (obj, props) {
			var prop;

			for (prop in props) {
				if (props.hasOwnProperty(prop)) {
					defineProperty(obj, prop, props[prop]);
				}
			}
		};
	}

	try {
		Object.create(null);

		create = Object.create;
	} catch (err) {
		// sigh
		create = (function () {
			var F = function () { };

			return function (proto, props) {
				var obj;

				if (proto === null) {
					return {};
				}

				F.prototype = proto;
				obj = new F();

				if (props) {
					Object.defineProperties(obj, props);
				}

				return obj;
			};
		})();
	}

	function utils_object__extend(target) {
		for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
			sources[_key - 1] = arguments[_key];
		}

		var prop, source;

		while (source = sources.shift()) {
			for (prop in source) {
				if (hasOwn.call(source, prop)) {
					target[prop] = source[prop];
				}
			}
		}

		return target;
	}

	function fillGaps(target) {
		for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
			sources[_key - 1] = arguments[_key];
		}

		sources.forEach(function (s) {
			for (var key in s) {
				if (s.hasOwnProperty(key) && !(key in target)) {
					target[key] = s[key];
				}
			}
		});

		return target;
	}

	var hasOwn = Object.prototype.hasOwnProperty;

	// thanks, http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
	var is__toString = Object.prototype.toString,
		arrayLikePattern = /^\[object (?:Array|FileList)\]$/;
	function isArray(thing) {
		return is__toString.call(thing) === "[object Array]";
	}

	function isArrayLike(obj) {
		return arrayLikePattern.test(is__toString.call(obj));
	}

	function isEqual(a, b) {
		if (a === null && b === null) {
			return true;
		}

		if (typeof a === "object" || typeof b === "object") {
			return false;
		}

		return a === b;
	}

	function is__isNumeric(thing) {
		return !isNaN(parseFloat(thing)) && isFinite(thing);
	}

	function isObject(thing) {
		return thing && is__toString.call(thing) === "[object Object]";
	}

	var noop = function () { };

	/* global console */
	var alreadyWarned = {},
		log,
		printWarning,
		welcome;

	if (hasConsole) {
		(function () {
			var welcomeIntro = ["%cRactive.js %c0.7.3 %cin debug mode, %cmore...", "color: rgb(114, 157, 52); font-weight: normal;", "color: rgb(85, 85, 85); font-weight: normal;", "color: rgb(85, 85, 85); font-weight: normal;", "color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;"];
			var welcomeMessage = "You're running Ractive 0.7.3 in debug mode - messages will be printed to the console to help you fix problems and optimise your application.\n\nTo disable debug mode, add this line at the start of your app:\n  Ractive.DEBUG = false;\n\nTo disable debug mode when your app is minified, add this snippet:\n  Ractive.DEBUG = /unminified/.test(function(){/*unminified*/});\n\nGet help and support:\n  http://docs.ractivejs.org\n  http://stackoverflow.com/questions/tagged/ractivejs\n  http://groups.google.com/forum/#!forum/ractive-js\n  http://twitter.com/ractivejs\n\nFound a bug? Raise an issue:\n  https://github.com/ractivejs/ractive/issues\n\n";

			welcome = function () {
				var hasGroup = !!console.groupCollapsed;
				console[hasGroup ? "groupCollapsed" : "log"].apply(console, welcomeIntro);
				console.log(welcomeMessage);
				if (hasGroup) {
					console.groupEnd(welcomeIntro);
				}

				welcome = noop;
			};

			printWarning = function (message, args) {
				welcome();

				// extract information about the instance this message pertains to, if applicable
				if (typeof args[args.length - 1] === "object") {
					var options = args.pop();
					var ractive = options ? options.ractive : null;

					if (ractive) {
						// if this is an instance of a component that we know the name of, add
						// it to the message
						var _name = undefined;
						if (ractive.component && (_name = ractive.component.name)) {
							message = "<" + _name + "> " + message;
						}

						var node = undefined;
						if (node = options.node || ractive.fragment && ractive.fragment.rendered && ractive.find("*")) {
							args.push(node);
						}
					}
				}

				console.warn.apply(console, ["%cRactive.js: %c" + message, "color: rgb(114, 157, 52);", "color: rgb(85, 85, 85);"].concat(args));
			};

			log = function () {
				console.log.apply(console, arguments);
			};
		})();
	} else {
		printWarning = log = welcome = noop;
	}

	function format(message, args) {
		return message.replace(/%s/g, function () {
			return args.shift();
		});
	}

	function fatal(message) {
		for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
			args[_key - 1] = arguments[_key];
		}

		message = format(message, args);
		throw new Error(message);
	}

	function logIfDebug() {
		if (_Ractive.DEBUG) {
			log.apply(null, arguments);
		}
	}

	function warn(message) {
		for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
			args[_key - 1] = arguments[_key];
		}

		message = format(message, args);
		printWarning(message, args);
	}

	function warnOnce(message) {
		for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
			args[_key - 1] = arguments[_key];
		}

		message = format(message, args);

		if (alreadyWarned[message]) {
			return;
		}

		alreadyWarned[message] = true;
		printWarning(message, args);
	}

	function warnIfDebug() {
		if (_Ractive.DEBUG) {
			warn.apply(null, arguments);
		}
	}

	function warnOnceIfDebug() {
		if (_Ractive.DEBUG) {
			warnOnce.apply(null, arguments);
		}
	}

	// Error messages that are used (or could be) in multiple places
	var badArguments = "Bad arguments";
	var noRegistryFunctionReturn = "A function was specified for \"%s\" %s, but no %s was returned";
	var missingPlugin = function (name, type) {
		return "Missing \"" + name + "\" " + type + " plugin. You may need to download a plugin via http://docs.ractivejs.org/latest/plugins#" + type + "s";
	};

	function findInViewHierarchy(registryName, ractive, name) {
		var instance = findInstance(registryName, ractive, name);
		return instance ? instance[registryName][name] : null;
	}

	function findInstance(registryName, ractive, name) {
		while (ractive) {
			if (name in ractive[registryName]) {
				return ractive;
			}

			if (ractive.isolated) {
				return null;
			}

			ractive = ractive.parent;
		}
	}

	var interpolate = function (from, to, ractive, type) {
		if (from === to) {
			return snap(to);
		}

		if (type) {

			var interpol = findInViewHierarchy("interpolators", ractive, type);
			if (interpol) {
				return interpol(from, to) || snap(to);
			}

			fatal(missingPlugin(type, "interpolator"));
		}

		return static_interpolators.number(from, to) || static_interpolators.array(from, to) || static_interpolators.object(from, to) || snap(to);
	};

	var shared_interpolate = interpolate;

	function snap(to) {
		return function () {
			return to;
		};
	}

	var interpolators = {
		number: function (from, to) {
			var delta;

			if (!is__isNumeric(from) || !is__isNumeric(to)) {
				return null;
			}

			from = +from;
			to = +to;

			delta = to - from;

			if (!delta) {
				return function () {
					return from;
				};
			}

			return function (t) {
				return from + t * delta;
			};
		},

		array: function (from, to) {
			var intermediate, interpolators, len, i;

			if (!isArray(from) || !isArray(to)) {
				return null;
			}

			intermediate = [];
			interpolators = [];

			i = len = Math.min(from.length, to.length);
			while (i--) {
				interpolators[i] = shared_interpolate(from[i], to[i]);
			}

			// surplus values - don't interpolate, but don't exclude them either
			for (i = len; i < from.length; i += 1) {
				intermediate[i] = from[i];
			}

			for (i = len; i < to.length; i += 1) {
				intermediate[i] = to[i];
			}

			return function (t) {
				var i = len;

				while (i--) {
					intermediate[i] = interpolators[i](t);
				}

				return intermediate;
			};
		},

		object: function (from, to) {
			var properties, len, interpolators, intermediate, prop;

			if (!isObject(from) || !isObject(to)) {
				return null;
			}

			properties = [];
			intermediate = {};
			interpolators = {};

			for (prop in from) {
				if (hasOwn.call(from, prop)) {
					if (hasOwn.call(to, prop)) {
						properties.push(prop);
						interpolators[prop] = shared_interpolate(from[prop], to[prop]);
					} else {
						intermediate[prop] = from[prop];
					}
				}
			}

			for (prop in to) {
				if (hasOwn.call(to, prop) && !hasOwn.call(from, prop)) {
					intermediate[prop] = to[prop];
				}
			}

			len = properties.length;

			return function (t) {
				var i = len,
					prop;

				while (i--) {
					prop = properties[i];

					intermediate[prop] = interpolators[prop](t);
				}

				return intermediate;
			};
		}
	};

	var static_interpolators = interpolators;

	// This function takes a keypath such as 'foo.bar.baz', and returns
	// all the variants of that keypath that include a wildcard in place
	// of a key, such as 'foo.bar.*', 'foo.*.baz', 'foo.*.*' and so on.
	// These are then checked against the dependants map (ractive.viewmodel.depsMap)
	// to see if any pattern observers are downstream of one or more of
	// these wildcard keypaths (e.g. 'foo.bar.*.status')
	var utils_getPotentialWildcardMatches = getPotentialWildcardMatches;

	var starMaps = {};
	function getPotentialWildcardMatches(keypath) {
		var keys, starMap, mapper, i, result, wildcardKeypath;

		keys = keypath.split(".");
		if (!(starMap = starMaps[keys.length])) {
			starMap = getStarMap(keys.length);
		}

		result = [];

		mapper = function (star, i) {
			return star ? "*" : keys[i];
		};

		i = starMap.length;
		while (i--) {
			wildcardKeypath = starMap[i].map(mapper).join(".");

			if (!result.hasOwnProperty(wildcardKeypath)) {
				result.push(wildcardKeypath);
				result[wildcardKeypath] = true;
			}
		}

		return result;
	}

	// This function returns all the possible true/false combinations for
	// a given number - e.g. for two, the possible combinations are
	// [ true, true ], [ true, false ], [ false, true ], [ false, false ].
	// It does so by getting all the binary values between 0 and e.g. 11
	function getStarMap(num) {
		var ones = "",
			max,
			binary,
			starMap,
			mapper,
			i,
			j,
			l,
			map;

		if (!starMaps[num]) {
			starMap = [];

			while (ones.length < num) {
				ones += 1;
			}

			max = parseInt(ones, 2);

			mapper = function (digit) {
				return digit === "1";
			};

			for (i = 0; i <= max; i += 1) {
				binary = i.toString(2);
				while (binary.length < num) {
					binary = "0" + binary;
				}

				map = [];
				l = binary.length;
				for (j = 0; j < l; j++) {
					map.push(mapper(binary[j]));
				}
				starMap[i] = map;
			}

			starMaps[num] = starMap;
		}

		return starMaps[num];
	}

	var refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g;
	var patternPattern = /\*/;
	var keypathCache = {};

	var Keypath = function (str) {
		var keys = str.split(".");

		this.str = str;

		if (str[0] === "@") {
			this.isSpecial = true;
			this.value = decodeKeypath(str);
		}

		this.firstKey = keys[0];
		this.lastKey = keys.pop();

		this.isPattern = patternPattern.test(str);

		this.parent = str === "" ? null : getKeypath(keys.join("."));
		this.isRoot = !str;
	};

	Keypath.prototype = {
		equalsOrStartsWith: function (keypath) {
			return keypath === this || this.startsWith(keypath);
		},

		join: function (str) {
			return getKeypath(this.isRoot ? String(str) : this.str + "." + str);
		},

		replace: function (oldKeypath, newKeypath) {
			if (this === oldKeypath) {
				return newKeypath;
			}

			if (this.startsWith(oldKeypath)) {
				return newKeypath === null ? newKeypath : getKeypath(this.str.replace(oldKeypath.str + ".", newKeypath.str + "."));
			}
		},

		startsWith: function (keypath) {
			if (!keypath) {
				// TODO under what circumstances does this happen?
				return false;
			}

			return keypath && this.str.substr(0, keypath.str.length + 1) === keypath.str + ".";
		},

		toString: function () {
			throw new Error("Bad coercion");
		},

		valueOf: function () {
			throw new Error("Bad coercion");
		},

		wildcardMatches: function () {
			return this._wildcardMatches || (this._wildcardMatches = utils_getPotentialWildcardMatches(this.str));
		}
	};
	function assignNewKeypath(target, property, oldKeypath, newKeypath) {
		var existingKeypath = target[property];

		if (existingKeypath && (existingKeypath.equalsOrStartsWith(newKeypath) || !existingKeypath.equalsOrStartsWith(oldKeypath))) {
			return;
		}

		target[property] = existingKeypath ? existingKeypath.replace(oldKeypath, newKeypath) : newKeypath;
		return true;
	}

	function decodeKeypath(keypath) {
		var value = keypath.slice(2);

		if (keypath[1] === "i") {
			return is__isNumeric(value) ? +value : value;
		} else {
			return value;
		}
	}

	function getKeypath(str) {
		if (str == null) {
			return str;
		}

		// TODO it *may* be worth having two versions of this function - one where
		// keypathCache inherits from null, and one for IE8. Depends on how
		// much of an overhead hasOwnProperty is - probably negligible
		if (!keypathCache.hasOwnProperty(str)) {
			keypathCache[str] = new Keypath(str);
		}

		return keypathCache[str];
	}

	function getMatchingKeypaths(ractive, keypath) {
		var keys, key, matchingKeypaths;

		keys = keypath.str.split(".");
		matchingKeypaths = [rootKeypath];

		while (key = keys.shift()) {
			if (key === "*") {
				// expand to find all valid child keypaths
				matchingKeypaths = matchingKeypaths.reduce(expand, []);
			} else {
				if (matchingKeypaths[0] === rootKeypath) {
					// first key
					matchingKeypaths[0] = getKeypath(key);
				} else {
					matchingKeypaths = matchingKeypaths.map(concatenate(key));
				}
			}
		}

		return matchingKeypaths;

		function expand(matchingKeypaths, keypath) {
			var wrapper, value, keys;

			if (keypath.isRoot) {
				keys = [].concat(Object.keys(ractive.viewmodel.data), Object.keys(ractive.viewmodel.mappings), Object.keys(ractive.viewmodel.computations));
			} else {
				wrapper = ractive.viewmodel.wrapped[keypath.str];
				value = wrapper ? wrapper.get() : ractive.viewmodel.get(keypath);

				keys = value ? Object.keys(value) : null;
			}

			if (keys) {
				keys.forEach(function (key) {
					if (key !== "_ractive" || !isArray(value)) {
						matchingKeypaths.push(keypath.join(key));
					}
				});
			}

			return matchingKeypaths;
		}
	}

	function concatenate(key) {
		return function (keypath) {
			return keypath.join(key);
		};
	}
	function normalise(ref) {
		return ref ? ref.replace(refPattern, ".$1") : "";
	}

	var rootKeypath = getKeypath("");

	var shared_add = add;
	var shared_add__errorMessage = "Cannot add to a non-numeric value";
	function add(root, keypath, d) {
		if (typeof keypath !== "string" || !is__isNumeric(d)) {
			throw new Error("Bad arguments");
		}

		var value = undefined,
			changes = undefined;

		if (/\*/.test(keypath)) {
			changes = {};

			getMatchingKeypaths(root, getKeypath(normalise(keypath))).forEach(function (keypath) {
				var value = root.viewmodel.get(keypath);

				if (!is__isNumeric(value)) {
					throw new Error(shared_add__errorMessage);
				}

				changes[keypath.str] = value + d;
			});

			return root.set(changes);
		}

		value = root.get(keypath);

		if (!is__isNumeric(value)) {
			throw new Error(shared_add__errorMessage);
		}

		return root.set(keypath, +value + d);
	}

	var prototype_add = Ractive$add;
	function Ractive$add(keypath, d) {
		return shared_add(this, keypath, d === undefined ? 1 : +d);
	}

	var requestAnimationFrame;

	// If window doesn't exist, we don't need requestAnimationFrame
	if (typeof window === "undefined") {
		requestAnimationFrame = null;
	} else {
		// https://gist.github.com/paulirish/1579671
		(function (vendors, lastTime, window) {

			var x, setTimeout;

			if (window.requestAnimationFrame) {
				return;
			}

			for (x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
				window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"];
			}

			if (!window.requestAnimationFrame) {
				setTimeout = window.setTimeout;

				window.requestAnimationFrame = function (callback) {
					var currTime, timeToCall, id;

					currTime = Date.now();
					timeToCall = Math.max(0, 16 - (currTime - lastTime));
					id = setTimeout(function () {
						callback(currTime + timeToCall);
					}, timeToCall);

					lastTime = currTime + timeToCall;
					return id;
				};
			}
		})(vendors, 0, window);

		requestAnimationFrame = window.requestAnimationFrame;
	}

	var rAF = requestAnimationFrame;

	var getTime;

	if (typeof window !== "undefined" && window.performance && typeof window.performance.now === "function") {
		getTime = function () {
			return window.performance.now();
		};
	} else {
		getTime = function () {
			return Date.now();
		};
	}

	var utils_getTime = getTime;

	var deprecations = {
		construct: {
			deprecated: "beforeInit",
			replacement: "onconstruct"
		},
		render: {
			deprecated: "init",
			message: "The \"init\" method has been deprecated " + "and will likely be removed in a future release. " + "You can either use the \"oninit\" method which will fire " + "only once prior to, and regardless of, any eventual ractive " + "instance being rendered, or if you need to access the " + "rendered DOM, use \"onrender\" instead. " + "See http://docs.ractivejs.org/latest/migrating for more information."
		},
		complete: {
			deprecated: "complete",
			replacement: "oncomplete"
		}
	};

	function Hook(event) {
		this.event = event;
		this.method = "on" + event;
		this.deprecate = deprecations[event];
	}

	Hook.prototype.fire = function (ractive, arg) {
		function call(method) {
			if (ractive[method]) {
				arg ? ractive[method](arg) : ractive[method]();
				return true;
			}
		}

		call(this.method);

		if (!ractive[this.method] && this.deprecate && call(this.deprecate.deprecated)) {
			if (this.deprecate.message) {
				warnIfDebug(this.deprecate.message);
			} else {
				warnIfDebug("The method \"%s\" has been deprecated in favor of \"%s\" and will likely be removed in a future release. See http://docs.ractivejs.org/latest/migrating for more information.", this.deprecate.deprecated, this.deprecate.replacement);
			}
		}

		arg ? ractive.fire(this.event, arg) : ractive.fire(this.event);
	};

	var hooks_Hook = Hook;

	function addToArray(array, value) {
		var index = array.indexOf(value);

		if (index === -1) {
			array.push(value);
		}
	}

	function arrayContains(array, value) {
		for (var i = 0, c = array.length; i < c; i++) {
			if (array[i] == value) {
				return true;
			}
		}

		return false;
	}

	function arrayContentsMatch(a, b) {
		var i;

		if (!isArray(a) || !isArray(b)) {
			return false;
		}

		if (a.length !== b.length) {
			return false;
		}

		i = a.length;
		while (i--) {
			if (a[i] !== b[i]) {
				return false;
			}
		}

		return true;
	}

	function ensureArray(x) {
		if (typeof x === "string") {
			return [x];
		}

		if (x === undefined) {
			return [];
		}

		return x;
	}

	function lastItem(array) {
		return array[array.length - 1];
	}

	function removeFromArray(array, member) {
		var index = array.indexOf(member);

		if (index !== -1) {
			array.splice(index, 1);
		}
	}

	function toArray(arrayLike) {
		var array = [],
			i = arrayLike.length;
		while (i--) {
			array[i] = arrayLike[i];
		}

		return array;
	}

	var _Promise,
		PENDING = {},
		FULFILLED = {},
		REJECTED = {};

	if (typeof Promise === "function") {
		// use native Promise
		_Promise = Promise;
	} else {
		_Promise = function (callback) {
			var fulfilledHandlers = [],
				rejectedHandlers = [],
				state = PENDING,
				result,
				dispatchHandlers,
				makeResolver,
				fulfil,
				reject,
				promise;

			makeResolver = function (newState) {
				return function (value) {
					if (state !== PENDING) {
						return;
					}

					result = value;
					state = newState;

					dispatchHandlers = makeDispatcher(state === FULFILLED ? fulfilledHandlers : rejectedHandlers, result);

					// dispatch onFulfilled and onRejected handlers asynchronously
					wait(dispatchHandlers);
				};
			};

			fulfil = makeResolver(FULFILLED);
			reject = makeResolver(REJECTED);

			try {
				callback(fulfil, reject);
			} catch (err) {
				reject(err);
			}

			promise = {
				// `then()` returns a Promise - 2.2.7
				then: function (onFulfilled, onRejected) {
					var promise2 = new _Promise(function (fulfil, reject) {

						var processResolutionHandler = function (handler, handlers, forward) {

							// 2.2.1.1
							if (typeof handler === "function") {
								handlers.push(function (p1result) {
									var x;

									try {
										x = handler(p1result);
										utils_Promise__resolve(promise2, x, fulfil, reject);
									} catch (err) {
										reject(err);
									}
								});
							} else {
								// Forward the result of promise1 to promise2, if resolution handlers
								// are not given
								handlers.push(forward);
							}
						};

						// 2.2
						processResolutionHandler(onFulfilled, fulfilledHandlers, fulfil);
						processResolutionHandler(onRejected, rejectedHandlers, reject);

						if (state !== PENDING) {
							// If the promise has resolved already, dispatch the appropriate handlers asynchronously
							wait(dispatchHandlers);
						}
					});

					return promise2;
				}
			};

			promise["catch"] = function (onRejected) {
				return this.then(null, onRejected);
			};

			return promise;
		};

		_Promise.all = function (promises) {
			return new _Promise(function (fulfil, reject) {
				var result = [],
					pending,
					i,
					processPromise;

				if (!promises.length) {
					fulfil(result);
					return;
				}

				processPromise = function (promise, i) {
					if (promise && typeof promise.then === "function") {
						promise.then(function (value) {
							result[i] = value;
							--pending || fulfil(result);
						}, reject);
					} else {
						result[i] = promise;
						--pending || fulfil(result);
					}
				};

				pending = i = promises.length;
				while (i--) {
					processPromise(promises[i], i);
				}
			});
		};

		_Promise.resolve = function (value) {
			return new _Promise(function (fulfil) {
				fulfil(value);
			});
		};

		_Promise.reject = function (reason) {
			return new _Promise(function (fulfil, reject) {
				reject(reason);
			});
		};
	}

	var utils_Promise = _Promise;

	// TODO use MutationObservers or something to simulate setImmediate
	function wait(callback) {
		setTimeout(callback, 0);
	}

	function makeDispatcher(handlers, result) {
		return function () {
			var handler;

			while (handler = handlers.shift()) {
				handler(result);
			}
		};
	}

	function utils_Promise__resolve(promise, x, fulfil, reject) {
		// Promise Resolution Procedure
		var then;

		// 2.3.1
		if (x === promise) {
			throw new TypeError("A promise's fulfillment handler cannot return the same promise");
		}

		// 2.3.2
		if (x instanceof _Promise) {
			x.then(fulfil, reject);
		}

			// 2.3.3
		else if (x && (typeof x === "object" || typeof x === "function")) {
			try {
				then = x.then; // 2.3.3.1
			} catch (e) {
				reject(e); // 2.3.3.2
				return;
			}

			// 2.3.3.3
			if (typeof then === "function") {
				var called, resolvePromise, rejectPromise;

				resolvePromise = function (y) {
					if (called) {
						return;
					}
					called = true;
					utils_Promise__resolve(promise, y, fulfil, reject);
				};

				rejectPromise = function (r) {
					if (called) {
						return;
					}
					called = true;
					reject(r);
				};

				try {
					then.call(x, resolvePromise, rejectPromise);
				} catch (e) {
					if (!called) {
						// 2.3.3.3.4.1
						reject(e); // 2.3.3.3.4.2
						called = true;
						return;
					}
				}
			} else {
				fulfil(x);
			}
		} else {
			fulfil(x);
		}
	}

	var getInnerContext = function (fragment) {
		do {
			if (fragment.context !== undefined) {
				return fragment.context;
			}
		} while (fragment = fragment.parent);

		return rootKeypath;
	};

	var shared_resolveRef = resolveRef;

	function resolveRef(ractive, ref, fragment) {
		var keypath;

		ref = normalise(ref);

		// If a reference begins '~/', it's a top-level reference
		if (ref.substr(0, 2) === "~/") {
			keypath = getKeypath(ref.substring(2));
			createMappingIfNecessary(ractive, keypath.firstKey, fragment);
		}

			// If a reference begins with '.', it's either a restricted reference or
			// an ancestor reference...
		else if (ref[0] === ".") {
			keypath = resolveAncestorRef(getInnerContext(fragment), ref);

			if (keypath) {
				createMappingIfNecessary(ractive, keypath.firstKey, fragment);
			}
		}

			// ...otherwise we need to figure out the keypath based on context
		else {
			keypath = resolveAmbiguousReference(ractive, getKeypath(ref), fragment);
		}

		return keypath;
	}

	function resolveAncestorRef(baseContext, ref) {
		var contextKeys;

		// TODO...
		if (baseContext != undefined && typeof baseContext !== "string") {
			baseContext = baseContext.str;
		}

		// {{.}} means 'current context'
		if (ref === ".") return getKeypath(baseContext);

		contextKeys = baseContext ? baseContext.split(".") : [];

		// ancestor references (starting "../") go up the tree
		if (ref.substr(0, 3) === "../") {
			while (ref.substr(0, 3) === "../") {
				if (!contextKeys.length) {
					throw new Error("Could not resolve reference - too many \"../\" prefixes");
				}

				contextKeys.pop();
				ref = ref.substring(3);
			}

			contextKeys.push(ref);
			return getKeypath(contextKeys.join("."));
		}

		// not an ancestor reference - must be a restricted reference (prepended with "." or "./")
		if (!baseContext) {
			return getKeypath(ref.replace(/^\.\/?/, ""));
		}

		return getKeypath(baseContext + ref.replace(/^\.\//, "."));
	}

	function resolveAmbiguousReference(ractive, ref, fragment, isParentLookup) {
		var context, key, parentValue, hasContextChain, parentKeypath;

		if (ref.isRoot) {
			return ref;
		}

		key = ref.firstKey;

		while (fragment) {
			context = fragment.context;
			fragment = fragment.parent;

			if (!context) {
				continue;
			}

			hasContextChain = true;
			parentValue = ractive.viewmodel.get(context);

			if (parentValue && (typeof parentValue === "object" || typeof parentValue === "function") && key in parentValue) {
				return context.join(ref.str);
			}
		}

		// Root/computed/mapped property?
		if (isRootProperty(ractive.viewmodel, key)) {
			return ref;
		}

		// If this is an inline component, and it's not isolated, we
		// can try going up the scope chain
		if (ractive.parent && !ractive.isolated) {
			hasContextChain = true;
			fragment = ractive.component.parentFragment;

			key = getKeypath(key);

			if (parentKeypath = resolveAmbiguousReference(ractive.parent, key, fragment, true)) {
				// We need to create an inter-component binding
				ractive.viewmodel.map(key, {
					origin: ractive.parent.viewmodel,
					keypath: parentKeypath
				});

				return ref;
			}
		}

		// If there's no context chain, and the instance is either a) isolated or
		// b) an orphan, then we know that the keypath is identical to the reference
		if (!isParentLookup && !hasContextChain) {
			// the data object needs to have a property by this name,
			// to prevent future failed lookups
			ractive.viewmodel.set(ref, undefined);
			return ref;
		}
	}

	function createMappingIfNecessary(ractive, key) {
		var parentKeypath;

		if (!ractive.parent || ractive.isolated || isRootProperty(ractive.viewmodel, key)) {
			return;
		}

		key = getKeypath(key);

		if (parentKeypath = resolveAmbiguousReference(ractive.parent, key, ractive.component.parentFragment, true)) {
			ractive.viewmodel.map(key, {
				origin: ractive.parent.viewmodel,
				keypath: parentKeypath
			});
		}
	}

	function isRootProperty(viewmodel, key) {
		// special case for reference to root
		return key === "" || key in viewmodel.data || key in viewmodel.computations || key in viewmodel.mappings;
	}

	function teardown(x) {
		x.teardown();
	}

	function methodCallers__unbind(x) {
		x.unbind();
	}

	function methodCallers__unrender(x) {
		x.unrender();
	}

	function cancel(x) {
		x.cancel();
	}

	var TransitionManager = function (callback, parent) {
		this.callback = callback;
		this.parent = parent;

		this.intros = [];
		this.outros = [];

		this.children = [];
		this.totalChildren = this.outroChildren = 0;

		this.detachQueue = [];
		this.decoratorQueue = [];
		this.outrosComplete = false;

		if (parent) {
			parent.addChild(this);
		}
	};

	TransitionManager.prototype = {
		addChild: function (child) {
			this.children.push(child);

			this.totalChildren += 1;
			this.outroChildren += 1;
		},

		decrementOutros: function () {
			this.outroChildren -= 1;
			check(this);
		},

		decrementTotal: function () {
			this.totalChildren -= 1;
			check(this);
		},

		add: function (transition) {
			var list = transition.isIntro ? this.intros : this.outros;
			list.push(transition);
		},

		addDecorator: function (decorator) {
			this.decoratorQueue.push(decorator);
		},

		remove: function (transition) {
			var list = transition.isIntro ? this.intros : this.outros;
			removeFromArray(list, transition);
			check(this);
		},

		init: function () {
			this.ready = true;
			check(this);
		},

		detachNodes: function () {
			this.decoratorQueue.forEach(teardown);
			this.detachQueue.forEach(detach);
			this.children.forEach(detachNodes);
		}
	};

	function detach(element) {
		element.detach();
	}

	function detachNodes(tm) {
		tm.detachNodes();
	}

	function check(tm) {
		if (!tm.ready || tm.outros.length || tm.outroChildren) return;

		// If all outros are complete, and we haven't already done this,
		// we notify the parent if there is one, otherwise
		// start detaching nodes
		if (!tm.outrosComplete) {
			if (tm.parent) {
				tm.parent.decrementOutros(tm);
			} else {
				tm.detachNodes();
			}

			tm.outrosComplete = true;
		}

		// Once everything is done, we can notify parent transition
		// manager and call the callback
		if (!tm.intros.length && !tm.totalChildren) {
			if (typeof tm.callback === "function") {
				tm.callback();
			}

			if (tm.parent) {
				tm.parent.decrementTotal();
			}
		}
	}

	var global_TransitionManager = TransitionManager;

	var batch,
		runloop,
		unresolved = [],
		changeHook = new hooks_Hook("change");

	runloop = {
		start: function (instance, returnPromise) {
			var promise, fulfilPromise;

			if (returnPromise) {
				promise = new utils_Promise(function (f) {
					return fulfilPromise = f;
				});
			}

			batch = {
				previousBatch: batch,
				transitionManager: new global_TransitionManager(fulfilPromise, batch && batch.transitionManager),
				views: [],
				tasks: [],
				ractives: [],
				instance: instance
			};

			if (instance) {
				batch.ractives.push(instance);
			}

			return promise;
		},

		end: function () {
			flushChanges();

			batch.transitionManager.init();
			if (!batch.previousBatch && !!batch.instance) batch.instance.viewmodel.changes = [];
			batch = batch.previousBatch;
		},

		addRactive: function (ractive) {
			if (batch) {
				addToArray(batch.ractives, ractive);
			}
		},

		registerTransition: function (transition) {
			transition._manager = batch.transitionManager;
			batch.transitionManager.add(transition);
		},

		registerDecorator: function (decorator) {
			batch.transitionManager.addDecorator(decorator);
		},

		addView: function (view) {
			batch.views.push(view);
		},

		addUnresolved: function (thing) {
			unresolved.push(thing);
		},

		removeUnresolved: function (thing) {
			removeFromArray(unresolved, thing);
		},

		// synchronise node detachments with transition ends
		detachWhenReady: function (thing) {
			batch.transitionManager.detachQueue.push(thing);
		},

		scheduleTask: function (task, postRender) {
			var _batch;

			if (!batch) {
				task();
			} else {
				_batch = batch;
				while (postRender && _batch.previousBatch) {
					// this can't happen until the DOM has been fully updated
					// otherwise in some situations (with components inside elements)
					// transitions and decorators will initialise prematurely
					_batch = _batch.previousBatch;
				}

				_batch.tasks.push(task);
			}
		}
	};

	var global_runloop = runloop;

	function flushChanges() {
		var i, thing, changeHash;

		while (batch.ractives.length) {
			thing = batch.ractives.pop();
			changeHash = thing.viewmodel.applyChanges();

			if (changeHash) {
				changeHook.fire(thing, changeHash);
			}
		}

		attemptKeypathResolution();

		// Now that changes have been fully propagated, we can update the DOM
		// and complete other tasks
		for (i = 0; i < batch.views.length; i += 1) {
			batch.views[i].update();
		}
		batch.views.length = 0;

		for (i = 0; i < batch.tasks.length; i += 1) {
			batch.tasks[i]();
		}
		batch.tasks.length = 0;

		// If updating the view caused some model blowback - e.g. a triple
		// containing <option> elements caused the binding on the <select>
		// to update - then we start over
		if (batch.ractives.length) return flushChanges();
	}

	function attemptKeypathResolution() {
		var i, item, keypath, resolved;

		i = unresolved.length;

		// see if we can resolve any unresolved references
		while (i--) {
			item = unresolved[i];

			if (item.keypath) {
				// it resolved some other way. TODO how? two-way binding? Seems
				// weird that we'd still end up here
				unresolved.splice(i, 1);
				continue; // avoid removing the wrong thing should the next condition be true
			}

			if (keypath = shared_resolveRef(item.root, item.ref, item.parentFragment)) {
				(resolved || (resolved = [])).push({
					item: item,
					keypath: keypath
				});

				unresolved.splice(i, 1);
			}
		}

		if (resolved) {
			resolved.forEach(global_runloop__resolve);
		}
	}

	function global_runloop__resolve(resolved) {
		resolved.item.resolve(resolved.keypath);
	}

	var queue = [];

	var animations = {
		tick: function () {
			var i, animation, now;

			now = utils_getTime();

			global_runloop.start();

			for (i = 0; i < queue.length; i += 1) {
				animation = queue[i];

				if (!animation.tick(now)) {
					// animation is complete, remove it from the stack, and decrement i so we don't miss one
					queue.splice(i--, 1);
				}
			}

			global_runloop.end();

			if (queue.length) {
				rAF(animations.tick);
			} else {
				animations.running = false;
			}
		},

		add: function (animation) {
			queue.push(animation);

			if (!animations.running) {
				animations.running = true;
				rAF(animations.tick);
			}
		},

		// TODO optimise this
		abort: function (keypath, root) {
			var i = queue.length,
				animation;

			while (i--) {
				animation = queue[i];

				if (animation.root === root && animation.keypath === keypath) {
					animation.stop();
				}
			}
		}
	};

	var shared_animations = animations;

	var Animation = function (options) {
		var key;

		this.startTime = Date.now();

		// from and to
		for (key in options) {
			if (options.hasOwnProperty(key)) {
				this[key] = options[key];
			}
		}

		this.interpolator = shared_interpolate(this.from, this.to, this.root, this.interpolator);
		this.running = true;

		this.tick();
	};

	Animation.prototype = {
		tick: function () {
			var elapsed, t, value, timeNow, index, keypath;

			keypath = this.keypath;

			if (this.running) {
				timeNow = Date.now();
				elapsed = timeNow - this.startTime;

				if (elapsed >= this.duration) {
					if (keypath !== null) {
						global_runloop.start(this.root);
						this.root.viewmodel.set(keypath, this.to);
						global_runloop.end();
					}

					if (this.step) {
						this.step(1, this.to);
					}

					this.complete(this.to);

					index = this.root._animations.indexOf(this);

					// TODO investigate why this happens
					if (index === -1) {
						warnIfDebug("Animation was not found");
					}

					this.root._animations.splice(index, 1);

					this.running = false;
					return false; // remove from the stack
				}

				t = this.easing ? this.easing(elapsed / this.duration) : elapsed / this.duration;

				if (keypath !== null) {
					value = this.interpolator(t);
					global_runloop.start(this.root);
					this.root.viewmodel.set(keypath, value);
					global_runloop.end();
				}

				if (this.step) {
					this.step(t, value);
				}

				return true; // keep in the stack
			}

			return false; // remove from the stack
		},

		stop: function () {
			var index;

			this.running = false;

			index = this.root._animations.indexOf(this);

			// TODO investigate why this happens
			if (index === -1) {
				warnIfDebug("Animation was not found");
			}

			this.root._animations.splice(index, 1);
		}
	};

	var animate_Animation = Animation;

	var prototype_animate = Ractive$animate;

	var noAnimation = { stop: noop };
	function Ractive$animate(keypath, to, options) {
		var promise, fulfilPromise, k, animation, animations, easing, duration, step, complete, makeValueCollector, currentValues, collectValue, dummy, dummyOptions;

		promise = new utils_Promise(function (fulfil) {
			return fulfilPromise = fulfil;
		});

		// animate multiple keypaths
		if (typeof keypath === "object") {
			options = to || {};
			easing = options.easing;
			duration = options.duration;

			animations = [];

			// we don't want to pass the `step` and `complete` handlers, as they will
			// run for each animation! So instead we'll store the handlers and create
			// our own...
			step = options.step;
			complete = options.complete;

			if (step || complete) {
				currentValues = {};

				options.step = null;
				options.complete = null;

				makeValueCollector = function (keypath) {
					return function (t, value) {
						currentValues[keypath] = value;
					};
				};
			}

			for (k in keypath) {
				if (keypath.hasOwnProperty(k)) {
					if (step || complete) {
						collectValue = makeValueCollector(k);
						options = { easing: easing, duration: duration };

						if (step) {
							options.step = collectValue;
						}
					}

					options.complete = complete ? collectValue : noop;
					animations.push(animate(this, k, keypath[k], options));
				}
			}

			// Create a dummy animation, to facilitate step/complete
			// callbacks, and Promise fulfilment
			dummyOptions = { easing: easing, duration: duration };

			if (step) {
				dummyOptions.step = function (t) {
					return step(t, currentValues);
				};
			}

			if (complete) {
				promise.then(function (t) {
					return complete(t, currentValues);
				});
			}

			dummyOptions.complete = fulfilPromise;

			dummy = animate(this, null, null, dummyOptions);
			animations.push(dummy);

			promise.stop = function () {
				var animation;

				while (animation = animations.pop()) {
					animation.stop();
				}

				if (dummy) {
					dummy.stop();
				}
			};

			return promise;
		}

		// animate a single keypath
		options = options || {};

		if (options.complete) {
			promise.then(options.complete);
		}

		options.complete = fulfilPromise;
		animation = animate(this, keypath, to, options);

		promise.stop = function () {
			return animation.stop();
		};
		return promise;
	}

	function animate(root, keypath, to, options) {
		var easing, duration, animation, from;

		if (keypath) {
			keypath = getKeypath(normalise(keypath));
		}

		if (keypath !== null) {
			from = root.viewmodel.get(keypath);
		}

		// cancel any existing animation
		// TODO what about upstream/downstream keypaths?
		shared_animations.abort(keypath, root);

		// don't bother animating values that stay the same
		if (isEqual(from, to)) {
			if (options.complete) {
				options.complete(options.to);
			}

			return noAnimation;
		}

		// easing function
		if (options.easing) {
			if (typeof options.easing === "function") {
				easing = options.easing;
			} else {
				easing = root.easing[options.easing];
			}

			if (typeof easing !== "function") {
				easing = null;
			}
		}

		// duration
		duration = options.duration === undefined ? 400 : options.duration;

		// TODO store keys, use an internal set method
		animation = new animate_Animation({
			keypath: keypath,
			from: from,
			to: to,
			root: root,
			duration: duration,
			easing: easing,
			interpolator: options.interpolator,

			// TODO wrap callbacks if necessary, to use instance as context
			step: options.step,
			complete: options.complete
		});

		shared_animations.add(animation);
		root._animations.push(animation);

		return animation;
	}

	var prototype_detach = Ractive$detach;
	var prototype_detach__detachHook = new hooks_Hook("detach");
	function Ractive$detach() {
		if (this.detached) {
			return this.detached;
		}

		if (this.el) {
			removeFromArray(this.el.__ractive_instances__, this);
		}
		this.detached = this.fragment.detach();
		prototype_detach__detachHook.fire(this);
		return this.detached;
	}

	var prototype_find = Ractive$find;

	function Ractive$find(selector) {
		if (!this.el) {
			return null;
		}

		return this.fragment.find(selector);
	}

	var test = Query$test;
	function Query$test(item, noDirty) {
		var itemMatches;

		if (this._isComponentQuery) {
			itemMatches = !this.selector || item.name === this.selector;
		} else {
			itemMatches = item.node ? matches(item.node, this.selector) : null;
		}

		if (itemMatches) {
			this.push(item.node || item.instance);

			if (!noDirty) {
				this._makeDirty();
			}

			return true;
		}
	}

	var makeQuery_cancel = function () {
		var liveQueries, selector, index;

		liveQueries = this._root[this._isComponentQuery ? "liveComponentQueries" : "liveQueries"];
		selector = this.selector;

		index = liveQueries.indexOf(selector);

		if (index !== -1) {
			liveQueries.splice(index, 1);
			liveQueries[selector] = null;
		}
	};

	var sortByItemPosition = function (a, b) {
		var ancestryA, ancestryB, oldestA, oldestB, mutualAncestor, indexA, indexB, fragments, fragmentA, fragmentB;

		ancestryA = getAncestry(a.component || a._ractive.proxy);
		ancestryB = getAncestry(b.component || b._ractive.proxy);

		oldestA = lastItem(ancestryA);
		oldestB = lastItem(ancestryB);

		// remove items from the end of both ancestries as long as they are identical
		// - the final one removed is the closest mutual ancestor
		while (oldestA && oldestA === oldestB) {
			ancestryA.pop();
			ancestryB.pop();

			mutualAncestor = oldestA;

			oldestA = lastItem(ancestryA);
			oldestB = lastItem(ancestryB);
		}

		// now that we have the mutual ancestor, we can find which is earliest
		oldestA = oldestA.component || oldestA;
		oldestB = oldestB.component || oldestB;

		fragmentA = oldestA.parentFragment;
		fragmentB = oldestB.parentFragment;

		// if both items share a parent fragment, our job is easy
		if (fragmentA === fragmentB) {
			indexA = fragmentA.items.indexOf(oldestA);
			indexB = fragmentB.items.indexOf(oldestB);

			// if it's the same index, it means one contains the other,
			// so we see which has the longest ancestry
			return indexA - indexB || ancestryA.length - ancestryB.length;
		}

		// if mutual ancestor is a section, we first test to see which section
		// fragment comes first
		if (fragments = mutualAncestor.fragments) {
			indexA = fragments.indexOf(fragmentA);
			indexB = fragments.indexOf(fragmentB);

			return indexA - indexB || ancestryA.length - ancestryB.length;
		}

		throw new Error("An unexpected condition was met while comparing the position of two components. Please file an issue at https://github.com/RactiveJS/Ractive/issues - thanks!");
	};

	function getParent(item) {
		var parentFragment;

		if (parentFragment = item.parentFragment) {
			return parentFragment.owner;
		}

		if (item.component && (parentFragment = item.component.parentFragment)) {
			return parentFragment.owner;
		}
	}

	function getAncestry(item) {
		var ancestry, ancestor;

		ancestry = [item];

		ancestor = getParent(item);

		while (ancestor) {
			ancestry.push(ancestor);
			ancestor = getParent(ancestor);
		}

		return ancestry;
	}

	var sortByDocumentPosition = function (node, otherNode) {
		var bitmask;

		if (node.compareDocumentPosition) {
			bitmask = node.compareDocumentPosition(otherNode);
			return bitmask & 2 ? 1 : -1;
		}

		// In old IE, we can piggy back on the mechanism for
		// comparing component positions
		return sortByItemPosition(node, otherNode);
	};

	var sort = function () {
		this.sort(this._isComponentQuery ? sortByItemPosition : sortByDocumentPosition);
		this._dirty = false;
	};

	var makeQuery_dirty = function () {
		var _this = this;

		if (!this._dirty) {
			this._dirty = true;

			// Once the DOM has been updated, ensure the query
			// is correctly ordered
			global_runloop.scheduleTask(function () {
				_this._sort();
			});
		}
	};

	var remove = function (nodeOrComponent) {
		var index = this.indexOf(this._isComponentQuery ? nodeOrComponent.instance : nodeOrComponent);

		if (index !== -1) {
			this.splice(index, 1);
		}
	};

	var _makeQuery = makeQuery;
	function makeQuery(ractive, selector, live, isComponentQuery) {
		var query = [];

		defineProperties(query, {
			selector: { value: selector },
			live: { value: live },

			_isComponentQuery: { value: isComponentQuery },
			_test: { value: test }
		});

		if (!live) {
			return query;
		}

		defineProperties(query, {
			cancel: { value: makeQuery_cancel },

			_root: { value: ractive },
			_sort: { value: sort },
			_makeDirty: { value: makeQuery_dirty },
			_remove: { value: remove },

			_dirty: { value: false, writable: true }
		});

		return query;
	}

	var prototype_findAll = Ractive$findAll;
	function Ractive$findAll(selector, options) {
		var liveQueries, query;

		if (!this.el) {
			return [];
		}

		options = options || {};
		liveQueries = this._liveQueries;

		// Shortcut: if we're maintaining a live query with this
		// selector, we don't need to traverse the parallel DOM
		if (query = liveQueries[selector]) {

			// Either return the exact same query, or (if not live) a snapshot
			return options && options.live ? query : query.slice();
		}

		query = _makeQuery(this, selector, !!options.live, false);

		// Add this to the list of live queries Ractive needs to maintain,
		// if applicable
		if (query.live) {
			liveQueries.push(selector);
			liveQueries["_" + selector] = query;
		}

		this.fragment.findAll(selector, query);
		return query;
	}

	var prototype_findAllComponents = Ractive$findAllComponents;
	function Ractive$findAllComponents(selector, options) {
		var liveQueries, query;

		options = options || {};
		liveQueries = this._liveComponentQueries;

		// Shortcut: if we're maintaining a live query with this
		// selector, we don't need to traverse the parallel DOM
		if (query = liveQueries[selector]) {

			// Either return the exact same query, or (if not live) a snapshot
			return options && options.live ? query : query.slice();
		}

		query = _makeQuery(this, selector, !!options.live, true);

		// Add this to the list of live queries Ractive needs to maintain,
		// if applicable
		if (query.live) {
			liveQueries.push(selector);
			liveQueries["_" + selector] = query;
		}

		this.fragment.findAllComponents(selector, query);
		return query;
	}

	var prototype_findComponent = Ractive$findComponent;

	function Ractive$findComponent(selector) {
		return this.fragment.findComponent(selector);
	}

	var findContainer = Ractive$findContainer;

	function Ractive$findContainer(selector) {
		if (this.container) {
			if (this.container.component && this.container.component.name === selector) {
				return this.container;
			} else {
				return this.container.findContainer(selector);
			}
		}

		return null;
	}

	var findParent = Ractive$findParent;

	function Ractive$findParent(selector) {

		if (this.parent) {
			if (this.parent.component && this.parent.component.name === selector) {
				return this.parent;
			} else {
				return this.parent.findParent(selector);
			}
		}

		return null;
	}

	var eventStack = {
		enqueue: function (ractive, event) {
			if (ractive.event) {
				ractive._eventQueue = ractive._eventQueue || [];
				ractive._eventQueue.push(ractive.event);
			}
			ractive.event = event;
		},
		dequeue: function (ractive) {
			if (ractive._eventQueue && ractive._eventQueue.length) {
				ractive.event = ractive._eventQueue.pop();
			} else {
				delete ractive.event;
			}
		}
	};

	var shared_eventStack = eventStack;

	var shared_fireEvent = fireEvent;

	function fireEvent(ractive, eventName) {
		var options = arguments[2] === undefined ? {} : arguments[2];

		if (!eventName) {
			return;
		}

		if (!options.event) {
			options.event = {
				name: eventName,
				// until event not included as argument default
				_noArg: true
			};
		} else {
			options.event.name = eventName;
		}

		var eventNames = getKeypath(eventName).wildcardMatches();
		fireEventAs(ractive, eventNames, options.event, options.args, true);
	}

	function fireEventAs(ractive, eventNames, event, args) {
		var initialFire = arguments[4] === undefined ? false : arguments[4];

		var subscribers,
			i,
			bubble = true;

		shared_eventStack.enqueue(ractive, event);

		for (i = eventNames.length; i >= 0; i--) {
			subscribers = ractive._subs[eventNames[i]];

			if (subscribers) {
				bubble = notifySubscribers(ractive, subscribers, event, args) && bubble;
			}
		}

		shared_eventStack.dequeue(ractive);

		if (ractive.parent && bubble) {

			if (initialFire && ractive.component) {
				var fullName = ractive.component.name + "." + eventNames[eventNames.length - 1];
				eventNames = getKeypath(fullName).wildcardMatches();

				if (event) {
					event.component = ractive;
				}
			}

			fireEventAs(ractive.parent, eventNames, event, args);
		}
	}

	function notifySubscribers(ractive, subscribers, event, args) {
		var originalEvent = null,
			stopEvent = false;

		if (event && !event._noArg) {
			args = [event].concat(args);
		}

		// subscribers can be modified inflight, e.g. "once" functionality
		// so we need to copy to make sure everyone gets called
		subscribers = subscribers.slice();

		for (var i = 0, len = subscribers.length; i < len; i += 1) {
			if (subscribers[i].apply(ractive, args) === false) {
				stopEvent = true;
			}
		}

		if (event && !event._noArg && stopEvent && (originalEvent = event.original)) {
			originalEvent.preventDefault && originalEvent.preventDefault();
			originalEvent.stopPropagation && originalEvent.stopPropagation();
		}

		return !stopEvent;
	}

	var prototype_fire = Ractive$fire;
	function Ractive$fire(eventName) {

		var options = {
			args: Array.prototype.slice.call(arguments, 1)
		};

		shared_fireEvent(this, eventName, options);
	}

	var prototype_get = Ractive$get;
	var options = {
		capture: true, // top-level calls should be intercepted
		noUnwrap: true, // wrapped values should NOT be unwrapped
		fullRootGet: true // root get should return mappings
	};
	function Ractive$get(keypath) {
		var value;

		keypath = getKeypath(normalise(keypath));
		value = this.viewmodel.get(keypath, options);

		// Create inter-component binding, if necessary
		if (value === undefined && this.parent && !this.isolated) {
			if (shared_resolveRef(this, keypath.str, this.component.parentFragment)) {
				// creates binding as side-effect, if appropriate
				value = this.viewmodel.get(keypath);
			}
		}

		return value;
	}

	var insert = Ractive$insert;

	var insertHook = new hooks_Hook("insert");
	function Ractive$insert(target, anchor) {
		if (!this.fragment.rendered) {
			// TODO create, and link to, documentation explaining this
			throw new Error("The API has changed - you must call `ractive.render(target[, anchor])` to render your Ractive instance. Once rendered you can use `ractive.insert()`.");
		}

		target = getElement(target);
		anchor = getElement(anchor) || null;

		if (!target) {
			throw new Error("You must specify a valid target to insert into");
		}

		target.insertBefore(this.detach(), anchor);
		this.el = target;

		(target.__ractive_instances__ || (target.__ractive_instances__ = [])).push(this);
		this.detached = null;

		fireInsertHook(this);
	}

	function fireInsertHook(ractive) {
		insertHook.fire(ractive);

		ractive.findAllComponents("*").forEach(function (child) {
			fireInsertHook(child.instance);
		});
	}

	var prototype_merge = Ractive$merge;
	function Ractive$merge(keypath, array, options) {
		var currentArray, promise;

		keypath = getKeypath(normalise(keypath));
		currentArray = this.viewmodel.get(keypath);

		// If either the existing value or the new value isn't an
		// array, just do a regular set
		if (!isArray(currentArray) || !isArray(array)) {
			return this.set(keypath, array, options && options.complete);
		}

		// Manage transitions
		promise = global_runloop.start(this, true);
		this.viewmodel.merge(keypath, currentArray, array, options);
		global_runloop.end();

		return promise;
	}

	var Observer = function (ractive, keypath, callback, options) {
		this.root = ractive;
		this.keypath = keypath;
		this.callback = callback;
		this.defer = options.defer;

		// default to root as context, but allow it to be overridden
		this.context = options && options.context ? options.context : ractive;
	};

	Observer.prototype = {
		init: function (immediate) {
			this.value = this.root.get(this.keypath.str);

			if (immediate !== false) {
				this.update();
			} else {
				this.oldValue = this.value;
			}
		},

		setValue: function (value) {
			var _this = this;

			if (!isEqual(value, this.value)) {
				this.value = value;

				if (this.defer && this.ready) {
					global_runloop.scheduleTask(function () {
						return _this.update();
					});
				} else {
					this.update();
				}
			}
		},

		update: function () {
			// Prevent infinite loops
			if (this.updating) {
				return;
			}

			this.updating = true;

			this.callback.call(this.context, this.value, this.oldValue, this.keypath.str);
			this.oldValue = this.value;

			this.updating = false;
		}
	};

	var observe_Observer = Observer;

	var observe_getPattern = getPattern;
	function getPattern(ractive, pattern) {
		var matchingKeypaths, values;

		matchingKeypaths = getMatchingKeypaths(ractive, pattern);

		values = {};
		matchingKeypaths.forEach(function (keypath) {
			values[keypath.str] = ractive.get(keypath.str);
		});

		return values;
	}

	var PatternObserver,
		slice = Array.prototype.slice;

	PatternObserver = function (ractive, keypath, callback, options) {
		this.root = ractive;

		this.callback = callback;
		this.defer = options.defer;

		this.keypath = keypath;
		this.regex = new RegExp("^" + keypath.str.replace(/\./g, "\\.").replace(/\*/g, "([^\\.]+)") + "$");
		this.values = {};

		if (this.defer) {
			this.proxies = [];
		}

		// default to root as context, but allow it to be overridden
		this.context = options && options.context ? options.context : ractive;
	};

	PatternObserver.prototype = {
		init: function (immediate) {
			var values, keypath;

			values = observe_getPattern(this.root, this.keypath);

			if (immediate !== false) {
				for (keypath in values) {
					if (values.hasOwnProperty(keypath)) {
						this.update(getKeypath(keypath));
					}
				}
			} else {
				this.values = values;
			}
		},

		update: function (keypath) {
			var _this = this;

			var values;

			if (keypath.isPattern) {
				values = observe_getPattern(this.root, keypath);

				for (keypath in values) {
					if (values.hasOwnProperty(keypath)) {
						this.update(getKeypath(keypath));
					}
				}

				return;
			}

			// special case - array mutation should not trigger `array.*`
			// pattern observer with `array.length`
			if (this.root.viewmodel.implicitChanges[keypath.str]) {
				return;
			}

			if (this.defer && this.ready) {
				global_runloop.scheduleTask(function () {
					return _this.getProxy(keypath).update();
				});
				return;
			}

			this.reallyUpdate(keypath);
		},

		reallyUpdate: function (keypath) {
			var keypathStr, value, keys, args;

			keypathStr = keypath.str;
			value = this.root.viewmodel.get(keypath);

			// Prevent infinite loops
			if (this.updating) {
				this.values[keypathStr] = value;
				return;
			}

			this.updating = true;

			if (!isEqual(value, this.values[keypathStr]) || !this.ready) {
				keys = slice.call(this.regex.exec(keypathStr), 1);
				args = [value, this.values[keypathStr], keypathStr].concat(keys);

				this.values[keypathStr] = value;
				this.callback.apply(this.context, args);
			}

			this.updating = false;
		},

		getProxy: function (keypath) {
			var _this = this;

			if (!this.proxies[keypath.str]) {
				this.proxies[keypath.str] = {
					update: function () {
						return _this.reallyUpdate(keypath);
					}
				};
			}

			return this.proxies[keypath.str];
		}
	};

	var observe_PatternObserver = PatternObserver;

	var observe_getObserverFacade = getObserverFacade;
	var emptyObject = {};
	function getObserverFacade(ractive, keypath, callback, options) {
		var observer, isPatternObserver, cancelled;

		keypath = getKeypath(normalise(keypath));
		options = options || emptyObject;

		// pattern observers are treated differently
		if (keypath.isPattern) {
			observer = new observe_PatternObserver(ractive, keypath, callback, options);
			ractive.viewmodel.patternObservers.push(observer);
			isPatternObserver = true;
		} else {
			observer = new observe_Observer(ractive, keypath, callback, options);
		}

		observer.init(options.init);
		ractive.viewmodel.register(keypath, observer, isPatternObserver ? "patternObservers" : "observers");

		// This flag allows observers to initialise even with undefined values
		observer.ready = true;

		var facade = {
			cancel: function () {
				var index;

				if (cancelled) {
					return;
				}

				if (isPatternObserver) {
					index = ractive.viewmodel.patternObservers.indexOf(observer);

					ractive.viewmodel.patternObservers.splice(index, 1);
					ractive.viewmodel.unregister(keypath, observer, "patternObservers");
				} else {
					ractive.viewmodel.unregister(keypath, observer, "observers");
				}
				cancelled = true;
			}
		};

		ractive._observers.push(facade);
		return facade;
	}

	var observe = Ractive$observe;
	function Ractive$observe(keypath, callback, options) {

		var observers, map, keypaths, i;

		// Allow a map of keypaths to handlers
		if (isObject(keypath)) {
			options = callback;
			map = keypath;

			observers = [];

			for (keypath in map) {
				if (map.hasOwnProperty(keypath)) {
					callback = map[keypath];
					observers.push(this.observe(keypath, callback, options));
				}
			}

			return {
				cancel: function () {
					while (observers.length) {
						observers.pop().cancel();
					}
				}
			};
		}

		// Allow `ractive.observe( callback )` - i.e. observe entire model
		if (typeof keypath === "function") {
			options = callback;
			callback = keypath;
			keypath = "";

			return observe_getObserverFacade(this, keypath, callback, options);
		}

		keypaths = keypath.split(" ");

		// Single keypath
		if (keypaths.length === 1) {
			return observe_getObserverFacade(this, keypath, callback, options);
		}

		// Multiple space-separated keypaths
		observers = [];

		i = keypaths.length;
		while (i--) {
			keypath = keypaths[i];

			if (keypath) {
				observers.push(observe_getObserverFacade(this, keypath, callback, options));
			}
		}

		return {
			cancel: function () {
				while (observers.length) {
					observers.pop().cancel();
				}
			}
		};
	}

	var observeOnce = Ractive$observeOnce;

	function Ractive$observeOnce(property, callback, options) {

		var observer = this.observe(property, function () {
			callback.apply(this, arguments);
			observer.cancel();
		}, { init: false, defer: options && options.defer });

		return observer;
	}

	var shared_trim = function (str) {
		return str.trim();
	};

	var notEmptyString = function (str) {
		return str !== "";
	};

	var off = Ractive$off;
	function Ractive$off(eventName, callback) {
		var _this = this;

		var eventNames;

		// if no arguments specified, remove all callbacks
		if (!eventName) {
			// TODO use this code instead, once the following issue has been resolved
			// in PhantomJS (tests are unpassable otherwise!)
			// https://github.com/ariya/phantomjs/issues/11856
			// defineProperty( this, '_subs', { value: create( null ), configurable: true });
			for (eventName in this._subs) {
				delete this._subs[eventName];
			}
		} else {
			// Handle multiple space-separated event names
			eventNames = eventName.split(" ").map(shared_trim).filter(notEmptyString);

			eventNames.forEach(function (eventName) {
				var subscribers, index;

				// If we have subscribers for this event...
				if (subscribers = _this._subs[eventName]) {
					// ...if a callback was specified, only remove that
					if (callback) {
						index = subscribers.indexOf(callback);
						if (index !== -1) {
							subscribers.splice(index, 1);
						}
					}

						// ...otherwise remove all callbacks
					else {
						_this._subs[eventName] = [];
					}
				}
			});
		}

		return this;
	}

	var on = Ractive$on;
	function Ractive$on(eventName, callback) {
		var _this = this;

		var listeners, n, eventNames;

		// allow mutliple listeners to be bound in one go
		if (typeof eventName === "object") {
			listeners = [];

			for (n in eventName) {
				if (eventName.hasOwnProperty(n)) {
					listeners.push(this.on(n, eventName[n]));
				}
			}

			return {
				cancel: function () {
					var listener;

					while (listener = listeners.pop()) {
						listener.cancel();
					}
				}
			};
		}

		// Handle multiple space-separated event names
		eventNames = eventName.split(" ").map(shared_trim).filter(notEmptyString);

		eventNames.forEach(function (eventName) {
			(_this._subs[eventName] || (_this._subs[eventName] = [])).push(callback);
		});

		return {
			cancel: function () {
				return _this.off(eventName, callback);
			}
		};
	}

	var once = Ractive$once;

	function Ractive$once(eventName, handler) {

		var listener = this.on(eventName, function () {
			handler.apply(this, arguments);
			listener.cancel();
		});

		// so we can still do listener.cancel() manually
		return listener;
	}

	// This function takes an array, the name of a mutator method, and the
	// arguments to call that mutator method with, and returns an array that
	// maps the old indices to their new indices.

	// So if you had something like this...
	//
	//     array = [ 'a', 'b', 'c', 'd' ];
	//     array.push( 'e' );
	//
	// ...you'd get `[ 0, 1, 2, 3 ]` - in other words, none of the old indices
	// have changed. If you then did this...
	//
	//     array.unshift( 'z' );
	//
	// ...the indices would be `[ 1, 2, 3, 4, 5 ]` - every item has been moved
	// one higher to make room for the 'z'. If you removed an item, the new index
	// would be -1...
	//
	//     array.splice( 2, 2 );
	//
	// ...this would result in [ 0, 1, -1, -1, 2, 3 ].
	//
	// This information is used to enable fast, non-destructive shuffling of list
	// sections when you do e.g. `ractive.splice( 'items', 2, 2 );

	var shared_getNewIndices = getNewIndices;

	function getNewIndices(array, methodName, args) {
		var spliceArguments,
			len,
			newIndices = [],
			removeStart,
			removeEnd,
			balance,
			i;

		spliceArguments = getSpliceEquivalent(array, methodName, args);

		if (!spliceArguments) {
			return null; // TODO support reverse and sort?
		}

		len = array.length;
		balance = spliceArguments.length - 2 - spliceArguments[1];

		removeStart = Math.min(len, spliceArguments[0]);
		removeEnd = removeStart + spliceArguments[1];

		for (i = 0; i < removeStart; i += 1) {
			newIndices.push(i);
		}

		for (; i < removeEnd; i += 1) {
			newIndices.push(-1);
		}

		for (; i < len; i += 1) {
			newIndices.push(i + balance);
		}

		// there is a net shift for the rest of the array starting with index + balance
		if (balance !== 0) {
			newIndices.touchedFrom = spliceArguments[0];
		} else {
			newIndices.touchedFrom = array.length;
		}

		return newIndices;
	}

	// The pop, push, shift an unshift methods can all be represented
	// as an equivalent splice
	function getSpliceEquivalent(array, methodName, args) {
		switch (methodName) {
			case "splice":
				if (args[0] !== undefined && args[0] < 0) {
					args[0] = array.length + Math.max(args[0], -array.length);
				}

				while (args.length < 2) {
					args.push(0);
				}

				// ensure we only remove elements that exist
				args[1] = Math.min(args[1], array.length - args[0]);

				return args;

			case "sort":
			case "reverse":
				return null;

			case "pop":
				if (array.length) {
					return [array.length - 1, 1];
				}
				return [0, 0];

			case "push":
				return [array.length, 0].concat(args);

			case "shift":
				return [0, array.length ? 1 : 0];

			case "unshift":
				return [0, 0].concat(args);
		}
	}

	var arrayProto = Array.prototype;

	var makeArrayMethod = function (methodName) {
		return function (keypath) {
			for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
				args[_key - 1] = arguments[_key];
			}

			var array,
				newIndices = [],
				len,
				promise,
				result;

			keypath = getKeypath(normalise(keypath));

			array = this.viewmodel.get(keypath);
			len = array.length;

			if (!isArray(array)) {
				throw new Error("Called ractive." + methodName + "('" + keypath.str + "'), but '" + keypath.str + "' does not refer to an array");
			}

			newIndices = shared_getNewIndices(array, methodName, args);

			result = arrayProto[methodName].apply(array, args);
			promise = global_runloop.start(this, true).then(function () {
				return result;
			});

			if (!!newIndices) {
				this.viewmodel.smartUpdate(keypath, array, newIndices);
			} else {
				this.viewmodel.mark(keypath);
			}

			global_runloop.end();

			return promise;
		};
	};

	var pop = makeArrayMethod("pop");

	var push = makeArrayMethod("push");

	var css,
		update,
		styleElement,
		head,
		styleSheet,
		inDom,
		global_css__prefix = "/* Ractive.js component styles */\n",
		styles = [],
		dirty = false;

	if (!isClient) {
		// TODO handle encapsulated CSS in server-rendered HTML!
		css = {
			add: noop,
			apply: noop
		};
	} else {
		styleElement = document.createElement("style");
		styleElement.type = "text/css";

		head = document.getElementsByTagName("head")[0];

		inDom = false;

		// Internet Exploder won't let you use styleSheet.innerHTML - we have to
		// use styleSheet.cssText instead
		styleSheet = styleElement.styleSheet;

		update = function () {
			var css = global_css__prefix + styles.map(function (s) {
				return "\n/* {" + s.id + "} */\n" + s.styles;
			}).join("\n");

			if (styleSheet) {
				styleSheet.cssText = css;
			} else {
				styleElement.innerHTML = css;
			}

			if (!inDom) {
				head.appendChild(styleElement);
				inDom = true;
			}
		};

		css = {
			add: function (s) {
				styles.push(s);
				dirty = true;
			},

			apply: function () {
				if (dirty) {
					update();
					dirty = false;
				}
			}
		};
	}

	var global_css = css;

	var prototype_render = Ractive$render;

	var renderHook = new hooks_Hook("render"),
		completeHook = new hooks_Hook("complete");
	function Ractive$render(target, anchor) {
		var _this = this;

		var promise, instances, transitionsEnabled;

		// if `noIntro` is `true`, temporarily disable transitions
		transitionsEnabled = this.transitionsEnabled;
		if (this.noIntro) {
			this.transitionsEnabled = false;
		}

		promise = global_runloop.start(this, true);
		global_runloop.scheduleTask(function () {
			return renderHook.fire(_this);
		}, true);

		if (this.fragment.rendered) {
			throw new Error("You cannot call ractive.render() on an already rendered instance! Call ractive.unrender() first");
		}

		target = getElement(target) || this.el;
		anchor = getElement(anchor) || this.anchor;

		this.el = target;
		this.anchor = anchor;

		if (!this.append && target) {
			// Teardown any existing instances *before* trying to set up the new one -
			// avoids certain weird bugs
			var others = target.__ractive_instances__;
			if (others && others.length) {
				removeOtherInstances(others);
			}

			// make sure we are the only occupants
			target.innerHTML = ""; // TODO is this quicker than removeChild? Initial research inconclusive
		}

		if (this.cssId) {
			// ensure encapsulated CSS is up-to-date
			global_css.apply();
		}

		if (target) {
			if (!(instances = target.__ractive_instances__)) {
				target.__ractive_instances__ = [this];
			} else {
				instances.push(this);
			}

			if (anchor) {
				target.insertBefore(this.fragment.render(), anchor);
			} else {
				target.appendChild(this.fragment.render());
			}
		}

		global_runloop.end();

		this.transitionsEnabled = transitionsEnabled;

		return promise.then(function () {
			return completeHook.fire(_this);
		});
	}

	function removeOtherInstances(others) {
		others.splice(0, others.length).forEach(teardown);
	}

	var adaptConfigurator = {
		extend: function (Parent, proto, options) {
			proto.adapt = custom_adapt__combine(proto.adapt, ensureArray(options.adapt));
		},

		init: function () { }
	};

	var custom_adapt = adaptConfigurator;

	function custom_adapt__combine(a, b) {
		var c = a.slice(),
			i = b.length;

		while (i--) {
			if (! ~c.indexOf(b[i])) {
				c.push(b[i]);
			}
		}

		return c;
	}

	var transform = transformCss;

	var selectorsPattern = /(?:^|\})?\s*([^\{\}]+)\s*\{/g,
		commentsPattern = /\/\*.*?\*\//g,
		selectorUnitPattern = /((?:(?:\[[^\]+]\])|(?:[^\s\+\>\~:]))+)((?::[^\s\+\>\~\(]+(?:\([^\)]+\))?)?\s*[\s\+\>\~]?)\s*/g,
		mediaQueryPattern = /^@media/,
		dataRvcGuidPattern = /\[data-ractive-css~="\{[a-z0-9-]+\}"]/g;
	function transformCss(css, id) {
		var transformed, dataAttr, addGuid;

		dataAttr = "[data-ractive-css~=\"{" + id + "}\"]";

		addGuid = function (selector) {
			var selectorUnits,
				match,
				unit,
				base,
				prepended,
				appended,
				i,
				transformed = [];

			selectorUnits = [];

			while (match = selectorUnitPattern.exec(selector)) {
				selectorUnits.push({
					str: match[0],
					base: match[1],
					modifiers: match[2]
				});
			}

			// For each simple selector within the selector, we need to create a version
			// that a) combines with the id, and b) is inside the id
			base = selectorUnits.map(extractString);

			i = selectorUnits.length;
			while (i--) {
				appended = base.slice();

				// Pseudo-selectors should go after the attribute selector
				unit = selectorUnits[i];
				appended[i] = unit.base + dataAttr + unit.modifiers || "";

				prepended = base.slice();
				prepended[i] = dataAttr + " " + prepended[i];

				transformed.push(appended.join(" "), prepended.join(" "));
			}

			return transformed.join(", ");
		};

		if (dataRvcGuidPattern.test(css)) {
			transformed = css.replace(dataRvcGuidPattern, dataAttr);
		} else {
			transformed = css.replace(commentsPattern, "").replace(selectorsPattern, function (match, $1) {
				var selectors, transformed;

				// don't transform media queries!
				if (mediaQueryPattern.test($1)) return match;

				selectors = $1.split(",").map(trim);
				transformed = selectors.map(addGuid).join(", ") + " ";

				return match.replace($1, transformed);
			});
		}

		return transformed;
	}

	function trim(str) {
		if (str.trim) {
			return str.trim();
		}

		return str.replace(/^\s+/, "").replace(/\s+$/, "");
	}

	function extractString(unit) {
		return unit.str;
	}

	var css_css__uid = 1;

	var cssConfigurator = {
		name: "css",

		extend: function (Parent, proto, options) {
			if (options.css) {
				var id = css_css__uid++;
				var styles = options.noCssTransform ? options.css : transform(options.css, id);

				proto.cssId = id;
				global_css.add({ id: id, styles: styles });
			}
		},

		init: function () { }
	};

	var css_css = cssConfigurator;

	function validate(data) {
		// Warn if userOptions.data is a non-POJO
		if (data && data.constructor !== Object) {
			if (typeof data === "function") { } else if (typeof data !== "object") {
				fatal("data option must be an object or a function, `" + data + "` is not valid");
			} else {
				warnIfDebug("If supplied, options.data should be a plain JavaScript object - using a non-POJO as the root object may work, but is discouraged");
			}
		}
	}

	var dataConfigurator = {
		name: "data",

		extend: function (Parent, proto, options) {
			var key = undefined,
				value = undefined;

			// check for non-primitives, which could cause mutation-related bugs
			if (options.data && isObject(options.data)) {
				for (key in options.data) {
					value = options.data[key];

					if (value && typeof value === "object") {
						if (isObject(value) || isArray(value)) {
							warnIfDebug("Passing a `data` option with object and array properties to Ractive.extend() is discouraged, as mutating them is likely to cause bugs. Consider using a data function instead:\n\n  // this...\n  data: function () {\n    return {\n      myObject: {}\n    };\n  })\n\n  // instead of this:\n  data: {\n    myObject: {}\n  }");
						}
					}
				}
			}

			proto.data = custom_data__combine(proto.data, options.data);
		},

		init: function (Parent, ractive, options) {
			var result = custom_data__combine(Parent.prototype.data, options.data);

			if (typeof result === "function") {
				result = result.call(ractive);
			}

			return result || {};
		},

		reset: function (ractive) {
			var result = this.init(ractive.constructor, ractive, ractive.viewmodel);

			ractive.viewmodel.reset(result);
			return true;
		}
	};

	var custom_data = dataConfigurator;

	function custom_data__combine(parentValue, childValue) {
		validate(childValue);

		var parentIsFn = typeof parentValue === "function";
		var childIsFn = typeof childValue === "function";

		// Very important, otherwise child instance can become
		// the default data object on Ractive or a component.
		// then ractive.set() ends up setting on the prototype!
		if (!childValue && !parentIsFn) {
			childValue = {};
		}

		// Fast path, where we just need to copy properties from
		// parent to child
		if (!parentIsFn && !childIsFn) {
			return fromProperties(childValue, parentValue);
		}

		return function () {
			var child = childIsFn ? callDataFunction(childValue, this) : childValue;
			var parent = parentIsFn ? callDataFunction(parentValue, this) : parentValue;

			return fromProperties(child, parent);
		};
	}

	function callDataFunction(fn, context) {
		var data = fn.call(context);

		if (!data) return;

		if (typeof data !== "object") {
			fatal("Data function must return an object");
		}

		if (data.constructor !== Object) {
			warnOnceIfDebug("Data function returned something other than a plain JavaScript object. This might work, but is strongly discouraged");
		}

		return data;
	}

	function fromProperties(primary, secondary) {
		if (primary && secondary) {
			for (var key in secondary) {
				if (!(key in primary)) {
					primary[key] = secondary[key];
				}
			}

			return primary;
		}

		return primary || secondary;
	}

	// TODO do we need to support this in the new Ractive() case?

	var Parser,
		ParseError,
		parse_Parser__leadingWhitespace = /^\s+/;

	ParseError = function (message) {
		this.name = "ParseError";
		this.message = message;
		try {
			throw new Error(message);
		} catch (e) {
			this.stack = e.stack;
		}
	};

	ParseError.prototype = Error.prototype;

	Parser = function (str, options) {
		var items,
			item,
			lineStart = 0;

		this.str = str;
		this.options = options || {};
		this.pos = 0;

		this.lines = this.str.split("\n");
		this.lineEnds = this.lines.map(function (line) {
			var lineEnd = lineStart + line.length + 1; // +1 for the newline

			lineStart = lineEnd;
			return lineEnd;
		}, 0);

		// Custom init logic
		if (this.init) this.init(str, options);

		items = [];

		while (this.pos < this.str.length && (item = this.read())) {
			items.push(item);
		}

		this.leftover = this.remaining();
		this.result = this.postProcess ? this.postProcess(items, options) : items;
	};

	Parser.prototype = {
		read: function (converters) {
			var pos, i, len, item;

			if (!converters) converters = this.converters;

			pos = this.pos;

			len = converters.length;
			for (i = 0; i < len; i += 1) {
				this.pos = pos; // reset for each attempt

				if (item = converters[i](this)) {
					return item;
				}
			}

			return null;
		},

		getLinePos: function (char) {
			var lineNum = 0,
				lineStart = 0,
				columnNum;

			while (char >= this.lineEnds[lineNum]) {
				lineStart = this.lineEnds[lineNum];
				lineNum += 1;
			}

			columnNum = char - lineStart;
			return [lineNum + 1, columnNum + 1, char]; // line/col should be one-based, not zero-based!
		},

		error: function (message) {
			var pos = this.getLinePos(this.pos);
			var lineNum = pos[0];
			var columnNum = pos[1];

			var line = this.lines[pos[0] - 1];
			var numTabs = 0;
			var annotation = line.replace(/\t/g, function (match, char) {
				if (char < pos[1]) {
					numTabs += 1;
				}

				return "  ";
			}) + "\n" + new Array(pos[1] + numTabs).join(" ") + "^----";

			var error = new ParseError("" + message + " at line " + lineNum + " character " + columnNum + ":\n" + annotation);

			error.line = pos[0];
			error.character = pos[1];
			error.shortMessage = message;

			throw error;
		},

		matchString: function (string) {
			if (this.str.substr(this.pos, string.length) === string) {
				this.pos += string.length;
				return string;
			}
		},

		matchPattern: function (pattern) {
			var match;

			if (match = pattern.exec(this.remaining())) {
				this.pos += match[0].length;
				return match[1] || match[0];
			}
		},

		allowWhitespace: function () {
			this.matchPattern(parse_Parser__leadingWhitespace);
		},

		remaining: function () {
			return this.str.substring(this.pos);
		},

		nextChar: function () {
			return this.str.charAt(this.pos);
		}
	};

	Parser.extend = function (proto) {
		var Parent = this,
			Child,
			key;

		Child = function (str, options) {
			Parser.call(this, str, options);
		};

		Child.prototype = create(Parent.prototype);

		for (key in proto) {
			if (hasOwn.call(proto, key)) {
				Child.prototype[key] = proto[key];
			}
		}

		Child.extend = Parser.extend;
		return Child;
	};

	var parse_Parser = Parser;

	var TEXT = 1;
	var INTERPOLATOR = 2;
	var TRIPLE = 3;
	var SECTION = 4;
	var INVERTED = 5;
	var CLOSING = 6;
	var ELEMENT = 7;
	var PARTIAL = 8;
	var COMMENT = 9;
	var DELIMCHANGE = 10;
	var ATTRIBUTE = 13;
	var CLOSING_TAG = 14;
	var COMPONENT = 15;
	var YIELDER = 16;
	var INLINE_PARTIAL = 17;
	var DOCTYPE = 18;

	var NUMBER_LITERAL = 20;
	var STRING_LITERAL = 21;
	var ARRAY_LITERAL = 22;
	var OBJECT_LITERAL = 23;
	var BOOLEAN_LITERAL = 24;
	var REGEXP_LITERAL = 25;

	var GLOBAL = 26;
	var KEY_VALUE_PAIR = 27;

	var REFERENCE = 30;
	var REFINEMENT = 31;
	var MEMBER = 32;
	var PREFIX_OPERATOR = 33;
	var BRACKETED = 34;
	var CONDITIONAL = 35;
	var INFIX_OPERATOR = 36;

	var INVOCATION = 40;

	var SECTION_IF = 50;
	var SECTION_UNLESS = 51;
	var SECTION_EACH = 52;
	var SECTION_WITH = 53;
	var SECTION_IF_WITH = 54;

	var ELSE = 60;
	var ELSEIF = 61;

	var mustache_readDelimiterChange = readDelimiterChange;
	var delimiterChangePattern = /^[^\s=]+/,
		whitespacePattern = /^\s+/;
	function readDelimiterChange(parser) {
		var start, opening, closing;

		if (!parser.matchString("=")) {
			return null;
		}

		start = parser.pos;

		// allow whitespace before new opening delimiter
		parser.allowWhitespace();

		opening = parser.matchPattern(delimiterChangePattern);
		if (!opening) {
			parser.pos = start;
			return null;
		}

		// allow whitespace (in fact, it's necessary...)
		if (!parser.matchPattern(whitespacePattern)) {
			return null;
		}

		closing = parser.matchPattern(delimiterChangePattern);
		if (!closing) {
			parser.pos = start;
			return null;
		}

		// allow whitespace before closing '='
		parser.allowWhitespace();

		if (!parser.matchString("=")) {
			parser.pos = start;
			return null;
		}

		return [opening, closing];
	}

	var readRegexpLiteral = readRegexpLiteral__readNumberLiteral;
	var regexpPattern = /^(\/(?:[^\n\r\u2028\u2029/\\[]|\\.|\[(?:[^\n\r\u2028\u2029\]\\]|\\.)*])+\/(?:([gimuy])(?![a-z]*\2))*(?![a-zA-Z_$0-9]))/;
	function readRegexpLiteral__readNumberLiteral(parser) {
		var result;

		if (result = parser.matchPattern(regexpPattern)) {
			return {
				t: REGEXP_LITERAL,
				v: result
			};
		}

		return null;
	}

	var converters_readMustache = readMustache;

	var delimiterChangeToken = { t: DELIMCHANGE, exclude: true };
	function readMustache(parser) {
		var mustache, i;

		// If we're inside a <script> or <style> tag, and we're not
		// interpolating, bug out
		if (parser.interpolate[parser.inside] === false) {
			return null;
		}

		for (i = 0; i < parser.tags.length; i += 1) {
			if (mustache = readMustacheOfType(parser, parser.tags[i])) {
				return mustache;
			}
		}
	}

	function readMustacheOfType(parser, tag) {
		var start, mustache, reader, i;

		start = parser.pos;

		if (parser.matchString("\\" + tag.open)) {
			if (start === 0 || parser.str[start - 1] !== "\\") {
				return tag.open;
			}
		} else if (!parser.matchString(tag.open)) {
			return null;
		}

		// delimiter change?
		if (mustache = mustache_readDelimiterChange(parser)) {
			// find closing delimiter or abort...
			if (!parser.matchString(tag.close)) {
				return null;
			}

			// ...then make the switch
			tag.open = mustache[0];
			tag.close = mustache[1];
			parser.sortMustacheTags();

			return delimiterChangeToken;
		}

		parser.allowWhitespace();

		// illegal section closer
		if (parser.matchString("/")) {
			parser.pos -= 1;
			var rewind = parser.pos;
			if (!readRegexpLiteral(parser)) {
				parser.pos = rewind - tag.close.length;
				parser.error("Attempted to close a section that wasn't open");
			} else {
				parser.pos = rewind;
			}
		}

		for (i = 0; i < tag.readers.length; i += 1) {
			reader = tag.readers[i];

			if (mustache = reader(parser, tag)) {
				if (tag.isStatic) {
					mustache.s = true; // TODO make this `1` instead - more compact
				}

				if (parser.includeLinePositions) {
					mustache.p = parser.getLinePos(start);
				}

				return mustache;
			}
		}

		parser.pos = start;
		return null;
	}

	var expectedExpression = "Expected a JavaScript expression";
	var expectedParen = "Expected closing paren";

	var literal_readNumberLiteral = literal_readNumberLiteral__readNumberLiteral;
	var literal_readNumberLiteral__numberPattern = /^(?:[+-]?)0*(?:(?:(?:[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;
	function literal_readNumberLiteral__readNumberLiteral(parser) {
		var result;

		if (result = parser.matchPattern(literal_readNumberLiteral__numberPattern)) {
			return {
				t: NUMBER_LITERAL,
				v: result
			};
		}

		return null;
	}

	var literal_readBooleanLiteral = readBooleanLiteral;
	function readBooleanLiteral(parser) {
		var remaining = parser.remaining();

		if (remaining.substr(0, 4) === "true") {
			parser.pos += 4;
			return {
				t: BOOLEAN_LITERAL,
				v: "true"
			};
		}

		if (remaining.substr(0, 5) === "false") {
			parser.pos += 5;
			return {
				t: BOOLEAN_LITERAL,
				v: "false"
			};
		}

		return null;
	}

	var stringMiddlePattern, escapeSequencePattern, lineContinuationPattern;

	// Match one or more characters until: ", ', \, or EOL/EOF.
	// EOL/EOF is written as (?!.) (meaning there's no non-newline char next).
	stringMiddlePattern = /^(?=.)[^"'\\]+?(?:(?!.)|(?=["'\\]))/;

	// Match one escape sequence, including the backslash.
	escapeSequencePattern = /^\\(?:['"\\bfnrt]|0(?![0-9])|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|(?=.)[^ux0-9])/;

	// Match one ES5 line continuation (backslash + line terminator).
	lineContinuationPattern = /^\\(?:\r\n|[\u000A\u000D\u2028\u2029])/;

	// Helper for defining getDoubleQuotedString and getSingleQuotedString.
	var makeQuotedStringMatcher = function (okQuote) {
		return function (parser) {
			var start, literal, done, next;

			start = parser.pos;
			literal = "\"";
			done = false;

			while (!done) {
				next = parser.matchPattern(stringMiddlePattern) || parser.matchPattern(escapeSequencePattern) || parser.matchString(okQuote);
				if (next) {
					if (next === "\"") {
						literal += "\\\"";
					} else if (next === "\\'") {
						literal += "'";
					} else {
						literal += next;
					}
				} else {
					next = parser.matchPattern(lineContinuationPattern);
					if (next) {
						// convert \(newline-like) into a \u escape, which is allowed in JSON
						literal += "\\u" + ("000" + next.charCodeAt(1).toString(16)).slice(-4);
					} else {
						done = true;
					}
				}
			}

			literal += "\"";

			// use JSON.parse to interpret escapes
			return JSON.parse(literal);
		};
	};

	var getSingleQuotedString = makeQuotedStringMatcher("\"");
	var getDoubleQuotedString = makeQuotedStringMatcher("'");

	var readStringLiteral = function (parser) {
		var start, string;

		start = parser.pos;

		if (parser.matchString("\"")) {
			string = getDoubleQuotedString(parser);

			if (!parser.matchString("\"")) {
				parser.pos = start;
				return null;
			}

			return {
				t: STRING_LITERAL,
				v: string
			};
		}

		if (parser.matchString("'")) {
			string = getSingleQuotedString(parser);

			if (!parser.matchString("'")) {
				parser.pos = start;
				return null;
			}

			return {
				t: STRING_LITERAL,
				v: string
			};
		}

		return null;
	};

	var patterns__name = /^[a-zA-Z_$][a-zA-Z_$0-9]*/;

	// http://mathiasbynens.be/notes/javascript-properties
	// can be any name, string literal, or number literal
	var shared_readKey = readKey;
	var identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
	function readKey(parser) {
		var token;

		if (token = readStringLiteral(parser)) {
			return identifier.test(token.v) ? token.v : "\"" + token.v.replace(/"/g, "\\\"") + "\"";
		}

		if (token = literal_readNumberLiteral(parser)) {
			return token.v;
		}

		if (token = parser.matchPattern(patterns__name)) {
			return token;
		}
	}

	var keyValuePair = readKeyValuePair;
	function readKeyValuePair(parser) {
		var start, key, value;

		start = parser.pos;

		// allow whitespace between '{' and key
		parser.allowWhitespace();

		key = shared_readKey(parser);
		if (key === null) {
			parser.pos = start;
			return null;
		}

		// allow whitespace between key and ':'
		parser.allowWhitespace();

		// next character must be ':'
		if (!parser.matchString(":")) {
			parser.pos = start;
			return null;
		}

		// allow whitespace between ':' and value
		parser.allowWhitespace();

		// next expression must be a, well... expression
		value = converters_readExpression(parser);
		if (value === null) {
			parser.pos = start;
			return null;
		}

		return {
			t: KEY_VALUE_PAIR,
			k: key,
			v: value
		};
	}

	var objectLiteral_keyValuePairs = readKeyValuePairs;
	function readKeyValuePairs(parser) {
		var start, pairs, pair, keyValuePairs;

		start = parser.pos;

		pair = keyValuePair(parser);
		if (pair === null) {
			return null;
		}

		pairs = [pair];

		if (parser.matchString(",")) {
			keyValuePairs = readKeyValuePairs(parser);

			if (!keyValuePairs) {
				parser.pos = start;
				return null;
			}

			return pairs.concat(keyValuePairs);
		}

		return pairs;
	}

	var readObjectLiteral = function (parser) {
		var start, keyValuePairs;

		start = parser.pos;

		// allow whitespace
		parser.allowWhitespace();

		if (!parser.matchString("{")) {
			parser.pos = start;
			return null;
		}

		keyValuePairs = objectLiteral_keyValuePairs(parser);

		// allow whitespace between final value and '}'
		parser.allowWhitespace();

		if (!parser.matchString("}")) {
			parser.pos = start;
			return null;
		}

		return {
			t: OBJECT_LITERAL,
			m: keyValuePairs
		};
	};

	var shared_readExpressionList = readExpressionList;
	function readExpressionList(parser) {
		var start, expressions, expr, next;

		start = parser.pos;

		parser.allowWhitespace();

		expr = converters_readExpression(parser);

		if (expr === null) {
			return null;
		}

		expressions = [expr];

		// allow whitespace between expression and ','
		parser.allowWhitespace();

		if (parser.matchString(",")) {
			next = readExpressionList(parser);
			if (next === null) {
				parser.error(expectedExpression);
			}

			next.forEach(append);
		}

		function append(expression) {
			expressions.push(expression);
		}

		return expressions;
	}

	var readArrayLiteral = function (parser) {
		var start, expressionList;

		start = parser.pos;

		// allow whitespace before '['
		parser.allowWhitespace();

		if (!parser.matchString("[")) {
			parser.pos = start;
			return null;
		}

		expressionList = shared_readExpressionList(parser);

		if (!parser.matchString("]")) {
			parser.pos = start;
			return null;
		}

		return {
			t: ARRAY_LITERAL,
			m: expressionList
		};
	};

	var primary_readLiteral = readLiteral;
	function readLiteral(parser) {
		return literal_readNumberLiteral(parser) || literal_readBooleanLiteral(parser) || readStringLiteral(parser) || readObjectLiteral(parser) || readArrayLiteral(parser) || readRegexpLiteral(parser);
	}

	var primary_readReference = readReference;
	var prefixPattern = /^(?:~\/|(?:\.\.\/)+|\.\/(?:\.\.\/)*|\.)/,
		globals,
		keywords;

	// if a reference is a browser global, we don't deference it later, so it needs special treatment
	globals = /^(?:Array|console|Date|RegExp|decodeURIComponent|decodeURI|encodeURIComponent|encodeURI|isFinite|isNaN|parseFloat|parseInt|JSON|Math|NaN|undefined|null)\b/;

	// keywords are not valid references, with the exception of `this`
	keywords = /^(?:break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|var|void|while|with)$/;

	var legalReference = /^[a-zA-Z$_0-9]+(?:(?:\.[a-zA-Z$_0-9]+)|(?:\[[0-9]+\]))*/;
	var relaxedName = /^[a-zA-Z_$][-a-zA-Z_$0-9]*/;
	function readReference(parser) {
		var startPos, prefix, name, global, reference, lastDotIndex;

		startPos = parser.pos;

		name = parser.matchPattern(/^@(?:keypath|index|key)/);

		if (!name) {
			prefix = parser.matchPattern(prefixPattern) || "";
			name = !prefix && parser.relaxedNames && parser.matchPattern(relaxedName) || parser.matchPattern(legalReference);

			if (!name && prefix === ".") {
				prefix = "";
				name = ".";
			}
		}

		if (!name) {
			return null;
		}

		// bug out if it's a keyword (exception for ancestor/restricted refs - see https://github.com/ractivejs/ractive/issues/1497)
		if (!prefix && !parser.relaxedNames && keywords.test(name)) {
			parser.pos = startPos;
			return null;
		}

		// if this is a browser global, stop here
		if (!prefix && globals.test(name)) {
			global = globals.exec(name)[0];
			parser.pos = startPos + global.length;

			return {
				t: GLOBAL,
				v: global
			};
		}

		reference = (prefix || "") + normalise(name);

		if (parser.matchString("(")) {
			// if this is a method invocation (as opposed to a function) we need
			// to strip the method name from the reference combo, else the context
			// will be wrong
			lastDotIndex = reference.lastIndexOf(".");
			if (lastDotIndex !== -1) {
				reference = reference.substr(0, lastDotIndex);
				parser.pos = startPos + reference.length;
			} else {
				parser.pos -= 1;
			}
		}

		return {
			t: REFERENCE,
			n: reference.replace(/^this\./, "./").replace(/^this$/, ".")
		};
	}

	var primary_readBracketedExpression = readBracketedExpression;
	function readBracketedExpression(parser) {
		var start, expr;

		start = parser.pos;

		if (!parser.matchString("(")) {
			return null;
		}

		parser.allowWhitespace();

		expr = converters_readExpression(parser);
		if (!expr) {
			parser.error(expectedExpression);
		}

		parser.allowWhitespace();

		if (!parser.matchString(")")) {
			parser.error(expectedParen);
		}

		return {
			t: BRACKETED,
			x: expr
		};
	}

	var readPrimary = function (parser) {
		return primary_readLiteral(parser) || primary_readReference(parser) || primary_readBracketedExpression(parser);
	};

	var shared_readRefinement = readRefinement;
	function readRefinement(parser) {
		var start, name, expr;

		start = parser.pos;

		parser.allowWhitespace();

		// "." name
		if (parser.matchString(".")) {
			parser.allowWhitespace();

			if (name = parser.matchPattern(patterns__name)) {
				return {
					t: REFINEMENT,
					n: name
				};
			}

			parser.error("Expected a property name");
		}

		// "[" expression "]"
		if (parser.matchString("[")) {
			parser.allowWhitespace();

			expr = converters_readExpression(parser);
			if (!expr) {
				parser.error(expectedExpression);
			}

			parser.allowWhitespace();

			if (!parser.matchString("]")) {
				parser.error("Expected ']'");
			}

			return {
				t: REFINEMENT,
				x: expr
			};
		}

		return null;
	}

	var readMemberOrInvocation = function (parser) {
		var current, expression, refinement, expressionList;

		expression = readPrimary(parser);

		if (!expression) {
			return null;
		}

		while (expression) {
			current = parser.pos;

			if (refinement = shared_readRefinement(parser)) {
				expression = {
					t: MEMBER,
					x: expression,
					r: refinement
				};
			} else if (parser.matchString("(")) {
				parser.allowWhitespace();
				expressionList = shared_readExpressionList(parser);

				parser.allowWhitespace();

				if (!parser.matchString(")")) {
					parser.error(expectedParen);
				}

				expression = {
					t: INVOCATION,
					x: expression
				};

				if (expressionList) {
					expression.o = expressionList;
				}
			} else {
				break;
			}
		}

		return expression;
	};

	var readTypeOf, makePrefixSequenceMatcher;

	makePrefixSequenceMatcher = function (symbol, fallthrough) {
		return function (parser) {
			var expression;

			if (expression = fallthrough(parser)) {
				return expression;
			}

			if (!parser.matchString(symbol)) {
				return null;
			}

			parser.allowWhitespace();

			expression = converters_readExpression(parser);
			if (!expression) {
				parser.error(expectedExpression);
			}

			return {
				s: symbol,
				o: expression,
				t: PREFIX_OPERATOR
			};
		};
	};

	// create all prefix sequence matchers, return readTypeOf
	(function () {
		var i, len, matcher, prefixOperators, fallthrough;

		prefixOperators = "! ~ + - typeof".split(" ");

		fallthrough = readMemberOrInvocation;
		for (i = 0, len = prefixOperators.length; i < len; i += 1) {
			matcher = makePrefixSequenceMatcher(prefixOperators[i], fallthrough);
			fallthrough = matcher;
		}

		// typeof operator is higher precedence than multiplication, so provides the
		// fallthrough for the multiplication sequence matcher we're about to create
		// (we're skipping void and delete)
		readTypeOf = fallthrough;
	})();

	var readTypeof = readTypeOf;

	var readLogicalOr, makeInfixSequenceMatcher;

	makeInfixSequenceMatcher = function (symbol, fallthrough) {
		return function (parser) {
			var start, left, right;

			left = fallthrough(parser);
			if (!left) {
				return null;
			}

			// Loop to handle left-recursion in a case like `a * b * c` and produce
			// left association, i.e. `(a * b) * c`.  The matcher can't call itself
			// to parse `left` because that would be infinite regress.
			while (true) {
				start = parser.pos;

				parser.allowWhitespace();

				if (!parser.matchString(symbol)) {
					parser.pos = start;
					return left;
				}

				// special case - in operator must not be followed by [a-zA-Z_$0-9]
				if (symbol === "in" && /[a-zA-Z_$0-9]/.test(parser.remaining().charAt(0))) {
					parser.pos = start;
					return left;
				}

				parser.allowWhitespace();

				// right operand must also consist of only higher-precedence operators
				right = fallthrough(parser);
				if (!right) {
					parser.pos = start;
					return left;
				}

				left = {
					t: INFIX_OPERATOR,
					s: symbol,
					o: [left, right]
				};

				// Loop back around.  If we don't see another occurrence of the symbol,
				// we'll return left.
			}
		};
	};

	// create all infix sequence matchers, and return readLogicalOr
	(function () {
		var i, len, matcher, infixOperators, fallthrough;

		// All the infix operators on order of precedence (source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence)
		// Each sequence matcher will initially fall through to its higher precedence
		// neighbour, and only attempt to match if one of the higher precedence operators
		// (or, ultimately, a literal, reference, or bracketed expression) already matched
		infixOperators = "* / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | && ||".split(" ");

		// A typeof operator is higher precedence than multiplication
		fallthrough = readTypeof;
		for (i = 0, len = infixOperators.length; i < len; i += 1) {
			matcher = makeInfixSequenceMatcher(infixOperators[i], fallthrough);
			fallthrough = matcher;
		}

		// Logical OR is the fallthrough for the conditional matcher
		readLogicalOr = fallthrough;
	})();

	var expressions_readLogicalOr = readLogicalOr;

	// The conditional operator is the lowest precedence operator, so we start here
	var readConditional = getConditional;
	function getConditional(parser) {
		var start, expression, ifTrue, ifFalse;

		expression = expressions_readLogicalOr(parser);
		if (!expression) {
			return null;
		}

		start = parser.pos;

		parser.allowWhitespace();

		if (!parser.matchString("?")) {
			parser.pos = start;
			return expression;
		}

		parser.allowWhitespace();

		ifTrue = converters_readExpression(parser);
		if (!ifTrue) {
			parser.error(expectedExpression);
		}

		parser.allowWhitespace();

		if (!parser.matchString(":")) {
			parser.error("Expected \":\"");
		}

		parser.allowWhitespace();

		ifFalse = converters_readExpression(parser);
		if (!ifFalse) {
			parser.error(expectedExpression);
		}

		return {
			t: CONDITIONAL,
			o: [expression, ifTrue, ifFalse]
		};
	}

	var converters_readExpression = readExpression;
	function readExpression(parser) {
		// The conditional operator is the lowest precedence operator (except yield,
		// assignment operators, and commas, none of which are supported), so we
		// start there. If it doesn't match, it 'falls through' to progressively
		// higher precedence operators, until it eventually matches (or fails to
		// match) a 'primary' - a literal or a reference. This way, the abstract syntax
		// tree has everything in its proper place, i.e. 2 + 3 * 4 === 14, not 20.
		return readConditional(parser);
	}

	var utils_flattenExpression = flattenExpression;

	function flattenExpression(expression) {
		var refs;

		extractRefs(expression, refs = []);

		return {
			r: refs,
			s: stringify(expression)
		};

		function stringify(node) {
			switch (node.t) {
				case BOOLEAN_LITERAL:
				case GLOBAL:
				case NUMBER_LITERAL:
				case REGEXP_LITERAL:
					return node.v;

				case STRING_LITERAL:
					return JSON.stringify(String(node.v));

				case ARRAY_LITERAL:
					return "[" + (node.m ? node.m.map(stringify).join(",") : "") + "]";

				case OBJECT_LITERAL:
					return "{" + (node.m ? node.m.map(stringify).join(",") : "") + "}";

				case KEY_VALUE_PAIR:
					return node.k + ":" + stringify(node.v);

				case PREFIX_OPERATOR:
					return (node.s === "typeof" ? "typeof " : node.s) + stringify(node.o);

				case INFIX_OPERATOR:
					return stringify(node.o[0]) + (node.s.substr(0, 2) === "in" ? " " + node.s + " " : node.s) + stringify(node.o[1]);

				case INVOCATION:
					return stringify(node.x) + "(" + (node.o ? node.o.map(stringify).join(",") : "") + ")";

				case BRACKETED:
					return "(" + stringify(node.x) + ")";

				case MEMBER:
					return stringify(node.x) + stringify(node.r);

				case REFINEMENT:
					return node.n ? "." + node.n : "[" + stringify(node.x) + "]";

				case CONDITIONAL:
					return stringify(node.o[0]) + "?" + stringify(node.o[1]) + ":" + stringify(node.o[2]);

				case REFERENCE:
					return "_" + refs.indexOf(node.n);

				default:
					throw new Error("Expected legal JavaScript");
			}
		}
	}

	// TODO maybe refactor this?
	function extractRefs(node, refs) {
		var i, list;

		if (node.t === REFERENCE) {
			if (refs.indexOf(node.n) === -1) {
				refs.unshift(node.n);
			}
		}

		list = node.o || node.m;
		if (list) {
			if (isObject(list)) {
				extractRefs(list, refs);
			} else {
				i = list.length;
				while (i--) {
					extractRefs(list[i], refs);
				}
			}
		}

		if (node.x) {
			extractRefs(node.x, refs);
		}

		if (node.r) {
			extractRefs(node.r, refs);
		}

		if (node.v) {
			extractRefs(node.v, refs);
		}
	}

	var utils_refineExpression = refineExpression;

	var arrayMemberPattern = /^[0-9][1-9]*$/;
	function refineExpression(expression, mustache) {
		var referenceExpression;

		if (expression) {
			while (expression.t === BRACKETED && expression.x) {
				expression = expression.x;
			}

			// special case - integers should be treated as array members references,
			// rather than as expressions in their own right
			if (expression.t === REFERENCE) {
				mustache.r = expression.n;
			} else {
				if (expression.t === NUMBER_LITERAL && arrayMemberPattern.test(expression.v)) {
					mustache.r = expression.v;
				} else if (referenceExpression = getReferenceExpression(expression)) {
					mustache.rx = referenceExpression;
				} else {
					mustache.x = utils_flattenExpression(expression);
				}
			}

			return mustache;
		}
	}

	// TODO refactor this! it's bewildering
	function getReferenceExpression(expression) {
		var members = [],
			refinement;

		while (expression.t === MEMBER && expression.r.t === REFINEMENT) {
			refinement = expression.r;

			if (refinement.x) {
				if (refinement.x.t === REFERENCE) {
					members.unshift(refinement.x);
				} else {
					members.unshift(utils_flattenExpression(refinement.x));
				}
			} else {
				members.unshift(refinement.n);
			}

			expression = expression.x;
		}

		if (expression.t !== REFERENCE) {
			return null;
		}

		return {
			r: expression.n,
			m: members
		};
	}

	var mustache_readTriple = readTriple;
	function readTriple(parser, tag) {
		var expression = converters_readExpression(parser),
			triple;

		if (!expression) {
			return null;
		}

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "'");
		}

		triple = { t: TRIPLE };
		utils_refineExpression(expression, triple); // TODO handle this differently - it's mysterious

		return triple;
	}

	var mustache_readUnescaped = readUnescaped;
	function readUnescaped(parser, tag) {
		var expression, triple;

		if (!parser.matchString("&")) {
			return null;
		}

		parser.allowWhitespace();

		expression = converters_readExpression(parser);

		if (!expression) {
			return null;
		}

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "'");
		}

		triple = { t: TRIPLE };
		utils_refineExpression(expression, triple); // TODO handle this differently - it's mysterious

		return triple;
	}

	var mustache_readPartial = readPartial;
	function readPartial(parser, tag) {
		var start, nameStart, expression, context, partial;

		start = parser.pos;

		if (!parser.matchString(">")) {
			return null;
		}

		parser.allowWhitespace();
		nameStart = parser.pos;

		// Partial names can include hyphens, so we can't use readExpression
		// blindly. Instead, we use the `relaxedNames` flag to indicate that
		// `foo-bar` should be read as a single name, rather than 'subtract
		// bar from foo'
		parser.relaxedNames = true;
		expression = converters_readExpression(parser);
		parser.relaxedNames = false;

		parser.allowWhitespace();
		context = converters_readExpression(parser);
		parser.allowWhitespace();

		if (!expression) {
			return null;
		}

		partial = { t: PARTIAL };
		utils_refineExpression(expression, partial); // TODO...

		parser.allowWhitespace();

		// if we have another expression - e.g. `{{>foo bar}}` - then
		// we turn it into `{{#with bar}}{{>foo}}{{/with}}`
		if (context) {
			partial = {
				t: SECTION,
				n: SECTION_WITH,
				f: [partial]
			};

			utils_refineExpression(context, partial);
		}

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "'");
		}

		return partial;
	}

	var readMustacheComment = readComment;
	function readComment(parser, tag) {
		var index;

		if (!parser.matchString("!")) {
			return null;
		}

		index = parser.remaining().indexOf(tag.close);

		if (index !== -1) {
			parser.pos += index + tag.close.length;
			return { t: COMMENT };
		}
	}

	var converters_readExpressionOrReference = readExpressionOrReference;
	function readExpressionOrReference(parser, expectedFollowers) {
		var start, expression, i;

		start = parser.pos;
		expression = converters_readExpression(parser);

		if (!expression) {
			return null;
		}

		for (i = 0; i < expectedFollowers.length; i += 1) {
			if (parser.remaining().substr(0, expectedFollowers[i].length) === expectedFollowers[i]) {
				return expression;
			}
		}

		parser.pos = start;
		return primary_readReference(parser);
	}

	var mustache_readInterpolator = readInterpolator;
	function readInterpolator(parser, tag) {
		var start, expression, interpolator, err;

		start = parser.pos;

		// TODO would be good for perf if we could do away with the try-catch
		try {
			expression = converters_readExpressionOrReference(parser, [tag.close]);
		} catch (e) {
			err = e;
		}

		if (!expression) {
			if (parser.str.charAt(start) === "!") {
				// special case - comment
				parser.pos = start;
				return null;
			}

			if (err) {
				throw err;
			}
		}

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "' after reference");

			if (!expression) {
				// special case - comment
				if (parser.nextChar() === "!") {
					return null;
				}

				parser.error("Expected expression or legal reference");
			}
		}

		interpolator = { t: INTERPOLATOR };
		utils_refineExpression(expression, interpolator); // TODO handle this differently - it's mysterious

		return interpolator;
	}

	var mustache_readYielder = readYielder;
	var yieldPattern = /^yield\s*/;
	function readYielder(parser, tag) {
		var start, name, yielder;

		if (!parser.matchPattern(yieldPattern)) {
			return null;
		}

		start = parser.pos;
		name = parser.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-]*/);

		parser.allowWhitespace();

		if (!parser.matchString(tag.close)) {
			parser.error("expected legal partial name");
		}

		yielder = { t: YIELDER };

		if (name) {
			yielder.n = name;
		}

		return yielder;
	}

	var section_readClosing = readClosing;
	function readClosing(parser, tag) {
		var start, remaining, index, closing;

		start = parser.pos;

		if (!parser.matchString(tag.open)) {
			return null;
		}

		parser.allowWhitespace();

		if (!parser.matchString("/")) {
			parser.pos = start;
			return null;
		}

		parser.allowWhitespace();

		remaining = parser.remaining();
		index = remaining.indexOf(tag.close);

		if (index !== -1) {
			closing = {
				t: CLOSING,
				r: remaining.substr(0, index).split(" ")[0]
			};

			parser.pos += index;

			if (!parser.matchString(tag.close)) {
				parser.error("Expected closing delimiter '" + tag.close + "'");
			}

			return closing;
		}

		parser.pos = start;
		return null;
	}

	var section_readElse = section_readElse__readElse;
	var section_readElse__elsePattern = /^\s*else\s*/;
	function section_readElse__readElse(parser, tag) {
		var start = parser.pos;

		if (!parser.matchString(tag.open)) {
			return null;
		}

		if (!parser.matchPattern(section_readElse__elsePattern)) {
			parser.pos = start;
			return null;
		}

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "'");
		}

		return {
			t: ELSE
		};
	}

	var readElseIf = readElseIf__readElse;
	var readElseIf__elsePattern = /^\s*elseif\s+/;
	function readElseIf__readElse(parser, tag) {
		var start = parser.pos,
			expression;

		if (!parser.matchString(tag.open)) {
			return null;
		}

		if (!parser.matchPattern(readElseIf__elsePattern)) {
			parser.pos = start;
			return null;
		}

		expression = converters_readExpression(parser);

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "'");
		}

		return {
			t: ELSEIF,
			x: expression
		};
	}

	var handlebarsBlockCodes = {
		each: SECTION_EACH,
		"if": SECTION_IF,
		"if-with": SECTION_IF_WITH,
		"with": SECTION_WITH,
		unless: SECTION_UNLESS
	};

	var mustache_readSection = readSection;

	var indexRefPattern = /^\s*:\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/,
		keyIndexRefPattern = /^\s*,\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/,
		handlebarsBlockPattern = new RegExp("^(" + Object.keys(handlebarsBlockCodes).join("|") + ")\\b");
	function readSection(parser, tag) {
		var start, expression, section, child, children, hasElse, block, unlessBlock, conditions, closed, i, expectedClose;

		start = parser.pos;

		if (parser.matchString("^")) {
			section = { t: SECTION, f: [], n: SECTION_UNLESS };
		} else if (parser.matchString("#")) {
			section = { t: SECTION, f: [] };

			if (parser.matchString("partial")) {
				parser.pos = start - parser.standardDelimiters[0].length;
				parser.error("Partial definitions can only be at the top level of the template, or immediately inside components");
			}

			if (block = parser.matchPattern(handlebarsBlockPattern)) {
				expectedClose = block;
				section.n = handlebarsBlockCodes[block];
			}
		} else {
			return null;
		}

		parser.allowWhitespace();

		expression = converters_readExpression(parser);

		if (!expression) {
			parser.error("Expected expression");
		}

		// optional index and key references
		if (i = parser.matchPattern(indexRefPattern)) {
			var extra = undefined;

			if (extra = parser.matchPattern(keyIndexRefPattern)) {
				section.i = i + "," + extra;
			} else {
				section.i = i;
			}
		}

		parser.allowWhitespace();

		if (!parser.matchString(tag.close)) {
			parser.error("Expected closing delimiter '" + tag.close + "'");
		}

		parser.sectionDepth += 1;
		children = section.f;

		conditions = [];

		do {
			if (child = section_readClosing(parser, tag)) {
				if (expectedClose && child.r !== expectedClose) {
					parser.error("Expected " + tag.open + "/" + expectedClose + "" + tag.close);
				}

				parser.sectionDepth -= 1;
				closed = true;
			} else if (child = readElseIf(parser, tag)) {
				if (section.n === SECTION_UNLESS) {
					parser.error("{{else}} not allowed in {{#unless}}");
				}

				if (hasElse) {
					parser.error("illegal {{elseif...}} after {{else}}");
				}

				if (!unlessBlock) {
					unlessBlock = createUnlessBlock(expression, section.n);
				}

				unlessBlock.f.push({
					t: SECTION,
					n: SECTION_IF,
					x: utils_flattenExpression(mustache_readSection__combine(conditions.concat(child.x))),
					f: children = []
				});

				conditions.push(invert(child.x));
			} else if (child = section_readElse(parser, tag)) {
				if (section.n === SECTION_UNLESS) {
					parser.error("{{else}} not allowed in {{#unless}}");
				}

				if (hasElse) {
					parser.error("there can only be one {{else}} block, at the end of a section");
				}

				hasElse = true;

				// use an unless block if there's no elseif
				if (!unlessBlock) {
					unlessBlock = createUnlessBlock(expression, section.n);
					children = unlessBlock.f;
				} else {
					unlessBlock.f.push({
						t: SECTION,
						n: SECTION_IF,
						x: utils_flattenExpression(mustache_readSection__combine(conditions)),
						f: children = []
					});
				}
			} else {
				child = parser.read(READERS);

				if (!child) {
					break;
				}

				children.push(child);
			}
		} while (!closed);

		if (unlessBlock) {
			// special case - `with` should become `if-with` (TODO is this right?
			// seems to me that `with` ought to behave consistently, regardless
			// of the presence/absence of `else`. In other words should always
			// be `if-with`
			if (section.n === SECTION_WITH) {
				section.n = SECTION_IF_WITH;
			}

			section.l = unlessBlock;
		}

		utils_refineExpression(expression, section);

		// TODO if a section is empty it should be discarded. Don't do
		// that here though - we need to clean everything up first, as
		// it may contain removeable whitespace. As a temporary measure,
		// to pass the existing tests, remove empty `f` arrays
		if (!section.f.length) {
			delete section.f;
		}

		return section;
	}

	function createUnlessBlock(expression, sectionType) {
		var unlessBlock;

		if (sectionType === SECTION_WITH) {
			// special case - a `{{#with foo}}` section will render if `foo` is
			// truthy, so the `{{else}}` section needs to render if `foo` is falsy,
			// rather than adhering to the normal `{{#unless foo}}` logic (which
			// treats empty arrays/objects as falsy)
			unlessBlock = {
				t: SECTION,
				n: SECTION_IF,
				f: []
			};

			utils_refineExpression(invert(expression), unlessBlock);
		} else {
			unlessBlock = {
				t: SECTION,
				n: SECTION_UNLESS,
				f: []
			};

			utils_refineExpression(expression, unlessBlock);
		}

		return unlessBlock;
	}

	function invert(expression) {
		if (expression.t === PREFIX_OPERATOR && expression.s === "!") {
			return expression.o;
		}

		return {
			t: PREFIX_OPERATOR,
			s: "!",
			o: parensIfNecessary(expression)
		};
	}

	function mustache_readSection__combine(expressions) {
		if (expressions.length === 1) {
			return expressions[0];
		}

		return {
			t: INFIX_OPERATOR,
			s: "&&",
			o: [parensIfNecessary(expressions[0]), parensIfNecessary(mustache_readSection__combine(expressions.slice(1)))]
		};
	}

	function parensIfNecessary(expression) {
		// TODO only wrap if necessary
		return {
			t: BRACKETED,
			x: expression
		};
	}

	var converters_readHtmlComment = readHtmlComment;
	var OPEN_COMMENT = "<!--",
		CLOSE_COMMENT = "-->";
	function readHtmlComment(parser) {
		var start, content, remaining, endIndex, comment;

		start = parser.pos;

		if (!parser.matchString(OPEN_COMMENT)) {
			return null;
		}

		remaining = parser.remaining();
		endIndex = remaining.indexOf(CLOSE_COMMENT);

		if (endIndex === -1) {
			parser.error("Illegal HTML - expected closing comment sequence ('-->')");
		}

		content = remaining.substr(0, endIndex);
		parser.pos += endIndex + 3;

		comment = {
			t: COMMENT,
			c: content
		};

		if (parser.includeLinePositions) {
			comment.p = parser.getLinePos(start);
		}

		return comment;
	}

	var booleanAttributes, voidElementNames, htmlEntities, controlCharacters, entityPattern, lessThan, greaterThan, amp;

	// https://github.com/kangax/html-minifier/issues/63#issuecomment-37763316
	booleanAttributes = /^(allowFullscreen|async|autofocus|autoplay|checked|compact|controls|declare|default|defaultChecked|defaultMuted|defaultSelected|defer|disabled|enabled|formNoValidate|hidden|indeterminate|inert|isMap|itemScope|loop|multiple|muted|noHref|noResize|noShade|noValidate|noWrap|open|pauseOnExit|readOnly|required|reversed|scoped|seamless|selected|sortable|translate|trueSpeed|typeMustMatch|visible)$/i;
	voidElementNames = /^(?:area|base|br|col|command|doctype|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;

	htmlEntities = { quot: 34, amp: 38, apos: 39, lt: 60, gt: 62, nbsp: 160, iexcl: 161, cent: 162, pound: 163, curren: 164, yen: 165, brvbar: 166, sect: 167, uml: 168, copy: 169, ordf: 170, laquo: 171, not: 172, shy: 173, reg: 174, macr: 175, deg: 176, plusmn: 177, sup2: 178, sup3: 179, acute: 180, micro: 181, para: 182, middot: 183, cedil: 184, sup1: 185, ordm: 186, raquo: 187, frac14: 188, frac12: 189, frac34: 190, iquest: 191, Agrave: 192, Aacute: 193, Acirc: 194, Atilde: 195, Auml: 196, Aring: 197, AElig: 198, Ccedil: 199, Egrave: 200, Eacute: 201, Ecirc: 202, Euml: 203, Igrave: 204, Iacute: 205, Icirc: 206, Iuml: 207, ETH: 208, Ntilde: 209, Ograve: 210, Oacute: 211, Ocirc: 212, Otilde: 213, Ouml: 214, times: 215, Oslash: 216, Ugrave: 217, Uacute: 218, Ucirc: 219, Uuml: 220, Yacute: 221, THORN: 222, szlig: 223, agrave: 224, aacute: 225, acirc: 226, atilde: 227, auml: 228, aring: 229, aelig: 230, ccedil: 231, egrave: 232, eacute: 233, ecirc: 234, euml: 235, igrave: 236, iacute: 237, icirc: 238, iuml: 239, eth: 240, ntilde: 241, ograve: 242, oacute: 243, ocirc: 244, otilde: 245, ouml: 246, divide: 247, oslash: 248, ugrave: 249, uacute: 250, ucirc: 251, uuml: 252, yacute: 253, thorn: 254, yuml: 255, OElig: 338, oelig: 339, Scaron: 352, scaron: 353, Yuml: 376, fnof: 402, circ: 710, tilde: 732, Alpha: 913, Beta: 914, Gamma: 915, Delta: 916, Epsilon: 917, Zeta: 918, Eta: 919, Theta: 920, Iota: 921, Kappa: 922, Lambda: 923, Mu: 924, Nu: 925, Xi: 926, Omicron: 927, Pi: 928, Rho: 929, Sigma: 931, Tau: 932, Upsilon: 933, Phi: 934, Chi: 935, Psi: 936, Omega: 937, alpha: 945, beta: 946, gamma: 947, delta: 948, epsilon: 949, zeta: 950, eta: 951, theta: 952, iota: 953, kappa: 954, lambda: 955, mu: 956, nu: 957, xi: 958, omicron: 959, pi: 960, rho: 961, sigmaf: 962, sigma: 963, tau: 964, upsilon: 965, phi: 966, chi: 967, psi: 968, omega: 969, thetasym: 977, upsih: 978, piv: 982, ensp: 8194, emsp: 8195, thinsp: 8201, zwnj: 8204, zwj: 8205, lrm: 8206, rlm: 8207, ndash: 8211, mdash: 8212, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225, bull: 8226, hellip: 8230, permil: 8240, prime: 8242, Prime: 8243, lsaquo: 8249, rsaquo: 8250, oline: 8254, frasl: 8260, euro: 8364, image: 8465, weierp: 8472, real: 8476, trade: 8482, alefsym: 8501, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, harr: 8596, crarr: 8629, lArr: 8656, uArr: 8657, rArr: 8658, dArr: 8659, hArr: 8660, forall: 8704, part: 8706, exist: 8707, empty: 8709, nabla: 8711, isin: 8712, notin: 8713, ni: 8715, prod: 8719, sum: 8721, minus: 8722, lowast: 8727, radic: 8730, prop: 8733, infin: 8734, ang: 8736, and: 8743, or: 8744, cap: 8745, cup: 8746, int: 8747, there4: 8756, sim: 8764, cong: 8773, asymp: 8776, ne: 8800, equiv: 8801, le: 8804, ge: 8805, sub: 8834, sup: 8835, nsub: 8836, sube: 8838, supe: 8839, oplus: 8853, otimes: 8855, perp: 8869, sdot: 8901, lceil: 8968, rceil: 8969, lfloor: 8970, rfloor: 8971, lang: 9001, rang: 9002, loz: 9674, spades: 9824, clubs: 9827, hearts: 9829, diams: 9830 };
	controlCharacters = [8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376];
	entityPattern = new RegExp("&(#?(?:x[\\w\\d]+|\\d+|" + Object.keys(htmlEntities).join("|") + "));?", "g");

	function decodeCharacterReferences(html) {
		return html.replace(entityPattern, function (match, entity) {
			var code;

			// Handle named entities
			if (entity[0] !== "#") {
				code = htmlEntities[entity];
			} else if (entity[1] === "x") {
				code = parseInt(entity.substring(2), 16);
			} else {
				code = parseInt(entity.substring(1), 10);
			}

			if (!code) {
				return match;
			}

			return String.fromCharCode(validateCode(code));
		});
	}

	// some code points are verboten. If we were inserting HTML, the browser would replace the illegal
	// code points with alternatives in some cases - since we're bypassing that mechanism, we need
	// to replace them ourselves
	//
	// Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters
	function validateCode(code) {
		if (!code) {
			return 65533;
		}

		// line feed becomes generic whitespace
		if (code === 10) {
			return 32;
		}

		// ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...)
		if (code < 128) {
			return code;
		}

		// code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need
		// to correct the mistake or we'll end up with missing â‚¬ signs and so on
		if (code <= 159) {
			return controlCharacters[code - 128];
		}

		// basic multilingual plane
		if (code < 55296) {
			return code;
		}

		// UTF-16 surrogate halves
		if (code <= 57343) {
			return 65533;
		}

		// rest of the basic multilingual plane
		if (code <= 65535) {
			return code;
		}

		return 65533;
	}

	lessThan = /</g;
	greaterThan = />/g;
	amp = /&/g;

	function escapeHtml(str) {
		return str.replace(amp, "&amp;").replace(lessThan, "&lt;").replace(greaterThan, "&gt;");
	}

	var leadingLinebreak = /^\s*\r?\n/,
		trailingLinebreak = /\r?\n\s*$/;

	var stripStandalones = function (items) {
		var i, current, backOne, backTwo, lastSectionItem;

		for (i = 1; i < items.length; i += 1) {
			current = items[i];
			backOne = items[i - 1];
			backTwo = items[i - 2];

			// if we're at the end of a [text][comment][text] sequence...
			if (isString(current) && isComment(backOne) && isString(backTwo)) {

				// ... and the comment is a standalone (i.e. line breaks either side)...
				if (trailingLinebreak.test(backTwo) && leadingLinebreak.test(current)) {

					// ... then we want to remove the whitespace after the first line break
					items[i - 2] = backTwo.replace(trailingLinebreak, "\n");

					// and the leading line break of the second text token
					items[i] = current.replace(leadingLinebreak, "");
				}
			}

			// if the current item is a section, and it is preceded by a linebreak, and
			// its first item is a linebreak...
			if (isSection(current) && isString(backOne)) {
				if (trailingLinebreak.test(backOne) && isString(current.f[0]) && leadingLinebreak.test(current.f[0])) {
					items[i - 1] = backOne.replace(trailingLinebreak, "\n");
					current.f[0] = current.f[0].replace(leadingLinebreak, "");
				}
			}

			// if the last item was a section, and it is followed by a linebreak, and
			// its last item is a linebreak...
			if (isString(current) && isSection(backOne)) {
				lastSectionItem = lastItem(backOne.f);

				if (isString(lastSectionItem) && trailingLinebreak.test(lastSectionItem) && leadingLinebreak.test(current)) {
					backOne.f[backOne.f.length - 1] = lastSectionItem.replace(trailingLinebreak, "\n");
					items[i] = current.replace(leadingLinebreak, "");
				}
			}
		}

		return items;
	};

	function isString(item) {
		return typeof item === "string";
	}

	function isComment(item) {
		return item.t === COMMENT || item.t === DELIMCHANGE;
	}

	function isSection(item) {
		return (item.t === SECTION || item.t === INVERTED) && item.f;
	}

	var trimWhitespace = function (items, leadingPattern, trailingPattern) {
		var item;

		if (leadingPattern) {
			item = items[0];
			if (typeof item === "string") {
				item = item.replace(leadingPattern, "");

				if (!item) {
					items.shift();
				} else {
					items[0] = item;
				}
			}
		}

		if (trailingPattern) {
			item = lastItem(items);
			if (typeof item === "string") {
				item = item.replace(trailingPattern, "");

				if (!item) {
					items.pop();
				} else {
					items[items.length - 1] = item;
				}
			}
		}
	};

	var utils_cleanup = cleanup;
	var contiguousWhitespace = /[ \t\f\r\n]+/g;
	var preserveWhitespaceElements = /^(?:pre|script|style|textarea)$/i;
	var utils_cleanup__leadingWhitespace = /^[ \t\f\r\n]+/;
	var trailingWhitespace = /[ \t\f\r\n]+$/;
	var leadingNewLine = /^(?:\r\n|\r|\n)/;
	var trailingNewLine = /(?:\r\n|\r|\n)$/;
	function cleanup(items, stripComments, preserveWhitespace, removeLeadingWhitespace, removeTrailingWhitespace) {
		var i, item, previousItem, nextItem, preserveWhitespaceInsideFragment, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, key;

		// First pass - remove standalones and comments etc
		stripStandalones(items);

		i = items.length;
		while (i--) {
			item = items[i];

			// Remove delimiter changes, unsafe elements etc
			if (item.exclude) {
				items.splice(i, 1);
			}

				// Remove comments, unless we want to keep them
			else if (stripComments && item.t === COMMENT) {
				items.splice(i, 1);
			}
		}

		// If necessary, remove leading and trailing whitespace
		trimWhitespace(items, removeLeadingWhitespace ? utils_cleanup__leadingWhitespace : null, removeTrailingWhitespace ? trailingWhitespace : null);

		i = items.length;
		while (i--) {
			item = items[i];

			// Recurse
			if (item.f) {
				var isPreserveWhitespaceElement = item.t === ELEMENT && preserveWhitespaceElements.test(item.e);
				preserveWhitespaceInsideFragment = preserveWhitespace || isPreserveWhitespaceElement;

				if (!preserveWhitespace && isPreserveWhitespaceElement) {
					trimWhitespace(item.f, leadingNewLine, trailingNewLine);
				}

				if (!preserveWhitespaceInsideFragment) {
					previousItem = items[i - 1];
					nextItem = items[i + 1];

					// if the previous item was a text item with trailing whitespace,
					// remove leading whitespace inside the fragment
					if (!previousItem || typeof previousItem === "string" && trailingWhitespace.test(previousItem)) {
						removeLeadingWhitespaceInsideFragment = true;
					}

					// and vice versa
					if (!nextItem || typeof nextItem === "string" && utils_cleanup__leadingWhitespace.test(nextItem)) {
						removeTrailingWhitespaceInsideFragment = true;
					}
				}

				cleanup(item.f, stripComments, preserveWhitespaceInsideFragment, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment);
			}

			// Split if-else blocks into two (an if, and an unless)
			if (item.l) {
				cleanup(item.l.f, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment);

				items.splice(i + 1, 0, item.l);
				delete item.l; // TODO would be nice if there was a way around this
			}

			// Clean up element attributes
			if (item.a) {
				for (key in item.a) {
					if (item.a.hasOwnProperty(key) && typeof item.a[key] !== "string") {
						cleanup(item.a[key], stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment);
					}
				}
			}

			// Clean up conditional attributes
			if (item.m) {
				cleanup(item.m, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment);
			}

			// Clean up event handlers
			if (item.v) {
				for (key in item.v) {
					if (item.v.hasOwnProperty(key)) {
						// clean up names
						if (isArray(item.v[key].n)) {
							cleanup(item.v[key].n, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment);
						}

						// clean up params
						if (isArray(item.v[key].d)) {
							cleanup(item.v[key].d, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment);
						}
					}
				}
			}
		}

		// final pass - fuse text nodes together
		i = items.length;
		while (i--) {
			if (typeof items[i] === "string") {
				if (typeof items[i + 1] === "string") {
					items[i] = items[i] + items[i + 1];
					items.splice(i + 1, 1);
				}

				if (!preserveWhitespace) {
					items[i] = items[i].replace(contiguousWhitespace, " ");
				}

				if (items[i] === "") {
					items.splice(i, 1);
				}
			}
		}
	}

	var element_readClosingTag = readClosingTag;
	var closingTagPattern = /^([a-zA-Z]{1,}:?[a-zA-Z0-9\-]*)\s*\>/;
	function readClosingTag(parser) {
		var start, tag;

		start = parser.pos;

		// are we looking at a closing tag?
		if (!parser.matchString("</")) {
			return null;
		}

		if (tag = parser.matchPattern(closingTagPattern)) {
			if (parser.inside && tag !== parser.inside) {
				parser.pos = start;
				return null;
			}

			return {
				t: CLOSING_TAG,
				e: tag
			};
		}

		// We have an illegal closing tag, report it
		parser.pos -= 2;
		parser.error("Illegal closing tag");
	}

	var getLowestIndex = function (haystack, needles) {
		var i, index, lowest;

		i = needles.length;
		while (i--) {
			index = haystack.indexOf(needles[i]);

			// short circuit
			if (!index) {
				return 0;
			}

			if (index === -1) {
				continue;
			}

			if (!lowest || index < lowest) {
				lowest = index;
			}
		}

		return lowest || -1;
	};

	var element_readAttribute = readAttribute;

	var attributeNamePattern = /^[^\s"'>\/=]+/,
		unquotedAttributeValueTextPattern = /^[^\s"'=<>`]+/;
	function readAttribute(parser) {
		var attr, name, value;

		parser.allowWhitespace();

		name = parser.matchPattern(attributeNamePattern);
		if (!name) {
			return null;
		}

		attr = { name: name };

		value = readAttributeValue(parser);
		if (value != null) {
			// not null/undefined
			attr.value = value;
		}

		return attr;
	}

	function readAttributeValue(parser) {
		var start, valueStart, startDepth, value;

		start = parser.pos;

		// next character must be `=`, `/`, `>` or whitespace
		if (!/[=\/>\s]/.test(parser.nextChar())) {
			parser.error("Expected `=`, `/`, `>` or whitespace");
		}

		parser.allowWhitespace();

		if (!parser.matchString("=")) {
			parser.pos = start;
			return null;
		}

		parser.allowWhitespace();

		valueStart = parser.pos;
		startDepth = parser.sectionDepth;

		value = readQuotedAttributeValue(parser, "'") || readQuotedAttributeValue(parser, "\"") || readUnquotedAttributeValue(parser);

		if (value === null) {
			parser.error("Expected valid attribute value");
		}

		if (parser.sectionDepth !== startDepth) {
			parser.pos = valueStart;
			parser.error("An attribute value must contain as many opening section tags as closing section tags");
		}

		if (!value.length) {
			return "";
		}

		if (value.length === 1 && typeof value[0] === "string") {
			return decodeCharacterReferences(value[0]);
		}

		return value;
	}

	function readUnquotedAttributeValueToken(parser) {
		var start, text, haystack, needles, index;

		start = parser.pos;

		text = parser.matchPattern(unquotedAttributeValueTextPattern);

		if (!text) {
			return null;
		}

		haystack = text;
		needles = parser.tags.map(function (t) {
			return t.open;
		}); // TODO refactor... we do this in readText.js as well

		if ((index = getLowestIndex(haystack, needles)) !== -1) {
			text = text.substr(0, index);
			parser.pos = start + text.length;
		}

		return text;
	}

	function readUnquotedAttributeValue(parser) {
		var tokens, token;

		parser.inAttribute = true;

		tokens = [];

		token = converters_readMustache(parser) || readUnquotedAttributeValueToken(parser);
		while (token !== null) {
			tokens.push(token);
			token = converters_readMustache(parser) || readUnquotedAttributeValueToken(parser);
		}

		if (!tokens.length) {
			return null;
		}

		parser.inAttribute = false;
		return tokens;
	}

	function readQuotedAttributeValue(parser, quoteMark) {
		var start, tokens, token;

		start = parser.pos;

		if (!parser.matchString(quoteMark)) {
			return null;
		}

		parser.inAttribute = quoteMark;

		tokens = [];

		token = converters_readMustache(parser) || readQuotedStringToken(parser, quoteMark);
		while (token !== null) {
			tokens.push(token);
			token = converters_readMustache(parser) || readQuotedStringToken(parser, quoteMark);
		}

		if (!parser.matchString(quoteMark)) {
			parser.pos = start;
			return null;
		}

		parser.inAttribute = false;

		return tokens;
	}

	function readQuotedStringToken(parser, quoteMark) {
		var start, index, haystack, needles;

		start = parser.pos;
		haystack = parser.remaining();

		needles = parser.tags.map(function (t) {
			return t.open;
		}); // TODO refactor... we do this in readText.js as well
		needles.push(quoteMark);

		index = getLowestIndex(haystack, needles);

		if (index === -1) {
			parser.error("Quoted attribute value must have a closing quote");
		}

		if (!index) {
			return null;
		}

		parser.pos += index;
		return haystack.substr(0, index);
	}

	var JsonParser, specials, specialsPattern, parseJSON__numberPattern, placeholderPattern, placeholderAtStartPattern, onlyWhitespace;

	specials = {
		"true": true,
		"false": false,
		undefined: undefined,
		"null": null
	};

	specialsPattern = new RegExp("^(?:" + Object.keys(specials).join("|") + ")");
	parseJSON__numberPattern = /^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;
	placeholderPattern = /\$\{([^\}]+)\}/g;
	placeholderAtStartPattern = /^\$\{([^\}]+)\}/;
	onlyWhitespace = /^\s*$/;

	JsonParser = parse_Parser.extend({
		init: function (str, options) {
			this.values = options.values;
			this.allowWhitespace();
		},

		postProcess: function (result) {
			if (result.length !== 1 || !onlyWhitespace.test(this.leftover)) {
				return null;
			}

			return { value: result[0].v };
		},

		converters: [function getPlaceholder(parser) {
			var placeholder;

			if (!parser.values) {
				return null;
			}

			placeholder = parser.matchPattern(placeholderAtStartPattern);

			if (placeholder && parser.values.hasOwnProperty(placeholder)) {
				return { v: parser.values[placeholder] };
			}
		}, function getSpecial(parser) {
			var special;

			if (special = parser.matchPattern(specialsPattern)) {
				return { v: specials[special] };
			}
		}, function getNumber(parser) {
			var number;

			if (number = parser.matchPattern(parseJSON__numberPattern)) {
				return { v: +number };
			}
		}, function getString(parser) {
			var stringLiteral = readStringLiteral(parser),
				values;

			if (stringLiteral && (values = parser.values)) {
				return {
					v: stringLiteral.v.replace(placeholderPattern, function (match, $1) {
						return $1 in values ? values[$1] : $1;
					})
				};
			}

			return stringLiteral;
		}, function getObject(parser) {
			var result, pair;

			if (!parser.matchString("{")) {
				return null;
			}

			result = {};

			parser.allowWhitespace();

			if (parser.matchString("}")) {
				return { v: result };
			}

			while (pair = getKeyValuePair(parser)) {
				result[pair.key] = pair.value;

				parser.allowWhitespace();

				if (parser.matchString("}")) {
					return { v: result };
				}

				if (!parser.matchString(",")) {
					return null;
				}
			}

			return null;
		}, function getArray(parser) {
			var result, valueToken;

			if (!parser.matchString("[")) {
				return null;
			}

			result = [];

			parser.allowWhitespace();

			if (parser.matchString("]")) {
				return { v: result };
			}

			while (valueToken = parser.read()) {
				result.push(valueToken.v);

				parser.allowWhitespace();

				if (parser.matchString("]")) {
					return { v: result };
				}

				if (!parser.matchString(",")) {
					return null;
				}

				parser.allowWhitespace();
			}

			return null;
		}]
	});

	function getKeyValuePair(parser) {
		var key, valueToken, pair;

		parser.allowWhitespace();

		key = shared_readKey(parser);

		if (!key) {
			return null;
		}

		pair = { key: key };

		parser.allowWhitespace();
		if (!parser.matchString(":")) {
			return null;
		}
		parser.allowWhitespace();

		valueToken = parser.read();
		if (!valueToken) {
			return null;
		}

		pair.value = valueToken.v;

		return pair;
	}

	var parseJSON = function (str, values) {
		var parser = new JsonParser(str, {
			values: values
		});

		return parser.result;
	};

	// TODO clean this up, it's shocking
	var element_processDirective = processDirective;
	var methodCallPattern = /^([a-zA-Z_$][a-zA-Z_$0-9]*)\(/,
		methodCallExcessPattern = /\)\s*$/,
		ExpressionParser;

	ExpressionParser = parse_Parser.extend({
		converters: [converters_readExpression]
	});
	function processDirective(tokens, parentParser) {
		var result, match, parser, args, token, colonIndex, directiveName, directiveArgs, parsed;

		if (typeof tokens === "string") {
			if (match = methodCallPattern.exec(tokens)) {
				var end = tokens.lastIndexOf(")");

				// check for invalid method calls
				if (!methodCallExcessPattern.test(tokens)) {
					parentParser.error("Invalid input after method call expression '" + tokens.slice(end + 1) + "'");
				}

				result = { m: match[1] };
				args = "[" + tokens.slice(result.m.length + 1, end) + "]";

				parser = new ExpressionParser(args);
				result.a = utils_flattenExpression(parser.result[0]);

				return result;
			}

			if (tokens.indexOf(":") === -1) {
				return tokens.trim();
			}

			tokens = [tokens];
		}

		result = {};

		directiveName = [];
		directiveArgs = [];

		if (tokens) {
			while (tokens.length) {
				token = tokens.shift();

				if (typeof token === "string") {
					colonIndex = token.indexOf(":");

					if (colonIndex === -1) {
						directiveName.push(token);
					} else {

						// is the colon the first character?
						if (colonIndex) {
							// no
							directiveName.push(token.substr(0, colonIndex));
						}

						// if there is anything after the colon in this token, treat
						// it as the first token of the directiveArgs fragment
						if (token.length > colonIndex + 1) {
							directiveArgs[0] = token.substring(colonIndex + 1);
						}

						break;
					}
				} else {
					directiveName.push(token);
				}
			}

			directiveArgs = directiveArgs.concat(tokens);
		}

		if (!directiveName.length) {
			result = "";
		} else if (directiveArgs.length || typeof directiveName !== "string") {
			result = {
				// TODO is this really necessary? just use the array
				n: directiveName.length === 1 && typeof directiveName[0] === "string" ? directiveName[0] : directiveName
			};

			if (directiveArgs.length === 1 && typeof directiveArgs[0] === "string") {
				parsed = parseJSON("[" + directiveArgs[0] + "]");
				result.a = parsed ? parsed.value : directiveArgs[0].trim();
			} else {
				result.d = directiveArgs;
			}
		} else {
			result = directiveName;
		}

		return result;
	}

	var tagNamePattern = /^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/,
		validTagNameFollower = /^[\s\n\/>]/,
		onPattern = /^on/,
		proxyEventPattern = /^on-([a-zA-Z\\*\\.$_][a-zA-Z\\*\\.$_0-9\-]+)$/,
		reservedEventNames = /^(?:change|reset|teardown|update|construct|config|init|render|unrender|detach|insert)$/,
		directives = { "intro-outro": "t0", intro: "t1", outro: "t2", decorator: "o" },
		exclude = { exclude: true },
		disallowedContents;

	// based on http://developers.whatwg.org/syntax.html#syntax-tag-omission
	disallowedContents = {
		li: ["li"],
		dt: ["dt", "dd"],
		dd: ["dt", "dd"],
		p: "address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul".split(" "),
		rt: ["rt", "rp"],
		rp: ["rt", "rp"],
		optgroup: ["optgroup"],
		option: ["option", "optgroup"],
		thead: ["tbody", "tfoot"],
		tbody: ["tbody", "tfoot"],
		tfoot: ["tbody"],
		tr: ["tr", "tbody"],
		td: ["td", "th", "tr"],
		th: ["td", "th", "tr"]
	};

	var converters_readElement = readElement;

	function readElement(parser) {
		var start, element, directiveName, match, addProxyEvent, attribute, directive, selfClosing, children, partials, hasPartials, child, closed, pos, remaining, closingTag;

		start = parser.pos;

		if (parser.inside || parser.inAttribute) {
			return null;
		}

		if (!parser.matchString("<")) {
			return null;
		}

		// if this is a closing tag, abort straight away
		if (parser.nextChar() === "/") {
			return null;
		}

		element = {};
		if (parser.includeLinePositions) {
			element.p = parser.getLinePos(start);
		}

		if (parser.matchString("!")) {
			element.t = DOCTYPE;
			if (!parser.matchPattern(/^doctype/i)) {
				parser.error("Expected DOCTYPE declaration");
			}

			element.a = parser.matchPattern(/^(.+?)>/);
			return element;
		}

		element.t = ELEMENT;

		// element name
		element.e = parser.matchPattern(tagNamePattern);
		if (!element.e) {
			return null;
		}

		// next character must be whitespace, closing solidus or '>'
		if (!validTagNameFollower.test(parser.nextChar())) {
			parser.error("Illegal tag name");
		}

		addProxyEvent = function (name, directive) {
			var directiveName = directive.n || directive;

			if (reservedEventNames.test(directiveName)) {
				parser.pos -= directiveName.length;
				parser.error("Cannot use reserved event names (change, reset, teardown, update, construct, config, init, render, unrender, detach, insert)");
			}

			element.v[name] = directive;
		};

		parser.allowWhitespace();

		// directives and attributes
		while (attribute = converters_readMustache(parser) || element_readAttribute(parser)) {
			// regular attributes
			if (attribute.name) {
				// intro, outro, decorator
				if (directiveName = directives[attribute.name]) {
					element[directiveName] = element_processDirective(attribute.value, parser);
				}

					// on-click etc
				else if (match = proxyEventPattern.exec(attribute.name)) {
					if (!element.v) element.v = {};
					directive = element_processDirective(attribute.value, parser);
					addProxyEvent(match[1], directive);
				} else {
					if (!parser.sanitizeEventAttributes || !onPattern.test(attribute.name)) {
						if (!element.a) element.a = {};
						element.a[attribute.name] = attribute.value || (attribute.value === "" ? "" : 0);
					}
				}
			}

				// {{#if foo}}class='foo'{{/if}}
			else {
				if (!element.m) element.m = [];
				element.m.push(attribute);
			}

			parser.allowWhitespace();
		}

		// allow whitespace before closing solidus
		parser.allowWhitespace();

		// self-closing solidus?
		if (parser.matchString("/")) {
			selfClosing = true;
		}

		// closing angle bracket
		if (!parser.matchString(">")) {
			return null;
		}

		var lowerCaseName = element.e.toLowerCase();
		var preserveWhitespace = parser.preserveWhitespace;

		if (!selfClosing && !voidElementNames.test(element.e)) {
			parser.elementStack.push(lowerCaseName);

			// Special case - if we open a script element, further tags should
			// be ignored unless they're a closing script element
			if (lowerCaseName === "script" || lowerCaseName === "style") {
				parser.inside = lowerCaseName;
			}

			children = [];
			partials = create(null);

			do {
				pos = parser.pos;
				remaining = parser.remaining();

				// if for example we're in an <li> element, and we see another
				// <li> tag, close the first so they become siblings
				if (!canContain(lowerCaseName, remaining)) {
					closed = true;
				}

					// closing tag
				else if (closingTag = element_readClosingTag(parser)) {
					closed = true;

					var closingTagName = closingTag.e.toLowerCase();

					// if this *isn't* the closing tag for the current element...
					if (closingTagName !== lowerCaseName) {
						// rewind parser
						parser.pos = pos;

						// if it doesn't close a parent tag, error
						if (! ~parser.elementStack.indexOf(closingTagName)) {
							var errorMessage = "Unexpected closing tag";

							// add additional help for void elements, since component names
							// might clash with them
							if (voidElementNames.test(closingTagName)) {
								errorMessage += " (<" + closingTagName + "> is a void element - it cannot contain children)";
							}

							parser.error(errorMessage);
						}
					}
				}

					// implicit close by closing section tag. TODO clean this up
				else if (child = section_readClosing(parser, { open: parser.standardDelimiters[0], close: parser.standardDelimiters[1] })) {
					closed = true;
					parser.pos = pos;
				} else {
					if (child = parser.read(PARTIAL_READERS)) {
						if (partials[child.n]) {
							parser.pos = pos;
							parser.error("Duplicate partial definition");
						}

						utils_cleanup(child.f, parser.stripComments, preserveWhitespace, !preserveWhitespace, !preserveWhitespace);

						partials[child.n] = child.f;
						hasPartials = true;
					} else {
						if (child = parser.read(READERS)) {
							children.push(child);
						} else {
							closed = true;
						}
					}
				}
			} while (!closed);

			if (children.length) {
				element.f = children;
			}

			if (hasPartials) {
				element.p = partials;
			}

			parser.elementStack.pop();
		}

		parser.inside = null;

		if (parser.sanitizeElements && parser.sanitizeElements.indexOf(lowerCaseName) !== -1) {
			return exclude;
		}

		return element;
	}

	function canContain(name, remaining) {
		var match, disallowed;

		match = /^<([a-zA-Z][a-zA-Z0-9]*)/.exec(remaining);
		disallowed = disallowedContents[name];

		if (!match || !disallowed) {
			return true;
		}

		return ! ~disallowed.indexOf(match[1].toLowerCase());
	}

	var converters_readText = readText;
	function readText(parser) {
		var index, remaining, disallowed, barrier;

		remaining = parser.remaining();

		barrier = parser.inside ? "</" + parser.inside : "<";

		if (parser.inside && !parser.interpolate[parser.inside]) {
			index = remaining.indexOf(barrier);
		} else {
			disallowed = parser.tags.map(function (t) {
				return t.open;
			});
			disallowed = disallowed.concat(parser.tags.map(function (t) {
				return "\\" + t.open;
			}));

			// http://developers.whatwg.org/syntax.html#syntax-attributes
			if (parser.inAttribute === true) {
				// we're inside an unquoted attribute value
				disallowed.push("\"", "'", "=", "<", ">", "`");
			} else if (parser.inAttribute) {
				// quoted attribute value
				disallowed.push(parser.inAttribute);
			} else {
				disallowed.push(barrier);
			}

			index = getLowestIndex(remaining, disallowed);
		}

		if (!index) {
			return null;
		}

		if (index === -1) {
			index = remaining.length;
		}

		parser.pos += index;

		return parser.inside ? remaining.substr(0, index) : decodeCharacterReferences(remaining.substr(0, index));
	}

	var utils_escapeRegExp = escapeRegExp;
	var utils_escapeRegExp__pattern = /[-/\\^$*+?.()|[\]{}]/g;
	function escapeRegExp(str) {
		return str.replace(utils_escapeRegExp__pattern, "\\$&");
	}

	var converters_readPartialDefinitionComment = readPartialDefinitionComment;

	var startPattern = /^<!--\s*/,
		namePattern = /s*>\s*([a-zA-Z_$][-a-zA-Z_$0-9]*)\s*/,
		finishPattern = /\s*-->/,
		child;

	function readPartialDefinitionComment(parser) {
		var firstPos = parser.pos,
			open = parser.standardDelimiters[0],
			close = parser.standardDelimiters[1],
			content = undefined,
			closed = undefined;

		if (!parser.matchPattern(startPattern) || !parser.matchString(open)) {
			parser.pos = firstPos;
			return null;
		}

		var name = parser.matchPattern(namePattern);

		warnOnceIfDebug("Inline partial comments are deprecated.\nUse this...\n  {{#partial " + name + "}} ... {{/partial}}\n\n...instead of this:\n  <!-- {{>" + name + "}} --> ... <!-- {{/" + name + "}} -->'");

		// make sure the rest of the comment is in the correct place
		if (!parser.matchString(close) || !parser.matchPattern(finishPattern)) {
			parser.pos = firstPos;
			return null;
		}

		content = [];

		var endPattern = new RegExp("^<!--\\s*" + utils_escapeRegExp(open) + "\\s*\\/\\s*" + name + "\\s*" + utils_escapeRegExp(close) + "\\s*-->");

		do {
			if (parser.matchPattern(endPattern)) {
				closed = true;
			} else {
				child = parser.read(READERS);
				if (!child) {
					parser.error("expected closing comment ('<!-- " + open + "/" + name + "" + close + " -->')");
				}

				content.push(child);
			}
		} while (!closed);

		return {
			t: INLINE_PARTIAL,
			f: content,
			n: name
		};
	}

	var converters_readPartialDefinitionSection = readPartialDefinitionSection;
	var partialDefinitionSectionPattern = /^#\s*partial\s+/;
	function readPartialDefinitionSection(parser) {
		var start, name, content, child, closed;

		start = parser.pos;

		var delimiters = parser.standardDelimiters;

		if (!parser.matchString(delimiters[0])) {
			return null;
		}

		if (!parser.matchPattern(partialDefinitionSectionPattern)) {
			parser.pos = start;
			return null;
		}

		name = parser.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-]*/);

		if (!name) {
			parser.error("expected legal partial name");
		}

		if (!parser.matchString(delimiters[1])) {
			parser.error("Expected closing delimiter '" + delimiters[1] + "'");
		}

		content = [];

		do {
			// TODO clean this up
			if (child = section_readClosing(parser, { open: parser.standardDelimiters[0], close: parser.standardDelimiters[1] })) {
				if (!child.r === "partial") {
					parser.error("Expected " + delimiters[0] + "/partial" + delimiters[1]);
				}

				closed = true;
			} else {
				child = parser.read(READERS);

				if (!child) {
					parser.error("Expected " + delimiters[0] + "/partial" + delimiters[1]);
				}

				content.push(child);
			}
		} while (!closed);

		return {
			t: INLINE_PARTIAL,
			n: name,
			f: content
		};
	}

	var converters_readTemplate = readTemplate;
	function readTemplate(parser) {
		var fragment = [];
		var partials = create(null);
		var hasPartials = false;

		var preserveWhitespace = parser.preserveWhitespace;

		while (parser.pos < parser.str.length) {
			var pos = parser.pos,
				item = undefined,
				partial = undefined;

			if (partial = parser.read(PARTIAL_READERS)) {
				if (partials[partial.n]) {
					parser.pos = pos;
					parser.error("Duplicated partial definition");
				}

				utils_cleanup(partial.f, parser.stripComments, preserveWhitespace, !preserveWhitespace, !preserveWhitespace);

				partials[partial.n] = partial.f;
				hasPartials = true;
			} else if (item = parser.read(READERS)) {
				fragment.push(item);
			} else {
				parser.error("Unexpected template content");
			}
		}

		var result = {
			v: TEMPLATE_VERSION,
			t: fragment
		};

		if (hasPartials) {
			result.p = partials;
		}

		return result;
	}

	var _parse = parse;

	var STANDARD_READERS = [mustache_readPartial, mustache_readUnescaped, mustache_readSection, mustache_readYielder, mustache_readInterpolator, readMustacheComment];
	var TRIPLE_READERS = [mustache_readTriple];
	var STATIC_READERS = [mustache_readUnescaped, mustache_readSection, mustache_readInterpolator]; // TODO does it make sense to have a static section?

	var StandardParser = undefined;
	function parse(template, options) {
		return new StandardParser(template, options || {}).result;
	}

	var READERS = [converters_readMustache, converters_readHtmlComment, converters_readElement, converters_readText];
	var PARTIAL_READERS = [converters_readPartialDefinitionComment, converters_readPartialDefinitionSection];

	StandardParser = parse_Parser.extend({
		init: function (str, options) {
			var tripleDelimiters = options.tripleDelimiters || ["{{{", "}}}"],
				staticDelimiters = options.staticDelimiters || ["[[", "]]"],
				staticTripleDelimiters = options.staticTripleDelimiters || ["[[[", "]]]"];

			this.standardDelimiters = options.delimiters || ["{{", "}}"];

			this.tags = [{ isStatic: false, isTriple: false, open: this.standardDelimiters[0], close: this.standardDelimiters[1], readers: STANDARD_READERS }, { isStatic: false, isTriple: true, open: tripleDelimiters[0], close: tripleDelimiters[1], readers: TRIPLE_READERS }, { isStatic: true, isTriple: false, open: staticDelimiters[0], close: staticDelimiters[1], readers: STATIC_READERS }, { isStatic: true, isTriple: true, open: staticTripleDelimiters[0], close: staticTripleDelimiters[1], readers: TRIPLE_READERS }];

			this.sortMustacheTags();

			this.sectionDepth = 0;
			this.elementStack = [];

			this.interpolate = {
				script: !options.interpolate || options.interpolate.script !== false,
				style: !options.interpolate || options.interpolate.style !== false
			};

			if (options.sanitize === true) {
				options.sanitize = {
					// blacklist from https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json
					elements: "applet base basefont body frame frameset head html isindex link meta noframes noscript object param script style title".split(" "),
					eventAttributes: true
				};
			}

			this.stripComments = options.stripComments !== false;
			this.preserveWhitespace = options.preserveWhitespace;
			this.sanitizeElements = options.sanitize && options.sanitize.elements;
			this.sanitizeEventAttributes = options.sanitize && options.sanitize.eventAttributes;
			this.includeLinePositions = options.includeLinePositions;
		},

		postProcess: function (result) {
			// special case - empty string
			if (!result.length) {
				return { t: [], v: TEMPLATE_VERSION };
			}

			if (this.sectionDepth > 0) {
				this.error("A section was left open");
			}

			utils_cleanup(result[0].t, this.stripComments, this.preserveWhitespace, !this.preserveWhitespace, !this.preserveWhitespace);

			return result[0];
		},

		converters: [converters_readTemplate],

		sortMustacheTags: function () {
			// Sort in order of descending opening delimiter length (longer first),
			// to protect against opening delimiters being substrings of each other
			this.tags.sort(function (a, b) {
				return b.open.length - a.open.length;
			});
		}
	});

	var parseOptions = ["preserveWhitespace", "sanitize", "stripComments", "delimiters", "tripleDelimiters", "interpolate"];

	var parser = {
		fromId: fromId, isHashedId: isHashedId, isParsed: isParsed, getParseOptions: getParseOptions, createHelper: template_parser__createHelper,
		parse: doParse
	};

	function template_parser__createHelper(parseOptions) {
		var helper = create(parser);
		helper.parse = function (template, options) {
			return doParse(template, options || parseOptions);
		};
		return helper;
	}

	function doParse(template, parseOptions) {
		if (!_parse) {
			throw new Error("Missing Ractive.parse - cannot parse template. Either preparse or use the version that includes the parser");
		}

		return _parse(template, parseOptions || this.options);
	}

	function fromId(id, options) {
		var template;

		if (!isClient) {
			if (options && options.noThrow) {
				return;
			}
			throw new Error("Cannot retrieve template #" + id + " as Ractive is not running in a browser.");
		}

		if (isHashedId(id)) {
			id = id.substring(1);
		}

		if (!(template = document.getElementById(id))) {
			if (options && options.noThrow) {
				return;
			}
			throw new Error("Could not find template element with id #" + id);
		}

		if (template.tagName.toUpperCase() !== "SCRIPT") {
			if (options && options.noThrow) {
				return;
			}
			throw new Error("Template element with id #" + id + ", must be a <script> element");
		}

		return "textContent" in template ? template.textContent : template.innerHTML;
	}

	function isHashedId(id) {
		return id && id[0] === "#";
	}

	function isParsed(template) {
		return !(typeof template === "string");
	}

	function getParseOptions(ractive) {
		// Could be Ractive or a Component
		if (ractive.defaults) {
			ractive = ractive.defaults;
		}

		return parseOptions.reduce(function (val, key) {
			val[key] = ractive[key];
			return val;
		}, {});
	}

	var template_parser = parser;

	var templateConfigurator = {
		name: "template",

		extend: function extend(Parent, proto, options) {
			var template;

			// only assign if exists
			if ("template" in options) {
				template = options.template;

				if (typeof template === "function") {
					proto.template = template;
				} else {
					proto.template = parseIfString(template, proto);
				}
			}
		},

		init: function init(Parent, ractive, options) {
			var template, fn;

			// TODO because of prototypal inheritance, we might just be able to use
			// ractive.template, and not bother passing through the Parent object.
			// At present that breaks the test mocks' expectations
			template = "template" in options ? options.template : Parent.prototype.template;

			if (typeof template === "function") {
				fn = template;
				template = getDynamicTemplate(ractive, fn);

				ractive._config.template = {
					fn: fn,
					result: template
				};
			}

			template = parseIfString(template, ractive);

			// TODO the naming of this is confusing - ractive.template refers to [...],
			// but Component.prototype.template refers to {v:1,t:[],p:[]}...
			// it's unnecessary, because the developer never needs to access
			// ractive.template
			ractive.template = template.t;

			if (template.p) {
				extendPartials(ractive.partials, template.p);
			}
		},

		reset: function (ractive) {
			var result = resetValue(ractive),
				parsed;

			if (result) {
				parsed = parseIfString(result, ractive);

				ractive.template = parsed.t;
				extendPartials(ractive.partials, parsed.p, true);

				return true;
			}
		}
	};

	function resetValue(ractive) {
		var initial = ractive._config.template,
			result;

		// If this isn't a dynamic template, there's nothing to do
		if (!initial || !initial.fn) {
			return;
		}

		result = getDynamicTemplate(ractive, initial.fn);

		// TODO deep equality check to prevent unnecessary re-rendering
		// in the case of already-parsed templates
		if (result !== initial.result) {
			initial.result = result;
			result = parseIfString(result, ractive);
			return result;
		}
	}

	function getDynamicTemplate(ractive, fn) {
		var helper = template_template__createHelper(template_parser.getParseOptions(ractive));
		return fn.call(ractive, helper);
	}

	function template_template__createHelper(parseOptions) {
		var helper = create(template_parser);
		helper.parse = function (template, options) {
			return template_parser.parse(template, options || parseOptions);
		};
		return helper;
	}

	function parseIfString(template, ractive) {
		if (typeof template === "string") {
			// ID of an element containing the template?
			if (template[0] === "#") {
				template = template_parser.fromId(template);
			}

			template = _parse(template, template_parser.getParseOptions(ractive));
		}

			// Check that the template even exists
		else if (template == undefined) {
			throw new Error("The template cannot be " + template + ".");
		}

			// Check the parsed template has a version at all
		else if (typeof template.v !== "number") {
			throw new Error("The template parser was passed a non-string template, but the template doesn't have a version.  Make sure you're passing in the template you think you are.");
		}

			// Check we're using the correct version
		else if (template.v !== TEMPLATE_VERSION) {
			throw new Error("Mismatched template version (expected " + TEMPLATE_VERSION + ", got " + template.v + ") Please ensure you are using the latest version of Ractive.js in your build process as well as in your app");
		}

		return template;
	}

	function extendPartials(existingPartials, newPartials, overwrite) {
		if (!newPartials) return;

		// TODO there's an ambiguity here - we need to overwrite in the `reset()`
		// case, but not initially...

		for (var key in newPartials) {
			if (overwrite || !existingPartials.hasOwnProperty(key)) {
				existingPartials[key] = newPartials[key];
			}
		}
	}

	var template_template = templateConfigurator;

	var config_registries__registryNames, Registry, registries;

	config_registries__registryNames = ["adaptors", "components", "computed", "decorators", "easing", "events", "interpolators", "partials", "transitions"];

	Registry = function (name, useDefaults) {
		this.name = name;
		this.useDefaults = useDefaults;
	};

	Registry.prototype = {
		constructor: Registry,

		extend: function (Parent, proto, options) {
			this.configure(this.useDefaults ? Parent.defaults : Parent, this.useDefaults ? proto : proto.constructor, options);
		},

		init: function () { },

		configure: function (Parent, target, options) {
			var name = this.name,
				option = options[name],
				registry;

			registry = create(Parent[name]);

			for (var key in option) {
				registry[key] = option[key];
			}

			target[name] = registry;
		},

		reset: function (ractive) {
			var registry = ractive[this.name];
			var changed = false;
			Object.keys(registry).forEach(function (key) {
				var item = registry[key];
				if (item._fn) {
					if (item._fn.isOwner) {
						registry[key] = item._fn;
					} else {
						delete registry[key];
					}
					changed = true;
				}
			});
			return changed;
		}
	};

	registries = config_registries__registryNames.map(function (name) {
		return new Registry(name, name === "computed");
	});

	var config_registries = registries;

	/*this.configure(
	  this.useDefaults ? Parent.defaults : Parent,
	  ractive,
	  options );*/

	var wrapPrototype = wrap;

	function wrap(parent, name, method) {
		if (!/_super/.test(method)) {
			return method;
		}

		var wrapper = function wrapSuper() {
			var superMethod = getSuperMethod(wrapper._parent, name),
				hasSuper = ("_super" in this),
				oldSuper = this._super,
				result;

			this._super = superMethod;

			result = method.apply(this, arguments);

			if (hasSuper) {
				this._super = oldSuper;
			} else {
				delete this._super;
			}

			return result;
		};

		wrapper._parent = parent;
		wrapper._method = method;

		return wrapper;
	}

	function getSuperMethod(parent, name) {
		var value, method;

		if (name in parent) {
			value = parent[name];

			if (typeof value === "function") {
				method = value;
			} else {
				method = function returnValue() {
					return value;
				};
			}
		} else {
			method = noop;
		}

		return method;
	}

	var config_deprecate = deprecate;
	function getMessage(deprecated, correct, isError) {
		return "options." + deprecated + " has been deprecated in favour of options." + correct + "." + (isError ? " You cannot specify both options, please use options." + correct + "." : "");
	}

	function deprecateOption(options, deprecatedOption, correct) {
		if (deprecatedOption in options) {
			if (!(correct in options)) {
				warnIfDebug(getMessage(deprecatedOption, correct));
				options[correct] = options[deprecatedOption];
			} else {
				throw new Error(getMessage(deprecatedOption, correct, true));
			}
		}
	}
	function deprecate(options) {
		deprecateOption(options, "beforeInit", "onconstruct");
		deprecateOption(options, "init", "onrender");
		deprecateOption(options, "complete", "oncomplete");
		deprecateOption(options, "eventDefinitions", "events");

		// Using extend with Component instead of options,
		// like Human.extend( Spider ) means adaptors as a registry
		// gets copied to options. So we have to check if actually an array
		if (isArray(options.adaptors)) {
			deprecateOption(options, "adaptors", "adapt");
		}
	}

	var config, order, defaultKeys, custom, isBlacklisted, isStandardKey;

	custom = {
		adapt: custom_adapt,
		css: css_css,
		data: custom_data,
		template: template_template
	};

	defaultKeys = Object.keys(config_defaults);

	isStandardKey = makeObj(defaultKeys.filter(function (key) {
		return !custom[key];
	}));

	// blacklisted keys that we don't double extend
	isBlacklisted = makeObj(defaultKeys.concat(config_registries.map(function (r) {
		return r.name;
	})));

	order = [].concat(defaultKeys.filter(function (key) {
		return !config_registries[key] && !custom[key];
	}), config_registries, custom.data, custom.template, custom.css);

	config = {
		extend: function (Parent, proto, options) {
			return configure("extend", Parent, proto, options);
		},

		init: function (Parent, ractive, options) {
			return configure("init", Parent, ractive, options);
		},

		reset: function (ractive) {
			return order.filter(function (c) {
				return c.reset && c.reset(ractive);
			}).map(function (c) {
				return c.name;
			});
		},

		// this defines the order. TODO this isn't used anywhere in the codebase,
		// only in the test suite - should get rid of it
		order: order
	};

	function configure(method, Parent, target, options) {
		config_deprecate(options);

		for (var key in options) {
			if (isStandardKey.hasOwnProperty(key)) {
				var value = options[key];

				// warn the developer if they passed a function and ignore its value

				// NOTE: we allow some functions on "el" because we duck type element lists
				// and some libraries or ef'ed-up virtual browsers (phantomJS) return a
				// function object as the result of querySelector methods
				if (key !== "el" && typeof value === "function") {
					warnIfDebug("" + key + " is a Ractive option that does not expect a function and will be ignored", method === "init" ? target : null);
				} else {
					target[key] = value;
				}
			}
		}

		config_registries.forEach(function (registry) {
			registry[method](Parent, target, options);
		});

		custom_adapt[method](Parent, target, options);
		template_template[method](Parent, target, options);
		css_css[method](Parent, target, options);

		extendOtherMethods(Parent.prototype, target, options);
	}

	function extendOtherMethods(parent, target, options) {
		for (var key in options) {
			if (!isBlacklisted[key] && options.hasOwnProperty(key)) {
				var member = options[key];

				// if this is a method that overwrites a method, wrap it:
				if (typeof member === "function") {
					member = wrapPrototype(parent, key, member);
				}

				target[key] = member;
			}
		}
	}

	function makeObj(array) {
		var obj = {};
		array.forEach(function (x) {
			return obj[x] = true;
		});
		return obj;
	}

	var config_config = config;

	var prototype_bubble = Fragment$bubble;

	function Fragment$bubble() {
		this.dirtyValue = this.dirtyArgs = true;

		if (this.bound && typeof this.owner.bubble === "function") {
			this.owner.bubble();
		}
	}

	var Fragment_prototype_detach = Fragment$detach;

	function Fragment$detach() {
		var docFrag;

		if (this.items.length === 1) {
			return this.items[0].detach();
		}

		docFrag = document.createDocumentFragment();

		this.items.forEach(function (item) {
			var node = item.detach();

			// TODO The if {...} wasn't previously required - it is now, because we're
			// forcibly detaching everything to reorder sections after an update. That's
			// a non-ideal brute force approach, implemented to get all the tests to pass
			// - as soon as it's replaced with something more elegant, this should
			// revert to `docFrag.appendChild( item.detach() )`
			if (node) {
				docFrag.appendChild(node);
			}
		});

		return docFrag;
	}

	var Fragment_prototype_find = Fragment$find;

	function Fragment$find(selector) {
		var i, len, item, queryResult;

		if (this.items) {
			len = this.items.length;
			for (i = 0; i < len; i += 1) {
				item = this.items[i];

				if (item.find && (queryResult = item.find(selector))) {
					return queryResult;
				}
			}

			return null;
		}
	}

	var Fragment_prototype_findAll = Fragment$findAll;

	function Fragment$findAll(selector, query) {
		var i, len, item;

		if (this.items) {
			len = this.items.length;
			for (i = 0; i < len; i += 1) {
				item = this.items[i];

				if (item.findAll) {
					item.findAll(selector, query);
				}
			}
		}

		return query;
	}

	var Fragment_prototype_findAllComponents = Fragment$findAllComponents;

	function Fragment$findAllComponents(selector, query) {
		var i, len, item;

		if (this.items) {
			len = this.items.length;
			for (i = 0; i < len; i += 1) {
				item = this.items[i];

				if (item.findAllComponents) {
					item.findAllComponents(selector, query);
				}
			}
		}

		return query;
	}

	var Fragment_prototype_findComponent = Fragment$findComponent;

	function Fragment$findComponent(selector) {
		var len, i, item, queryResult;

		if (this.items) {
			len = this.items.length;
			for (i = 0; i < len; i += 1) {
				item = this.items[i];

				if (item.findComponent && (queryResult = item.findComponent(selector))) {
					return queryResult;
				}
			}

			return null;
		}
	}

	var prototype_findNextNode = Fragment$findNextNode;

	function Fragment$findNextNode(item) {
		var index = item.index,
			node;

		if (this.items[index + 1]) {
			node = this.items[index + 1].firstNode();
		}

			// if this is the root fragment, and there are no more items,
			// it means we're at the end...
		else if (this.owner === this.root) {
			if (!this.owner.component) {
				// TODO but something else could have been appended to
				// this.root.el, no?
				node = null;
			}

				// ...unless this is a component
			else {
				node = this.owner.component.findNextNode();
			}
		} else {
			node = this.owner.findNextNode(this);
		}

		return node;
	}

	var prototype_firstNode = Fragment$firstNode;

	function Fragment$firstNode() {
		if (this.items && this.items[0]) {
			return this.items[0].firstNode();
		}

		return null;
	}

	var shared_processItems = processItems;

	function processItems(items, values, guid, counter) {
		counter = counter || 0;

		return items.map(function (item) {
			var placeholderId, wrapped, value;

			if (item.text) {
				return item.text;
			}

			if (item.fragments) {
				return item.fragments.map(function (fragment) {
					return processItems(fragment.items, values, guid, counter);
				}).join("");
			}

			placeholderId = guid + "-" + counter++;

			if (item.keypath && (wrapped = item.root.viewmodel.wrapped[item.keypath.str])) {
				value = wrapped.value;
			} else {
				value = item.getValue();
			}

			values[placeholderId] = value;

			return "${" + placeholderId + "}";
		}).join("");
	}

	var getArgsList = Fragment$getArgsList;
	function Fragment$getArgsList() {
		var values, source, parsed, result;

		if (this.dirtyArgs) {
			source = shared_processItems(this.items, values = {}, this.root._guid);
			parsed = parseJSON("[" + source + "]", values);

			if (!parsed) {
				result = [this.toString()];
			} else {
				result = parsed.value;
			}

			this.argsList = result;
			this.dirtyArgs = false;
		}

		return this.argsList;
	}

	var getNode = Fragment$getNode;

	function Fragment$getNode() {
		var fragment = this;

		do {
			if (fragment.pElement) {
				return fragment.pElement.node;
			}
		} while (fragment = fragment.parent);

		return this.root.detached || this.root.el;
	}

	var prototype_getValue = Fragment$getValue;
	function Fragment$getValue() {
		var values, source, parsed, result;

		if (this.dirtyValue) {
			source = shared_processItems(this.items, values = {}, this.root._guid);
			parsed = parseJSON(source, values);

			if (!parsed) {
				result = this.toString();
			} else {
				result = parsed.value;
			}

			this.value = result;
			this.dirtyValue = false;
		}

		return this.value;
	}

	var shared_detach = function () {
		return detachNode(this.node);
	};

	var Text = function (options) {
		this.type = TEXT;
		this.text = options.template;
	};

	Text.prototype = {
		detach: shared_detach,

		firstNode: function () {
			return this.node;
		},

		render: function () {
			if (!this.node) {
				this.node = document.createTextNode(this.text);
			}

			return this.node;
		},

		toString: function (escape) {
			return escape ? escapeHtml(this.text) : this.text;
		},

		unrender: function (shouldDestroy) {
			if (shouldDestroy) {
				return this.detach();
			}
		}
	};

	var items_Text = Text;

	var shared_unbind = shared_unbind__unbind;

	function shared_unbind__unbind() {
		if (this.registered) {
			// this was registered as a dependant
			this.root.viewmodel.unregister(this.keypath, this);
		}

		if (this.resolver) {
			this.resolver.unbind();
		}
	}

	var Mustache_getValue = Mustache$getValue;

	function Mustache$getValue() {
		return this.value;
	}

	var ReferenceResolver = function (owner, ref, callback) {
		var keypath;

		this.ref = ref;
		this.resolved = false;

		this.root = owner.root;
		this.parentFragment = owner.parentFragment;
		this.callback = callback;

		keypath = shared_resolveRef(owner.root, ref, owner.parentFragment);
		if (keypath != undefined) {
			this.resolve(keypath);
		} else {
			global_runloop.addUnresolved(this);
		}
	};

	ReferenceResolver.prototype = {
		resolve: function (keypath) {
			if (this.keypath && !keypath) {
				// it was resolved, and now it's not. Can happen if e.g. `bar` in
				// `{{foo[bar]}}` becomes undefined
				global_runloop.addUnresolved(this);
			}

			this.resolved = true;

			this.keypath = keypath;
			this.callback(keypath);
		},

		forceResolution: function () {
			this.resolve(getKeypath(this.ref));
		},

		rebind: function (oldKeypath, newKeypath) {
			var keypath;

			if (this.keypath != undefined) {
				keypath = this.keypath.replace(oldKeypath, newKeypath);
				// was a new keypath created?
				if (keypath !== undefined) {
					// resolve it
					this.resolve(keypath);
				}
			}
		},

		unbind: function () {
			if (!this.resolved) {
				global_runloop.removeUnresolved(this);
			}
		}
	};

	var Resolvers_ReferenceResolver = ReferenceResolver;

	var SpecialResolver = function (owner, ref, callback) {
		this.parentFragment = owner.parentFragment;
		this.ref = ref;
		this.callback = callback;

		this.rebind();
	};

	var props = {
		"@keypath": { prefix: "c", prop: ["context"] },
		"@index": { prefix: "i", prop: ["index"] },
		"@key": { prefix: "k", prop: ["key", "index"] }
	};

	function getProp(target, prop) {
		var value;
		for (var i = 0; i < prop.prop.length; i++) {
			if ((value = target[prop.prop[i]]) !== undefined) {
				return value;
			}
		}
	}

	SpecialResolver.prototype = {
		rebind: function () {
			var ref = this.ref,
				fragment = this.parentFragment,
				prop = props[ref],
				value;

			if (!prop) {
				throw new Error("Unknown special reference \"" + ref + "\" - valid references are @index, @key and @keypath");
			}

			// have we already found the nearest parent?
			if (this.cached) {
				return this.callback(getKeypath("@" + prop.prefix + getProp(this.cached, prop)));
			}

			// special case for indices, which may cross component boundaries
			if (prop.prop.indexOf("index") !== -1 || prop.prop.indexOf("key") !== -1) {
				while (fragment) {
					if (fragment.owner.currentSubtype === SECTION_EACH && (value = getProp(fragment, prop)) !== undefined) {
						this.cached = fragment;

						fragment.registerIndexRef(this);

						return this.callback(getKeypath("@" + prop.prefix + value));
					}

					// watch for component boundaries
					if (!fragment.parent && fragment.owner && fragment.owner.component && fragment.owner.component.parentFragment && !fragment.owner.component.instance.isolated) {
						fragment = fragment.owner.component.parentFragment;
					} else {
						fragment = fragment.parent;
					}
				}
			} else {
				while (fragment) {
					if ((value = getProp(fragment, prop)) !== undefined) {
						return this.callback(getKeypath("@" + prop.prefix + value.str));
					}

					fragment = fragment.parent;
				}
			}
		},

		unbind: function () {
			if (this.cached) {
				this.cached.unregisterIndexRef(this);
			}
		}
	};

	var Resolvers_SpecialResolver = SpecialResolver;

	var IndexResolver = function (owner, ref, callback) {
		this.parentFragment = owner.parentFragment;
		this.ref = ref;
		this.callback = callback;

		ref.ref.fragment.registerIndexRef(this);

		this.rebind();
	};

	IndexResolver.prototype = {
		rebind: function () {
			var index,
				ref = this.ref.ref;

			if (ref.ref.t === "k") {
				index = "k" + ref.fragment.key;
			} else {
				index = "i" + ref.fragment.index;
			}

			if (index !== undefined) {
				this.callback(getKeypath("@" + index));
			}
		},

		unbind: function () {
			this.ref.ref.fragment.unregisterIndexRef(this);
		}
	};

	var Resolvers_IndexResolver = IndexResolver;

	var Resolvers_findIndexRefs = findIndexRefs;

	function findIndexRefs(fragment, refName) {
		var result = {},
			refs,
			fragRefs,
			ref,
			i,
			owner,
			hit = false;

		if (!refName) {
			result.refs = refs = {};
		}

		while (fragment) {
			if ((owner = fragment.owner) && (fragRefs = owner.indexRefs)) {

				// we're looking for a particular ref, and it's here
				if (refName && (ref = owner.getIndexRef(refName))) {
					result.ref = {
						fragment: fragment,
						ref: ref
					};
					return result;
				}

					// we're collecting refs up-tree
				else if (!refName) {
					for (i in fragRefs) {
						ref = fragRefs[i];

						// don't overwrite existing refs - they should shadow parents
						if (!refs[ref.n]) {
							hit = true;
							refs[ref.n] = {
								fragment: fragment,
								ref: ref
							};
						}
					}
				}
			}

			// watch for component boundaries
			if (!fragment.parent && fragment.owner && fragment.owner.component && fragment.owner.component.parentFragment && !fragment.owner.component.instance.isolated) {
				result.componentBoundary = true;
				fragment = fragment.owner.component.parentFragment;
			} else {
				fragment = fragment.parent;
			}
		}

		if (!hit) {
			return undefined;
		} else {
			return result;
		}
	}

	findIndexRefs.resolve = function resolve(indices) {
		var refs = {},
			k,
			ref;

		for (k in indices.refs) {
			ref = indices.refs[k];
			refs[ref.ref.n] = ref.ref.t === "k" ? ref.fragment.key : ref.fragment.index;
		}

		return refs;
	};

	var Resolvers_createReferenceResolver = createReferenceResolver;
	function createReferenceResolver(owner, ref, callback) {
		var indexRef;

		if (ref.charAt(0) === "@") {
			return new Resolvers_SpecialResolver(owner, ref, callback);
		}

		if (indexRef = Resolvers_findIndexRefs(owner.parentFragment, ref)) {
			return new Resolvers_IndexResolver(owner, indexRef, callback);
		}

		return new Resolvers_ReferenceResolver(owner, ref, callback);
	}

	var shared_getFunctionFromString = getFunctionFromString;
	var cache = {};
	function getFunctionFromString(str, i) {
		var fn, args;

		if (cache[str]) {
			return cache[str];
		}

		args = [];
		while (i--) {
			args[i] = "_" + i;
		}

		fn = new Function(args.join(","), "return(" + str + ")");

		cache[str] = fn;
		return fn;
	}

	var ExpressionResolver,
		Resolvers_ExpressionResolver__bind = Function.prototype.bind;

	ExpressionResolver = function (owner, parentFragment, expression, callback) {
		var _this = this;

		var ractive;

		ractive = owner.root;

		this.root = ractive;
		this.parentFragment = parentFragment;
		this.callback = callback;
		this.owner = owner;
		this.str = expression.s;
		this.keypaths = [];

		// Create resolvers for each reference
		this.pending = expression.r.length;
		this.refResolvers = expression.r.map(function (ref, i) {
			return Resolvers_createReferenceResolver(_this, ref, function (keypath) {
				_this.resolve(i, keypath);
			});
		});

		this.ready = true;
		this.bubble();
	};

	ExpressionResolver.prototype = {
		bubble: function () {
			if (!this.ready) {
				return;
			}

			this.uniqueString = getUniqueString(this.str, this.keypaths);
			this.keypath = createExpressionKeypath(this.uniqueString);

			this.createEvaluator();
			this.callback(this.keypath);
		},

		unbind: function () {
			var resolver;

			while (resolver = this.refResolvers.pop()) {
				resolver.unbind();
			}
		},

		resolve: function (index, keypath) {
			this.keypaths[index] = keypath;
			this.bubble();
		},

		createEvaluator: function () {
			var _this = this;

			var computation, valueGetters, signature, keypath, fn;

			keypath = this.keypath;
			computation = this.root.viewmodel.computations[keypath.str];

			// only if it doesn't exist yet!
			if (!computation) {
				fn = shared_getFunctionFromString(this.str, this.refResolvers.length);

				valueGetters = this.keypaths.map(function (keypath) {
					var value;

					if (keypath === "undefined") {
						return function () {
							return undefined;
						};
					}

					// 'special' keypaths encode a value
					if (keypath.isSpecial) {
						value = keypath.value;
						return function () {
							return value;
						};
					}

					return function () {
						var value = _this.root.viewmodel.get(keypath, { noUnwrap: true, fullRootGet: true });
						if (typeof value === "function") {
							value = wrapFunction(value, _this.root);
						}
						return value;
					};
				});

				signature = {
					deps: this.keypaths.filter(isValidDependency),
					getter: function () {
						var args = valueGetters.map(call);
						return fn.apply(null, args);
					}
				};

				computation = this.root.viewmodel.compute(keypath, signature);
			} else {
				this.root.viewmodel.mark(keypath);
			}
		},

		rebind: function (oldKeypath, newKeypath) {
			// TODO only bubble once, no matter how many references are affected by the rebind
			this.refResolvers.forEach(function (r) {
				return r.rebind(oldKeypath, newKeypath);
			});
		}
	};

	var Resolvers_ExpressionResolver = ExpressionResolver;

	function call(value) {
		return value.call();
	}

	function getUniqueString(str, keypaths) {
		// get string that is unique to this expression
		return str.replace(/_([0-9]+)/g, function (match, $1) {
			var keypath, value;

			// make sure we're not replacing a non-keypath _[0-9]
			if (+$1 >= keypaths.length) {
				return "_" + $1;
			}

			keypath = keypaths[$1];

			if (keypath === undefined) {
				return "undefined";
			}

			if (keypath.isSpecial) {
				value = keypath.value;
				return typeof value === "number" ? value : "\"" + value + "\"";
			}

			return keypath.str;
		});
	}

	function createExpressionKeypath(uniqueString) {
		// Sanitize by removing any periods or square brackets. Otherwise
		// we can't split the keypath into keys!
		// Remove asterisks too, since they mess with pattern observers
		return getKeypath("${" + uniqueString.replace(/[\.\[\]]/g, "-").replace(/\*/, "#MUL#") + "}");
	}

	function isValidDependency(keypath) {
		return keypath !== undefined && keypath[0] !== "@";
	}

	function wrapFunction(fn, ractive) {
		var wrapped, prop, key;

		if (fn.__ractive_nowrap) {
			return fn;
		}

		prop = "__ractive_" + ractive._guid;
		wrapped = fn[prop];

		if (wrapped) {
			return wrapped;
		} else if (/this/.test(fn.toString())) {
			defineProperty(fn, prop, {
				value: Resolvers_ExpressionResolver__bind.call(fn, ractive),
				configurable: true
			});

			// Add properties/methods to wrapped function
			for (key in fn) {
				if (fn.hasOwnProperty(key)) {
					fn[prop][key] = fn[key];
				}
			}

			ractive._boundFunctions.push({
				fn: fn,
				prop: prop
			});

			return fn[prop];
		}

		defineProperty(fn, "__ractive_nowrap", {
			value: fn
		});

		return fn.__ractive_nowrap;
	}

	var MemberResolver = function (template, resolver, parentFragment) {
		var _this = this;

		this.resolver = resolver;
		this.root = resolver.root;
		this.parentFragment = parentFragment;
		this.viewmodel = resolver.root.viewmodel;

		if (typeof template === "string") {
			this.value = template;
		}

			// Simple reference?
		else if (template.t === REFERENCE) {
			this.refResolver = Resolvers_createReferenceResolver(this, template.n, function (keypath) {
				_this.resolve(keypath);
			});
		}

			// Otherwise we have an expression in its own right
		else {
			new Resolvers_ExpressionResolver(resolver, parentFragment, template, function (keypath) {
				_this.resolve(keypath);
			});
		}
	};

	MemberResolver.prototype = {
		resolve: function (keypath) {
			if (this.keypath) {
				this.viewmodel.unregister(this.keypath, this);
			}

			this.keypath = keypath;
			this.value = this.viewmodel.get(keypath);

			this.bind();

			this.resolver.bubble();
		},

		bind: function () {
			this.viewmodel.register(this.keypath, this);
		},

		rebind: function (oldKeypath, newKeypath) {
			if (this.refResolver) {
				this.refResolver.rebind(oldKeypath, newKeypath);
			}
		},

		setValue: function (value) {
			this.value = value;
			this.resolver.bubble();
		},

		unbind: function () {
			if (this.keypath) {
				this.viewmodel.unregister(this.keypath, this);
			}

			if (this.refResolver) {
				this.refResolver.unbind();
			}
		},

		forceResolution: function () {
			if (this.refResolver) {
				this.refResolver.forceResolution();
			}
		}
	};

	var ReferenceExpressionResolver_MemberResolver = MemberResolver;

	var ReferenceExpressionResolver = function (mustache, template, callback) {
		var _this = this;

		var ractive, ref, keypath, parentFragment;

		this.parentFragment = parentFragment = mustache.parentFragment;
		this.root = ractive = mustache.root;
		this.mustache = mustache;

		this.ref = ref = template.r;
		this.callback = callback;

		this.unresolved = [];

		// Find base keypath
		if (keypath = shared_resolveRef(ractive, ref, parentFragment)) {
			this.base = keypath;
		} else {
			this.baseResolver = new Resolvers_ReferenceResolver(this, ref, function (keypath) {
				_this.base = keypath;
				_this.baseResolver = null;
				_this.bubble();
			});
		}

		// Find values for members, or mark them as unresolved
		this.members = template.m.map(function (template) {
			return new ReferenceExpressionResolver_MemberResolver(template, _this, parentFragment);
		});

		this.ready = true;
		this.bubble(); // trigger initial resolution if possible
	};

	ReferenceExpressionResolver.prototype = {
		getKeypath: function () {
			var values = this.members.map(ReferenceExpressionResolver_ReferenceExpressionResolver__getValue);

			if (!values.every(isDefined) || this.baseResolver) {
				return null;
			}

			return this.base.join(values.join("."));
		},

		bubble: function () {
			if (!this.ready || this.baseResolver) {
				return;
			}

			this.callback(this.getKeypath());
		},

		unbind: function () {
			this.members.forEach(methodCallers__unbind);
		},

		rebind: function (oldKeypath, newKeypath) {
			var changed;

			if (this.base) {
				var newBase = this.base.replace(oldKeypath, newKeypath);
				if (newBase && newBase !== this.base) {
					this.base = newBase;
					changed = true;
				}
			}

			this.members.forEach(function (members) {
				if (members.rebind(oldKeypath, newKeypath)) {
					changed = true;
				}
			});

			if (changed) {
				this.bubble();
			}
		},

		forceResolution: function () {
			if (this.baseResolver) {
				this.base = getKeypath(this.ref);

				this.baseResolver.unbind();
				this.baseResolver = null;
			}

			this.members.forEach(forceResolution);
			this.bubble();
		}
	};

	function ReferenceExpressionResolver_ReferenceExpressionResolver__getValue(member) {
		return member.value;
	}

	function isDefined(value) {
		return value != undefined;
	}

	function forceResolution(member) {
		member.forceResolution();
	}

	var ReferenceExpressionResolver_ReferenceExpressionResolver = ReferenceExpressionResolver;

	var Mustache_initialise = Mustache$init;
	function Mustache$init(mustache, options) {

		var ref, parentFragment, template;

		parentFragment = options.parentFragment;
		template = options.template;

		mustache.root = parentFragment.root;
		mustache.parentFragment = parentFragment;
		mustache.pElement = parentFragment.pElement;

		mustache.template = options.template;
		mustache.index = options.index || 0;
		mustache.isStatic = options.template.s;

		mustache.type = options.template.t;

		mustache.registered = false;

		// if this is a simple mustache, with a reference, we just need to resolve
		// the reference to a keypath
		if (ref = template.r) {
			mustache.resolver = Resolvers_createReferenceResolver(mustache, ref, resolve);
		}

		// if it's an expression, we have a bit more work to do
		if (options.template.x) {
			mustache.resolver = new Resolvers_ExpressionResolver(mustache, parentFragment, options.template.x, resolveAndRebindChildren);
		}

		if (options.template.rx) {
			mustache.resolver = new ReferenceExpressionResolver_ReferenceExpressionResolver(mustache, options.template.rx, resolveAndRebindChildren);
		}

		// Special case - inverted sections
		if (mustache.template.n === SECTION_UNLESS && !mustache.hasOwnProperty("value")) {
			mustache.setValue(undefined);
		}

		function resolve(keypath) {
			mustache.resolve(keypath);
		}

		function resolveAndRebindChildren(newKeypath) {
			var oldKeypath = mustache.keypath;

			if (newKeypath != oldKeypath) {
				mustache.resolve(newKeypath);

				if (oldKeypath !== undefined) {
					mustache.fragments && mustache.fragments.forEach(function (f) {
						f.rebind(oldKeypath, newKeypath);
					});
				}
			}
		}
	}

	var Mustache_resolve = Mustache$resolve;

	function Mustache$resolve(keypath) {
		var wasResolved, value, twowayBinding;

		// 'Special' keypaths, e.g. @foo or @7, encode a value
		if (keypath && keypath.isSpecial) {
			this.keypath = keypath;
			this.setValue(keypath.value);
			return;
		}

		// If we resolved previously, we need to unregister
		if (this.registered) {
			// undefined or null
			this.root.viewmodel.unregister(this.keypath, this);
			this.registered = false;

			wasResolved = true;
		}

		this.keypath = keypath;

		// If the new keypath exists, we need to register
		// with the viewmodel
		if (keypath != undefined) {
			// undefined or null
			value = this.root.viewmodel.get(keypath);
			this.root.viewmodel.register(keypath, this);

			this.registered = true;
		}

		// Either way we need to queue up a render (`value`
		// will be `undefined` if there's no keypath)
		this.setValue(value);

		// Two-way bindings need to point to their new target keypath
		if (wasResolved && (twowayBinding = this.twowayBinding)) {
			twowayBinding.rebound();
		}
	}

	var Mustache_rebind = Mustache$rebind;

	function Mustache$rebind(oldKeypath, newKeypath) {
		// Children first
		if (this.fragments) {
			this.fragments.forEach(function (f) {
				return f.rebind(oldKeypath, newKeypath);
			});
		}

		// Expression mustache?
		if (this.resolver) {
			this.resolver.rebind(oldKeypath, newKeypath);
		}
	}

	var Mustache = {
		getValue: Mustache_getValue,
		init: Mustache_initialise,
		resolve: Mustache_resolve,
		rebind: Mustache_rebind
	};

	var Interpolator = function (options) {
		this.type = INTERPOLATOR;
		Mustache.init(this, options);
	};

	Interpolator.prototype = {
		update: function () {
			this.node.data = this.value == undefined ? "" : this.value;
		},
		resolve: Mustache.resolve,
		rebind: Mustache.rebind,
		detach: shared_detach,

		unbind: shared_unbind,

		render: function () {
			if (!this.node) {
				this.node = document.createTextNode(safeToStringValue(this.value));
			}

			return this.node;
		},

		unrender: function (shouldDestroy) {
			if (shouldDestroy) {
				detachNode(this.node);
			}
		},

		getValue: Mustache.getValue,

		// TEMP
		setValue: function (value) {
			var wrapper;

			// TODO is there a better way to approach this?
			if (this.keypath && (wrapper = this.root.viewmodel.wrapped[this.keypath.str])) {
				value = wrapper.get();
			}

			if (!isEqual(value, this.value)) {
				this.value = value;
				this.parentFragment.bubble();

				if (this.node) {
					global_runloop.addView(this);
				}
			}
		},

		firstNode: function () {
			return this.node;
		},

		toString: function (escape) {
			var string = "" + safeToStringValue(this.value);
			return escape ? escapeHtml(string) : string;
		}
	};

	var items_Interpolator = Interpolator;

	var Section_prototype_bubble = Section$bubble;

	function Section$bubble() {
		this.parentFragment.bubble();
	}

	var Section_prototype_detach = Section$detach;

	function Section$detach() {
		var docFrag;

		if (this.fragments.length === 1) {
			return this.fragments[0].detach();
		}

		docFrag = document.createDocumentFragment();

		this.fragments.forEach(function (item) {
			docFrag.appendChild(item.detach());
		});

		return docFrag;
	}

	var find = Section$find;

	function Section$find(selector) {
		var i, len, queryResult;

		len = this.fragments.length;
		for (i = 0; i < len; i += 1) {
			if (queryResult = this.fragments[i].find(selector)) {
				return queryResult;
			}
		}

		return null;
	}

	var findAll = Section$findAll;

	function Section$findAll(selector, query) {
		var i, len;

		len = this.fragments.length;
		for (i = 0; i < len; i += 1) {
			this.fragments[i].findAll(selector, query);
		}
	}

	var findAllComponents = Section$findAllComponents;

	function Section$findAllComponents(selector, query) {
		var i, len;

		len = this.fragments.length;
		for (i = 0; i < len; i += 1) {
			this.fragments[i].findAllComponents(selector, query);
		}
	}

	var findComponent = Section$findComponent;

	function Section$findComponent(selector) {
		var i, len, queryResult;

		len = this.fragments.length;
		for (i = 0; i < len; i += 1) {
			if (queryResult = this.fragments[i].findComponent(selector)) {
				return queryResult;
			}
		}

		return null;
	}

	var findNextNode = Section$findNextNode;

	function Section$findNextNode(fragment) {
		if (this.fragments[fragment.index + 1]) {
			return this.fragments[fragment.index + 1].firstNode();
		}

		return this.parentFragment.findNextNode(this);
	}

	var firstNode = Section$firstNode;

	function Section$firstNode() {
		var len, i, node;

		if (len = this.fragments.length) {
			for (i = 0; i < len; i += 1) {
				if (node = this.fragments[i].firstNode()) {
					return node;
				}
			}
		}

		return this.parentFragment.findNextNode(this);
	}

	var shuffle = Section$shuffle;

	function Section$shuffle(newIndices) {
		var _this = this;

		var parentFragment, firstChange, i, newLength, reboundFragments, fragmentOptions, fragment;

		// short circuit any double-updates, and ensure that this isn't applied to
		// non-list sections
		if (this.shuffling || this.unbound || this.currentSubtype !== SECTION_EACH) {
			return;
		}

		this.shuffling = true;
		global_runloop.scheduleTask(function () {
			return _this.shuffling = false;
		});

		parentFragment = this.parentFragment;

		reboundFragments = [];

		// TODO: need to update this
		// first, rebind existing fragments
		newIndices.forEach(function (newIndex, oldIndex) {
			var fragment, by, oldKeypath, newKeypath, deps;

			if (newIndex === oldIndex) {
				reboundFragments[newIndex] = _this.fragments[oldIndex];
				return;
			}

			fragment = _this.fragments[oldIndex];

			if (firstChange === undefined) {
				firstChange = oldIndex;
			}

			// does this fragment need to be torn down?
			if (newIndex === -1) {
				_this.fragmentsToUnrender.push(fragment);
				fragment.unbind();
				return;
			}

			// Otherwise, it needs to be rebound to a new index
			by = newIndex - oldIndex;
			oldKeypath = _this.keypath.join(oldIndex);
			newKeypath = _this.keypath.join(newIndex);

			fragment.index = newIndex;

			// notify any registered index refs directly
			if (deps = fragment.registeredIndexRefs) {
				deps.forEach(shuffle__blindRebind);
			}

			fragment.rebind(oldKeypath, newKeypath);
			reboundFragments[newIndex] = fragment;
		});

		newLength = this.root.viewmodel.get(this.keypath).length;

		// If nothing changed with the existing fragments, then we start adding
		// new fragments at the end...
		if (firstChange === undefined) {
			// ...unless there are no new fragments to add
			if (this.length === newLength) {
				return;
			}

			firstChange = this.length;
		}

		this.length = this.fragments.length = newLength;

		if (this.rendered) {
			global_runloop.addView(this);
		}

		// Prepare new fragment options
		fragmentOptions = {
			template: this.template.f,
			root: this.root,
			owner: this
		};

		// Add as many new fragments as we need to, or add back existing
		// (detached) fragments
		for (i = firstChange; i < newLength; i += 1) {
			fragment = reboundFragments[i];

			if (!fragment) {
				this.fragmentsToCreate.push(i);
			}

			this.fragments[i] = fragment;
		}
	}

	function shuffle__blindRebind(dep) {
		// the keypath doesn't actually matter here as it won't have changed
		dep.rebind("", "");
	}

	var prototype_rebind = function (oldKeypath, newKeypath) {
		Mustache.rebind.call(this, oldKeypath, newKeypath);
	};

	var Section_prototype_render = Section$render;

	function Section$render() {
		var _this = this;

		this.docFrag = document.createDocumentFragment();

		this.fragments.forEach(function (f) {
			return _this.docFrag.appendChild(f.render());
		});

		this.renderedFragments = this.fragments.slice();
		this.fragmentsToRender = [];

		this.rendered = true;
		return this.docFrag;
	}

	var setValue = Section$setValue;

	function Section$setValue(value) {
		var _this = this;

		var wrapper, fragmentOptions;

		if (this.updating) {
			// If a child of this section causes a re-evaluation - for example, an
			// expression refers to a function that mutates the array that this
			// section depends on - we'll end up with a double rendering bug (see
			// https://github.com/ractivejs/ractive/issues/748). This prevents it.
			return;
		}

		this.updating = true;

		// with sections, we need to get the fake value if we have a wrapped object
		if (this.keypath && (wrapper = this.root.viewmodel.wrapped[this.keypath.str])) {
			value = wrapper.get();
		}

		// If any fragments are awaiting creation after a splice,
		// this is the place to do it
		if (this.fragmentsToCreate.length) {
			fragmentOptions = {
				template: this.template.f || [],
				root: this.root,
				pElement: this.pElement,
				owner: this
			};

			this.fragmentsToCreate.forEach(function (index) {
				var fragment;

				fragmentOptions.context = _this.keypath.join(index);
				fragmentOptions.index = index;

				fragment = new virtualdom_Fragment(fragmentOptions);
				_this.fragmentsToRender.push(_this.fragments[index] = fragment);
			});

			this.fragmentsToCreate.length = 0;
		} else if (reevaluateSection(this, value)) {
			this.bubble();

			if (this.rendered) {
				global_runloop.addView(this);
			}
		}

		this.value = value;
		this.updating = false;
	}

	function changeCurrentSubtype(section, value, obj) {
		if (value === SECTION_EACH) {
			// make sure ref type is up to date for key or value indices
			if (section.indexRefs && section.indexRefs[0]) {
				var ref = section.indexRefs[0];

				// when switching flavors, make sure the section gets updated
				if (obj && ref.t === "i" || !obj && ref.t === "k") {
					// if switching from object to list, unbind all of the old fragments
					if (!obj) {
						section.length = 0;
						section.fragmentsToUnrender = section.fragments.slice(0);
						section.fragmentsToUnrender.forEach(function (f) {
							return f.unbind();
						});
					}
				}

				ref.t = obj ? "k" : "i";
			}
		}

		section.currentSubtype = value;
	}

	function reevaluateSection(section, value) {
		var fragmentOptions = {
			template: section.template.f || [],
			root: section.root,
			pElement: section.parentFragment.pElement,
			owner: section
		};

		section.hasContext = true;

		// If we already know the section type, great
		// TODO can this be optimised? i.e. pick an reevaluateSection function during init
		// and avoid doing this each time?
		if (section.subtype) {
			switch (section.subtype) {
				case SECTION_IF:
					section.hasContext = false;
					return reevaluateConditionalSection(section, value, false, fragmentOptions);

				case SECTION_UNLESS:
					section.hasContext = false;
					return reevaluateConditionalSection(section, value, true, fragmentOptions);

				case SECTION_WITH:
					return reevaluateContextSection(section, fragmentOptions);

				case SECTION_IF_WITH:
					return reevaluateConditionalContextSection(section, value, fragmentOptions);

				case SECTION_EACH:
					if (isObject(value)) {
						changeCurrentSubtype(section, section.subtype, true);
						return reevaluateListObjectSection(section, value, fragmentOptions);
					}

					// Fallthrough - if it's a conditional or an array we need to continue
			}
		}

		// Otherwise we need to work out what sort of section we're dealing with
		section.ordered = !!isArrayLike(value);

		// Ordered list section
		if (section.ordered) {
			changeCurrentSubtype(section, SECTION_EACH, false);
			return reevaluateListSection(section, value, fragmentOptions);
		}

		// Unordered list, or context
		if (isObject(value) || typeof value === "function") {
			// Index reference indicates section should be treated as a list
			if (section.template.i) {
				changeCurrentSubtype(section, SECTION_EACH, true);
				return reevaluateListObjectSection(section, value, fragmentOptions);
			}

			// Otherwise, object provides context for contents
			changeCurrentSubtype(section, SECTION_WITH, false);
			return reevaluateContextSection(section, fragmentOptions);
		}

		// Conditional section
		changeCurrentSubtype(section, SECTION_IF, false);
		section.hasContext = false;
		return reevaluateConditionalSection(section, value, false, fragmentOptions);
	}

	function reevaluateListSection(section, value, fragmentOptions) {
		var i, length, fragment;

		length = value.length;

		if (length === section.length) {
			// Nothing to do
			return false;
		}

		// if the array is shorter than it was previously, remove items
		if (length < section.length) {
			section.fragmentsToUnrender = section.fragments.splice(length, section.length - length);
			section.fragmentsToUnrender.forEach(methodCallers__unbind);
		}

			// otherwise...
		else {
			if (length > section.length) {
				// add any new ones
				for (i = section.length; i < length; i += 1) {
					// append list item to context stack
					fragmentOptions.context = section.keypath.join(i);
					fragmentOptions.index = i;

					fragment = new virtualdom_Fragment(fragmentOptions);
					section.fragmentsToRender.push(section.fragments[i] = fragment);
				}
			}
		}

		section.length = length;
		return true;
	}

	function reevaluateListObjectSection(section, value, fragmentOptions) {
		var id, i, hasKey, fragment, changed, deps;

		hasKey = section.hasKey || (section.hasKey = {});

		// remove any fragments that should no longer exist
		i = section.fragments.length;
		while (i--) {
			fragment = section.fragments[i];

			if (!(fragment.key in value)) {
				changed = true;

				fragment.unbind();
				section.fragmentsToUnrender.push(fragment);
				section.fragments.splice(i, 1);

				hasKey[fragment.key] = false;
			}
		}

		// notify any dependents about changed indices
		i = section.fragments.length;
		while (i--) {
			fragment = section.fragments[i];

			if (fragment.index !== i) {
				fragment.index = i;
				if (deps = fragment.registeredIndexRefs) {
					deps.forEach(setValue__blindRebind);
				}
			}
		}

		// add any that haven't been created yet
		i = section.fragments.length;
		for (id in value) {
			if (!hasKey[id]) {
				changed = true;

				fragmentOptions.context = section.keypath.join(id);
				fragmentOptions.key = id;
				fragmentOptions.index = i++;

				fragment = new virtualdom_Fragment(fragmentOptions);

				section.fragmentsToRender.push(fragment);
				section.fragments.push(fragment);
				hasKey[id] = true;
			}
		}

		section.length = section.fragments.length;
		return changed;
	}

	function reevaluateConditionalContextSection(section, value, fragmentOptions) {
		if (value) {
			return reevaluateContextSection(section, fragmentOptions);
		} else {
			return removeSectionFragments(section);
		}
	}

	function reevaluateContextSection(section, fragmentOptions) {
		var fragment;

		// ...then if it isn't rendered, render it, adding section.keypath to the context stack
		// (if it is already rendered, then any children dependent on the context stack
		// will update themselves without any prompting)
		if (!section.length) {
			// append this section to the context stack
			fragmentOptions.context = section.keypath;
			fragmentOptions.index = 0;

			fragment = new virtualdom_Fragment(fragmentOptions);

			section.fragmentsToRender.push(section.fragments[0] = fragment);
			section.length = 1;

			return true;
		}
	}

	function reevaluateConditionalSection(section, value, inverted, fragmentOptions) {
		var doRender, emptyArray, emptyObject, fragment, name;

		emptyArray = isArrayLike(value) && value.length === 0;
		emptyObject = false;
		if (!isArrayLike(value) && isObject(value)) {
			emptyObject = true;
			for (name in value) {
				emptyObject = false;
				break;
			}
		}

		if (inverted) {
			doRender = emptyArray || emptyObject || !value;
		} else {
			doRender = value && !emptyArray && !emptyObject;
		}

		if (doRender) {
			if (!section.length) {
				// no change to context stack
				fragmentOptions.index = 0;

				fragment = new virtualdom_Fragment(fragmentOptions);
				section.fragmentsToRender.push(section.fragments[0] = fragment);
				section.length = 1;

				return true;
			}

			if (section.length > 1) {
				section.fragmentsToUnrender = section.fragments.splice(1);
				section.fragmentsToUnrender.forEach(methodCallers__unbind);

				return true;
			}
		} else {
			return removeSectionFragments(section);
		}
	}

	function removeSectionFragments(section) {
		if (section.length) {
			section.fragmentsToUnrender = section.fragments.splice(0, section.fragments.length).filter(isRendered);
			section.fragmentsToUnrender.forEach(methodCallers__unbind);
			section.length = section.fragmentsToRender.length = 0;
			return true;
		}
	}

	function isRendered(fragment) {
		return fragment.rendered;
	}

	function setValue__blindRebind(dep) {
		// the keypath doesn't actually matter here as it won't have changed
		dep.rebind("", "");
	}

	var prototype_toString = Section$toString;

	function Section$toString(escape) {
		var str, i, len;

		str = "";

		i = 0;
		len = this.length;

		for (i = 0; i < len; i += 1) {
			str += this.fragments[i].toString(escape);
		}

		return str;
	}

	var prototype_unbind = Section$unbind;
	function Section$unbind() {
		var _this = this;

		this.fragments.forEach(methodCallers__unbind);
		this.fragmentsToRender.forEach(function (f) {
			return removeFromArray(_this.fragments, f);
		});
		this.fragmentsToRender = [];
		shared_unbind.call(this);

		this.length = 0;
		this.unbound = true;
	}

	var prototype_unrender = Section$unrender;

	function Section$unrender(shouldDestroy) {
		this.fragments.forEach(shouldDestroy ? unrenderAndDestroy : prototype_unrender__unrender);
		this.renderedFragments = [];
		this.rendered = false;
	}

	function unrenderAndDestroy(fragment) {
		fragment.unrender(true);
	}

	function prototype_unrender__unrender(fragment) {
		fragment.unrender(false);
	}

	var prototype_update = Section$update;

	function Section$update() {
		var fragment, renderIndex, renderedFragments, anchor, target, i, len;

		// `this.renderedFragments` is in the order of the previous render.
		// If fragments have shuffled about, this allows us to quickly
		// reinsert them in the correct place
		renderedFragments = this.renderedFragments;

		// Remove fragments that have been marked for destruction
		while (fragment = this.fragmentsToUnrender.pop()) {
			fragment.unrender(true);
			renderedFragments.splice(renderedFragments.indexOf(fragment), 1);
		}

		// Render new fragments (but don't insert them yet)
		while (fragment = this.fragmentsToRender.shift()) {
			fragment.render();
		}

		if (this.rendered) {
			target = this.parentFragment.getNode();
		}

		len = this.fragments.length;
		for (i = 0; i < len; i += 1) {
			fragment = this.fragments[i];
			renderIndex = renderedFragments.indexOf(fragment, i); // search from current index - it's guaranteed to be the same or higher

			if (renderIndex === i) {
				// already in the right place. insert accumulated nodes (if any) and carry on
				if (this.docFrag.childNodes.length) {
					anchor = fragment.firstNode();
					target.insertBefore(this.docFrag, anchor);
				}

				continue;
			}

			this.docFrag.appendChild(fragment.detach());

			// update renderedFragments
			if (renderIndex !== -1) {
				renderedFragments.splice(renderIndex, 1);
			}
			renderedFragments.splice(i, 0, fragment);
		}

		if (this.rendered && this.docFrag.childNodes.length) {
			anchor = this.parentFragment.findNextNode(this);
			target.insertBefore(this.docFrag, anchor);
		}

		// Save the rendering order for next time
		this.renderedFragments = this.fragments.slice();
	}

	var Section = function (options) {
		this.type = SECTION;
		this.subtype = this.currentSubtype = options.template.n;
		this.inverted = this.subtype === SECTION_UNLESS;

		this.pElement = options.pElement;

		this.fragments = [];
		this.fragmentsToCreate = [];
		this.fragmentsToRender = [];
		this.fragmentsToUnrender = [];

		if (options.template.i) {
			this.indexRefs = options.template.i.split(",").map(function (k, i) {
				return { n: k, t: i === 0 ? "k" : "i" };
			});
		}

		this.renderedFragments = [];

		this.length = 0; // number of times this section is rendered

		Mustache.init(this, options);
	};

	Section.prototype = {
		bubble: Section_prototype_bubble,
		detach: Section_prototype_detach,
		find: find,
		findAll: findAll,
		findAllComponents: findAllComponents,
		findComponent: findComponent,
		findNextNode: findNextNode,
		firstNode: firstNode,
		getIndexRef: function (name) {
			if (this.indexRefs) {
				var i = this.indexRefs.length;
				while (i--) {
					var ref = this.indexRefs[i];
					if (ref.n === name) {
						return ref;
					}
				}
			}
		},
		getValue: Mustache.getValue,
		shuffle: shuffle,
		rebind: prototype_rebind,
		render: Section_prototype_render,
		resolve: Mustache.resolve,
		setValue: setValue,
		toString: prototype_toString,
		unbind: prototype_unbind,
		unrender: prototype_unrender,
		update: prototype_update
	};

	var _Section = Section;

	var Triple_prototype_detach = Triple$detach;

	function Triple$detach() {
		var len, i;

		if (this.docFrag) {
			len = this.nodes.length;
			for (i = 0; i < len; i += 1) {
				this.docFrag.appendChild(this.nodes[i]);
			}

			return this.docFrag;
		}
	}

	var Triple_prototype_find = Triple$find;
	function Triple$find(selector) {
		var i, len, node, queryResult;

		len = this.nodes.length;
		for (i = 0; i < len; i += 1) {
			node = this.nodes[i];

			if (node.nodeType !== 1) {
				continue;
			}

			if (matches(node, selector)) {
				return node;
			}

			if (queryResult = node.querySelector(selector)) {
				return queryResult;
			}
		}

		return null;
	}

	var Triple_prototype_findAll = Triple$findAll;
	function Triple$findAll(selector, queryResult) {
		var i, len, node, queryAllResult, numNodes, j;

		len = this.nodes.length;
		for (i = 0; i < len; i += 1) {
			node = this.nodes[i];

			if (node.nodeType !== 1) {
				continue;
			}

			if (matches(node, selector)) {
				queryResult.push(node);
			}

			if (queryAllResult = node.querySelectorAll(selector)) {
				numNodes = queryAllResult.length;
				for (j = 0; j < numNodes; j += 1) {
					queryResult.push(queryAllResult[j]);
				}
			}
		}
	}

	var Triple_prototype_firstNode = Triple$firstNode;

	function Triple$firstNode() {
		if (this.rendered && this.nodes[0]) {
			return this.nodes[0];
		}

		return this.parentFragment.findNextNode(this);
	}

	var elementCache = {},
		ieBug,
		ieBlacklist;

	try {
		createElement("table").innerHTML = "foo";
	} catch (err) {
		ieBug = true;

		ieBlacklist = {
			TABLE: ["<table class=\"x\">", "</table>"],
			THEAD: ["<table><thead class=\"x\">", "</thead></table>"],
			TBODY: ["<table><tbody class=\"x\">", "</tbody></table>"],
			TR: ["<table><tr class=\"x\">", "</tr></table>"],
			SELECT: ["<select class=\"x\">", "</select>"]
		};
	}

	var insertHtml = function (html, node, docFrag) {
		var container,
			nodes = [],
			wrapper,
			selectedOption,
			child,
			i;

		// render 0 and false
		if (html != null && html !== "") {
			if (ieBug && (wrapper = ieBlacklist[node.tagName])) {
				container = element("DIV");
				container.innerHTML = wrapper[0] + html + wrapper[1];
				container = container.querySelector(".x");

				if (container.tagName === "SELECT") {
					selectedOption = container.options[container.selectedIndex];
				}
			} else if (node.namespaceURI === namespaces.svg) {
				container = element("DIV");
				container.innerHTML = "<svg class=\"x\">" + html + "</svg>";
				container = container.querySelector(".x");
			} else {
				container = element(node.tagName);
				container.innerHTML = html;

				if (container.tagName === "SELECT") {
					selectedOption = container.options[container.selectedIndex];
				}
			}

			while (child = container.firstChild) {
				nodes.push(child);
				docFrag.appendChild(child);
			}

			// This is really annoying. Extracting <option> nodes from the
			// temporary container <select> causes the remaining ones to
			// become selected. So now we have to deselect them. IE8, you
			// amaze me. You really do
			// ...and now Chrome too
			if (node.tagName === "SELECT") {
				i = nodes.length;
				while (i--) {
					if (nodes[i] !== selectedOption) {
						nodes[i].selected = false;
					}
				}
			}
		}

		return nodes;
	};

	function element(tagName) {
		return elementCache[tagName] || (elementCache[tagName] = createElement(tagName));
	}

	var helpers_updateSelect = updateSelect;

	function updateSelect(parentElement) {
		var selectedOptions, option, value;

		if (!parentElement || parentElement.name !== "select" || !parentElement.binding) {
			return;
		}

		selectedOptions = toArray(parentElement.node.options).filter(isSelected);

		// If one of them had a `selected` attribute, we need to sync
		// the model to the view
		if (parentElement.getAttribute("multiple")) {
			value = selectedOptions.map(function (o) {
				return o.value;
			});
		} else if (option = selectedOptions[0]) {
			value = option.value;
		}

		if (value !== undefined) {
			parentElement.binding.setValue(value);
		}

		parentElement.bubble();
	}

	function isSelected(option) {
		return option.selected;
	}

	var Triple_prototype_render = Triple$render;
	function Triple$render() {
		if (this.rendered) {
			throw new Error("Attempted to render an item that was already rendered");
		}

		this.docFrag = document.createDocumentFragment();
		this.nodes = insertHtml(this.value, this.parentFragment.getNode(), this.docFrag);

		// Special case - we're inserting the contents of a <select>
		helpers_updateSelect(this.pElement);

		this.rendered = true;
		return this.docFrag;
	}

	var prototype_setValue = Triple$setValue;
	function Triple$setValue(value) {
		var wrapper;

		// TODO is there a better way to approach this?
		if (wrapper = this.root.viewmodel.wrapped[this.keypath.str]) {
			value = wrapper.get();
		}

		if (value !== this.value) {
			this.value = value;
			this.parentFragment.bubble();

			if (this.rendered) {
				global_runloop.addView(this);
			}
		}
	}

	var Triple_prototype_toString = Triple$toString;
	function Triple$toString() {
		return this.value != undefined ? decodeCharacterReferences("" + this.value) : "";
	}

	var Triple_prototype_unrender = Triple$unrender;
	function Triple$unrender(shouldDestroy) {
		if (this.rendered && shouldDestroy) {
			this.nodes.forEach(detachNode);
			this.rendered = false;
		}

		// TODO update live queries
	}

	var Triple_prototype_update = Triple$update;
	function Triple$update() {
		var node, parentNode;

		if (!this.rendered) {
			return;
		}

		// Remove existing nodes
		while (this.nodes && this.nodes.length) {
			node = this.nodes.pop();
			node.parentNode.removeChild(node);
		}

		// Insert new nodes
		parentNode = this.parentFragment.getNode();

		this.nodes = insertHtml(this.value, parentNode, this.docFrag);
		parentNode.insertBefore(this.docFrag, this.parentFragment.findNextNode(this));

		// Special case - we're inserting the contents of a <select>
		helpers_updateSelect(this.pElement);
	}

	var Triple = function (options) {
		this.type = TRIPLE;
		Mustache.init(this, options);
	};

	Triple.prototype = {
		detach: Triple_prototype_detach,
		find: Triple_prototype_find,
		findAll: Triple_prototype_findAll,
		firstNode: Triple_prototype_firstNode,
		getValue: Mustache.getValue,
		rebind: Mustache.rebind,
		render: Triple_prototype_render,
		resolve: Mustache.resolve,
		setValue: prototype_setValue,
		toString: Triple_prototype_toString,
		unbind: shared_unbind,
		unrender: Triple_prototype_unrender,
		update: Triple_prototype_update
	};

	var _Triple = Triple;

	var Element_prototype_bubble = function () {
		this.parentFragment.bubble();
	};

	var Element_prototype_detach = Element$detach;

	function Element$detach() {
		var node = this.node,
			parentNode;

		if (node) {
			// need to check for parent node - DOM may have been altered
			// by something other than Ractive! e.g. jQuery UI...
			if (parentNode = node.parentNode) {
				parentNode.removeChild(node);
			}

			return node;
		}
	}

	var Element_prototype_find = function (selector) {
		if (!this.node) {
			// this element hasn't been rendered yet
			return null;
		}

		if (matches(this.node, selector)) {
			return this.node;
		}

		if (this.fragment && this.fragment.find) {
			return this.fragment.find(selector);
		}
	};

	var Element_prototype_findAll = function (selector, query) {
		// Add this node to the query, if applicable, and register the
		// query on this element
		if (query._test(this, true) && query.live) {
			(this.liveQueries || (this.liveQueries = [])).push(query);
		}

		if (this.fragment) {
			this.fragment.findAll(selector, query);
		}
	};

	var Element_prototype_findAllComponents = function (selector, query) {
		if (this.fragment) {
			this.fragment.findAllComponents(selector, query);
		}
	};

	var Element_prototype_findComponent = function (selector) {
		if (this.fragment) {
			return this.fragment.findComponent(selector);
		}
	};

	var Element_prototype_findNextNode = Element$findNextNode;

	function Element$findNextNode() {
		return null;
	}

	var Element_prototype_firstNode = Element$firstNode;

	function Element$firstNode() {
		return this.node;
	}

	var getAttribute = Element$getAttribute;

	function Element$getAttribute(name) {
		if (!this.attributes || !this.attributes[name]) {
			return;
		}

		return this.attributes[name].value;
	}

	var truthy = /^true|on|yes|1$/i;
	var processBindingAttributes__isNumeric = /^[0-9]+$/;

	var processBindingAttributes = function (element, template) {
		var val, attrs, attributes;

		attributes = template.a || {};
		attrs = {};

		// attributes that are present but don't have a value (=)
		// will be set to the number 0, which we condider to be true
		// the string '0', however is false

		val = attributes.twoway;
		if (val !== undefined) {
			attrs.twoway = val === 0 || truthy.test(val);
		}

		val = attributes.lazy;
		if (val !== undefined) {
			// check for timeout value
			if (val !== 0 && processBindingAttributes__isNumeric.test(val)) {
				attrs.lazy = parseInt(val);
			} else {
				attrs.lazy = val === 0 || truthy.test(val);
			}
		}

		return attrs;
	};

	var Attribute_prototype_bubble = Attribute$bubble;
	function Attribute$bubble() {
		var value = this.useProperty || !this.rendered ? this.fragment.getValue() : this.fragment.toString();

		// TODO this can register the attribute multiple times (see render test
		// 'Attribute with nested mustaches')
		if (!isEqual(value, this.value)) {

			// Need to clear old id from ractive.nodes
			if (this.name === "id" && this.value) {
				delete this.root.nodes[this.value];
			}

			this.value = value;

			if (this.name === "value" && this.node) {
				// We need to store the value on the DOM like this so we
				// can retrieve it later without it being coerced to a string
				this.node._ractive.value = value;
			}

			if (this.rendered) {
				global_runloop.addView(this);
			}
		}
	}

	var svgCamelCaseElements, svgCamelCaseAttributes, createMap, map;
	svgCamelCaseElements = "altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath vkern".split(" ");
	svgCamelCaseAttributes = "attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits contentScriptType contentStyleType diffuseConstant edgeMode externalResourcesRequired filterRes filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan".split(" ");

	createMap = function (items) {
		var map = {},
			i = items.length;
		while (i--) {
			map[items[i].toLowerCase()] = items[i];
		}
		return map;
	};

	map = createMap(svgCamelCaseElements.concat(svgCamelCaseAttributes));

	var enforceCase = function (elementName) {
		var lowerCaseElementName = elementName.toLowerCase();
		return map[lowerCaseElementName] || lowerCaseElementName;
	};

	var determineNameAndNamespace = function (attribute, name) {
		var colonIndex, namespacePrefix;

		// are we dealing with a namespaced attribute, e.g. xlink:href?
		colonIndex = name.indexOf(":");
		if (colonIndex !== -1) {

			// looks like we are, yes...
			namespacePrefix = name.substr(0, colonIndex);

			// ...unless it's a namespace *declaration*, which we ignore (on the assumption
			// that only valid namespaces will be used)
			if (namespacePrefix !== "xmlns") {
				name = name.substring(colonIndex + 1);

				attribute.name = enforceCase(name);
				attribute.namespace = namespaces[namespacePrefix.toLowerCase()];
				attribute.namespacePrefix = namespacePrefix;

				if (!attribute.namespace) {
					throw "Unknown namespace (\"" + namespacePrefix + "\")";
				}

				return;
			}
		}

		// SVG attribute names are case sensitive
		attribute.name = attribute.element.namespace !== namespaces.html ? enforceCase(name) : name;
	};

	var helpers_getInterpolator = getInterpolator;
	function getInterpolator(attribute) {
		var items = attribute.fragment.items;

		if (items.length !== 1) {
			return;
		}

		if (items[0].type === INTERPOLATOR) {
			return items[0];
		}
	}

	var prototype_init = Attribute$init;
	function Attribute$init(options) {
		this.type = ATTRIBUTE;
		this.element = options.element;
		this.root = options.root;

		determineNameAndNamespace(this, options.name);
		this.isBoolean = booleanAttributes.test(this.name);

		// if it's an empty attribute, or just a straight key-value pair, with no
		// mustache shenanigans, set the attribute accordingly and go home
		if (!options.value || typeof options.value === "string") {
			this.value = this.isBoolean ? true : options.value || "";
			return;
		}

		// otherwise we need to do some work

		// share parentFragment with parent element
		this.parentFragment = this.element.parentFragment;

		this.fragment = new virtualdom_Fragment({
			template: options.value,
			root: this.root,
			owner: this
		});

		// TODO can we use this.fragment.toString() in some cases? It's quicker
		this.value = this.fragment.getValue();

		// Store a reference to this attribute's interpolator, if its fragment
		// takes the form `{{foo}}`. This is necessary for two-way binding and
		// for correctly rendering HTML later
		this.interpolator = helpers_getInterpolator(this);
		this.isBindable = !!this.interpolator && !this.interpolator.isStatic;

		// mark as ready
		this.ready = true;
	}

	var Attribute_prototype_rebind = Attribute$rebind;

	function Attribute$rebind(oldKeypath, newKeypath) {
		if (this.fragment) {
			this.fragment.rebind(oldKeypath, newKeypath);
		}
	}

	var Attribute_prototype_render = Attribute$render;
	var propertyNames = {
		"accept-charset": "acceptCharset",
		accesskey: "accessKey",
		bgcolor: "bgColor",
		"class": "className",
		codebase: "codeBase",
		colspan: "colSpan",
		contenteditable: "contentEditable",
		datetime: "dateTime",
		dirname: "dirName",
		"for": "htmlFor",
		"http-equiv": "httpEquiv",
		ismap: "isMap",
		maxlength: "maxLength",
		novalidate: "noValidate",
		pubdate: "pubDate",
		readonly: "readOnly",
		rowspan: "rowSpan",
		tabindex: "tabIndex",
		usemap: "useMap"
	};
	function Attribute$render(node) {
		var propertyName;

		this.node = node;

		// should we use direct property access, or setAttribute?
		if (!node.namespaceURI || node.namespaceURI === namespaces.html) {
			propertyName = propertyNames[this.name] || this.name;

			if (node[propertyName] !== undefined) {
				this.propertyName = propertyName;
			}

			// is attribute a boolean attribute or 'value'? If so we're better off doing e.g.
			// node.selected = true rather than node.setAttribute( 'selected', '' )
			if (this.isBoolean || this.isTwoway) {
				this.useProperty = true;
			}

			if (propertyName === "value") {
				node._ractive.value = this.value;
			}
		}

		this.rendered = true;
		this.update();
	}

	var Attribute_prototype_toString = Attribute$toString;

	function Attribute$toString() {
		var _ref = this;

		var name = _ref.name;
		var namespacePrefix = _ref.namespacePrefix;
		var value = _ref.value;
		var interpolator = _ref.interpolator;
		var fragment = _ref.fragment;

		// Special case - select and textarea values (should not be stringified)
		if (name === "value" && (this.element.name === "select" || this.element.name === "textarea")) {
			return;
		}

		// Special case - content editable
		if (name === "value" && this.element.getAttribute("contenteditable") !== undefined) {
			return;
		}

		// Special case - radio names
		if (name === "name" && this.element.name === "input" && interpolator) {
			return "name={{" + (interpolator.keypath.str || interpolator.ref) + "}}";
		}

		// Boolean attributes
		if (this.isBoolean) {
			return value ? name : "";
		}

		if (fragment) {
			// special case - this catches undefined/null values (#1211)
			if (fragment.items.length === 1 && fragment.items[0].value == null) {
				return "";
			}

			value = fragment.toString();
		}

		if (namespacePrefix) {
			name = namespacePrefix + ":" + name;
		}

		return value ? name + "=\"" + Attribute_prototype_toString__escape(value) + "\"" : name;
	}

	function Attribute_prototype_toString__escape(value) {
		return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
	}

	var Attribute_prototype_unbind = Attribute$unbind;

	function Attribute$unbind() {
		// ignore non-dynamic attributes
		if (this.fragment) {
			this.fragment.unbind();
		}

		if (this.name === "id") {
			delete this.root.nodes[this.value];
		}
	}

	var updateSelectValue = Attribute$updateSelect;

	function Attribute$updateSelect() {
		var value = this.value,
			options,
			option,
			optionValue,
			i;

		if (!this.locked) {
			this.node._ractive.value = value;

			options = this.node.options;
			i = options.length;

			while (i--) {
				option = options[i];
				optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive

				if (optionValue == value) {
					// double equals as we may be comparing numbers with strings
					option.selected = true;
					break;
				}
			}
		}

		// if we're still here, it means the new value didn't match any of the options...
		// TODO figure out what to do in this situation
	}

	var updateMultipleSelectValue = Attribute$updateMultipleSelect;
	function Attribute$updateMultipleSelect() {
		var value = this.value,
			options,
			i,
			option,
			optionValue;

		if (!isArray(value)) {
			value = [value];
		}

		options = this.node.options;
		i = options.length;

		while (i--) {
			option = options[i];
			optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive
			option.selected = arrayContains(value, optionValue);
		}
	}

	var updateRadioName = Attribute$updateRadioName;

	function Attribute$updateRadioName() {
		var _ref = this;

		var node = _ref.node;
		var value = _ref.value;

		node.checked = value == node._ractive.value;
	}

	var updateRadioValue = Attribute$updateRadioValue;
	function Attribute$updateRadioValue() {
		var wasChecked,
			node = this.node,
			binding,
			bindings,
			i;

		wasChecked = node.checked;

		node.value = this.element.getAttribute("value");
		node.checked = this.element.getAttribute("value") === this.element.getAttribute("name");

		// This is a special case - if the input was checked, and the value
		// changed so that it's no longer checked, the twoway binding is
		// most likely out of date. To fix it we have to jump through some
		// hoops... this is a little kludgy but it works
		if (wasChecked && !node.checked && this.element.binding) {
			bindings = this.element.binding.siblings;

			if (i = bindings.length) {
				while (i--) {
					binding = bindings[i];

					if (!binding.element.node) {
						// this is the initial render, siblings are still rendering!
						// we'll come back later...
						return;
					}

					if (binding.element.node.checked) {
						global_runloop.addRactive(binding.root);
						return binding.handleChange();
					}
				}

				this.root.viewmodel.set(binding.keypath, undefined);
			}
		}
	}

	var updateCheckboxName = Attribute$updateCheckboxName;
	function Attribute$updateCheckboxName() {
		var _ref = this;

		var element = _ref.element;
		var node = _ref.node;
		var value = _ref.value; var binding = element.binding; var valueAttribute; var i;

		valueAttribute = element.getAttribute("value");

		if (!isArray(value)) {
			binding.isChecked = node.checked = value == valueAttribute;
		} else {
			i = value.length;
			while (i--) {
				if (valueAttribute == value[i]) {
					binding.isChecked = node.checked = true;
					return;
				}
			}
			binding.isChecked = node.checked = false;
		}
	}

	var updateClassName = Attribute$updateClassName;
	function Attribute$updateClassName() {
		this.node.className = safeToStringValue(this.value);
	}

	var updateIdAttribute = Attribute$updateIdAttribute;

	function Attribute$updateIdAttribute() {
		var _ref = this;

		var node = _ref.node;
		var value = _ref.value;

		this.root.nodes[value] = node;
		node.id = value;
	}

	var updateIEStyleAttribute = Attribute$updateIEStyleAttribute;

	function Attribute$updateIEStyleAttribute() {
		var node, value;

		node = this.node;
		value = this.value;

		if (value === undefined) {
			value = "";
		}

		node.style.setAttribute("cssText", value);
	}

	var updateContentEditableValue = Attribute$updateContentEditableValue;

	function Attribute$updateContentEditableValue() {
		var value = this.value;

		if (value === undefined) {
			value = "";
		}

		if (!this.locked) {
			this.node.innerHTML = value;
		}
	}

	var updateValue = Attribute$updateValue;

	function Attribute$updateValue() {
		var _ref = this;

		var node = _ref.node;
		var value = _ref.value;

		// store actual value, so it doesn't get coerced to a string
		node._ractive.value = value;

		// with two-way binding, only update if the change wasn't initiated by the user
		// otherwise the cursor will often be sent to the wrong place
		if (!this.locked) {
			node.value = value == undefined ? "" : value;
		}
	}

	var updateBoolean = Attribute$updateBooleanAttribute;

	function Attribute$updateBooleanAttribute() {
		// with two-way binding, only update if the change wasn't initiated by the user
		// otherwise the cursor will often be sent to the wrong place
		if (!this.locked) {
			this.node[this.propertyName] = this.value;
		}
	}

	var updateEverythingElse = Attribute$updateEverythingElse;

	function Attribute$updateEverythingElse() {
		var _ref = this;

		var node = _ref.node;
		var namespace = _ref.namespace;
		var name = _ref.name;
		var value = _ref.value;
		var fragment = _ref.fragment;

		if (namespace) {
			node.setAttributeNS(namespace, name, (fragment || value).toString());
		} else if (!this.isBoolean) {
			if (value == null) {
				node.removeAttribute(name);
			} else {
				node.setAttribute(name, (fragment || value).toString());
			}
		}

			// Boolean attributes - truthy becomes '', falsy means 'remove attribute'
		else {
			if (value) {
				node.setAttribute(name, "");
			} else {
				node.removeAttribute(name);
			}
		}
	}

	// There are a few special cases when it comes to updating attributes. For this reason,
	// the prototype .update() method points to this method, which waits until the
	// attribute has finished initialising, then replaces the prototype method with a more
	// suitable one. That way, we save ourselves doing a bunch of tests on each call
	var Attribute_prototype_update = Attribute$update;
	function Attribute$update() {
		var _ref = this;

		var name = _ref.name;
		var element = _ref.element;
		var node = _ref.node; var type; var updateMethod;

		if (name === "id") {
			updateMethod = updateIdAttribute;
		} else if (name === "value") {
			// special case - selects
			if (element.name === "select" && name === "value") {
				updateMethod = element.getAttribute("multiple") ? updateMultipleSelectValue : updateSelectValue;
			} else if (element.name === "textarea") {
				updateMethod = updateValue;
			}

				// special case - contenteditable
			else if (element.getAttribute("contenteditable") != null) {
				updateMethod = updateContentEditableValue;
			}

				// special case - <input>
			else if (element.name === "input") {
				type = element.getAttribute("type");

				// type='file' value='{{fileList}}'>
				if (type === "file") {
					updateMethod = noop; // read-only
				}

					// type='radio' name='{{twoway}}'
				else if (type === "radio" && element.binding && element.binding.name === "name") {
					updateMethod = updateRadioValue;
				} else {
					updateMethod = updateValue;
				}
			}
		}

			// special case - <input type='radio' name='{{twoway}}' value='foo'>
		else if (this.isTwoway && name === "name") {
			if (node.type === "radio") {
				updateMethod = updateRadioName;
			} else if (node.type === "checkbox") {
				updateMethod = updateCheckboxName;
			}
		}

			// special case - style attributes in Internet Exploder
		else if (name === "style" && node.style.setAttribute) {
			updateMethod = updateIEStyleAttribute;
		}

			// special case - class names. IE fucks things up, again
		else if (name === "class" && (!node.namespaceURI || node.namespaceURI === namespaces.html)) {
			updateMethod = updateClassName;
		} else if (this.useProperty) {
			updateMethod = updateBoolean;
		}

		if (!updateMethod) {
			updateMethod = updateEverythingElse;
		}

		this.update = updateMethod;
		this.update();
	}

	var Attribute = function (options) {
		this.init(options);
	};

	Attribute.prototype = {
		bubble: Attribute_prototype_bubble,
		init: prototype_init,
		rebind: Attribute_prototype_rebind,
		render: Attribute_prototype_render,
		toString: Attribute_prototype_toString,
		unbind: Attribute_prototype_unbind,
		update: Attribute_prototype_update
	};

	var _Attribute = Attribute;

	var createAttributes = function (element, attributes) {
		var name,
			attribute,
			result = [];

		for (name in attributes) {
			// skip binding attributes
			if (name === "twoway" || name === "lazy") {
				continue;
			}

			if (attributes.hasOwnProperty(name)) {
				attribute = new _Attribute({
					element: element,
					name: name,
					value: attributes[name],
					root: element.root
				});

				result[name] = attribute;

				if (name !== "value") {
					result.push(attribute);
				}
			}
		}

		// value attribute goes last. This is because it
		// may get clamped on render otherwise, e.g. in
		// `<input type='range' value='999' min='0' max='1000'>`
		// since default max is 100
		if (attribute = result.value) {
			result.push(attribute);
		}

		return result;
	};

	var _ConditionalAttribute__div;

	if (typeof document !== "undefined") {
		_ConditionalAttribute__div = createElement("div");
	}

	var ConditionalAttribute = function (element, template) {
		this.element = element;
		this.root = element.root;
		this.parentFragment = element.parentFragment;

		this.attributes = [];

		this.fragment = new virtualdom_Fragment({
			root: element.root,
			owner: this,
			template: [template]
		});
	};

	ConditionalAttribute.prototype = {
		bubble: function () {
			if (this.node) {
				this.update();
			}

			this.element.bubble();
		},

		rebind: function (oldKeypath, newKeypath) {
			this.fragment.rebind(oldKeypath, newKeypath);
		},

		render: function (node) {
			this.node = node;
			this.isSvg = node.namespaceURI === namespaces.svg;

			this.update();
		},

		unbind: function () {
			this.fragment.unbind();
		},

		update: function () {
			var _this = this;

			var str, attrs;

			str = this.fragment.toString();
			attrs = parseAttributes(str, this.isSvg);

			// any attributes that previously existed but no longer do
			// must be removed
			this.attributes.filter(function (a) {
				return notIn(attrs, a);
			}).forEach(function (a) {
				_this.node.removeAttribute(a.name);
			});

			attrs.forEach(function (a) {
				_this.node.setAttribute(a.name, a.value);
			});

			this.attributes = attrs;
		},

		toString: function () {
			return this.fragment.toString();
		}
	};

	var _ConditionalAttribute = ConditionalAttribute;

	function parseAttributes(str, isSvg) {
		var tag = isSvg ? "svg" : "div";
		_ConditionalAttribute__div.innerHTML = "<" + tag + " " + str + "></" + tag + ">";

		return toArray(_ConditionalAttribute__div.childNodes[0].attributes);
	}

	function notIn(haystack, needle) {
		var i = haystack.length;

		while (i--) {
			if (haystack[i].name === needle.name) {
				return false;
			}
		}

		return true;
	}

	var createConditionalAttributes = function (element, attributes) {
		if (!attributes) {
			return [];
		}

		return attributes.map(function (a) {
			return new _ConditionalAttribute(element, a);
		});
	};

	var Binding = function (element) {
		var interpolator, keypath, value, parentForm;

		this.element = element;
		this.root = element.root;
		this.attribute = element.attributes[this.name || "value"];

		interpolator = this.attribute.interpolator;
		interpolator.twowayBinding = this;

		if (keypath = interpolator.keypath) {
			if (keypath.str.slice(-1) === "}") {
				warnOnceIfDebug("Two-way binding does not work with expressions (`%s` on <%s>)", interpolator.resolver.uniqueString, element.name, { ractive: this.root });
				return false;
			}

			if (keypath.isSpecial) {
				warnOnceIfDebug("Two-way binding does not work with %s", interpolator.resolver.ref, { ractive: this.root });
				return false;
			}
		} else {
			// A mustache may be *ambiguous*. Let's say we were given
			// `value="{{bar}}"`. If the context was `foo`, and `foo.bar`
			// *wasn't* `undefined`, the keypath would be `foo.bar`.
			// Then, any user input would result in `foo.bar` being updated.
			//
			// If, however, `foo.bar` *was* undefined, and so was `bar`, we would be
			// left with an unresolved partial keypath - so we are forced to make an
			// assumption. That assumption is that the input in question should
			// be forced to resolve to `bar`, and any user input would affect `bar`
			// and not `foo.bar`.
			//
			// Did that make any sense? No? Oh. Sorry. Well the moral of the story is
			// be explicit when using two-way data-binding about what keypath you're
			// updating. Using it in lists is probably a recipe for confusion...
			var ref = interpolator.template.r ? "'" + interpolator.template.r + "' reference" : "expression";
			warnIfDebug("The %s being used for two-way binding is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity", ref, { ractive: this.root });
			interpolator.resolver.forceResolution();
			keypath = interpolator.keypath;
		}

		this.attribute.isTwoway = true;
		this.keypath = keypath;

		// initialise value, if it's undefined
		value = this.root.viewmodel.get(keypath);

		if (value === undefined && this.getInitialValue) {
			value = this.getInitialValue();

			if (value !== undefined) {
				this.root.viewmodel.set(keypath, value);
			}
		}

		if (parentForm = findParentForm(element)) {
			this.resetValue = value;
			parentForm.formBindings.push(this);
		}
	};

	Binding.prototype = {
		handleChange: function () {
			var _this = this;

			global_runloop.start(this.root);
			this.attribute.locked = true;
			this.root.viewmodel.set(this.keypath, this.getValue());
			global_runloop.scheduleTask(function () {
				return _this.attribute.locked = false;
			});
			global_runloop.end();
		},

		rebound: function () {
			var bindings, oldKeypath, newKeypath;

			oldKeypath = this.keypath;
			newKeypath = this.attribute.interpolator.keypath;

			// The attribute this binding is linked to has already done the work
			if (oldKeypath === newKeypath) {
				return;
			}

			removeFromArray(this.root._twowayBindings[oldKeypath.str], this);

			this.keypath = newKeypath;

			bindings = this.root._twowayBindings[newKeypath.str] || (this.root._twowayBindings[newKeypath.str] = []);
			bindings.push(this);
		},

		unbind: function () { }
	};

	Binding.extend = function (properties) {
		var Parent = this,
			SpecialisedBinding;

		SpecialisedBinding = function (element) {
			Binding.call(this, element);

			if (this.init) {
				this.init();
			}
		};

		SpecialisedBinding.prototype = create(Parent.prototype);
		utils_object__extend(SpecialisedBinding.prototype, properties);

		SpecialisedBinding.extend = Binding.extend;

		return SpecialisedBinding;
	};

	var Binding_Binding = Binding;

	function findParentForm(element) {
		while (element = element.parent) {
			if (element.name === "form") {
				return element;
			}
		}
	}

	// this is called when the element is unbound.
	// Specialised bindings can override it

	// This is the handler for DOM events that would lead to a change in the model
	// (i.e. change, sometimes, input, and occasionally click and keyup)
	var handleDomEvent = handleChange;

	function handleChange() {
		this._ractive.binding.handleChange();
	}

	var GenericBinding;

	GenericBinding = Binding_Binding.extend({
		getInitialValue: function () {
			return "";
		},

		getValue: function () {
			return this.element.node.value;
		},

		render: function () {
			var node = this.element.node,
				lazy,
				timeout = false;
			this.rendered = true;

			// any lazy setting for this element overrides the root
			// if the value is a number, it's a timeout
			lazy = this.root.lazy;
			if (this.element.lazy === true) {
				lazy = true;
			} else if (this.element.lazy === false) {
				lazy = false;
			} else if (is__isNumeric(this.element.lazy)) {
				lazy = false;
				timeout = +this.element.lazy;
			} else if (is__isNumeric(lazy || "")) {
				timeout = +lazy;
				lazy = false;

				// make sure the timeout is available to the handler
				this.element.lazy = timeout;
			}

			this.handler = timeout ? handleDelay : handleDomEvent;

			node.addEventListener("change", handleDomEvent, false);

			if (!lazy) {
				node.addEventListener("input", this.handler, false);

				if (node.attachEvent) {
					node.addEventListener("keyup", this.handler, false);
				}
			}

			node.addEventListener("blur", handleBlur, false);
		},

		unrender: function () {
			var node = this.element.node;
			this.rendered = false;

			node.removeEventListener("change", handleDomEvent, false);
			node.removeEventListener("input", this.handler, false);
			node.removeEventListener("keyup", this.handler, false);
			node.removeEventListener("blur", handleBlur, false);
		}
	});

	var Binding_GenericBinding = GenericBinding;

	function handleBlur() {
		var value;

		handleDomEvent.call(this);

		value = this._ractive.root.viewmodel.get(this._ractive.binding.keypath);
		this.value = value == undefined ? "" : value;
	}

	function handleDelay() {
		var binding = this._ractive.binding,
			el = this;

		if (!!binding._timeout) clearTimeout(binding._timeout);

		binding._timeout = setTimeout(function () {
			if (binding.rendered) handleDomEvent.call(el);
			binding._timeout = undefined;
		}, binding.element.lazy);
	}

	var ContentEditableBinding = Binding_GenericBinding.extend({
		getInitialValue: function () {
			return this.element.fragment ? this.element.fragment.toString() : "";
		},

		getValue: function () {
			return this.element.node.innerHTML;
		}
	});

	var Binding_ContentEditableBinding = ContentEditableBinding;

	var shared_getSiblings = getSiblings;
	var sets = {};
	function getSiblings(id, group, keypath) {
		var hash = id + group + keypath;
		return sets[hash] || (sets[hash] = []);
	}

	var RadioBinding = Binding_Binding.extend({
		name: "checked",

		init: function () {
			this.siblings = shared_getSiblings(this.root._guid, "radio", this.element.getAttribute("name"));
			this.siblings.push(this);
		},

		render: function () {
			var node = this.element.node;

			node.addEventListener("change", handleDomEvent, false);

			if (node.attachEvent) {
				node.addEventListener("click", handleDomEvent, false);
			}
		},

		unrender: function () {
			var node = this.element.node;

			node.removeEventListener("change", handleDomEvent, false);
			node.removeEventListener("click", handleDomEvent, false);
		},

		handleChange: function () {
			global_runloop.start(this.root);

			this.siblings.forEach(function (binding) {
				binding.root.viewmodel.set(binding.keypath, binding.getValue());
			});

			global_runloop.end();
		},

		getValue: function () {
			return this.element.node.checked;
		},

		unbind: function () {
			removeFromArray(this.siblings, this);
		}
	});

	var Binding_RadioBinding = RadioBinding;

	var RadioNameBinding = Binding_Binding.extend({
		name: "name",

		init: function () {
			this.siblings = shared_getSiblings(this.root._guid, "radioname", this.keypath.str);
			this.siblings.push(this);

			this.radioName = true; // so that ractive.updateModel() knows what to do with this
		},

		getInitialValue: function () {
			if (this.element.getAttribute("checked")) {
				return this.element.getAttribute("value");
			}
		},

		render: function () {
			var node = this.element.node;

			node.name = "{{" + this.keypath.str + "}}";
			node.checked = this.root.viewmodel.get(this.keypath) == this.element.getAttribute("value");

			node.addEventListener("change", handleDomEvent, false);

			if (node.attachEvent) {
				node.addEventListener("click", handleDomEvent, false);
			}
		},

		unrender: function () {
			var node = this.element.node;

			node.removeEventListener("change", handleDomEvent, false);
			node.removeEventListener("click", handleDomEvent, false);
		},

		getValue: function () {
			var node = this.element.node;
			return node._ractive ? node._ractive.value : node.value;
		},

		handleChange: function () {
			// If this <input> is the one that's checked, then the value of its
			// `name` keypath gets set to its value
			if (this.element.node.checked) {
				Binding_Binding.prototype.handleChange.call(this);
			}
		},

		rebound: function (oldKeypath, newKeypath) {
			var node;

			Binding_Binding.prototype.rebound.call(this, oldKeypath, newKeypath);

			if (node = this.element.node) {
				node.name = "{{" + this.keypath.str + "}}";
			}
		},

		unbind: function () {
			removeFromArray(this.siblings, this);
		}
	});

	var Binding_RadioNameBinding = RadioNameBinding;

	var CheckboxNameBinding = Binding_Binding.extend({
		name: "name",

		getInitialValue: function () {
			// This only gets called once per group (of inputs that
			// share a name), because it only gets called if there
			// isn't an initial value. By the same token, we can make
			// a note of that fact that there was no initial value,
			// and populate it using any `checked` attributes that
			// exist (which users should avoid, but which we should
			// support anyway to avoid breaking expectations)
			this.noInitialValue = true;
			return [];
		},

		init: function () {
			var existingValue, bindingValue;

			this.checkboxName = true; // so that ractive.updateModel() knows what to do with this

			// Each input has a reference to an array containing it and its
			// siblings, as two-way binding depends on being able to ascertain
			// the status of all inputs within the group
			this.siblings = shared_getSiblings(this.root._guid, "checkboxes", this.keypath.str);
			this.siblings.push(this);

			if (this.noInitialValue) {
				this.siblings.noInitialValue = true;
			}

			// If no initial value was set, and this input is checked, we
			// update the model
			if (this.siblings.noInitialValue && this.element.getAttribute("checked")) {
				existingValue = this.root.viewmodel.get(this.keypath);
				bindingValue = this.element.getAttribute("value");

				existingValue.push(bindingValue);
			}
		},

		unbind: function () {
			removeFromArray(this.siblings, this);
		},

		render: function () {
			var node = this.element.node,
				existingValue,
				bindingValue;

			existingValue = this.root.viewmodel.get(this.keypath);
			bindingValue = this.element.getAttribute("value");

			if (isArray(existingValue)) {
				this.isChecked = arrayContains(existingValue, bindingValue);
			} else {
				this.isChecked = existingValue == bindingValue;
			}

			node.name = "{{" + this.keypath.str + "}}";
			node.checked = this.isChecked;

			node.addEventListener("change", handleDomEvent, false);

			// in case of IE emergency, bind to click event as well
			if (node.attachEvent) {
				node.addEventListener("click", handleDomEvent, false);
			}
		},

		unrender: function () {
			var node = this.element.node;

			node.removeEventListener("change", handleDomEvent, false);
			node.removeEventListener("click", handleDomEvent, false);
		},

		changed: function () {
			var wasChecked = !!this.isChecked;
			this.isChecked = this.element.node.checked;
			return this.isChecked === wasChecked;
		},

		handleChange: function () {
			this.isChecked = this.element.node.checked;
			Binding_Binding.prototype.handleChange.call(this);
		},

		getValue: function () {
			return this.siblings.filter(isChecked).map(Binding_CheckboxNameBinding__getValue);
		}
	});

	function isChecked(binding) {
		return binding.isChecked;
	}

	function Binding_CheckboxNameBinding__getValue(binding) {
		return binding.element.getAttribute("value");
	}

	var Binding_CheckboxNameBinding = CheckboxNameBinding;

	var CheckboxBinding = Binding_Binding.extend({
		name: "checked",

		render: function () {
			var node = this.element.node;

			node.addEventListener("change", handleDomEvent, false);

			if (node.attachEvent) {
				node.addEventListener("click", handleDomEvent, false);
			}
		},

		unrender: function () {
			var node = this.element.node;

			node.removeEventListener("change", handleDomEvent, false);
			node.removeEventListener("click", handleDomEvent, false);
		},

		getValue: function () {
			return this.element.node.checked;
		}
	});

	var Binding_CheckboxBinding = CheckboxBinding;

	var SelectBinding = Binding_Binding.extend({
		getInitialValue: function () {
			var options = this.element.options,
				len,
				i,
				value,
				optionWasSelected;

			if (this.element.getAttribute("value") !== undefined) {
				return;
			}

			i = len = options.length;

			if (!len) {
				return;
			}

			// take the final selected option...
			while (i--) {
				if (options[i].getAttribute("selected")) {
					value = options[i].getAttribute("value");
					optionWasSelected = true;
					break;
				}
			}

			// or the first non-disabled option, if none are selected
			if (!optionWasSelected) {
				while (++i < len) {
					if (!options[i].getAttribute("disabled")) {
						value = options[i].getAttribute("value");
						break;
					}
				}
			}

			// This is an optimisation (aka hack) that allows us to forgo some
			// other more expensive work
			if (value !== undefined) {
				this.element.attributes.value.value = value;
			}

			return value;
		},

		render: function () {
			this.element.node.addEventListener("change", handleDomEvent, false);
		},

		unrender: function () {
			this.element.node.removeEventListener("change", handleDomEvent, false);
		},

		// TODO this method is an anomaly... is it necessary?
		setValue: function (value) {
			this.root.viewmodel.set(this.keypath, value);
		},

		getValue: function () {
			var options, i, len, option, optionValue;

			options = this.element.node.options;
			len = options.length;

			for (i = 0; i < len; i += 1) {
				option = options[i];

				if (options[i].selected) {
					optionValue = option._ractive ? option._ractive.value : option.value;
					return optionValue;
				}
			}
		},

		forceUpdate: function () {
			var _this = this;

			var value = this.getValue();

			if (value !== undefined) {
				this.attribute.locked = true;
				global_runloop.scheduleTask(function () {
					return _this.attribute.locked = false;
				});
				this.root.viewmodel.set(this.keypath, value);
			}
		}
	});

	var Binding_SelectBinding = SelectBinding;

	var MultipleSelectBinding = Binding_SelectBinding.extend({
		getInitialValue: function () {
			return this.element.options.filter(function (option) {
				return option.getAttribute("selected");
			}).map(function (option) {
				return option.getAttribute("value");
			});
		},

		render: function () {
			var valueFromModel;

			this.element.node.addEventListener("change", handleDomEvent, false);

			valueFromModel = this.root.viewmodel.get(this.keypath);

			if (valueFromModel === undefined) {
				// get value from DOM, if possible
				this.handleChange();
			}
		},

		unrender: function () {
			this.element.node.removeEventListener("change", handleDomEvent, false);
		},

		setValue: function () {
			throw new Error("TODO not implemented yet");
		},

		getValue: function () {
			var selectedValues, options, i, len, option, optionValue;

			selectedValues = [];
			options = this.element.node.options;
			len = options.length;

			for (i = 0; i < len; i += 1) {
				option = options[i];

				if (option.selected) {
					optionValue = option._ractive ? option._ractive.value : option.value;
					selectedValues.push(optionValue);
				}
			}

			return selectedValues;
		},

		handleChange: function () {
			var attribute, previousValue, value;

			attribute = this.attribute;
			previousValue = attribute.value;

			value = this.getValue();

			if (previousValue === undefined || !arrayContentsMatch(value, previousValue)) {
				Binding_SelectBinding.prototype.handleChange.call(this);
			}

			return this;
		},

		forceUpdate: function () {
			var _this = this;

			var value = this.getValue();

			if (value !== undefined) {
				this.attribute.locked = true;
				global_runloop.scheduleTask(function () {
					return _this.attribute.locked = false;
				});
				this.root.viewmodel.set(this.keypath, value);
			}
		},

		updateModel: function () {
			if (this.attribute.value === undefined || !this.attribute.value.length) {
				this.root.viewmodel.set(this.keypath, this.initialValue);
			}
		}
	});

	var Binding_MultipleSelectBinding = MultipleSelectBinding;

	var FileListBinding = Binding_Binding.extend({
		render: function () {
			this.element.node.addEventListener("change", handleDomEvent, false);
		},

		unrender: function () {
			this.element.node.removeEventListener("change", handleDomEvent, false);
		},

		getValue: function () {
			return this.element.node.files;
		}
	});

	var Binding_FileListBinding = FileListBinding;

	var NumericBinding = Binding_GenericBinding.extend({
		getInitialValue: function () {
			return undefined;
		},

		getValue: function () {
			var value = parseFloat(this.element.node.value);
			return isNaN(value) ? undefined : value;
		}
	});

	var init_createTwowayBinding = createTwowayBinding;

	function createTwowayBinding(element) {
		var attributes = element.attributes,
			type,
			Binding,
			bindName,
			bindChecked,
			binding;

		// if this is a late binding, and there's already one, it
		// needs to be torn down
		if (element.binding) {
			element.binding.teardown();
			element.binding = null;
		}

		// contenteditable
		if (
			// if the contenteditable attribute is true or is bindable and may thus become true
		(element.getAttribute("contenteditable") || !!attributes.contenteditable && isBindable(attributes.contenteditable)) && isBindable(attributes.value)) {
			Binding = Binding_ContentEditableBinding;
		}

			// <input>
		else if (element.name === "input") {
			type = element.getAttribute("type");

			if (type === "radio" || type === "checkbox") {
				bindName = isBindable(attributes.name);
				bindChecked = isBindable(attributes.checked);

				// we can either bind the name attribute, or the checked attribute - not both
				if (bindName && bindChecked) {
					warnIfDebug("A radio input can have two-way binding on its name attribute, or its checked attribute - not both", { ractive: element.root });
				}

				if (bindName) {
					Binding = type === "radio" ? Binding_RadioNameBinding : Binding_CheckboxNameBinding;
				} else if (bindChecked) {
					Binding = type === "radio" ? Binding_RadioBinding : Binding_CheckboxBinding;
				}
			} else if (type === "file" && isBindable(attributes.value)) {
				Binding = Binding_FileListBinding;
			} else if (isBindable(attributes.value)) {
				Binding = type === "number" || type === "range" ? NumericBinding : Binding_GenericBinding;
			}
		}

			// <select>
		else if (element.name === "select" && isBindable(attributes.value)) {
			Binding = element.getAttribute("multiple") ? Binding_MultipleSelectBinding : Binding_SelectBinding;
		}

			// <textarea>
		else if (element.name === "textarea" && isBindable(attributes.value)) {
			Binding = Binding_GenericBinding;
		}

		if (Binding && (binding = new Binding(element)) && binding.keypath) {
			return binding;
		}
	}

	function isBindable(attribute) {
		return attribute && attribute.isBindable;
	}

	// and this element also has a value attribute to bind

	var EventHandler_prototype_bubble = EventHandler$bubble;

	function EventHandler$bubble() {
		var hasAction = this.getAction();

		if (hasAction && !this.hasListener) {
			this.listen();
		} else if (!hasAction && this.hasListener) {
			this.unrender();
		}
	}

	// This function may be overwritten, if the event directive
	// includes parameters
	var EventHandler_prototype_fire = EventHandler$fire;
	function EventHandler$fire(event) {
		shared_fireEvent(this.root, this.getAction(), { event: event });
	}

	var getAction = EventHandler$getAction;

	function EventHandler$getAction() {
		return this.action.toString().trim();
	}

	var EventHandler_prototype_init = EventHandler$init;

	var eventPattern = /^event(?:\.(.+))?/;
	function EventHandler$init(element, name, template) {
		var _this = this;

		var action, refs, ractive;

		this.element = element;
		this.root = element.root;
		this.parentFragment = element.parentFragment;
		this.name = name;

		if (name.indexOf("*") !== -1) {
			fatal("Only component proxy-events may contain \"*\" wildcards, <%s on-%s=\"...\"/> is not valid", element.name, name);
			this.invalid = true;
		}

		if (template.m) {
			refs = template.a.r;

			// This is a method call
			this.method = template.m;
			this.keypaths = [];
			this.fn = shared_getFunctionFromString(template.a.s, refs.length);

			this.parentFragment = element.parentFragment;
			ractive = this.root;

			// Create resolvers for each reference
			this.refResolvers = [];
			refs.forEach(function (ref, i) {
				var match = undefined;

				// special case - the `event` object
				if (match = eventPattern.exec(ref)) {
					_this.keypaths[i] = {
						eventObject: true,
						refinements: match[1] ? match[1].split(".") : []
					};
				} else {
					_this.refResolvers.push(Resolvers_createReferenceResolver(_this, ref, function (keypath) {
						return _this.resolve(i, keypath);
					}));
				}
			});

			this.fire = fireMethodCall;
		} else {
			// Get action ('foo' in 'on-click='foo')
			action = template.n || template;
			if (typeof action !== "string") {
				action = new virtualdom_Fragment({
					template: action,
					root: this.root,
					owner: this
				});
			}

			this.action = action;

			// Get parameters
			if (template.d) {
				this.dynamicParams = new virtualdom_Fragment({
					template: template.d,
					root: this.root,
					owner: this.element
				});

				this.fire = fireEventWithDynamicParams;
			} else if (template.a) {
				this.params = template.a;
				this.fire = fireEventWithParams;
			}
		}
	}

	function fireMethodCall(event) {
		var ractive, values, args;

		ractive = this.root;

		if (typeof ractive[this.method] !== "function") {
			throw new Error("Attempted to call a non-existent method (\"" + this.method + "\")");
		}

		values = this.keypaths.map(function (keypath) {
			var value, len, i;

			if (keypath === undefined) {
				// not yet resolved
				return undefined;
			}

			// TODO the refinements stuff would be better handled at parse time
			if (keypath.eventObject) {
				value = event;

				if (len = keypath.refinements.length) {
					for (i = 0; i < len; i += 1) {
						value = value[keypath.refinements[i]];
					}
				}
			} else {
				value = ractive.viewmodel.get(keypath);
			}

			return value;
		});

		shared_eventStack.enqueue(ractive, event);

		args = this.fn.apply(null, values);
		ractive[this.method].apply(ractive, args);

		shared_eventStack.dequeue(ractive);
	}

	function fireEventWithParams(event) {
		shared_fireEvent(this.root, this.getAction(), { event: event, args: this.params });
	}

	function fireEventWithDynamicParams(event) {
		var args = this.dynamicParams.getArgsList();

		// need to strip [] from ends if a string!
		if (typeof args === "string") {
			args = args.substr(1, args.length - 2);
		}

		shared_fireEvent(this.root, this.getAction(), { event: event, args: args });
	}

	var shared_genericHandler = genericHandler;
	function genericHandler(event) {
		var storage,
			handler,
			indices,
			index = {};

		storage = this._ractive;
		handler = storage.events[event.type];

		if (indices = Resolvers_findIndexRefs(handler.element.parentFragment)) {
			index = Resolvers_findIndexRefs.resolve(indices);
		}

		handler.fire({
			node: this,
			original: event,
			index: index,
			keypath: storage.keypath.str,
			context: storage.root.viewmodel.get(storage.keypath)
		});
	}

	var listen = EventHandler$listen;

	var customHandlers = {},
		touchEvents = {
			touchstart: true,
			touchmove: true,
			touchend: true,
			touchcancel: true,
			//not w3c, but supported in some browsers
			touchleave: true
		};
	function EventHandler$listen() {
		var definition,
			name = this.name;

		if (this.invalid) {
			return;
		}

		if (definition = findInViewHierarchy("events", this.root, name)) {
			this.custom = definition(this.node, getCustomHandler(name));
		} else {
			// Looks like we're dealing with a standard DOM event... but let's check
			if (!("on" + name in this.node) && !(window && "on" + name in window) && !isJsdom) {

				// okay to use touch events if this browser doesn't support them
				if (!touchEvents[name]) {
					warnOnceIfDebug(missingPlugin(name, "event"), { node: this.node });
				}

				return;
			}

			this.node.addEventListener(name, shared_genericHandler, false);
		}

		this.hasListener = true;
	}

	function getCustomHandler(name) {
		if (!customHandlers[name]) {
			customHandlers[name] = function (event) {
				var storage = event.node._ractive;

				event.index = storage.index;
				event.keypath = storage.keypath.str;
				event.context = storage.root.viewmodel.get(storage.keypath);

				storage.events[name].fire(event);
			};
		}

		return customHandlers[name];
	}

	var EventHandler_prototype_rebind = EventHandler$rebind;

	function EventHandler$rebind(oldKeypath, newKeypath) {
		var fragment;
		if (this.method) {
			fragment = this.element.parentFragment;
			this.refResolvers.forEach(rebind);

			return;
		}

		if (typeof this.action !== "string") {
			rebind(this.action);
		}

		if (this.dynamicParams) {
			rebind(this.dynamicParams);
		}

		function rebind(thing) {
			thing && thing.rebind(oldKeypath, newKeypath);
		}
	}

	var EventHandler_prototype_render = EventHandler$render;

	function EventHandler$render() {
		this.node = this.element.node;
		// store this on the node itself, so it can be retrieved by a
		// universal handler
		this.node._ractive.events[this.name] = this;

		if (this.method || this.getAction()) {
			this.listen();
		}
	}

	var prototype_resolve = EventHandler$resolve;

	function EventHandler$resolve(index, keypath) {
		this.keypaths[index] = keypath;
	}

	var EventHandler_prototype_unbind = EventHandler$unbind;
	function EventHandler$unbind() {
		if (this.method) {
			this.refResolvers.forEach(methodCallers__unbind);
			return;
		}

		// Tear down dynamic name
		if (typeof this.action !== "string") {
			this.action.unbind();
		}

		// Tear down dynamic parameters
		if (this.dynamicParams) {
			this.dynamicParams.unbind();
		}
	}

	var EventHandler_prototype_unrender = EventHandler$unrender;
	function EventHandler$unrender() {

		if (this.custom) {
			this.custom.teardown();
		} else {
			this.node.removeEventListener(this.name, shared_genericHandler, false);
		}

		this.hasListener = false;
	}

	var EventHandler = function (element, name, template) {
		this.init(element, name, template);
	};

	EventHandler.prototype = {
		bubble: EventHandler_prototype_bubble,
		fire: EventHandler_prototype_fire,
		getAction: getAction,
		init: EventHandler_prototype_init,
		listen: listen,
		rebind: EventHandler_prototype_rebind,
		render: EventHandler_prototype_render,
		resolve: prototype_resolve,
		unbind: EventHandler_prototype_unbind,
		unrender: EventHandler_prototype_unrender
	};

	var _EventHandler = EventHandler;

	var createEventHandlers = function (element, template) {
		var i,
			name,
			names,
			handler,
			result = [];

		for (name in template) {
			if (template.hasOwnProperty(name)) {
				names = name.split("-");
				i = names.length;

				while (i--) {
					handler = new _EventHandler(element, names[i], template[name]);
					result.push(handler);
				}
			}
		}

		return result;
	};

	var Decorator = function (element, template) {
		var self = this,
			ractive,
			name,
			fragment;

		this.element = element;
		this.root = ractive = element.root;

		name = template.n || template;

		if (typeof name !== "string") {
			fragment = new virtualdom_Fragment({
				template: name,
				root: ractive,
				owner: element
			});

			name = fragment.toString();
			fragment.unbind();

			if (name === "") {
				// empty string okay, just no decorator
				return;
			}
		}

		if (template.a) {
			this.params = template.a;
		} else if (template.d) {
			this.fragment = new virtualdom_Fragment({
				template: template.d,
				root: ractive,
				owner: element
			});

			this.params = this.fragment.getArgsList();

			this.fragment.bubble = function () {
				this.dirtyArgs = this.dirtyValue = true;
				self.params = this.getArgsList();

				if (self.ready) {
					self.update();
				}
			};
		}

		this.fn = findInViewHierarchy("decorators", ractive, name);

		if (!this.fn) {
			fatal(missingPlugin(name, "decorator"));
		}
	};

	Decorator.prototype = {
		init: function () {
			var node, result, args;

			node = this.element.node;

			if (this.params) {
				args = [node].concat(this.params);
				result = this.fn.apply(this.root, args);
			} else {
				result = this.fn.call(this.root, node);
			}

			if (!result || !result.teardown) {
				throw new Error("Decorator definition must return an object with a teardown method");
			}

			// TODO does this make sense?
			this.actual = result;
			this.ready = true;
		},

		update: function () {
			if (this.actual.update) {
				this.actual.update.apply(this.root, this.params);
			} else {
				this.actual.teardown(true);
				this.init();
			}
		},

		rebind: function (oldKeypath, newKeypath) {
			if (this.fragment) {
				this.fragment.rebind(oldKeypath, newKeypath);
			}
		},

		teardown: function (updating) {
			this.torndown = true;
			if (this.ready) {
				this.actual.teardown();
			}

			if (!updating && this.fragment) {
				this.fragment.unbind();
			}
		}
	};

	var _Decorator = Decorator;

	function select__bubble() {
		var _this = this;

		if (!this.dirty) {
			this.dirty = true;

			global_runloop.scheduleTask(function () {
				sync(_this);
				_this.dirty = false;
			});
		}

		this.parentFragment.bubble(); // default behaviour
	}

	function sync(selectElement) {
		var selectNode, selectValue, isMultiple, options, optionWasSelected;

		selectNode = selectElement.node;

		if (!selectNode) {
			return;
		}

		options = toArray(selectNode.options);

		selectValue = selectElement.getAttribute("value");
		isMultiple = selectElement.getAttribute("multiple");

		// If the <select> has a specified value, that should override
		// these options
		if (selectValue !== undefined) {
			options.forEach(function (o) {
				var optionValue, shouldSelect;

				optionValue = o._ractive ? o._ractive.value : o.value;
				shouldSelect = isMultiple ? valueContains(selectValue, optionValue) : selectValue == optionValue;

				if (shouldSelect) {
					optionWasSelected = true;
				}

				o.selected = shouldSelect;
			});

			if (!optionWasSelected) {
				if (options[0]) {
					options[0].selected = true;
				}

				if (selectElement.binding) {
					selectElement.binding.forceUpdate();
				}
			}
		}

			// Otherwise the value should be initialised according to which
			// <option> element is selected, if twoway binding is in effect
		else if (selectElement.binding) {
			selectElement.binding.forceUpdate();
		}
	}

	function valueContains(selectValue, optionValue) {
		var i = selectValue.length;
		while (i--) {
			if (selectValue[i] == optionValue) {
				return true;
			}
		}
	}

	function special_option__init(option, template) {
		option.select = findParentSelect(option.parent);

		// we might be inside a <datalist> element
		if (!option.select) {
			return;
		}

		option.select.options.push(option);

		// If the value attribute is missing, use the element's content
		if (!template.a) {
			template.a = {};
		}

		// ...as long as it isn't disabled
		if (template.a.value === undefined && !template.a.hasOwnProperty("disabled")) {
			template.a.value = template.f;
		}

		// If there is a `selected` attribute, but the <select>
		// already has a value, delete it
		if ("selected" in template.a && option.select.getAttribute("value") !== undefined) {
			delete template.a.selected;
		}
	}

	function special_option__unbind(option) {
		if (option.select) {
			removeFromArray(option.select.options, option);
		}
	}

	function findParentSelect(element) {
		if (!element) {
			return;
		}

		do {
			if (element.name === "select") {
				return element;
			}
		} while (element = element.parent);
	}

	var Element_prototype_init = Element$init;
	function Element$init(options) {
		var parentFragment, template, ractive, binding, bindings, twoway, bindingAttrs;

		this.type = ELEMENT;

		// stuff we'll need later
		parentFragment = this.parentFragment = options.parentFragment;
		template = this.template = options.template;

		this.parent = options.pElement || parentFragment.pElement;

		this.root = ractive = parentFragment.root;
		this.index = options.index;
		this.key = options.key;

		this.name = enforceCase(template.e);

		// Special case - <option> elements
		if (this.name === "option") {
			special_option__init(this, template);
		}

		// Special case - <select> elements
		if (this.name === "select") {
			this.options = [];
			this.bubble = select__bubble; // TODO this is a kludge
		}

		// Special case - <form> elements
		if (this.name === "form") {
			this.formBindings = [];
		}

		// handle binding attributes first (twoway, lazy)
		bindingAttrs = processBindingAttributes(this, template);

		// create attributes
		this.attributes = createAttributes(this, template.a);
		this.conditionalAttributes = createConditionalAttributes(this, template.m);

		// append children, if there are any
		if (template.f) {
			this.fragment = new virtualdom_Fragment({
				template: template.f,
				root: ractive,
				owner: this,
				pElement: this,
				cssIds: null
			});
		}

		// the element setting should override the ractive setting
		twoway = ractive.twoway;
		if (bindingAttrs.twoway === false) twoway = false; else if (bindingAttrs.twoway === true) twoway = true;

		this.twoway = twoway;
		this.lazy = bindingAttrs.lazy;

		// create twoway binding
		if (twoway && (binding = init_createTwowayBinding(this, template.a))) {
			this.binding = binding;

			// register this with the root, so that we can do ractive.updateModel()
			bindings = this.root._twowayBindings[binding.keypath.str] || (this.root._twowayBindings[binding.keypath.str] = []);
			bindings.push(binding);
		}

		// create event proxies
		if (template.v) {
			this.eventHandlers = createEventHandlers(this, template.v);
		}

		// create decorator
		if (template.o) {
			this.decorator = new _Decorator(this, template.o);
		}

		// create transitions
		this.intro = template.t0 || template.t1;
		this.outro = template.t0 || template.t2;
	}

	var Element_prototype_rebind = Element$rebind;
	function Element$rebind(oldKeypath, newKeypath) {
		var i, storage, liveQueries, ractive;

		if (this.attributes) {
			this.attributes.forEach(rebind);
		}

		if (this.conditionalAttributes) {
			this.conditionalAttributes.forEach(rebind);
		}

		if (this.eventHandlers) {
			this.eventHandlers.forEach(rebind);
		}

		if (this.decorator) {
			rebind(this.decorator);
		}

		// rebind children
		if (this.fragment) {
			rebind(this.fragment);
		}

		// Update live queries, if necessary
		if (liveQueries = this.liveQueries) {
			ractive = this.root;

			i = liveQueries.length;
			while (i--) {
				liveQueries[i]._makeDirty();
			}
		}

		if (this.node && (storage = this.node._ractive)) {

			// adjust keypath if needed
			assignNewKeypath(storage, "keypath", oldKeypath, newKeypath);
		}

		function rebind(thing) {
			thing.rebind(oldKeypath, newKeypath);
		}
	}

	function special_img__render(img) {
		var loadHandler;

		// if this is an <img>, and we're in a crap browser, we may need to prevent it
		// from overriding width and height when it loads the src
		if (img.attributes.width || img.attributes.height) {
			img.node.addEventListener("load", loadHandler = function () {
				var width = img.getAttribute("width"),
					height = img.getAttribute("height");

				if (width !== undefined) {
					img.node.setAttribute("width", width);
				}

				if (height !== undefined) {
					img.node.setAttribute("height", height);
				}

				img.node.removeEventListener("load", loadHandler, false);
			}, false);
		}
	}

	function form__render(element) {
		element.node.addEventListener("reset", handleReset, false);
	}

	function form__unrender(element) {
		element.node.removeEventListener("reset", handleReset, false);
	}

	function handleReset() {
		var element = this._ractive.proxy;

		global_runloop.start();
		element.formBindings.forEach(updateModel);
		global_runloop.end();
	}

	function updateModel(binding) {
		binding.root.viewmodel.set(binding.keypath, binding.resetValue);
	}

	var Transition_prototype_init = Transition$init;
	function Transition$init(element, template, isIntro) {
		var ractive, name, fragment;

		this.element = element;
		this.root = ractive = element.root;
		this.isIntro = isIntro;

		name = template.n || template;

		if (typeof name !== "string") {
			fragment = new virtualdom_Fragment({
				template: name,
				root: ractive,
				owner: element
			});

			name = fragment.toString();
			fragment.unbind();

			if (name === "") {
				// empty string okay, just no transition
				return;
			}
		}

		this.name = name;

		if (template.a) {
			this.params = template.a;
		} else if (template.d) {
			// TODO is there a way to interpret dynamic arguments without all the
			// 'dependency thrashing'?
			fragment = new virtualdom_Fragment({
				template: template.d,
				root: ractive,
				owner: element
			});

			this.params = fragment.getArgsList();
			fragment.unbind();
		}

		this._fn = findInViewHierarchy("transitions", ractive, name);

		if (!this._fn) {
			warnOnceIfDebug(missingPlugin(name, "transition"), { ractive: this.root });
		}
	}

	var camelCase = function (hyphenatedStr) {
		return hyphenatedStr.replace(/-([a-zA-Z])/g, function (match, $1) {
			return $1.toUpperCase();
		});
	};

	var helpers_prefix__prefix, prefixCache, helpers_prefix__testStyle;

	if (!isClient) {
		helpers_prefix__prefix = null;
	} else {
		prefixCache = {};
		helpers_prefix__testStyle = createElement("div").style;

		helpers_prefix__prefix = function (prop) {
			var i, vendor, capped;

			prop = camelCase(prop);

			if (!prefixCache[prop]) {
				if (helpers_prefix__testStyle[prop] !== undefined) {
					prefixCache[prop] = prop;
				} else {
					// test vendors...
					capped = prop.charAt(0).toUpperCase() + prop.substring(1);

					i = vendors.length;
					while (i--) {
						vendor = vendors[i];
						if (helpers_prefix__testStyle[vendor + capped] !== undefined) {
							prefixCache[prop] = vendor + capped;
							break;
						}
					}
				}
			}

			return prefixCache[prop];
		};
	}

	var helpers_prefix = helpers_prefix__prefix;

	var getStyle, prototype_getStyle__getComputedStyle;

	if (!isClient) {
		getStyle = null;
	} else {
		prototype_getStyle__getComputedStyle = window.getComputedStyle || legacy.getComputedStyle;

		getStyle = function (props) {
			var computedStyle, styles, i, prop, value;

			computedStyle = prototype_getStyle__getComputedStyle(this.node);

			if (typeof props === "string") {
				value = computedStyle[helpers_prefix(props)];
				if (value === "0px") {
					value = 0;
				}
				return value;
			}

			if (!isArray(props)) {
				throw new Error("Transition$getStyle must be passed a string, or an array of strings representing CSS properties");
			}

			styles = {};

			i = props.length;
			while (i--) {
				prop = props[i];
				value = computedStyle[helpers_prefix(prop)];
				if (value === "0px") {
					value = 0;
				}
				styles[prop] = value;
			}

			return styles;
		};
	}

	var prototype_getStyle = getStyle;

	var setStyle = function (style, value) {
		var prop;

		if (typeof style === "string") {
			this.node.style[helpers_prefix(style)] = value;
		} else {
			for (prop in style) {
				if (style.hasOwnProperty(prop)) {
					this.node.style[helpers_prefix(prop)] = style[prop];
				}
			}
		}

		return this;
	};

	var Ticker = function (options) {
		var easing;

		this.duration = options.duration;
		this.step = options.step;
		this.complete = options.complete;

		// easing
		if (typeof options.easing === "string") {
			easing = options.root.easing[options.easing];

			if (!easing) {
				warnOnceIfDebug(missingPlugin(options.easing, "easing"));
				easing = linear;
			}
		} else if (typeof options.easing === "function") {
			easing = options.easing;
		} else {
			easing = linear;
		}

		this.easing = easing;

		this.start = utils_getTime();
		this.end = this.start + this.duration;

		this.running = true;
		shared_animations.add(this);
	};

	Ticker.prototype = {
		tick: function (now) {
			var elapsed, eased;

			if (!this.running) {
				return false;
			}

			if (now > this.end) {
				if (this.step) {
					this.step(1);
				}

				if (this.complete) {
					this.complete(1);
				}

				return false;
			}

			elapsed = now - this.start;
			eased = this.easing(elapsed / this.duration);

			if (this.step) {
				this.step(eased);
			}

			return true;
		},

		stop: function () {
			if (this.abort) {
				this.abort();
			}

			this.running = false;
		}
	};

	var shared_Ticker = Ticker;
	function linear(t) {
		return t;
	}

	var unprefixPattern = new RegExp("^-(?:" + vendors.join("|") + ")-");

	var unprefix = function (prop) {
		return prop.replace(unprefixPattern, "");
	};

	var vendorPattern = new RegExp("^(?:" + vendors.join("|") + ")([A-Z])");

	var hyphenate = function (str) {
		var hyphenated;

		if (!str) {
			return ""; // edge case
		}

		if (vendorPattern.test(str)) {
			str = "-" + str;
		}

		hyphenated = str.replace(/[A-Z]/g, function (match) {
			return "-" + match.toLowerCase();
		});

		return hyphenated;
	};

	var createTransitions,
		animateStyle_createTransitions__testStyle,
		TRANSITION,
		TRANSITIONEND,
		CSS_TRANSITIONS_ENABLED,
		TRANSITION_DURATION,
		TRANSITION_PROPERTY,
		TRANSITION_TIMING_FUNCTION,
		canUseCssTransitions = {},
		cannotUseCssTransitions = {};

	if (!isClient) {
		createTransitions = null;
	} else {
		animateStyle_createTransitions__testStyle = createElement("div").style;

		// determine some facts about our environment
		(function () {
			if (animateStyle_createTransitions__testStyle.transition !== undefined) {
				TRANSITION = "transition";
				TRANSITIONEND = "transitionend";
				CSS_TRANSITIONS_ENABLED = true;
			} else if (animateStyle_createTransitions__testStyle.webkitTransition !== undefined) {
				TRANSITION = "webkitTransition";
				TRANSITIONEND = "webkitTransitionEnd";
				CSS_TRANSITIONS_ENABLED = true;
			} else {
				CSS_TRANSITIONS_ENABLED = false;
			}
		})();

		if (TRANSITION) {
			TRANSITION_DURATION = TRANSITION + "Duration";
			TRANSITION_PROPERTY = TRANSITION + "Property";
			TRANSITION_TIMING_FUNCTION = TRANSITION + "TimingFunction";
		}

		createTransitions = function (t, to, options, changedProperties, resolve) {

			// Wait a beat (otherwise the target styles will be applied immediately)
			// TODO use a fastdom-style mechanism?
			setTimeout(function () {

				var hashPrefix, jsTransitionsComplete, cssTransitionsComplete, checkComplete, transitionEndHandler;

				checkComplete = function () {
					if (jsTransitionsComplete && cssTransitionsComplete) {
						// will changes to events and fire have an unexpected consequence here?
						t.root.fire(t.name + ":end", t.node, t.isIntro);
						resolve();
					}
				};

				// this is used to keep track of which elements can use CSS to animate
				// which properties
				hashPrefix = (t.node.namespaceURI || "") + t.node.tagName;

				t.node.style[TRANSITION_PROPERTY] = changedProperties.map(helpers_prefix).map(hyphenate).join(",");
				t.node.style[TRANSITION_TIMING_FUNCTION] = hyphenate(options.easing || "linear");
				t.node.style[TRANSITION_DURATION] = options.duration / 1000 + "s";

				transitionEndHandler = function (event) {
					var index;

					index = changedProperties.indexOf(camelCase(unprefix(event.propertyName)));
					if (index !== -1) {
						changedProperties.splice(index, 1);
					}

					if (changedProperties.length) {
						// still transitioning...
						return;
					}

					t.node.removeEventListener(TRANSITIONEND, transitionEndHandler, false);

					cssTransitionsComplete = true;
					checkComplete();
				};

				t.node.addEventListener(TRANSITIONEND, transitionEndHandler, false);

				setTimeout(function () {
					var i = changedProperties.length,
						hash,
						originalValue,
						index,
						propertiesToTransitionInJs = [],
						prop,
						suffix;

					while (i--) {
						prop = changedProperties[i];
						hash = hashPrefix + prop;

						if (CSS_TRANSITIONS_ENABLED && !cannotUseCssTransitions[hash]) {
							t.node.style[helpers_prefix(prop)] = to[prop];

							// If we're not sure if CSS transitions are supported for
							// this tag/property combo, find out now
							if (!canUseCssTransitions[hash]) {
								originalValue = t.getStyle(prop);

								// if this property is transitionable in this browser,
								// the current style will be different from the target style
								canUseCssTransitions[hash] = t.getStyle(prop) != to[prop];
								cannotUseCssTransitions[hash] = !canUseCssTransitions[hash];

								// Reset, if we're going to use timers after all
								if (cannotUseCssTransitions[hash]) {
									t.node.style[helpers_prefix(prop)] = originalValue;
								}
							}
						}

						if (!CSS_TRANSITIONS_ENABLED || cannotUseCssTransitions[hash]) {
							// we need to fall back to timer-based stuff
							if (originalValue === undefined) {
								originalValue = t.getStyle(prop);
							}

							// need to remove this from changedProperties, otherwise transitionEndHandler
							// will get confused
							index = changedProperties.indexOf(prop);
							if (index === -1) {
								warnIfDebug("Something very strange happened with transitions. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!", { node: t.node });
							} else {
								changedProperties.splice(index, 1);
							}

							// TODO Determine whether this property is animatable at all

							suffix = /[^\d]*$/.exec(to[prop])[0];

							// ...then kick off a timer-based transition
							propertiesToTransitionInJs.push({
								name: helpers_prefix(prop),
								interpolator: shared_interpolate(parseFloat(originalValue), parseFloat(to[prop])),
								suffix: suffix
							});
						}
					}

					// javascript transitions
					if (propertiesToTransitionInJs.length) {
						new shared_Ticker({
							root: t.root,
							duration: options.duration,
							easing: camelCase(options.easing || ""),
							step: function (pos) {
								var prop, i;

								i = propertiesToTransitionInJs.length;
								while (i--) {
									prop = propertiesToTransitionInJs[i];
									t.node.style[prop.name] = prop.interpolator(pos) + prop.suffix;
								}
							},
							complete: function () {
								jsTransitionsComplete = true;
								checkComplete();
							}
						});
					} else {
						jsTransitionsComplete = true;
					}

					if (!changedProperties.length) {
						// We need to cancel the transitionEndHandler, and deal with
						// the fact that it will never fire
						t.node.removeEventListener(TRANSITIONEND, transitionEndHandler, false);
						cssTransitionsComplete = true;
						checkComplete();
					}
				}, 0);
			}, options.delay || 0);
		};
	}

	var animateStyle_createTransitions = createTransitions;

	var hidden, vendor, animateStyle_visibility__prefix, animateStyle_visibility__i, visibility;

	if (typeof document !== "undefined") {
		hidden = "hidden";

		visibility = {};

		if (hidden in document) {
			animateStyle_visibility__prefix = "";
		} else {
			animateStyle_visibility__i = vendors.length;
			while (animateStyle_visibility__i--) {
				vendor = vendors[animateStyle_visibility__i];
				hidden = vendor + "Hidden";

				if (hidden in document) {
					animateStyle_visibility__prefix = vendor;
				}
			}
		}

		if (animateStyle_visibility__prefix !== undefined) {
			document.addEventListener(animateStyle_visibility__prefix + "visibilitychange", onChange);

			// initialise
			onChange();
		} else {
			// gah, we're in an old browser
			if ("onfocusout" in document) {
				document.addEventListener("focusout", onHide);
				document.addEventListener("focusin", onShow);
			} else {
				window.addEventListener("pagehide", onHide);
				window.addEventListener("blur", onHide);

				window.addEventListener("pageshow", onShow);
				window.addEventListener("focus", onShow);
			}

			visibility.hidden = false; // until proven otherwise. Not ideal but hey
		}
	}

	function onChange() {
		visibility.hidden = document[hidden];
	}

	function onHide() {
		visibility.hidden = true;
	}

	function onShow() {
		visibility.hidden = false;
	}

	var animateStyle_visibility = visibility;

	var animateStyle, _animateStyle__getComputedStyle, resolved;

	if (!isClient) {
		animateStyle = null;
	} else {
		_animateStyle__getComputedStyle = window.getComputedStyle || legacy.getComputedStyle;

		animateStyle = function (style, value, options) {
			var _this = this;

			var to;

			if (arguments.length === 4) {
				throw new Error("t.animateStyle() returns a promise - use .then() instead of passing a callback");
			}

			// Special case - page isn't visible. Don't animate anything, because
			// that way you'll never get CSS transitionend events
			if (animateStyle_visibility.hidden) {
				this.setStyle(style, value);
				return resolved || (resolved = utils_Promise.resolve());
			}

			if (typeof style === "string") {
				to = {};
				to[style] = value;
			} else {
				to = style;

				// shuffle arguments
				options = value;
			}

			// As of 0.3.9, transition authors should supply an `option` object with
			// `duration` and `easing` properties (and optional `delay`), plus a
			// callback function that gets called after the animation completes

			// TODO remove this check in a future version
			if (!options) {
				warnOnceIfDebug("The \"%s\" transition does not supply an options object to `t.animateStyle()`. This will break in a future version of Ractive. For more info see https://github.com/RactiveJS/Ractive/issues/340", this.name);
				options = this;
			}

			var promise = new utils_Promise(function (resolve) {
				var propertyNames, changedProperties, computedStyle, current, from, i, prop;

				// Edge case - if duration is zero, set style synchronously and complete
				if (!options.duration) {
					_this.setStyle(to);
					resolve();
					return;
				}

				// Get a list of the properties we're animating
				propertyNames = Object.keys(to);
				changedProperties = [];

				// Store the current styles
				computedStyle = _animateStyle__getComputedStyle(_this.node);

				from = {};
				i = propertyNames.length;
				while (i--) {
					prop = propertyNames[i];
					current = computedStyle[helpers_prefix(prop)];

					if (current === "0px") {
						current = 0;
					}

					// we need to know if we're actually changing anything
					if (current != to[prop]) {
						// use != instead of !==, so we can compare strings with numbers
						changedProperties.push(prop);

						// make the computed style explicit, so we can animate where
						// e.g. height='auto'
						_this.node.style[helpers_prefix(prop)] = current;
					}
				}

				// If we're not actually changing anything, the transitionend event
				// will never fire! So we complete early
				if (!changedProperties.length) {
					resolve();
					return;
				}

				animateStyle_createTransitions(_this, to, options, changedProperties, resolve);
			});

			return promise;
		};
	}

	var _animateStyle = animateStyle;

	var processParams = function (params, defaults) {
		if (typeof params === "number") {
			params = { duration: params };
		} else if (typeof params === "string") {
			if (params === "slow") {
				params = { duration: 600 };
			} else if (params === "fast") {
				params = { duration: 200 };
			} else {
				params = { duration: 400 };
			}
		} else if (!params) {
			params = {};
		}

		return fillGaps({}, params, defaults);
	};

	var prototype_start = Transition$start;

	function Transition$start() {
		var _this = this;

		var node, originalStyle, completed;

		node = this.node = this.element.node;
		originalStyle = node.getAttribute("style");

		// create t.complete() - we don't want this on the prototype,
		// because we don't want `this` silliness when passing it as
		// an argument
		this.complete = function (noReset) {
			if (completed) {
				return;
			}

			if (!noReset && _this.isIntro) {
				resetStyle(node, originalStyle);
			}

			node._ractive.transition = null;
			_this._manager.remove(_this);

			completed = true;
		};

		// If the transition function doesn't exist, abort
		if (!this._fn) {
			this.complete();
			return;
		}

		this._fn.apply(this.root, [this].concat(this.params));
	}

	function resetStyle(node, style) {
		if (style) {
			node.setAttribute("style", style);
		} else {

			// Next line is necessary, to remove empty style attribute!
			// See http://stackoverflow.com/a/7167553
			node.getAttribute("style");
			node.removeAttribute("style");
		}
	}

	var Transition = function (owner, template, isIntro) {
		this.init(owner, template, isIntro);
	};

	Transition.prototype = {
		init: Transition_prototype_init,
		start: prototype_start,
		getStyle: prototype_getStyle,
		setStyle: setStyle,
		animateStyle: _animateStyle,
		processParams: processParams
	};

	var _Transition = Transition;

	var Element_prototype_render = Element$render;

	var updateCss, updateScript;

	updateCss = function () {
		var node = this.node,
			content = this.fragment.toString(false);

		// IE8 has no styleSheet unless there's a type text/css
		if (window && window.appearsToBeIELessEqual8) {
			node.type = "text/css";
		}

		if (node.styleSheet) {
			node.styleSheet.cssText = content;
		} else {

			while (node.hasChildNodes()) {
				node.removeChild(node.firstChild);
			}

			node.appendChild(document.createTextNode(content));
		}
	};

	updateScript = function () {
		if (!this.node.type || this.node.type === "text/javascript") {
			warnIfDebug("Script tag was updated. This does not cause the code to be re-evaluated!", { ractive: this.root });
			// As it happens, we ARE in a position to re-evaluate the code if we wanted
			// to - we could eval() it, or insert it into a fresh (temporary) script tag.
			// But this would be a terrible idea with unpredictable results, so let's not.
		}

		this.node.text = this.fragment.toString(false);
	};
	function Element$render() {
		var _this = this;

		var root = this.root,
			namespace,
			node,
			transition;

		namespace = getNamespace(this);
		node = this.node = createElement(this.name, namespace);

		// Is this a top-level node of a component? If so, we may need to add
		// a data-ractive-css attribute, for CSS encapsulation
		if (this.parentFragment.cssIds) {
			this.node.setAttribute("data-ractive-css", this.parentFragment.cssIds.map(function (x) {
				return "{" + x + "}";
			}).join(" "));
		}

		// Add _ractive property to the node - we use this object to store stuff
		// related to proxy events, two-way bindings etc
		defineProperty(this.node, "_ractive", {
			value: {
				proxy: this,
				keypath: getInnerContext(this.parentFragment),
				events: create(null),
				root: root
			}
		});

		// Render attributes
		this.attributes.forEach(function (a) {
			return a.render(node);
		});
		this.conditionalAttributes.forEach(function (a) {
			return a.render(node);
		});

		// Render children
		if (this.fragment) {
			// Special case - <script> element
			if (this.name === "script") {
				this.bubble = updateScript;
				this.node.text = this.fragment.toString(false); // bypass warning initially
				this.fragment.unrender = noop; // TODO this is a kludge
			}

				// Special case - <style> element
			else if (this.name === "style") {
				this.bubble = updateCss;
				this.bubble();
				this.fragment.unrender = noop;
			}

				// Special case - contenteditable
			else if (this.binding && this.getAttribute("contenteditable")) {
				this.fragment.unrender = noop;
			} else {
				this.node.appendChild(this.fragment.render());
			}
		}

		// deal with two-way bindings
		if (this.binding) {
			this.binding.render();
			this.node._ractive.binding = this.binding;
		}

		// Add proxy event handlers
		if (this.eventHandlers) {
			this.eventHandlers.forEach(function (h) {
				return h.render();
			});
		}

		if (this.name === "option") {
			processOption(this);
		}

		// Special cases
		if (this.name === "img") {
			// if this is an <img>, and we're in a crap browser, we may
			// need to prevent it from overriding width and height when
			// it loads the src
			special_img__render(this);
		} else if (this.name === "form") {
			// forms need to keep track of their bindings, in case of reset
			form__render(this);
		} else if (this.name === "input" || this.name === "textarea") {
			// inputs and textareas should store their initial value as
			// `defaultValue` in case of reset
			this.node.defaultValue = this.node.value;
		} else if (this.name === "option") {
			// similarly for option nodes
			this.node.defaultSelected = this.node.selected;
		}

		// apply decorator(s)
		if (this.decorator && this.decorator.fn) {
			global_runloop.scheduleTask(function () {
				if (!_this.decorator.torndown) {
					_this.decorator.init();
				}
			}, true);
		}

		// trigger intro transition
		if (root.transitionsEnabled && this.intro) {
			transition = new _Transition(this, this.intro, true);
			global_runloop.registerTransition(transition);
			global_runloop.scheduleTask(function () {
				return transition.start();
			}, true);

			this.transition = transition;
		}

		if (this.node.autofocus) {
			// Special case. Some browsers (*cough* Firefix *cough*) have a problem
			// with dynamically-generated elements having autofocus, and they won't
			// allow you to programmatically focus the element until it's in the DOM
			global_runloop.scheduleTask(function () {
				return _this.node.focus();
			}, true);
		}

		updateLiveQueries(this);
		return this.node;
	}

	function getNamespace(element) {
		var namespace, xmlns, parent;

		// Use specified namespace...
		if (xmlns = element.getAttribute("xmlns")) {
			namespace = xmlns;
		}

			// ...or SVG namespace, if this is an <svg> element
		else if (element.name === "svg") {
			namespace = namespaces.svg;
		} else if (parent = element.parent) {
			// ...or HTML, if the parent is a <foreignObject>
			if (parent.name === "foreignObject") {
				namespace = namespaces.html;
			}

				// ...or inherit from the parent node
			else {
				namespace = parent.node.namespaceURI;
			}
		} else {
			namespace = element.root.el.namespaceURI;
		}

		return namespace;
	}

	function processOption(option) {
		var optionValue, selectValue, i;

		if (!option.select) {
			return;
		}

		selectValue = option.select.getAttribute("value");
		if (selectValue === undefined) {
			return;
		}

		optionValue = option.getAttribute("value");

		if (option.select.node.multiple && isArray(selectValue)) {
			i = selectValue.length;
			while (i--) {
				if (optionValue == selectValue[i]) {
					option.node.selected = true;
					break;
				}
			}
		} else {
			option.node.selected = optionValue == selectValue;
		}
	}

	function updateLiveQueries(element) {
		var instance, liveQueries, i, selector, query;

		// Does this need to be added to any live queries?
		instance = element.root;

		do {
			liveQueries = instance._liveQueries;

			i = liveQueries.length;
			while (i--) {
				selector = liveQueries[i];
				query = liveQueries["_" + selector];

				if (query._test(element)) {
					// keep register of applicable selectors, for when we teardown
					(element.liveQueries || (element.liveQueries = [])).push(query);
				}
			}
		} while (instance = instance.parent);
	}

	var Element_prototype_toString = function () {
		var str, escape;

		if (this.template.y) {
			// DOCTYPE declaration
			return "<!DOCTYPE" + this.template.dd + ">";
		}

		str = "<" + this.template.e;

		str += this.attributes.map(stringifyAttribute).join("") + this.conditionalAttributes.map(stringifyAttribute).join("");

		// Special case - selected options
		if (this.name === "option" && optionIsSelected(this)) {
			str += " selected";
		}

		// Special case - two-way radio name bindings
		if (this.name === "input" && inputIsCheckedRadio(this)) {
			str += " checked";
		}

		str += ">";

		// Special case - textarea
		if (this.name === "textarea" && this.getAttribute("value") !== undefined) {
			str += escapeHtml(this.getAttribute("value"));
		}

			// Special case - contenteditable
		else if (this.getAttribute("contenteditable") !== undefined) {
			str += this.getAttribute("value") || "";
		}

		if (this.fragment) {
			escape = this.name !== "script" && this.name !== "style";
			str += this.fragment.toString(escape);
		}

		// add a closing tag if this isn't a void element
		if (!voidElementNames.test(this.template.e)) {
			str += "</" + this.template.e + ">";
		}

		return str;
	};

	function optionIsSelected(element) {
		var optionValue, selectValue, i;

		optionValue = element.getAttribute("value");

		if (optionValue === undefined || !element.select) {
			return false;
		}

		selectValue = element.select.getAttribute("value");

		if (selectValue == optionValue) {
			return true;
		}

		if (element.select.getAttribute("multiple") && isArray(selectValue)) {
			i = selectValue.length;
			while (i--) {
				if (selectValue[i] == optionValue) {
					return true;
				}
			}
		}
	}

	function inputIsCheckedRadio(element) {
		var attributes, typeAttribute, valueAttribute, nameAttribute;

		attributes = element.attributes;

		typeAttribute = attributes.type;
		valueAttribute = attributes.value;
		nameAttribute = attributes.name;

		if (!typeAttribute || typeAttribute.value !== "radio" || !valueAttribute || !nameAttribute.interpolator) {
			return;
		}

		if (valueAttribute.value === nameAttribute.interpolator.value) {
			return true;
		}
	}

	function stringifyAttribute(attribute) {
		var str = attribute.toString();
		return str ? " " + str : "";
	}

	var Element_prototype_unbind = Element$unbind;
	function Element$unbind() {
		if (this.fragment) {
			this.fragment.unbind();
		}

		if (this.binding) {
			this.binding.unbind();
		}

		if (this.eventHandlers) {
			this.eventHandlers.forEach(methodCallers__unbind);
		}

		// Special case - <option>
		if (this.name === "option") {
			special_option__unbind(this);
		}

		this.attributes.forEach(methodCallers__unbind);
		this.conditionalAttributes.forEach(methodCallers__unbind);
	}

	var Element_prototype_unrender = Element$unrender;

	function Element$unrender(shouldDestroy) {
		var binding, bindings, transition;

		if (transition = this.transition) {
			transition.complete();
		}

		// Detach as soon as we can
		if (this.name === "option") {
			// <option> elements detach immediately, so that
			// their parent <select> element syncs correctly, and
			// since option elements can't have transitions anyway
			this.detach();
		} else if (shouldDestroy) {
			global_runloop.detachWhenReady(this);
		}

		// Children first. that way, any transitions on child elements will be
		// handled by the current transitionManager
		if (this.fragment) {
			this.fragment.unrender(false);
		}

		if (binding = this.binding) {
			this.binding.unrender();

			this.node._ractive.binding = null;
			bindings = this.root._twowayBindings[binding.keypath.str];
			bindings.splice(bindings.indexOf(binding), 1);
		}

		// Remove event handlers
		if (this.eventHandlers) {
			this.eventHandlers.forEach(methodCallers__unrender);
		}

		if (this.decorator) {
			global_runloop.registerDecorator(this.decorator);
		}

		// trigger outro transition if necessary
		if (this.root.transitionsEnabled && this.outro) {
			transition = new _Transition(this, this.outro, false);
			global_runloop.registerTransition(transition);
			global_runloop.scheduleTask(function () {
				return transition.start();
			});
		}

		// Remove this node from any live queries
		if (this.liveQueries) {
			removeFromLiveQueries(this);
		}

		if (this.name === "form") {
			form__unrender(this);
		}
	}

	function removeFromLiveQueries(element) {
		var query, selector, i;

		i = element.liveQueries.length;
		while (i--) {
			query = element.liveQueries[i];
			selector = query.selector;

			query._remove(element.node);
		}
	}

	var Element = function (options) {
		this.init(options);
	};

	Element.prototype = {
		bubble: Element_prototype_bubble,
		detach: Element_prototype_detach,
		find: Element_prototype_find,
		findAll: Element_prototype_findAll,
		findAllComponents: Element_prototype_findAllComponents,
		findComponent: Element_prototype_findComponent,
		findNextNode: Element_prototype_findNextNode,
		firstNode: Element_prototype_firstNode,
		getAttribute: getAttribute,
		init: Element_prototype_init,
		rebind: Element_prototype_rebind,
		render: Element_prototype_render,
		toString: Element_prototype_toString,
		unbind: Element_prototype_unbind,
		unrender: Element_prototype_unrender
	};

	var _Element = Element;

	var deIndent__empty = /^\s*$/,
		deIndent__leadingWhitespace = /^\s*/;

	var deIndent = function (str) {
		var lines, firstLine, lastLine, minIndent;

		lines = str.split("\n");

		// remove first and last line, if they only contain whitespace
		firstLine = lines[0];
		if (firstLine !== undefined && deIndent__empty.test(firstLine)) {
			lines.shift();
		}

		lastLine = lastItem(lines);
		if (lastLine !== undefined && deIndent__empty.test(lastLine)) {
			lines.pop();
		}

		minIndent = lines.reduce(reducer, null);

		if (minIndent) {
			str = lines.map(function (line) {
				return line.replace(minIndent, "");
			}).join("\n");
		}

		return str;
	};

	function reducer(previous, line) {
		var lineIndent = deIndent__leadingWhitespace.exec(line)[0];

		if (previous === null || lineIndent.length < previous.length) {
			return lineIndent;
		}

		return previous;
	}

	var Partial_getPartialTemplate = getPartialTemplate;

	function getPartialTemplate(ractive, name, parentFragment) {
		var partial;

		// If the partial in instance or view heirarchy instances, great
		if (partial = getPartialFromRegistry(ractive, name, parentFragment || {})) {
			return partial;
		}

		// Does it exist on the page as a script tag?
		partial = template_parser.fromId(name, { noThrow: true });

		if (partial) {
			// is this necessary?
			partial = deIndent(partial);

			// parse and register to this ractive instance
			var parsed = template_parser.parse(partial, template_parser.getParseOptions(ractive));

			// register (and return main partial if there are others in the template)
			return ractive.partials[name] = parsed.t;
		}
	}

	function getPartialFromRegistry(ractive, name, parentFragment) {
		var fn = undefined,
			partial = findParentPartial(name, parentFragment.owner);

		// if there was an instance up-hierarchy, cool
		if (partial) return partial;

		// find first instance in the ractive or view hierarchy that has this partial
		var instance = findInstance("partials", ractive, name);

		if (!instance) {
			return;
		}

		partial = instance.partials[name];

		// partial is a function?
		if (typeof partial === "function") {
			fn = partial.bind(instance);
			fn.isOwner = instance.partials.hasOwnProperty(name);
			partial = fn.call(ractive, template_parser);
		}

		if (!partial && partial !== "") {
			warnIfDebug(noRegistryFunctionReturn, name, "partial", "partial", { ractive: ractive });
			return;
		}

		// If this was added manually to the registry,
		// but hasn't been parsed, parse it now
		if (!template_parser.isParsed(partial)) {

			// use the parseOptions of the ractive instance on which it was found
			var parsed = template_parser.parse(partial, template_parser.getParseOptions(instance));

			// Partials cannot contain nested partials!
			// TODO add a test for this
			if (parsed.p) {
				warnIfDebug("Partials ({{>%s}}) cannot contain nested inline partials", name, { ractive: ractive });
			}

			// if fn, use instance to store result, otherwise needs to go
			// in the correct point in prototype chain on instance or constructor
			var target = fn ? instance : findOwner(instance, name);

			// may be a template with partials, which need to be registered and main template extracted
			target.partials[name] = partial = parsed.t;
		}

		// store for reset
		if (fn) {
			partial._fn = fn;
		}

		return partial.v ? partial.t : partial;
	}

	function findOwner(ractive, key) {
		return ractive.partials.hasOwnProperty(key) ? ractive : findConstructor(ractive.constructor, key);
	}

	function findConstructor(constructor, key) {
		if (!constructor) {
			return;
		}
		return constructor.partials.hasOwnProperty(key) ? constructor : findConstructor(constructor._Parent, key);
	}

	function findParentPartial(name, parent) {
		if (parent) {
			if (parent.template && parent.template.p && parent.template.p[name]) {
				return parent.template.p[name];
			} else if (parent.parentFragment && parent.parentFragment.owner) {
				return findParentPartial(name, parent.parentFragment.owner);
			}
		}
	}

	var applyIndent = function (string, indent) {
		var indented;

		if (!indent) {
			return string;
		}

		indented = string.split("\n").map(function (line, notFirstLine) {
			return notFirstLine ? indent + line : line;
		}).join("\n");

		return indented;
	};

	var missingPartialMessage = "Could not find template for partial \"%s\"";

	var Partial = function (options) {
		var parentFragment, template;

		parentFragment = this.parentFragment = options.parentFragment;

		this.root = parentFragment.root;
		this.type = PARTIAL;
		this.index = options.index;
		this.name = options.template.r;
		this.rendered = false;

		this.fragment = this.fragmentToRender = this.fragmentToUnrender = null;

		Mustache.init(this, options);

		// If this didn't resolve, it most likely means we have a named partial
		// (i.e. `{{>foo}}` means 'use the foo partial', not 'use the partial
		// whose name is the value of `foo`')
		if (!this.keypath) {
			if (template = Partial_getPartialTemplate(this.root, this.name, parentFragment)) {
				shared_unbind.call(this); // prevent any further changes
				this.isNamed = true;
				this.setTemplate(template);
			} else {
				warnOnceIfDebug(missingPartialMessage, this.name);
			}
		}
	};

	Partial.prototype = {
		bubble: function () {
			this.parentFragment.bubble();
		},

		detach: function () {
			return this.fragment.detach();
		},

		find: function (selector) {
			return this.fragment.find(selector);
		},

		findAll: function (selector, query) {
			return this.fragment.findAll(selector, query);
		},

		findComponent: function (selector) {
			return this.fragment.findComponent(selector);
		},

		findAllComponents: function (selector, query) {
			return this.fragment.findAllComponents(selector, query);
		},

		firstNode: function () {
			return this.fragment.firstNode();
		},

		findNextNode: function () {
			return this.parentFragment.findNextNode(this);
		},

		getPartialName: function () {
			if (this.isNamed && this.name) return this.name; else if (this.value === undefined) return this.name; else return this.value;
		},

		getValue: function () {
			return this.fragment.getValue();
		},

		rebind: function (oldKeypath, newKeypath) {
			// named partials aren't bound, so don't rebind
			if (!this.isNamed) {
				Mustache_rebind.call(this, oldKeypath, newKeypath);
			}

			if (this.fragment) {
				this.fragment.rebind(oldKeypath, newKeypath);
			}
		},

		render: function () {
			this.docFrag = document.createDocumentFragment();
			this.update();

			this.rendered = true;
			return this.docFrag;
		},

		resolve: Mustache.resolve,

		setValue: function (value) {
			var template;

			if (value !== undefined && value === this.value) {
				// nothing has changed, so no work to be done
				return;
			}

			if (value !== undefined) {
				template = Partial_getPartialTemplate(this.root, "" + value, this.parentFragment);
			}

			// we may be here if we have a partial like `{{>foo}}` and `foo` is the
			// name of both a data property (whose value ISN'T the name of a partial)
			// and a partial. In those cases, this becomes a named partial
			if (!template && this.name && (template = Partial_getPartialTemplate(this.root, this.name, this.parentFragment))) {
				shared_unbind.call(this);
				this.isNamed = true;
			}

			if (!template) {
				warnOnceIfDebug(missingPartialMessage, this.name, { ractive: this.root });
			}

			this.value = value;

			this.setTemplate(template || []);

			this.bubble();

			if (this.rendered) {
				global_runloop.addView(this);
			}
		},

		setTemplate: function (template) {
			if (this.fragment) {
				this.fragment.unbind();
				if (this.rendered) {
					this.fragmentToUnrender = this.fragment;
				}
			}

			this.fragment = new virtualdom_Fragment({
				template: template,
				root: this.root,
				owner: this,
				pElement: this.parentFragment.pElement
			});

			this.fragmentToRender = this.fragment;
		},

		toString: function (toString) {
			var string, previousItem, lastLine, match;

			string = this.fragment.toString(toString);

			previousItem = this.parentFragment.items[this.index - 1];

			if (!previousItem || previousItem.type !== TEXT) {
				return string;
			}

			lastLine = previousItem.text.split("\n").pop();

			if (match = /^\s+$/.exec(lastLine)) {
				return applyIndent(string, match[0]);
			}

			return string;
		},

		unbind: function () {
			if (!this.isNamed) {
				// dynamic partial - need to unbind self
				shared_unbind.call(this);
			}

			if (this.fragment) {
				this.fragment.unbind();
			}
		},

		unrender: function (shouldDestroy) {
			if (this.rendered) {
				if (this.fragment) {
					this.fragment.unrender(shouldDestroy);
				}
				this.rendered = false;
			}
		},

		update: function () {
			var target, anchor;

			if (this.fragmentToUnrender) {
				this.fragmentToUnrender.unrender(true);
				this.fragmentToUnrender = null;
			}

			if (this.fragmentToRender) {
				this.docFrag.appendChild(this.fragmentToRender.render());
				this.fragmentToRender = null;
			}

			if (this.rendered) {
				target = this.parentFragment.getNode();
				anchor = this.parentFragment.findNextNode(this);
				target.insertBefore(this.docFrag, anchor);
			}
		}
	};

	var _Partial = Partial;

	// finds the component constructor in the registry or view hierarchy registries

	var Component_getComponent = getComponent;
	function getComponent(ractive, name) {

		var Component,
			instance = findInstance("components", ractive, name);

		if (instance) {
			Component = instance.components[name];

			// best test we have for not Ractive.extend
			if (!Component._Parent) {
				// function option, execute and store for reset
				var fn = Component.bind(instance);
				fn.isOwner = instance.components.hasOwnProperty(name);
				Component = fn();

				if (!Component) {
					warnIfDebug(noRegistryFunctionReturn, name, "component", "component", { ractive: ractive });

					return;
				}

				if (typeof Component === "string") {
					// allow string lookup
					Component = getComponent(ractive, Component);
				}

				Component._fn = fn;
				instance.components[name] = Component;
			}
		}

		return Component;
	}

	var Component_prototype_detach = Component$detach;
	var Component_prototype_detach__detachHook = new hooks_Hook("detach");
	function Component$detach() {
		var detached = this.instance.fragment.detach();
		Component_prototype_detach__detachHook.fire(this.instance);
		return detached;
	}

	var Component_prototype_find = Component$find;

	function Component$find(selector) {
		return this.instance.fragment.find(selector);
	}

	var Component_prototype_findAll = Component$findAll;

	function Component$findAll(selector, query) {
		return this.instance.fragment.findAll(selector, query);
	}

	var Component_prototype_findAllComponents = Component$findAllComponents;

	function Component$findAllComponents(selector, query) {
		query._test(this, true);

		if (this.instance.fragment) {
			this.instance.fragment.findAllComponents(selector, query);
		}
	}

	var Component_prototype_findComponent = Component$findComponent;

	function Component$findComponent(selector) {
		if (!selector || selector === this.name) {
			return this.instance;
		}

		if (this.instance.fragment) {
			return this.instance.fragment.findComponent(selector);
		}

		return null;
	}

	var Component_prototype_findNextNode = Component$findNextNode;

	function Component$findNextNode() {
		return this.parentFragment.findNextNode(this);
	}

	var Component_prototype_firstNode = Component$firstNode;

	function Component$firstNode() {
		if (this.rendered) {
			return this.instance.fragment.firstNode();
		}

		return null;
	}

	var processWrapper = function (wrapper, array, methodName, newIndices) {
		var root = wrapper.root;
		var keypath = wrapper.keypath;

		if (!!newIndices) {
			root.viewmodel.smartUpdate(keypath, array, newIndices);
		} else {
			// If this is a sort or reverse, we just do root.set()...
			// TODO use merge logic?
			root.viewmodel.mark(keypath);
		}
	};

	var patchedArrayProto = [],
		mutatorMethods = ["pop", "push", "reverse", "shift", "sort", "splice", "unshift"],
		testObj,
		patchArrayMethods,
		unpatchArrayMethods;

	mutatorMethods.forEach(function (methodName) {
		var method = function () {
			for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
				args[_key] = arguments[_key];
			}

			var newIndices, result, wrapper, i;

			newIndices = shared_getNewIndices(this, methodName, args);

			// apply the underlying method
			result = Array.prototype[methodName].apply(this, arguments);

			// trigger changes
			global_runloop.start();

			this._ractive.setting = true;
			i = this._ractive.wrappers.length;
			while (i--) {
				wrapper = this._ractive.wrappers[i];

				global_runloop.addRactive(wrapper.root);
				processWrapper(wrapper, this, methodName, newIndices);
			}

			global_runloop.end();

			this._ractive.setting = false;
			return result;
		};

		defineProperty(patchedArrayProto, methodName, {
			value: method
		});
	});

	// can we use prototype chain injection?
	// http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/#wrappers_prototype_chain_injection
	testObj = {};

	if (testObj.__proto__) {
		// yes, we can
		patchArrayMethods = function (array) {
			array.__proto__ = patchedArrayProto;
		};

		unpatchArrayMethods = function (array) {
			array.__proto__ = Array.prototype;
		};
	} else {
		// no, we can't
		patchArrayMethods = function (array) {
			var i, methodName;

			i = mutatorMethods.length;
			while (i--) {
				methodName = mutatorMethods[i];
				defineProperty(array, methodName, {
					value: patchedArrayProto[methodName],
					configurable: true
				});
			}
		};

		unpatchArrayMethods = function (array) {
			var i;

			i = mutatorMethods.length;
			while (i--) {
				delete array[mutatorMethods[i]];
			}
		};
	}

	patchArrayMethods.unpatch = unpatchArrayMethods;
	var patch = patchArrayMethods;

	var arrayAdaptor,

	// helpers
	ArrayWrapper, array_index__errorMessage;

	arrayAdaptor = {
		filter: function (object) {
			// wrap the array if a) b) it's an array, and b) either it hasn't been wrapped already,
			// or the array didn't trigger the get() itself
			return isArray(object) && (!object._ractive || !object._ractive.setting);
		},
		wrap: function (ractive, array, keypath) {
			return new ArrayWrapper(ractive, array, keypath);
		}
	};

	ArrayWrapper = function (ractive, array, keypath) {
		this.root = ractive;
		this.value = array;
		this.keypath = getKeypath(keypath);

		// if this array hasn't already been ractified, ractify it
		if (!array._ractive) {

			// define a non-enumerable _ractive property to store the wrappers
			defineProperty(array, "_ractive", {
				value: {
					wrappers: [],
					instances: [],
					setting: false
				},
				configurable: true
			});

			patch(array);
		}

		// store the ractive instance, so we can handle transitions later
		if (!array._ractive.instances[ractive._guid]) {
			array._ractive.instances[ractive._guid] = 0;
			array._ractive.instances.push(ractive);
		}

		array._ractive.instances[ractive._guid] += 1;
		array._ractive.wrappers.push(this);
	};

	ArrayWrapper.prototype = {
		get: function () {
			return this.value;
		},
		teardown: function () {
			var array, storage, wrappers, instances, index;

			array = this.value;
			storage = array._ractive;
			wrappers = storage.wrappers;
			instances = storage.instances;

			// if teardown() was invoked because we're clearing the cache as a result of
			// a change that the array itself triggered, we can save ourselves the teardown
			// and immediate setup
			if (storage.setting) {
				return false; // so that we don't remove it from this.root.viewmodel.wrapped
			}

			index = wrappers.indexOf(this);
			if (index === -1) {
				throw new Error(array_index__errorMessage);
			}

			wrappers.splice(index, 1);

			// if nothing else depends on this array, we can revert it to its
			// natural state
			if (!wrappers.length) {
				delete array._ractive;
				patch.unpatch(this.value);
			} else {
				// remove ractive instance if possible
				instances[this.root._guid] -= 1;
				if (!instances[this.root._guid]) {
					index = instances.indexOf(this.root);

					if (index === -1) {
						throw new Error(array_index__errorMessage);
					}

					instances.splice(index, 1);
				}
			}
		}
	};

	array_index__errorMessage = "Something went wrong in a rather interesting way";
	var array_index = arrayAdaptor;

	var numeric = /^\s*[0-9]+\s*$/;

	var createBranch = function (key) {
		return numeric.test(key) ? [] : {};
	};

	var magicAdaptor, MagicWrapper;

	try {
		Object.defineProperty({}, "test", { value: 0 });

		magicAdaptor = {
			filter: function (object, keypath, ractive) {
				var parentWrapper, parentValue;

				if (!keypath) {
					return false;
				}

				keypath = getKeypath(keypath);

				// If the parent value is a wrapper, other than a magic wrapper,
				// we shouldn't wrap this property
				if ((parentWrapper = ractive.viewmodel.wrapped[keypath.parent.str]) && !parentWrapper.magic) {
					return false;
				}

				parentValue = ractive.viewmodel.get(keypath.parent);

				// if parentValue is an array that doesn't include this member,
				// we should return false otherwise lengths will get messed up
				if (isArray(parentValue) && /^[0-9]+$/.test(keypath.lastKey)) {
					return false;
				}

				return parentValue && (typeof parentValue === "object" || typeof parentValue === "function");
			},
			wrap: function (ractive, property, keypath) {
				return new MagicWrapper(ractive, property, keypath);
			}
		};

		MagicWrapper = function (ractive, value, keypath) {
			var objKeypath, template, siblings;

			keypath = getKeypath(keypath);

			this.magic = true;

			this.ractive = ractive;
			this.keypath = keypath;
			this.value = value;

			this.prop = keypath.lastKey;

			objKeypath = keypath.parent;
			this.obj = objKeypath.isRoot ? ractive.viewmodel.data : ractive.viewmodel.get(objKeypath);

			template = this.originalDescriptor = Object.getOwnPropertyDescriptor(this.obj, this.prop);

			// Has this property already been wrapped?
			if (template && template.set && (siblings = template.set._ractiveWrappers)) {

				// Yes. Register this wrapper to this property, if it hasn't been already
				if (siblings.indexOf(this) === -1) {
					siblings.push(this);
				}

				return; // already wrapped
			}

			// No, it hasn't been wrapped
			createAccessors(this, value, template);
		};

		MagicWrapper.prototype = {
			get: function () {
				return this.value;
			},
			reset: function (value) {
				if (this.updating) {
					return;
				}

				this.updating = true;
				this.obj[this.prop] = value; // trigger set() accessor
				global_runloop.addRactive(this.ractive);
				this.ractive.viewmodel.mark(this.keypath, { keepExistingWrapper: true });
				this.updating = false;
				return true;
			},
			set: function (key, value) {
				if (this.updating) {
					return;
				}

				if (!this.obj[this.prop]) {
					this.updating = true;
					this.obj[this.prop] = createBranch(key);
					this.updating = false;
				}

				this.obj[this.prop][key] = value;
			},
			teardown: function () {
				var template, set, value, wrappers, index;

				// If this method was called because the cache was being cleared as a
				// result of a set()/update() call made by this wrapper, we return false
				// so that it doesn't get torn down
				if (this.updating) {
					return false;
				}

				template = Object.getOwnPropertyDescriptor(this.obj, this.prop);
				set = template && template.set;

				if (!set) {
					// most likely, this was an array member that was spliced out
					return;
				}

				wrappers = set._ractiveWrappers;

				index = wrappers.indexOf(this);
				if (index !== -1) {
					wrappers.splice(index, 1);
				}

				// Last one out, turn off the lights
				if (!wrappers.length) {
					value = this.obj[this.prop];

					Object.defineProperty(this.obj, this.prop, this.originalDescriptor || {
						writable: true,
						enumerable: true,
						configurable: true
					});

					this.obj[this.prop] = value;
				}
			}
		};
	} catch (err) {
		magicAdaptor = false; // no magic in this browser
	}

	var adaptors_magic = magicAdaptor;

	function createAccessors(originalWrapper, value, template) {

		var object, property, oldGet, oldSet, get, set;

		object = originalWrapper.obj;
		property = originalWrapper.prop;

		// Is this template configurable?
		if (template && !template.configurable) {
			// Special case - array length
			if (property === "length") {
				return;
			}

			throw new Error("Cannot use magic mode with property \"" + property + "\" - object is not configurable");
		}

		// Time to wrap this property
		if (template) {
			oldGet = template.get;
			oldSet = template.set;
		}

		get = oldGet || function () {
			return value;
		};

		set = function (v) {
			if (oldSet) {
				oldSet(v);
			}

			value = oldGet ? oldGet() : v;
			set._ractiveWrappers.forEach(updateWrapper);
		};

		function updateWrapper(wrapper) {
			var keypath, ractive;

			wrapper.value = value;

			if (wrapper.updating) {
				return;
			}

			ractive = wrapper.ractive;
			keypath = wrapper.keypath;

			wrapper.updating = true;
			global_runloop.start(ractive);

			ractive.viewmodel.mark(keypath);

			global_runloop.end();
			wrapper.updating = false;
		}

		// Create an array of wrappers, in case other keypaths/ractives depend on this property.
		// Handily, we can store them as a property of the set function. Yay JavaScript.
		set._ractiveWrappers = [originalWrapper];
		Object.defineProperty(object, property, { get: get, set: set, enumerable: true, configurable: true });
	}

	var magicArrayAdaptor, MagicArrayWrapper;

	if (adaptors_magic) {
		magicArrayAdaptor = {
			filter: function (object, keypath, ractive) {
				return adaptors_magic.filter(object, keypath, ractive) && array_index.filter(object);
			},

			wrap: function (ractive, array, keypath) {
				return new MagicArrayWrapper(ractive, array, keypath);
			}
		};

		MagicArrayWrapper = function (ractive, array, keypath) {
			this.value = array;

			this.magic = true;

			this.magicWrapper = adaptors_magic.wrap(ractive, array, keypath);
			this.arrayWrapper = array_index.wrap(ractive, array, keypath);
		};

		MagicArrayWrapper.prototype = {
			get: function () {
				return this.value;
			},
			teardown: function () {
				this.arrayWrapper.teardown();
				this.magicWrapper.teardown();
			},
			reset: function (value) {
				return this.magicWrapper.reset(value);
			}
		};
	}

	var magicArray = magicArrayAdaptor;

	var prototype_adapt = Viewmodel$adapt;

	var prefixers = {};
	function Viewmodel$adapt(keypath, value) {
		var len, i, adaptor, wrapped;

		if (!this.adaptors) return;

		// Do we have an adaptor for this value?
		len = this.adaptors.length;
		for (i = 0; i < len; i += 1) {
			adaptor = this.adaptors[i];

			if (adaptor.filter(value, keypath, this.ractive)) {
				wrapped = this.wrapped[keypath] = adaptor.wrap(this.ractive, value, keypath, getPrefixer(keypath));
				wrapped.value = value;
				return;
			}
		}
	}

	function prefixKeypath(obj, prefix) {
		var prefixed = {},
			key;

		if (!prefix) {
			return obj;
		}

		prefix += ".";

		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				prefixed[prefix + key] = obj[key];
			}
		}

		return prefixed;
	}

	function getPrefixer(rootKeypath) {
		var rootDot;

		if (!prefixers[rootKeypath]) {
			rootDot = rootKeypath ? rootKeypath + "." : "";

			prefixers[rootKeypath] = function (relativeKeypath, value) {
				var obj;

				if (typeof relativeKeypath === "string") {
					obj = {};
					obj[rootDot + relativeKeypath] = value;
					return obj;
				}

				if (typeof relativeKeypath === "object") {
					// 'relativeKeypath' is in fact a hash, not a keypath
					return rootDot ? prefixKeypath(relativeKeypath, rootKeypath) : relativeKeypath;
				}
			};
		}

		return prefixers[rootKeypath];
	}

	// TEMP

	var helpers_getUpstreamChanges = getUpstreamChanges;
	function getUpstreamChanges(changes) {
		var upstreamChanges = [rootKeypath],
			i,
			keypath;

		i = changes.length;
		while (i--) {
			keypath = changes[i].parent;

			while (keypath && !keypath.isRoot) {
				if (changes.indexOf(keypath) === -1) {
					addToArray(upstreamChanges, keypath);
				}
				keypath = keypath.parent;
			}
		}

		return upstreamChanges;
	}

	var applyChanges_notifyPatternObservers = notifyPatternObservers;

	function notifyPatternObservers(viewmodel, keypath, onlyDirect) {
		var potentialWildcardMatches;

		updateMatchingPatternObservers(viewmodel, keypath);

		if (onlyDirect) {
			return;
		}

		potentialWildcardMatches = keypath.wildcardMatches();
		potentialWildcardMatches.forEach(function (upstreamPattern) {
			cascade(viewmodel, upstreamPattern, keypath);
		});
	}

	function cascade(viewmodel, upstreamPattern, keypath) {
		var group, map, actualChildKeypath;

		// TODO should be one or the other
		upstreamPattern = upstreamPattern.str || upstreamPattern;

		group = viewmodel.depsMap.patternObservers;
		map = group && group[upstreamPattern];

		if (!map) {
			return;
		}

		map.forEach(function (childKeypath) {
			actualChildKeypath = keypath.join(childKeypath.lastKey); // 'foo.bar.baz'

			updateMatchingPatternObservers(viewmodel, actualChildKeypath);
			cascade(viewmodel, childKeypath, actualChildKeypath);
		});
	}

	function updateMatchingPatternObservers(viewmodel, keypath) {
		viewmodel.patternObservers.forEach(function (observer) {
			if (observer.regex.test(keypath.str)) {
				observer.update(keypath);
			}
		});
	}

	var applyChanges = Viewmodel$applyChanges;

	function Viewmodel$applyChanges() {
		var _this = this;

		var self = this,
			changes,
			upstreamChanges,
			hash = {},
			bindings;

		changes = this.changes;

		if (!changes.length) {
			// TODO we end up here on initial render. Perhaps we shouldn't?
			return;
		}

		function invalidateComputation(computation) {
			var key = computation.key;

			if (computation.viewmodel === self) {
				self.clearCache(key.str);
				computation.invalidate();

				changes.push(key);
				cascade(key);
			} else {
				computation.viewmodel.mark(key);
			}
		}

		function cascade(keypath) {
			var map, computations;

			if (self.noCascade.hasOwnProperty(keypath.str)) {
				return;
			}

			if (computations = self.deps.computed[keypath.str]) {
				computations.forEach(invalidateComputation);
			}

			if (map = self.depsMap.computed[keypath.str]) {
				map.forEach(cascade);
			}
		}

		changes.slice().forEach(cascade);

		upstreamChanges = helpers_getUpstreamChanges(changes);
		upstreamChanges.forEach(function (keypath) {
			var computations;

			// make sure we haven't already been down this particular keypath in this turn
			if (changes.indexOf(keypath) === -1 && (computations = self.deps.computed[keypath.str])) {
				computations.forEach(invalidateComputation);
			}
		});

		this.changes = [];

		// Pattern observers are a weird special case
		if (this.patternObservers.length) {
			upstreamChanges.forEach(function (keypath) {
				return applyChanges_notifyPatternObservers(_this, keypath, true);
			});
			changes.forEach(function (keypath) {
				return applyChanges_notifyPatternObservers(_this, keypath);
			});
		}

		if (this.deps.observers) {
			upstreamChanges.forEach(function (keypath) {
				return notifyUpstreamDependants(_this, null, keypath, "observers");
			});
			notifyAllDependants(this, changes, "observers");
		}

		if (this.deps["default"]) {
			bindings = [];
			upstreamChanges.forEach(function (keypath) {
				return notifyUpstreamDependants(_this, bindings, keypath, "default");
			});

			if (bindings.length) {
				notifyBindings(this, bindings, changes);
			}

			notifyAllDependants(this, changes, "default");
		}

		// Return a hash of keypaths to updated values
		changes.forEach(function (keypath) {
			hash[keypath.str] = _this.get(keypath);
		});

		this.implicitChanges = {};
		this.noCascade = {};

		return hash;
	}

	function notifyUpstreamDependants(viewmodel, bindings, keypath, groupName) {
		var dependants, value;

		if (dependants = findDependants(viewmodel, keypath, groupName)) {
			value = viewmodel.get(keypath);

			dependants.forEach(function (d) {
				// don't "set" the parent value, refine it
				// i.e. not data = value, but data[foo] = fooValue
				if (bindings && d.refineValue) {
					bindings.push(d);
				} else {
					d.setValue(value);
				}
			});
		}
	}

	function notifyBindings(viewmodel, bindings, changes) {

		bindings.forEach(function (binding) {
			var useSet = false,
				i = 0,
				length = changes.length,
				refinements = [];

			while (i < length) {
				var keypath = changes[i];

				if (keypath === binding.keypath) {
					useSet = true;
					break;
				}

				if (keypath.slice(0, binding.keypath.length) === binding.keypath) {
					refinements.push(keypath);
				}

				i++;
			}

			if (useSet) {
				binding.setValue(viewmodel.get(binding.keypath));
			}

			if (refinements.length) {
				binding.refineValue(refinements);
			}
		});
	}

	function notifyAllDependants(viewmodel, keypaths, groupName) {
		var queue = [];

		addKeypaths(keypaths);
		queue.forEach(dispatch);

		function addKeypaths(keypaths) {
			keypaths.forEach(addKeypath);
			keypaths.forEach(cascade);
		}

		function addKeypath(keypath) {
			var deps = findDependants(viewmodel, keypath, groupName);

			if (deps) {
				queue.push({
					keypath: keypath,
					deps: deps
				});
			}
		}

		function cascade(keypath) {
			var childDeps;

			if (childDeps = viewmodel.depsMap[groupName][keypath.str]) {
				addKeypaths(childDeps);
			}
		}

		function dispatch(set) {
			var value = viewmodel.get(set.keypath);
			set.deps.forEach(function (d) {
				return d.setValue(value);
			});
		}
	}

	function findDependants(viewmodel, keypath, groupName) {
		var group = viewmodel.deps[groupName];
		return group ? group[keypath.str] : null;
	}

	var capture = Viewmodel$capture;

	function Viewmodel$capture() {
		this.captureGroups.push([]);
	}

	var clearCache = Viewmodel$clearCache;

	function Viewmodel$clearCache(keypath, keepExistingWrapper) {
		var cacheMap, wrapper;

		if (!keepExistingWrapper) {
			// Is there a wrapped property at this keypath?
			if (wrapper = this.wrapped[keypath]) {
				// Did we unwrap it?
				if (wrapper.teardown() !== false) {
					// Is this right?
					// What's the meaning of returning false from teardown?
					// Could there be a GC ramification if this is a "real" ractive.teardown()?
					this.wrapped[keypath] = null;
				}
			}
		}

		this.cache[keypath] = undefined;

		if (cacheMap = this.cacheMap[keypath]) {
			while (cacheMap.length) {
				this.clearCache(cacheMap.pop());
			}
		}
	}

	var UnresolvedDependency = function (computation, ref) {
		this.computation = computation;
		this.viewmodel = computation.viewmodel;
		this.ref = ref;

		// TODO this seems like a red flag!
		this.root = this.viewmodel.ractive;
		this.parentFragment = this.root.component && this.root.component.parentFragment;
	};

	UnresolvedDependency.prototype = {
		resolve: function (keypath) {
			this.computation.softDeps.push(keypath);
			this.computation.unresolvedDeps[keypath.str] = null;
			this.viewmodel.register(keypath, this.computation, "computed");
		}
	};

	var Computation_UnresolvedDependency = UnresolvedDependency;

	var Computation = function (key, signature) {
		this.key = key;

		this.getter = signature.getter;
		this.setter = signature.setter;

		this.hardDeps = signature.deps || [];
		this.softDeps = [];
		this.unresolvedDeps = {};

		this.depValues = {};

		this._dirty = this._firstRun = true;
	};

	Computation.prototype = {
		constructor: Computation,

		init: function (viewmodel) {
			var _this = this;

			var initial;

			this.viewmodel = viewmodel;
			this.bypass = true;

			initial = viewmodel.get(this.key);
			viewmodel.clearCache(this.key.str);

			this.bypass = false;

			if (this.setter && initial !== undefined) {
				this.set(initial);
			}

			if (this.hardDeps) {
				this.hardDeps.forEach(function (d) {
					return viewmodel.register(d, _this, "computed");
				});
			}
		},

		invalidate: function () {
			this._dirty = true;
		},

		get: function () {
			var _this = this;

			var newDeps,
				dependenciesChanged,
				dependencyValuesChanged = false;

			if (this.getting) {
				// prevent double-computation (e.g. caused by array mutation inside computation)
				var msg = "The " + this.key.str + " computation indirectly called itself. This probably indicates a bug in the computation. It is commonly caused by `array.sort(...)` - if that's the case, clone the array first with `array.slice().sort(...)`";
				warnOnce(msg);
				return this.value;
			}

			this.getting = true;

			if (this._dirty) {
				// determine whether the inputs have changed, in case this depends on
				// other computed values
				if (this._firstRun || !this.hardDeps.length && !this.softDeps.length) {
					dependencyValuesChanged = true;
				} else {
					[this.hardDeps, this.softDeps].forEach(function (deps) {
						var keypath, value, i;

						if (dependencyValuesChanged) {
							return;
						}

						i = deps.length;
						while (i--) {
							keypath = deps[i];
							value = _this.viewmodel.get(keypath);

							if (!isEqual(value, _this.depValues[keypath.str])) {
								_this.depValues[keypath.str] = value;
								dependencyValuesChanged = true;

								return;
							}
						}
					});
				}

				if (dependencyValuesChanged) {
					this.viewmodel.capture();

					try {
						this.value = this.getter();
					} catch (err) {
						warnIfDebug("Failed to compute \"%s\"", this.key.str);
						logIfDebug(err.stack || err);

						this.value = void 0;
					}

					newDeps = this.viewmodel.release();
					dependenciesChanged = this.updateDependencies(newDeps);

					if (dependenciesChanged) {
						[this.hardDeps, this.softDeps].forEach(function (deps) {
							deps.forEach(function (keypath) {
								_this.depValues[keypath.str] = _this.viewmodel.get(keypath);
							});
						});
					}
				}

				this._dirty = false;
			}

			this.getting = this._firstRun = false;
			return this.value;
		},

		set: function (value) {
			if (this.setting) {
				this.value = value;
				return;
			}

			if (!this.setter) {
				throw new Error("Computed properties without setters are read-only. (This may change in a future version of Ractive!)");
			}

			this.setter(value);
		},

		updateDependencies: function (newDeps) {
			var i, oldDeps, keypath, dependenciesChanged, unresolved;

			oldDeps = this.softDeps;

			// remove dependencies that are no longer used
			i = oldDeps.length;
			while (i--) {
				keypath = oldDeps[i];

				if (newDeps.indexOf(keypath) === -1) {
					dependenciesChanged = true;
					this.viewmodel.unregister(keypath, this, "computed");
				}
			}

			// create references for any new dependencies
			i = newDeps.length;
			while (i--) {
				keypath = newDeps[i];

				if (oldDeps.indexOf(keypath) === -1 && (!this.hardDeps || this.hardDeps.indexOf(keypath) === -1)) {
					dependenciesChanged = true;

					// if this keypath is currently unresolved, we need to mark
					// it as such. TODO this is a bit muddy...
					if (isUnresolved(this.viewmodel, keypath) && !this.unresolvedDeps[keypath.str]) {
						unresolved = new Computation_UnresolvedDependency(this, keypath.str);
						newDeps.splice(i, 1);

						this.unresolvedDeps[keypath.str] = unresolved;
						global_runloop.addUnresolved(unresolved);
					} else {
						this.viewmodel.register(keypath, this, "computed");
					}
				}
			}

			if (dependenciesChanged) {
				this.softDeps = newDeps.slice();
			}

			return dependenciesChanged;
		}
	};

	function isUnresolved(viewmodel, keypath) {
		var key = keypath.firstKey;

		return !(key in viewmodel.data) && !(key in viewmodel.computations) && !(key in viewmodel.mappings);
	}

	var Computation_Computation = Computation;

	var compute = Viewmodel$compute;
	function Viewmodel$compute(key, signature) {
		var computation = new Computation_Computation(key, signature);

		if (this.ready) {
			computation.init(this);
		}

		return this.computations[key.str] = computation;
	}

	var FAILED_LOOKUP = { FAILED_LOOKUP: true };

	var viewmodel_prototype_get = Viewmodel$get;

	var viewmodel_prototype_get__empty = {};
	function Viewmodel$get(keypath, options) {
		var cache = this.cache,
			value,
			computation,
			wrapped,
			captureGroup,
			keypathStr = keypath.str,
			key;

		options = options || viewmodel_prototype_get__empty;

		// capture the keypath, if we're inside a computation
		if (options.capture && (captureGroup = lastItem(this.captureGroups))) {
			if (! ~captureGroup.indexOf(keypath)) {
				captureGroup.push(keypath);
			}
		}

		if (hasOwn.call(this.mappings, keypath.firstKey)) {
			return this.mappings[keypath.firstKey].get(keypath, options);
		}

		if (keypath.isSpecial) {
			return keypath.value;
		}

		if (cache[keypathStr] === undefined) {

			// Is this a computed property?
			if ((computation = this.computations[keypathStr]) && !computation.bypass) {
				value = computation.get();
				this.adapt(keypathStr, value);
			}

				// Is this a wrapped property?
			else if (wrapped = this.wrapped[keypathStr]) {
				value = wrapped.value;
			}

				// Is it the root?
			else if (keypath.isRoot) {
				this.adapt("", this.data);
				value = this.data;
			}

				// No? Then we need to retrieve the value one key at a time
			else {
				value = retrieve(this, keypath);
			}

			cache[keypathStr] = value;
		} else {
			value = cache[keypathStr];
		}

		if (!options.noUnwrap && (wrapped = this.wrapped[keypathStr])) {
			value = wrapped.get();
		}

		if (keypath.isRoot && options.fullRootGet) {
			for (key in this.mappings) {
				value[key] = this.mappings[key].getValue();
			}
		}

		return value === FAILED_LOOKUP ? void 0 : value;
	}

	function retrieve(viewmodel, keypath) {

		var parentValue, cacheMap, value, wrapped;

		parentValue = viewmodel.get(keypath.parent);

		if (wrapped = viewmodel.wrapped[keypath.parent.str]) {
			parentValue = wrapped.get();
		}

		if (parentValue === null || parentValue === undefined) {
			return;
		}

		// update cache map
		if (!(cacheMap = viewmodel.cacheMap[keypath.parent.str])) {
			viewmodel.cacheMap[keypath.parent.str] = [keypath.str];
		} else {
			if (cacheMap.indexOf(keypath.str) === -1) {
				cacheMap.push(keypath.str);
			}
		}

		// If this property doesn't exist, we return a sentinel value
		// so that we know to query parent scope (if such there be)
		if (typeof parentValue === "object" && !(keypath.lastKey in parentValue)) {
			return viewmodel.cache[keypath.str] = FAILED_LOOKUP;
		}

		value = parentValue[keypath.lastKey];

		// Do we have an adaptor for this value?
		viewmodel.adapt(keypath.str, value, false);

		// Update cache
		viewmodel.cache[keypath.str] = value;
		return value;
	}

	var viewmodel_prototype_init = Viewmodel$init;

	function Viewmodel$init() {
		var key;

		for (key in this.computations) {
			this.computations[key].init(this);
		}
	}

	var prototype_map = Viewmodel$map;

	function Viewmodel$map(key, options) {
		var mapping = this.mappings[key.str] = new Mapping(key, options);
		mapping.initViewmodel(this);
		return mapping;
	}

	var Mapping = function (localKey, options) {
		this.localKey = localKey;
		this.keypath = options.keypath;
		this.origin = options.origin;

		this.deps = [];
		this.unresolved = [];

		this.resolved = false;
	};

	Mapping.prototype = {
		forceResolution: function () {
			// TODO warn, as per #1692?
			this.keypath = this.localKey;
			this.setup();
		},

		get: function (keypath, options) {
			if (!this.resolved) {
				return undefined;
			}
			return this.origin.get(this.map(keypath), options);
		},

		getValue: function () {
			if (!this.keypath) {
				return undefined;
			}
			return this.origin.get(this.keypath);
		},

		initViewmodel: function (viewmodel) {
			this.local = viewmodel;
			this.setup();
		},

		map: function (keypath) {
			if (typeof this.keypath === undefined) {
				return this.localKey;
			}
			return keypath.replace(this.localKey, this.keypath);
		},

		register: function (keypath, dependant, group) {
			this.deps.push({ keypath: keypath, dep: dependant, group: group });

			if (this.resolved) {
				this.origin.register(this.map(keypath), dependant, group);
			}
		},

		resolve: function (keypath) {
			if (this.keypath !== undefined) {
				this.unbind(true);
			}

			this.keypath = keypath;
			this.setup();
		},

		set: function (keypath, value) {
			if (!this.resolved) {
				this.forceResolution();
			}

			this.origin.set(this.map(keypath), value);
		},

		setup: function () {
			var _this = this;

			if (this.keypath === undefined) {
				return;
			}

			this.resolved = true;

			// accumulated dependants can now be registered
			if (this.deps.length) {
				this.deps.forEach(function (d) {
					var keypath = _this.map(d.keypath);
					_this.origin.register(keypath, d.dep, d.group);

					// TODO this is a bit of a red flag... all deps should be the same?
					if (d.dep.setValue) {
						d.dep.setValue(_this.origin.get(keypath));
					} else if (d.dep.invalidate) {
						d.dep.invalidate();
					} else {
						throw new Error("An unexpected error occurred. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!");
					}
				});

				this.origin.mark(this.keypath);
			}
		},

		setValue: function (value) {
			if (!this.keypath) {
				throw new Error("Mapping does not have keypath, cannot set value. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!");
			}

			this.origin.set(this.keypath, value);
		},

		unbind: function (keepLocal) {
			var _this = this;

			if (!keepLocal) {
				delete this.local.mappings[this.localKey];
			}

			if (!this.resolved) {
				return;
			}

			this.deps.forEach(function (d) {
				_this.origin.unregister(_this.map(d.keypath), d.dep, d.group);
			});

			if (this.tracker) {
				this.origin.unregister(this.keypath, this.tracker);
			}
		},

		unregister: function (keypath, dependant, group) {
			var deps, i;

			if (!this.resolved) {
				return;
			}

			deps = this.deps;
			i = deps.length;

			while (i--) {
				if (deps[i].dep === dependant) {
					deps.splice(i, 1);
					break;
				}
			}
			this.origin.unregister(this.map(keypath), dependant, group);
		}
	};

	var mark = Viewmodel$mark;

	function Viewmodel$mark(keypath, options) {
		var computation,
			keypathStr = keypath.str;

		// implicit changes (i.e. `foo.length` on `ractive.push('foo',42)`)
		// should not be picked up by pattern observers
		if (options) {
			if (options.implicit) {
				this.implicitChanges[keypathStr] = true;
			}
			if (options.noCascade) {
				this.noCascade[keypathStr] = true;
			}
		}

		if (computation = this.computations[keypathStr]) {
			computation.invalidate();
		}

		if (this.changes.indexOf(keypath) === -1) {
			this.changes.push(keypath);
		}

		// pass on keepExistingWrapper, if we can
		var keepExistingWrapper = options ? options.keepExistingWrapper : false;

		this.clearCache(keypathStr, keepExistingWrapper);

		if (this.ready) {
			this.onchange();
		}
	}

	var mapOldToNewIndex = function (oldArray, newArray) {
		var usedIndices, firstUnusedIndex, newIndices, changed;

		usedIndices = {};
		firstUnusedIndex = 0;

		newIndices = oldArray.map(function (item, i) {
			var index, start, len;

			start = firstUnusedIndex;
			len = newArray.length;

			do {
				index = newArray.indexOf(item, start);

				if (index === -1) {
					changed = true;
					return -1;
				}

				start = index + 1;
			} while (usedIndices[index] && start < len);

			// keep track of the first unused index, so we don't search
			// the whole of newArray for each item in oldArray unnecessarily
			if (index === firstUnusedIndex) {
				firstUnusedIndex += 1;
			}

			if (index !== i) {
				changed = true;
			}

			usedIndices[index] = true;
			return index;
		});

		return newIndices;
	};

	var merge = Viewmodel$merge;

	var comparators = {};
	function Viewmodel$merge(keypath, currentArray, array, options) {
		var oldArray, newArray, comparator, newIndices;

		this.mark(keypath);

		if (options && options.compare) {

			comparator = getComparatorFunction(options.compare);

			try {
				oldArray = currentArray.map(comparator);
				newArray = array.map(comparator);
			} catch (err) {
				// fallback to an identity check - worst case scenario we have
				// to do more DOM manipulation than we thought...
				warnIfDebug("merge(): \"%s\" comparison failed. Falling back to identity checking", keypath);

				oldArray = currentArray;
				newArray = array;
			}
		} else {
			oldArray = currentArray;
			newArray = array;
		}

		// find new indices for members of oldArray
		newIndices = mapOldToNewIndex(oldArray, newArray);

		this.smartUpdate(keypath, array, newIndices, currentArray.length !== array.length);
	}

	function stringify(item) {
		return JSON.stringify(item);
	}

	function getComparatorFunction(comparator) {
		// If `compare` is `true`, we use JSON.stringify to compare
		// objects that are the same shape, but non-identical - i.e.
		// { foo: 'bar' } !== { foo: 'bar' }
		if (comparator === true) {
			return stringify;
		}

		if (typeof comparator === "string") {
			if (!comparators[comparator]) {
				comparators[comparator] = function (item) {
					return item[comparator];
				};
			}

			return comparators[comparator];
		}

		if (typeof comparator === "function") {
			return comparator;
		}

		throw new Error("The `compare` option must be a function, or a string representing an identifying field (or `true` to use JSON.stringify)");
	}

	var register = Viewmodel$register;

	function Viewmodel$register(keypath, dependant) {
		var group = arguments[2] === undefined ? "default" : arguments[2];

		var mapping, depsByKeypath, deps;

		if (dependant.isStatic) {
			return; // TODO we should never get here if a dependant is static...
		}

		if (mapping = this.mappings[keypath.firstKey]) {
			mapping.register(keypath, dependant, group);
		} else {
			depsByKeypath = this.deps[group] || (this.deps[group] = {});
			deps = depsByKeypath[keypath.str] || (depsByKeypath[keypath.str] = []);

			deps.push(dependant);

			if (!this.depsMap[group]) {
				this.depsMap[group] = {};
			}

			if (!keypath.isRoot) {
				register__updateDependantsMap(this, keypath, group);
			}
		}
	}

	function register__updateDependantsMap(viewmodel, keypath, group) {
		var map, parent, keypathStr;

		// update dependants map
		while (!keypath.isRoot) {
			map = viewmodel.depsMap[group];
			parent = map[keypath.parent.str] || (map[keypath.parent.str] = []);

			keypathStr = keypath.str;

			// TODO find an alternative to this nasty approach
			if (parent["_" + keypathStr] === undefined) {
				parent["_" + keypathStr] = 0;
				parent.push(keypath);
			}

			parent["_" + keypathStr] += 1;
			keypath = keypath.parent;
		}
	}

	var release = Viewmodel$release;

	function Viewmodel$release() {
		return this.captureGroups.pop();
	}

	var reset = Viewmodel$reset;

	function Viewmodel$reset(data) {
		this.data = data;
		this.clearCache("");
	}

	var prototype_set = Viewmodel$set;

	function Viewmodel$set(keypath, value) {
		var options = arguments[2] === undefined ? {} : arguments[2];

		var mapping, computation, wrapper, keepExistingWrapper;

		// unless data is being set for data tracking purposes
		if (!options.noMapping) {
			// If this data belongs to a different viewmodel,
			// pass the change along
			if (mapping = this.mappings[keypath.firstKey]) {
				return mapping.set(keypath, value);
			}
		}

		computation = this.computations[keypath.str];
		if (computation) {
			if (computation.setting) {
				// let the other computation set() handle things...
				return;
			}
			computation.set(value);
			value = computation.get();
		}

		if (isEqual(this.cache[keypath.str], value)) {
			return;
		}

		wrapper = this.wrapped[keypath.str];

		// If we have a wrapper with a `reset()` method, we try and use it. If the
		// `reset()` method returns false, the wrapper should be torn down, and
		// (most likely) a new one should be created later
		if (wrapper && wrapper.reset) {
			keepExistingWrapper = wrapper.reset(value) !== false;

			if (keepExistingWrapper) {
				value = wrapper.get();
			}
		}

		if (!computation && !keepExistingWrapper) {
			resolveSet(this, keypath, value);
		}

		if (!options.silent) {
			this.mark(keypath);
		} else {
			// We're setting a parent of the original target keypath (i.e.
			// creating a fresh branch) - we need to clear the cache, but
			// not mark it as a change
			this.clearCache(keypath.str);
		}
	}

	function resolveSet(viewmodel, keypath, value) {
		var wrapper, parentValue, wrapperSet, valueSet;

		wrapperSet = function () {
			if (wrapper.set) {
				wrapper.set(keypath.lastKey, value);
			} else {
				parentValue = wrapper.get();
				valueSet();
			}
		};

		valueSet = function () {
			if (!parentValue) {
				parentValue = createBranch(keypath.lastKey);
				viewmodel.set(keypath.parent, parentValue, { silent: true });
			}
			parentValue[keypath.lastKey] = value;
		};

		wrapper = viewmodel.wrapped[keypath.parent.str];

		if (wrapper) {
			wrapperSet();
		} else {
			parentValue = viewmodel.get(keypath.parent);

			// may have been wrapped via the above .get()
			// call on viewmodel if this is first access via .set()!
			if (wrapper = viewmodel.wrapped[keypath.parent.str]) {
				wrapperSet();
			} else {
				valueSet();
			}
		}
	}

	var smartUpdate = Viewmodel$smartUpdate;

	var implicitOption = { implicit: true },
		noCascadeOption = { noCascade: true };
	function Viewmodel$smartUpdate(keypath, array, newIndices) {
		var _this = this;

		var dependants, oldLength, i;

		oldLength = newIndices.length;

		// Indices that are being removed should be marked as dirty
		newIndices.forEach(function (newIndex, oldIndex) {
			if (newIndex === -1) {
				_this.mark(keypath.join(oldIndex), noCascadeOption);
			}
		});

		// Update the model
		// TODO allow existing array to be updated in place, rather than replaced?
		this.set(keypath, array, { silent: true });

		if (dependants = this.deps["default"][keypath.str]) {
			dependants.filter(canShuffle).forEach(function (d) {
				return d.shuffle(newIndices, array);
			});
		}

		if (oldLength !== array.length) {
			this.mark(keypath.join("length"), implicitOption);

			for (i = newIndices.touchedFrom; i < array.length; i += 1) {
				this.mark(keypath.join(i));
			}

			// don't allow removed indexes beyond end of new array to trigger recomputations
			// TODO is this still necessary, now that computations are lazy?
			for (i = array.length; i < oldLength; i += 1) {
				this.mark(keypath.join(i), noCascadeOption);
			}
		}
	}

	function canShuffle(dependant) {
		return typeof dependant.shuffle === "function";
	}

	var prototype_teardown = Viewmodel$teardown;

	function Viewmodel$teardown() {
		var _this = this;

		var unresolvedImplicitDependency;

		// Clear entire cache - this has the desired side-effect
		// of unwrapping adapted values (e.g. arrays)
		Object.keys(this.cache).forEach(function (keypath) {
			return _this.clearCache(keypath);
		});

		// Teardown any failed lookups - we don't need them to resolve any more
		while (unresolvedImplicitDependency = this.unresolvedImplicitDependencies.pop()) {
			unresolvedImplicitDependency.teardown();
		}
	}

	var unregister = Viewmodel$unregister;

	function Viewmodel$unregister(keypath, dependant) {
		var group = arguments[2] === undefined ? "default" : arguments[2];

		var mapping, deps, index;

		if (dependant.isStatic) {
			return;
		}

		if (mapping = this.mappings[keypath.firstKey]) {
			return mapping.unregister(keypath, dependant, group);
		}

		deps = this.deps[group][keypath.str];
		index = deps.indexOf(dependant);

		if (index === -1) {
			throw new Error("Attempted to remove a dependant that was no longer registered! This should not happen. If you are seeing this bug in development please raise an issue at https://github.com/RactiveJS/Ractive/issues - thanks");
		}

		deps.splice(index, 1);

		if (keypath.isRoot) {
			return;
		}

		unregister__updateDependantsMap(this, keypath, group);
	}

	function unregister__updateDependantsMap(viewmodel, keypath, group) {
		var map, parent;

		// update dependants map
		while (!keypath.isRoot) {
			map = viewmodel.depsMap[group];
			parent = map[keypath.parent.str];

			parent["_" + keypath.str] -= 1;

			if (!parent["_" + keypath.str]) {
				// remove from parent deps map
				removeFromArray(parent, keypath);
				parent["_" + keypath.str] = undefined;
			}

			keypath = keypath.parent;
		}
	}

	var Viewmodel = function (options) {
		var adapt = options.adapt;
		var data = options.data;
		var ractive = options.ractive;
		var computed = options.computed;
		var mappings = options.mappings;
		var key;
		var mapping;

		// TODO is it possible to remove this reference?
		this.ractive = ractive;

		this.adaptors = adapt;
		this.onchange = options.onchange;

		this.cache = {}; // we need to be able to use hasOwnProperty, so can't inherit from null
		this.cacheMap = create(null);

		this.deps = {
			computed: create(null),
			"default": create(null)
		};
		this.depsMap = {
			computed: create(null),
			"default": create(null)
		};

		this.patternObservers = [];

		this.specials = create(null);

		this.wrapped = create(null);
		this.computations = create(null);

		this.captureGroups = [];
		this.unresolvedImplicitDependencies = [];

		this.changes = [];
		this.implicitChanges = {};
		this.noCascade = {};

		this.data = data;

		// set up explicit mappings
		this.mappings = create(null);
		for (key in mappings) {
			this.map(getKeypath(key), mappings[key]);
		}

		if (data) {
			// if data exists locally, but is missing on the parent,
			// we transfer ownership to the parent
			for (key in data) {
				if ((mapping = this.mappings[key]) && mapping.getValue() === undefined) {
					mapping.setValue(data[key]);
				}
			}
		}

		for (key in computed) {
			if (mappings && key in mappings) {
				fatal("Cannot map to a computed property ('%s')", key);
			}

			this.compute(getKeypath(key), computed[key]);
		}

		this.ready = true;
	};

	Viewmodel.prototype = {
		adapt: prototype_adapt,
		applyChanges: applyChanges,
		capture: capture,
		clearCache: clearCache,
		compute: compute,
		get: viewmodel_prototype_get,
		init: viewmodel_prototype_init,
		map: prototype_map,
		mark: mark,
		merge: merge,
		register: register,
		release: release,
		reset: reset,
		set: prototype_set,
		smartUpdate: smartUpdate,
		teardown: prototype_teardown,
		unregister: unregister
	};

	var viewmodel_Viewmodel = Viewmodel;

	function HookQueue(event) {
		this.hook = new hooks_Hook(event);
		this.inProcess = {};
		this.queue = {};
	}

	HookQueue.prototype = {

		constructor: HookQueue,

		begin: function (ractive) {
			this.inProcess[ractive._guid] = true;
		},

		end: function (ractive) {

			var parent = ractive.parent;

			// If this is *isn't* a child of a component that's in process,
			// it should call methods or fire at this point
			if (!parent || !this.inProcess[parent._guid]) {
				fire(this, ractive);
			}
				// elsewise, handoff to parent to fire when ready
			else {
				getChildQueue(this.queue, parent).push(ractive);
			}

			delete this.inProcess[ractive._guid];
		}
	};

	function getChildQueue(queue, ractive) {
		return queue[ractive._guid] || (queue[ractive._guid] = []);
	}

	function fire(hookQueue, ractive) {

		var childQueue = getChildQueue(hookQueue.queue, ractive);

		hookQueue.hook.fire(ractive);

		// queue is "live" because components can end up being
		// added while hooks fire on parents that modify data values.
		while (childQueue.length) {
			fire(hookQueue, childQueue.shift());
		}

		delete hookQueue.queue[ractive._guid];
	}

	var hooks_HookQueue = HookQueue;

	var helpers_getComputationSignatures = getComputationSignatures;

	var helpers_getComputationSignatures__pattern = /\$\{([^\}]+)\}/g;
	function getComputationSignatures(ractive, computed) {
		var signatures = {},
			key;

		for (key in computed) {
			signatures[key] = getComputationSignature(ractive, key, computed[key]);
		}

		return signatures;
	}

	function getComputationSignature(ractive, key, signature) {
		var getter, setter;

		if (typeof signature === "function") {
			getter = helpers_getComputationSignatures__bind(signature, ractive);
		}

		if (typeof signature === "string") {
			getter = createFunctionFromString(ractive, signature);
		}

		if (typeof signature === "object") {
			if (typeof signature.get === "string") {
				getter = createFunctionFromString(ractive, signature.get);
			} else if (typeof signature.get === "function") {
				getter = helpers_getComputationSignatures__bind(signature.get, ractive);
			} else {
				fatal("`%s` computation must have a `get()` method", key);
			}

			if (typeof signature.set === "function") {
				setter = helpers_getComputationSignatures__bind(signature.set, ractive);
			}
		}

		return { getter: getter, setter: setter };
	}

	function createFunctionFromString(ractive, str) {
		var functionBody, hasThis, fn;

		functionBody = "return (" + str.replace(helpers_getComputationSignatures__pattern, function (match, keypath) {
			hasThis = true;
			return "__ractive.get(\"" + keypath + "\")";
		}) + ");";

		if (hasThis) {
			functionBody = "var __ractive = this; " + functionBody;
		}

		fn = new Function(functionBody);
		return hasThis ? fn.bind(ractive) : fn;
	}

	function helpers_getComputationSignatures__bind(fn, context) {
		return /this/.test(fn.toString()) ? fn.bind(context) : fn;
	}

	var constructHook = new hooks_Hook("construct");
	var configHook = new hooks_Hook("config");
	var initHook = new hooks_HookQueue("init");
	var initialise__uid = 0;

	var initialise__registryNames = ["adaptors", "components", "decorators", "easing", "events", "interpolators", "partials", "transitions"];

	var initialise = initialiseRactiveInstance;

	function initialiseRactiveInstance(ractive) {
		var userOptions = arguments[1] === undefined ? {} : arguments[1];
		var options = arguments[2] === undefined ? {} : arguments[2];

		var el, viewmodel;

		if (_Ractive.DEBUG) {
			welcome();
		}

		initialiseProperties(ractive, options);

		// TODO remove this, eventually
		defineProperty(ractive, "data", { get: deprecateRactiveData });

		// TODO don't allow `onconstruct` with `new Ractive()`, there's no need for it
		constructHook.fire(ractive, userOptions);

		// Add registries
		initialise__registryNames.forEach(function (name) {
			ractive[name] = utils_object__extend(create(ractive.constructor[name] || null), userOptions[name]);
		});

		// Create a viewmodel
		viewmodel = new viewmodel_Viewmodel({
			adapt: getAdaptors(ractive, ractive.adapt, userOptions),
			data: custom_data.init(ractive.constructor, ractive, userOptions),
			computed: helpers_getComputationSignatures(ractive, utils_object__extend(create(ractive.constructor.prototype.computed), userOptions.computed)),
			mappings: options.mappings,
			ractive: ractive,
			onchange: function () {
				return global_runloop.addRactive(ractive);
			}
		});

		ractive.viewmodel = viewmodel;

		// This can't happen earlier, because computed properties may call `ractive.get()`, etc
		viewmodel.init();

		// init config from Parent and options
		config_config.init(ractive.constructor, ractive, userOptions);

		configHook.fire(ractive);
		initHook.begin(ractive);

		// // If this is a component with a function `data` property, call the function
		// // with `ractive` as context (unless the child was also a function)
		// if ( typeof ractive.constructor.prototype.data === 'function' && typeof userOptions.data !== 'function' ) {
		// 	viewmodel.reset( ractive.constructor.prototype.data.call( ractive ) || fatal( '`data` functions must return a data object' ) );
		// }

		// Render virtual DOM
		if (ractive.template) {
			var cssIds = undefined;

			if (options.cssIds || ractive.cssId) {
				cssIds = options.cssIds ? options.cssIds.slice() : [];

				if (ractive.cssId) {
					cssIds.push(ractive.cssId);
				}
			}

			ractive.fragment = new virtualdom_Fragment({
				template: ractive.template,
				root: ractive,
				owner: ractive, // saves doing `if ( this.parent ) { /*...*/ }` later on
				cssIds: cssIds
			});
		}

		initHook.end(ractive);

		// render automatically ( if `el` is specified )
		if (el = getElement(ractive.el)) {
			var promise = ractive.render(el, ractive.append);

			if (_Ractive.DEBUG_PROMISES) {
				promise["catch"](function (err) {
					warnOnceIfDebug("Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n  Ractive.DEBUG_PROMISES = false;");
					warnIfDebug("An error happened during rendering", { ractive: ractive });
					err.stack && logIfDebug(err.stack);

					throw err;
				});
			}
		}
	}

	function getAdaptors(ractive, protoAdapt, userOptions) {
		var adapt, magic, modifyArrays;

		protoAdapt = protoAdapt.map(lookup);
		adapt = ensureArray(userOptions.adapt).map(lookup);

		adapt = initialise__combine(protoAdapt, adapt);

		magic = "magic" in userOptions ? userOptions.magic : ractive.magic;
		modifyArrays = "modifyArrays" in userOptions ? userOptions.modifyArrays : ractive.modifyArrays;

		if (magic) {
			if (!environment__magic) {
				throw new Error("Getters and setters (magic mode) are not supported in this browser");
			}

			if (modifyArrays) {
				adapt.push(magicArray);
			}

			adapt.push(adaptors_magic);
		}

		if (modifyArrays) {
			adapt.push(array_index);
		}

		return adapt;

		function lookup(adaptor) {
			if (typeof adaptor === "string") {
				adaptor = findInViewHierarchy("adaptors", ractive, adaptor);

				if (!adaptor) {
					fatal(missingPlugin(adaptor, "adaptor"));
				}
			}

			return adaptor;
		}
	}

	function initialise__combine(a, b) {
		var c = a.slice(),
			i = b.length;

		while (i--) {
			if (! ~c.indexOf(b[i])) {
				c.push(b[i]);
			}
		}

		return c;
	}

	function initialiseProperties(ractive, options) {
		// Generate a unique identifier, for places where you'd use a weak map if it
		// existed
		ractive._guid = "r-" + initialise__uid++;

		// events
		ractive._subs = create(null);

		// storage for item configuration from instantiation to reset,
		// like dynamic functions or original values
		ractive._config = {};

		// two-way bindings
		ractive._twowayBindings = create(null);

		// animations (so we can stop any in progress at teardown)
		ractive._animations = [];

		// nodes registry
		ractive.nodes = {};

		// live queries
		ractive._liveQueries = [];
		ractive._liveComponentQueries = [];

		// bound data functions
		ractive._boundFunctions = [];

		// observers
		ractive._observers = [];

		// properties specific to inline components
		if (options.component) {
			ractive.parent = options.parent;
			ractive.container = options.container || null;
			ractive.root = ractive.parent.root;

			ractive.component = options.component;
			options.component.instance = ractive;

			// for hackability, this could be an open option
			// for any ractive instance, but for now, just
			// for components and just for ractive...
			ractive._inlinePartials = options.inlinePartials;
		} else {
			ractive.root = ractive;
			ractive.parent = ractive.container = null;
		}
	}

	function deprecateRactiveData() {
		throw new Error("Using `ractive.data` is no longer supported - you must use the `ractive.get()` API instead");
	}

	function ComplexParameter(component, template, callback) {
		this.parentFragment = component.parentFragment;
		this.callback = callback;

		this.fragment = new virtualdom_Fragment({
			template: template,
			root: component.root,
			owner: this
		});

		this.update();
	}

	var initialise_ComplexParameter = ComplexParameter;

	ComplexParameter.prototype = {
		bubble: function () {
			if (!this.dirty) {
				this.dirty = true;
				global_runloop.addView(this);
			}
		},

		update: function () {
			this.callback(this.fragment.getValue());
			this.dirty = false;
		},

		rebind: function (oldKeypath, newKeypath) {
			this.fragment.rebind(oldKeypath, newKeypath);
		},

		unbind: function () {
			this.fragment.unbind();
		}
	};

	var createInstance = function (component, Component, attributes, yieldTemplate, partials) {
		var instance,
			parentFragment,
			ractive,
			fragment,
			container,
			inlinePartials = {},
			data = {},
			mappings = {},
			ready,
			resolvers = [];

		parentFragment = component.parentFragment;
		ractive = component.root;

		partials = partials || {};
		utils_object__extend(inlinePartials, partials);

		// Make contents available as a {{>content}} partial
		partials.content = yieldTemplate || [];

		// set a default partial for yields with no name
		inlinePartials[""] = partials.content;

		if (Component.defaults.el) {
			warnIfDebug("The <%s/> component has a default `el` property; it has been disregarded", component.name);
		}

		// find container
		fragment = parentFragment;
		while (fragment) {
			if (fragment.owner.type === YIELDER) {
				container = fragment.owner.container;
				break;
			}

			fragment = fragment.parent;
		}

		// each attribute represents either a) data or b) a mapping
		if (attributes) {
			Object.keys(attributes).forEach(function (key) {
				var attribute = attributes[key],
					parsed,
					resolver;

				if (typeof attribute === "string") {
					// it's static data
					parsed = parseJSON(attribute);
					data[key] = parsed ? parsed.value : attribute;
				} else if (attribute === 0) {
					// it had no '=', so we'll call it true
					data[key] = true;
				} else if (isArray(attribute)) {
					// this represents dynamic data
					if (isSingleInterpolator(attribute)) {
						mappings[key] = {
							origin: component.root.viewmodel,
							keypath: undefined
						};

						resolver = createResolver(component, attribute[0], function (keypath) {
							if (keypath.isSpecial) {
								if (ready) {
									instance.set(key, keypath.value); // TODO use viewmodel?
								} else {
									data[key] = keypath.value;

									// TODO errr.... would be better if we didn't have to do this
									delete mappings[key];
								}
							} else {
								if (ready) {
									instance.viewmodel.mappings[key].resolve(keypath);
								} else {
									// resolved immediately
									mappings[key].keypath = keypath;
								}
							}
						});
					} else {
						resolver = new initialise_ComplexParameter(component, attribute, function (value) {
							if (ready) {
								instance.set(key, value); // TODO use viewmodel?
							} else {
								data[key] = value;
							}
						});
					}

					resolvers.push(resolver);
				} else {
					throw new Error("erm wut");
				}
			});
		}

		instance = create(Component.prototype);

		initialise(instance, {
			el: null,
			append: true,
			data: data,
			partials: partials,
			magic: ractive.magic || Component.defaults.magic,
			modifyArrays: ractive.modifyArrays,
			// need to inherit runtime parent adaptors
			adapt: ractive.adapt
		}, {
			parent: ractive,
			component: component,
			container: container,
			mappings: mappings,
			inlinePartials: inlinePartials,
			cssIds: parentFragment.cssIds
		});

		ready = true;
		component.resolvers = resolvers;

		return instance;
	};

	function createResolver(component, template, callback) {
		var resolver;

		if (template.r) {
			resolver = Resolvers_createReferenceResolver(component, template.r, callback);
		} else if (template.x) {
			resolver = new Resolvers_ExpressionResolver(component, component.parentFragment, template.x, callback);
		} else if (template.rx) {
			resolver = new ReferenceExpressionResolver_ReferenceExpressionResolver(component, template.rx, callback);
		}

		return resolver;
	}

	function isSingleInterpolator(template) {
		return template.length === 1 && template[0].t === INTERPOLATOR;
	}

	// TODO how should event arguments be handled? e.g.
	// <widget on-foo='bar:1,2,3'/>
	// The event 'bar' will be fired on the parent instance
	// when 'foo' fires on the child, but the 1,2,3 arguments
	// will be lost

	var initialise_propagateEvents = propagateEvents;

	function propagateEvents(component, eventsDescriptor) {
		var eventName;

		for (eventName in eventsDescriptor) {
			if (eventsDescriptor.hasOwnProperty(eventName)) {
				propagateEvent(component.instance, component.root, eventName, eventsDescriptor[eventName]);
			}
		}
	}

	function propagateEvent(childInstance, parentInstance, eventName, proxyEventName) {
		if (typeof proxyEventName !== "string") {
			fatal("Components currently only support simple events - you cannot include arguments. Sorry!");
		}

		childInstance.on(eventName, function () {
			var event, args;

			// semi-weak test, but what else? tag the event obj ._isEvent ?
			if (arguments.length && arguments[0] && arguments[0].node) {
				event = Array.prototype.shift.call(arguments);
			}

			args = Array.prototype.slice.call(arguments);

			shared_fireEvent(parentInstance, proxyEventName, { event: event, args: args });

			// cancel bubbling
			return false;
		});
	}

	var initialise_updateLiveQueries = function (component) {
		var ancestor, query;

		// If there's a live query for this component type, add it
		ancestor = component.root;
		while (ancestor) {
			if (query = ancestor._liveComponentQueries["_" + component.name]) {
				query.push(component.instance);
			}

			ancestor = ancestor.parent;
		}
	};

	var Component_prototype_init = Component$init;
	function Component$init(options, Component) {
		var parentFragment, root;

		if (!Component) {
			throw new Error("Component \"" + this.name + "\" not found");
		}

		parentFragment = this.parentFragment = options.parentFragment;
		root = parentFragment.root;

		this.root = root;
		this.type = COMPONENT;
		this.name = options.template.e;
		this.index = options.index;
		this.indexRefBindings = {};
		this.yielders = {};
		this.resolvers = [];

		createInstance(this, Component, options.template.a, options.template.f, options.template.p);
		initialise_propagateEvents(this, options.template.v);

		// intro, outro and decorator directives have no effect
		if (options.template.t0 || options.template.t1 || options.template.t2 || options.template.o) {
			warnIfDebug("The \"intro\", \"outro\" and \"decorator\" directives have no effect on components", { ractive: this.instance });
		}

		initialise_updateLiveQueries(this);
	}

	var Component_prototype_rebind = Component$rebind;

	function Component$rebind(oldKeypath, newKeypath) {
		var query;

		this.resolvers.forEach(rebind);

		for (var k in this.yielders) {
			if (this.yielders[k][0]) {
				rebind(this.yielders[k][0]);
			}
		}

		if (query = this.root._liveComponentQueries["_" + this.name]) {
			query._makeDirty();
		}

		function rebind(x) {
			x.rebind(oldKeypath, newKeypath);
		}
	}

	var Component_prototype_render = Component$render;

	function Component$render() {
		var instance = this.instance;

		instance.render(this.parentFragment.getNode());

		this.rendered = true;
		return instance.fragment.detach();
	}

	var Component_prototype_toString = Component$toString;

	function Component$toString() {
		return this.instance.fragment.toString();
	}

	var Component_prototype_unbind = Component$unbind;

	var Component_prototype_unbind__teardownHook = new hooks_Hook("teardown");
	function Component$unbind() {
		var instance = this.instance;

		this.resolvers.forEach(methodCallers__unbind);

		removeFromLiveComponentQueries(this);

		instance._observers.forEach(cancel);

		// teardown the instance
		instance.fragment.unbind();
		instance.viewmodel.teardown();

		if (instance.fragment.rendered && instance.el.__ractive_instances__) {
			removeFromArray(instance.el.__ractive_instances__, instance);
		}

		Component_prototype_unbind__teardownHook.fire(instance);
	}

	function removeFromLiveComponentQueries(component) {
		var instance, query;

		instance = component.root;

		do {
			if (query = instance._liveComponentQueries["_" + component.name]) {
				query._remove(component);
			}
		} while (instance = instance.parent);
	}

	var Component_prototype_unrender = Component$unrender;

	function Component$unrender(shouldDestroy) {
		this.shouldDestroy = shouldDestroy;
		this.instance.unrender();
	}

	var Component = function (options, Constructor) {
		this.init(options, Constructor);
	};

	Component.prototype = {
		detach: Component_prototype_detach,
		find: Component_prototype_find,
		findAll: Component_prototype_findAll,
		findAllComponents: Component_prototype_findAllComponents,
		findComponent: Component_prototype_findComponent,
		findNextNode: Component_prototype_findNextNode,
		firstNode: Component_prototype_firstNode,
		init: Component_prototype_init,
		rebind: Component_prototype_rebind,
		render: Component_prototype_render,
		toString: Component_prototype_toString,
		unbind: Component_prototype_unbind,
		unrender: Component_prototype_unrender
	};

	var _Component = Component;

	var Comment = function (options) {
		this.type = COMMENT;
		this.value = options.template.c;
	};

	Comment.prototype = {
		detach: shared_detach,

		firstNode: function () {
			return this.node;
		},

		render: function () {
			if (!this.node) {
				this.node = document.createComment(this.value);
			}

			return this.node;
		},

		toString: function () {
			return "<!--" + this.value + "-->";
		},

		unrender: function (shouldDestroy) {
			if (shouldDestroy) {
				this.node.parentNode.removeChild(this.node);
			}
		}
	};

	var items_Comment = Comment;

	var Yielder = function (options) {
		var container, component;

		this.type = YIELDER;

		this.container = container = options.parentFragment.root;
		this.component = component = container.component;

		this.container = container;
		this.containerFragment = options.parentFragment;
		this.parentFragment = component.parentFragment;

		var name = this.name = options.template.n || "";

		var template = container._inlinePartials[name];

		if (!template) {
			warnIfDebug("Could not find template for partial \"" + name + "\"", { ractive: options.root });
			template = [];
		}

		this.fragment = new virtualdom_Fragment({
			owner: this,
			root: container.parent,
			template: template,
			pElement: this.containerFragment.pElement
		});

		// even though only one yielder is allowed, we need to have an array of them
		// as it's possible to cause a yielder to be created before the last one
		// was destroyed in the same turn of the runloop
		if (!isArray(component.yielders[name])) {
			component.yielders[name] = [this];
		} else {
			component.yielders[name].push(this);
		}

		global_runloop.scheduleTask(function () {
			if (component.yielders[name].length > 1) {
				throw new Error("A component template can only have one {{yield" + (name ? " " + name : "") + "}} declaration at a time");
			}
		});
	};

	Yielder.prototype = {
		detach: function () {
			return this.fragment.detach();
		},

		find: function (selector) {
			return this.fragment.find(selector);
		},

		findAll: function (selector, query) {
			return this.fragment.findAll(selector, query);
		},

		findComponent: function (selector) {
			return this.fragment.findComponent(selector);
		},

		findAllComponents: function (selector, query) {
			return this.fragment.findAllComponents(selector, query);
		},

		findNextNode: function () {
			return this.containerFragment.findNextNode(this);
		},

		firstNode: function () {
			return this.fragment.firstNode();
		},

		getValue: function (options) {
			return this.fragment.getValue(options);
		},

		render: function () {
			return this.fragment.render();
		},

		unbind: function () {
			this.fragment.unbind();
		},

		unrender: function (shouldDestroy) {
			this.fragment.unrender(shouldDestroy);
			removeFromArray(this.component.yielders[this.name], this);
		},

		rebind: function (oldKeypath, newKeypath) {
			this.fragment.rebind(oldKeypath, newKeypath);
		},

		toString: function () {
			return this.fragment.toString();
		}
	};

	var items_Yielder = Yielder;

	var Doctype = function (options) {
		this.declaration = options.template.a;
	};

	Doctype.prototype = {
		init: noop,
		render: noop,
		unrender: noop,
		teardown: noop,
		toString: function () {
			return "<!DOCTYPE" + this.declaration + ">";
		}
	};

	var items_Doctype = Doctype;

	var Fragment_prototype_init = Fragment$init;

	function Fragment$init(options) {
		var _this = this;

		this.owner = options.owner; // The item that owns this fragment - an element, section, partial, or attribute
		this.parent = this.owner.parentFragment;

		// inherited properties
		this.root = options.root;
		this.pElement = options.pElement;
		this.context = options.context;
		this.index = options.index;
		this.key = options.key;
		this.registeredIndexRefs = [];

		// encapsulated styles should be inherited until they get applied by an element
		this.cssIds = "cssIds" in options ? options.cssIds : this.parent ? this.parent.cssIds : null;

		this.items = options.template.map(function (template, i) {
			return createItem({
				parentFragment: _this,
				pElement: options.pElement,
				template: template,
				index: i
			});
		});

		this.value = this.argsList = null;
		this.dirtyArgs = this.dirtyValue = true;

		this.bound = true;
	}

	function createItem(options) {
		if (typeof options.template === "string") {
			return new items_Text(options);
		}

		switch (options.template.t) {
			case YIELDER:
				return new items_Yielder(options);
			case INTERPOLATOR:
				return new items_Interpolator(options);
			case SECTION:
				return new _Section(options);
			case TRIPLE:
				return new _Triple(options);
			case ELEMENT:
				var constructor = undefined;
				if (constructor = Component_getComponent(options.parentFragment.root, options.template.e)) {
					return new _Component(options, constructor);
				}
				return new _Element(options);
			case PARTIAL:
				return new _Partial(options);
			case COMMENT:
				return new items_Comment(options);
			case DOCTYPE:
				return new items_Doctype(options);

			default:
				throw new Error("Something very strange happened. Please file an issue at https://github.com/ractivejs/ractive/issues. Thanks!");
		}
	}

	var Fragment_prototype_rebind = Fragment$rebind;
	function Fragment$rebind(oldKeypath, newKeypath) {

		// assign new context keypath if needed
		if (!this.owner || this.owner.hasContext) {
			assignNewKeypath(this, "context", oldKeypath, newKeypath);
		}

		this.items.forEach(function (item) {
			if (item.rebind) {
				item.rebind(oldKeypath, newKeypath);
			}
		});
	}

	var Fragment_prototype_render = Fragment$render;

	function Fragment$render() {
		var result;

		if (this.items.length === 1) {
			result = this.items[0].render();
		} else {
			result = document.createDocumentFragment();

			this.items.forEach(function (item) {
				result.appendChild(item.render());
			});
		}

		this.rendered = true;
		return result;
	}

	var Fragment_prototype_toString = Fragment$toString;

	function Fragment$toString(escape) {
		if (!this.items) {
			return "";
		}

		return this.items.map(escape ? toEscapedString : Fragment_prototype_toString__toString).join("");
	}

	function Fragment_prototype_toString__toString(item) {
		return item.toString();
	}

	function toEscapedString(item) {
		return item.toString(true);
	}

	var Fragment_prototype_unbind = Fragment$unbind;

	function Fragment$unbind() {
		if (!this.bound) {
			return;
		}

		this.items.forEach(unbindItem);
		this.bound = false;
	}

	function unbindItem(item) {
		if (item.unbind) {
			item.unbind();
		}
	}

	var Fragment_prototype_unrender = Fragment$unrender;

	function Fragment$unrender(shouldDestroy) {
		if (!this.rendered) {
			throw new Error("Attempted to unrender a fragment that was not rendered");
		}

		this.items.forEach(function (i) {
			return i.unrender(shouldDestroy);
		});
		this.rendered = false;
	}

	var Fragment = function (options) {
		this.init(options);
	};

	Fragment.prototype = {
		bubble: prototype_bubble,
		detach: Fragment_prototype_detach,
		find: Fragment_prototype_find,
		findAll: Fragment_prototype_findAll,
		findAllComponents: Fragment_prototype_findAllComponents,
		findComponent: Fragment_prototype_findComponent,
		findNextNode: prototype_findNextNode,
		firstNode: prototype_firstNode,
		getArgsList: getArgsList,
		getNode: getNode,
		getValue: prototype_getValue,
		init: Fragment_prototype_init,
		rebind: Fragment_prototype_rebind,
		registerIndexRef: function (idx) {
			var idxs = this.registeredIndexRefs;
			if (idxs.indexOf(idx) === -1) {
				idxs.push(idx);
			}
		},
		render: Fragment_prototype_render,
		toString: Fragment_prototype_toString,
		unbind: Fragment_prototype_unbind,
		unregisterIndexRef: function (idx) {
			var idxs = this.registeredIndexRefs;
			idxs.splice(idxs.indexOf(idx), 1);
		},
		unrender: Fragment_prototype_unrender
	};

	var virtualdom_Fragment = Fragment;

	var prototype_reset = Ractive$reset;
	var shouldRerender = ["template", "partials", "components", "decorators", "events"],
		resetHook = new hooks_Hook("reset");
	function Ractive$reset(data) {
		var promise, wrapper, changes, i, rerender;

		data = data || {};

		if (typeof data !== "object") {
			throw new Error("The reset method takes either no arguments, or an object containing new data");
		}

		// If the root object is wrapped, try and use the wrapper's reset value
		if ((wrapper = this.viewmodel.wrapped[""]) && wrapper.reset) {
			if (wrapper.reset(data) === false) {
				// reset was rejected, we need to replace the object
				this.viewmodel.reset(data);
			}
		} else {
			this.viewmodel.reset(data);
		}

		// reset config items and track if need to rerender
		changes = config_config.reset(this);

		i = changes.length;
		while (i--) {
			if (shouldRerender.indexOf(changes[i]) > -1) {
				rerender = true;
				break;
			}
		}

		if (rerender) {
			var component = undefined;

			this.viewmodel.mark(rootKeypath);

			// Is this is a component, we need to set the `shouldDestroy`
			// flag, otherwise it will assume by default that a parent node
			// will be detached, and therefore it doesn't need to bother
			// detaching its own nodes
			if (component = this.component) {
				component.shouldDestroy = true;
			}

			this.unrender();

			if (component) {
				component.shouldDestroy = false;
			}

			// If the template changed, we need to destroy the parallel DOM
			// TODO if we're here, presumably it did?
			if (this.fragment.template !== this.template) {
				this.fragment.unbind();

				this.fragment = new virtualdom_Fragment({
					template: this.template,
					root: this,
					owner: this
				});
			}

			promise = this.render(this.el, this.anchor);
		} else {
			promise = global_runloop.start(this, true);
			this.viewmodel.mark(rootKeypath);
			global_runloop.end();
		}

		resetHook.fire(this, data);

		return promise;
	}

	var resetPartial = function (name, partial) {
		var promise,
			collection = [];

		function collect(source, dest, ractive) {
			// if this is a component and it has its own partial, bail
			if (ractive && ractive.partials[name]) return;

			source.forEach(function (item) {
				// queue to rerender if the item is a partial and the current name matches
				if (item.type === PARTIAL && item.getPartialName() === name) {
					dest.push(item);
				}

				// if it has a fragment, process its items
				if (item.fragment) {
					collect(item.fragment.items, dest, ractive);
				}

				// or if it has fragments
				if (isArray(item.fragments)) {
					collect(item.fragments, dest, ractive);
				}

					// or if it is itself a fragment, process its items
				else if (isArray(item.items)) {
					collect(item.items, dest, ractive);
				}

					// or if it is a component, step in and process its items
				else if (item.type === COMPONENT && item.instance) {
					collect(item.instance.fragment.items, dest, item.instance);
				}

				// if the item is an element, process its attributes too
				if (item.type === ELEMENT) {
					if (isArray(item.attributes)) {
						collect(item.attributes, dest, ractive);
					}

					if (isArray(item.conditionalAttributes)) {
						collect(item.conditionalAttributes, dest, ractive);
					}
				}
			});
		}

		collect(this.fragment.items, collection);
		this.partials[name] = partial;

		promise = global_runloop.start(this, true);

		collection.forEach(function (item) {
			item.value = undefined;
			item.setValue(name);
		});

		global_runloop.end();

		return promise;
	};

	// TODO should resetTemplate be asynchronous? i.e. should it be a case
	// of outro, update template, intro? I reckon probably not, since that
	// could be achieved with unrender-resetTemplate-render. Also, it should
	// conceptually be similar to resetPartial, which couldn't be async

	var resetTemplate = Ractive$resetTemplate;
	function Ractive$resetTemplate(template) {
		var transitionsEnabled, component;

		template_template.init(null, this, { template: template });

		transitionsEnabled = this.transitionsEnabled;
		this.transitionsEnabled = false;

		// Is this is a component, we need to set the `shouldDestroy`
		// flag, otherwise it will assume by default that a parent node
		// will be detached, and therefore it doesn't need to bother
		// detaching its own nodes
		if (component = this.component) {
			component.shouldDestroy = true;
		}

		this.unrender();

		if (component) {
			component.shouldDestroy = false;
		}

		// remove existing fragment and create new one
		this.fragment.unbind();
		this.fragment = new virtualdom_Fragment({
			template: this.template,
			root: this,
			owner: this
		});

		this.render(this.el, this.anchor);

		this.transitionsEnabled = transitionsEnabled;
	}

	var reverse = makeArrayMethod("reverse");

	var Ractive_prototype_set = Ractive$set;

	function Ractive$set(keypath, value) {
		var map, promise;

		promise = global_runloop.start(this, true);

		// Set multiple keypaths in one go
		if (isObject(keypath)) {
			map = keypath;

			for (keypath in map) {
				if (map.hasOwnProperty(keypath)) {
					value = map[keypath];
					set(this, keypath, value);
				}
			}
		}

			// Set a single keypath
		else {
			set(this, keypath, value);
		}

		global_runloop.end();

		return promise;
	}

	function set(ractive, keypath, value) {
		keypath = getKeypath(normalise(keypath));

		if (keypath.isPattern) {
			getMatchingKeypaths(ractive, keypath).forEach(function (keypath) {
				ractive.viewmodel.set(keypath, value);
			});
		} else {
			ractive.viewmodel.set(keypath, value);
		}
	}

	var shift = makeArrayMethod("shift");

	var prototype_sort = makeArrayMethod("sort");

	var splice = makeArrayMethod("splice");

	var subtract = Ractive$subtract;
	function Ractive$subtract(keypath, d) {
		return shared_add(this, keypath, d === undefined ? -1 : -d);
	}

	// Teardown. This goes through the root fragment and all its children, removing observers
	// and generally cleaning up after itself

	var Ractive_prototype_teardown = Ractive$teardown;

	var Ractive_prototype_teardown__teardownHook = new hooks_Hook("teardown");
	function Ractive$teardown() {
		var promise;

		this.fragment.unbind();
		this.viewmodel.teardown();

		this._observers.forEach(cancel);

		if (this.fragment.rendered && this.el.__ractive_instances__) {
			removeFromArray(this.el.__ractive_instances__, this);
		}

		this.shouldDestroy = true;
		promise = this.fragment.rendered ? this.unrender() : utils_Promise.resolve();

		Ractive_prototype_teardown__teardownHook.fire(this);

		this._boundFunctions.forEach(deleteFunctionCopy);

		return promise;
	}

	function deleteFunctionCopy(bound) {
		delete bound.fn[bound.prop];
	}

	var toggle = Ractive$toggle;
	function Ractive$toggle(keypath) {
		var _this = this;

		if (typeof keypath !== "string") {
			throw new TypeError(badArguments);
		}

		var changes = undefined;

		if (/\*/.test(keypath)) {
			changes = {};

			getMatchingKeypaths(this, getKeypath(normalise(keypath))).forEach(function (keypath) {
				changes[keypath.str] = !_this.viewmodel.get(keypath);
			});

			return this.set(changes);
		}

		return this.set(keypath, !this.get(keypath));
	}

	var toHTML = Ractive$toHTML;

	function Ractive$toHTML() {
		return this.fragment.toString(true);
	}

	var Ractive_prototype_unrender = Ractive$unrender;
	var unrenderHook = new hooks_Hook("unrender");
	function Ractive$unrender() {
		var promise, shouldDestroy;

		if (!this.fragment.rendered) {
			warnIfDebug("ractive.unrender() was called on a Ractive instance that was not rendered");
			return utils_Promise.resolve();
		}

		promise = global_runloop.start(this, true);

		// If this is a component, and the component isn't marked for destruction,
		// don't detach nodes from the DOM unnecessarily
		shouldDestroy = !this.component || this.component.shouldDestroy || this.shouldDestroy;

		// Cancel any animations in progress
		while (this._animations[0]) {
			this._animations[0].stop(); // it will remove itself from the index
		}

		this.fragment.unrender(shouldDestroy);

		removeFromArray(this.el.__ractive_instances__, this);

		unrenderHook.fire(this);

		global_runloop.end();
		return promise;
	}

	var unshift = makeArrayMethod("unshift");

	var Ractive_prototype_update = Ractive$update;
	var updateHook = new hooks_Hook("update");
	function Ractive$update(keypath) {
		var promise;

		keypath = getKeypath(keypath) || rootKeypath;

		promise = global_runloop.start(this, true);
		this.viewmodel.mark(keypath);
		global_runloop.end();

		updateHook.fire(this, keypath);

		return promise;
	}

	var prototype_updateModel = Ractive$updateModel;

	function Ractive$updateModel(keypath, cascade) {
		var values, key, bindings;

		if (typeof keypath === "string" && !cascade) {
			bindings = this._twowayBindings[keypath];
		} else {
			bindings = [];

			for (key in this._twowayBindings) {
				if (!keypath || getKeypath(key).equalsOrStartsWith(keypath)) {
					// TODO is this right?
					bindings.push.apply(bindings, this._twowayBindings[key]);
				}
			}
		}

		values = consolidate(this, bindings);
		return this.set(values);
	}

	function consolidate(ractive, bindings) {
		var values = {},
			checkboxGroups = [];

		bindings.forEach(function (b) {
			var oldValue, newValue;

			// special case - radio name bindings
			if (b.radioName && !b.element.node.checked) {
				return;
			}

			// special case - checkbox name bindings come in groups, so
			// we want to get the value once at most
			if (b.checkboxName) {
				if (!checkboxGroups[b.keypath.str] && !b.changed()) {
					checkboxGroups.push(b.keypath);
					checkboxGroups[b.keypath.str] = b;
				}

				return;
			}

			oldValue = b.attribute.value;
			newValue = b.getValue();

			if (arrayContentsMatch(oldValue, newValue)) {
				return;
			}

			if (!isEqual(oldValue, newValue)) {
				values[b.keypath.str] = newValue;
			}
		});

		// Handle groups of `<input type='checkbox' name='{{foo}}' ...>`
		if (checkboxGroups.length) {
			checkboxGroups.forEach(function (keypath) {
				var binding, oldValue, newValue;

				binding = checkboxGroups[keypath.str]; // one to represent the entire group
				oldValue = binding.attribute.value;
				newValue = binding.getValue();

				if (!arrayContentsMatch(oldValue, newValue)) {
					values[keypath.str] = newValue;
				}
			});
		}

		return values;
	}

	var prototype = {
		add: prototype_add,
		animate: prototype_animate,
		detach: prototype_detach,
		find: prototype_find,
		findAll: prototype_findAll,
		findAllComponents: prototype_findAllComponents,
		findComponent: prototype_findComponent,
		findContainer: findContainer,
		findParent: findParent,
		fire: prototype_fire,
		get: prototype_get,
		insert: insert,
		merge: prototype_merge,
		observe: observe,
		observeOnce: observeOnce,
		off: off,
		on: on,
		once: once,
		pop: pop,
		push: push,
		render: prototype_render,
		reset: prototype_reset,
		resetPartial: resetPartial,
		resetTemplate: resetTemplate,
		reverse: reverse,
		set: Ractive_prototype_set,
		shift: shift,
		sort: prototype_sort,
		splice: splice,
		subtract: subtract,
		teardown: Ractive_prototype_teardown,
		toggle: toggle,
		toHTML: toHTML,
		toHtml: toHTML,
		unrender: Ractive_prototype_unrender,
		unshift: unshift,
		update: Ractive_prototype_update,
		updateModel: prototype_updateModel
	};

	var wrapMethod = function (method, superMethod, force) {

		if (force || needsSuper(method, superMethod)) {

			return function () {

				var hasSuper = ("_super" in this),
					_super = this._super,
					result;

				this._super = superMethod;

				result = method.apply(this, arguments);

				if (hasSuper) {
					this._super = _super;
				}

				return result;
			};
		} else {
			return method;
		}
	};

	function needsSuper(method, superMethod) {
		return typeof superMethod === "function" && /_super/.test(method);
	}

	var unwrapExtended = unwrap;

	function unwrap(Child) {
		var options = {};

		while (Child) {
			addRegistries(Child, options);
			addOtherOptions(Child, options);

			if (Child._Parent !== _Ractive) {
				Child = Child._Parent;
			} else {
				Child = false;
			}
		}

		return options;
	}

	function addRegistries(Child, options) {
		config_registries.forEach(function (r) {
			addRegistry(r.useDefaults ? Child.prototype : Child, options, r.name);
		});
	}

	function addRegistry(target, options, name) {
		var registry,
			keys = Object.keys(target[name]);

		if (!keys.length) {
			return;
		}

		if (!(registry = options[name])) {
			registry = options[name] = {};
		}

		keys.filter(function (key) {
			return !(key in registry);
		}).forEach(function (key) {
			return registry[key] = target[name][key];
		});
	}

	function addOtherOptions(Child, options) {
		Object.keys(Child.prototype).forEach(function (key) {
			if (key === "computed") {
				return;
			}

			var value = Child.prototype[key];

			if (!(key in options)) {
				options[key] = value._method ? value._method : value;
			}

				// is it a wrapped function?
			else if (typeof options[key] === "function" && typeof value === "function" && options[key]._method) {

				var result = undefined,
					needsSuper = value._method;

				if (needsSuper) {
					value = value._method;
				}

				// rewrap bound directly to parent fn
				result = wrapMethod(options[key]._method, value);

				if (needsSuper) {
					result._method = result;
				}

				options[key] = result;
			}
		});
	}

	var _extend = _extend__extend;

	function _extend__extend() {
		for (var _len = arguments.length, options = Array(_len), _key = 0; _key < _len; _key++) {
			options[_key] = arguments[_key];
		}

		if (!options.length) {
			return extendOne(this);
		} else {
			return options.reduce(extendOne, this);
		}
	}

	function extendOne(Parent) {
		var options = arguments[1] === undefined ? {} : arguments[1];

		var Child, proto;

		// if we're extending with another Ractive instance...
		//
		//   var Human = Ractive.extend(...), Spider = Ractive.extend(...);
		//   var Spiderman = Human.extend( Spider );
		//
		// ...inherit prototype methods and default options as well
		if (options.prototype instanceof _Ractive) {
			options = unwrapExtended(options);
		}

		Child = function (options) {
			if (!(this instanceof Child)) return new Child(options);
			initialise(this, options);
		};

		proto = create(Parent.prototype);
		proto.constructor = Child;

		// Static properties
		defineProperties(Child, {
			// alias prototype as defaults
			defaults: { value: proto },

			// extendable
			extend: { value: _extend__extend, writable: true, configurable: true },

			// Parent - for IE8, can't use Object.getPrototypeOf
			_Parent: { value: Parent }
		});

		// extend configuration
		config_config.extend(Parent, proto, options);

		custom_data.extend(Parent, proto, options);

		if (options.computed) {
			proto.computed = utils_object__extend(create(Parent.prototype.computed), options.computed);
		}

		Child.prototype = proto;

		return Child;
	}

	var getNodeInfo = function (node) {
		var info = {},
			priv,
			indices;

		if (!node || !(priv = node._ractive)) {
			return info;
		}

		info.ractive = priv.root;
		info.keypath = priv.keypath.str;
		info.index = {};

		// find all index references and resolve them
		if (indices = Resolvers_findIndexRefs(priv.proxy.parentFragment)) {
			info.index = Resolvers_findIndexRefs.resolve(indices);
		}

		return info;
	};

	var Ractive, properties;

	// Main Ractive required object
	Ractive = function (options) {
		if (!(this instanceof Ractive)) return new Ractive(options);
		initialise(this, options);
	};

	// Ractive properties
	properties = {

		// debug flag
		DEBUG: { writable: true, value: true },
		DEBUG_PROMISES: { writable: true, value: true },

		// static methods:
		extend: { value: _extend },
		getNodeInfo: { value: getNodeInfo },
		parse: { value: _parse },

		// Namespaced constructors
		Promise: { value: utils_Promise },

		// support
		svg: { value: svg },
		magic: { value: environment__magic },

		// version
		VERSION: { value: "0.7.3" },

		// Plugins
		adaptors: { writable: true, value: {} },
		components: { writable: true, value: {} },
		decorators: { writable: true, value: {} },
		easing: { writable: true, value: static_easing },
		events: { writable: true, value: {} },
		interpolators: { writable: true, value: static_interpolators },
		partials: { writable: true, value: {} },
		transitions: { writable: true, value: {} }
	};

	// Ractive properties
	defineProperties(Ractive, properties);

	Ractive.prototype = utils_object__extend(prototype, config_defaults);

	Ractive.prototype.constructor = Ractive;

	// alias prototype as defaults
	Ractive.defaults = Ractive.prototype;

	// Ractive.js makes liberal use of things like Array.prototype.indexOf. In
	// older browsers, these are made available via a shim - here, we do a quick
	// pre-flight check to make sure that either a) we're not in a shit browser,
	// or b) we're using a Ractive-legacy.js build
	var FUNCTION = "function";

	if (typeof Date.now !== FUNCTION || typeof String.prototype.trim !== FUNCTION || typeof Object.keys !== FUNCTION || typeof Array.prototype.indexOf !== FUNCTION || typeof Array.prototype.forEach !== FUNCTION || typeof Array.prototype.map !== FUNCTION || typeof Array.prototype.filter !== FUNCTION || typeof window !== "undefined" && typeof window.addEventListener !== FUNCTION) {
		throw new Error("It looks like you're attempting to use Ractive.js in an older browser. You'll need to use one of the 'legacy builds' in order to continue - see http://docs.ractivejs.org/latest/legacy-builds for more information.");
	}

	var _Ractive = Ractive;

	return _Ractive;

}));
//# sourceMappingURL=ractive.js.map
;
//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

(function () {

	// Baseline setup
	// --------------

	// Establish the root object, `window` in the browser, or `exports` on the server.
	var root = this;

	// Save the previous value of the `_` variable.
	var previousUnderscore = root._;

	// Save bytes in the minified (but not gzipped) version:
	var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

	// Create quick reference variables for speed access to core prototypes.
	var
		push = ArrayProto.push,
		slice = ArrayProto.slice,
		toString = ObjProto.toString,
		hasOwnProperty = ObjProto.hasOwnProperty;

	// All **ECMAScript 5** native function implementations that we hope to use
	// are declared here.
	var
		nativeIsArray = Array.isArray,
		nativeKeys = Object.keys,
		nativeBind = FuncProto.bind,
		nativeCreate = Object.create;

	// Naked function reference for surrogate-prototype-swapping.
	var Ctor = function () { };

	// Create a safe reference to the Underscore object for use below.
	var _ = function (obj) {
		if (obj instanceof _) return obj;
		if (!(this instanceof _)) return new _(obj);
		this._wrapped = obj;
	};

	// Export the Underscore object for **Node.js**, with
	// backwards-compatibility for the old `require()` API. If we're in
	// the browser, add `_` as a global object.
	if (typeof exports !== 'undefined') {
		if (typeof module !== 'undefined' && module.exports) {
			exports = module.exports = _;
		}
		exports._ = _;
	} else {
		root._ = _;
	}

	// Current version.
	_.VERSION = '1.8.3';

	// Internal function that returns an efficient (for current engines) version
	// of the passed-in callback, to be repeatedly applied in other Underscore
	// functions.
	var optimizeCb = function (func, context, argCount) {
		if (context === void 0) return func;
		switch (argCount == null ? 3 : argCount) {
			case 1: return function (value) {
				return func.call(context, value);
			};
			case 2: return function (value, other) {
				return func.call(context, value, other);
			};
			case 3: return function (value, index, collection) {
				return func.call(context, value, index, collection);
			};
			case 4: return function (accumulator, value, index, collection) {
				return func.call(context, accumulator, value, index, collection);
			};
		}
		return function () {
			return func.apply(context, arguments);
		};
	};

	// A mostly-internal function to generate callbacks that can be applied
	// to each element in a collection, returning the desired result � either
	// identity, an arbitrary callback, a property matcher, or a property accessor.
	var cb = function (value, context, argCount) {
		if (value == null) return _.identity;
		if (_.isFunction(value)) return optimizeCb(value, context, argCount);
		if (_.isObject(value)) return _.matcher(value);
		return _.property(value);
	};
	_.iteratee = function (value, context) {
		return cb(value, context, Infinity);
	};

	// An internal function for creating assigner functions.
	var createAssigner = function (keysFunc, undefinedOnly) {
		return function (obj) {
			var length = arguments.length;
			if (length < 2 || obj == null) return obj;
			for (var index = 1; index < length; index++) {
				var source = arguments[index],
					keys = keysFunc(source),
					l = keys.length;
				for (var i = 0; i < l; i++) {
					var key = keys[i];
					if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
				}
			}
			return obj;
		};
	};

	// An internal function for creating a new object that inherits from another.
	var baseCreate = function (prototype) {
		if (!_.isObject(prototype)) return {};
		if (nativeCreate) return nativeCreate(prototype);
		Ctor.prototype = prototype;
		var result = new Ctor;
		Ctor.prototype = null;
		return result;
	};

	var property = function (key) {
		return function (obj) {
			return obj == null ? void 0 : obj[key];
		};
	};

	// Helper for collection methods to determine whether a collection
	// should be iterated as an array or as an object
	// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
	// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
	var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
	var getLength = property('length');
	var isArrayLike = function (collection) {
		var length = getLength(collection);
		return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
	};

	// Collection Functions
	// --------------------

	// The cornerstone, an `each` implementation, aka `forEach`.
	// Handles raw objects in addition to array-likes. Treats all
	// sparse array-likes as if they were dense.
	_.each = _.forEach = function (obj, iteratee, context) {
		iteratee = optimizeCb(iteratee, context);
		var i, length;
		if (isArrayLike(obj)) {
			for (i = 0, length = obj.length; i < length; i++) {
				iteratee(obj[i], i, obj);
			}
		} else {
			var keys = _.keys(obj);
			for (i = 0, length = keys.length; i < length; i++) {
				iteratee(obj[keys[i]], keys[i], obj);
			}
		}
		return obj;
	};

	// Return the results of applying the iteratee to each element.
	_.map = _.collect = function (obj, iteratee, context) {
		iteratee = cb(iteratee, context);
		var keys = !isArrayLike(obj) && _.keys(obj),
			length = (keys || obj).length,
			results = Array(length);
		for (var index = 0; index < length; index++) {
			var currentKey = keys ? keys[index] : index;
			results[index] = iteratee(obj[currentKey], currentKey, obj);
		}
		return results;
	};

	// Create a reducing function iterating left or right.
	function createReduce(dir) {
		// Optimized iterator function as using arguments.length
		// in the main function will deoptimize the, see #1991.
		function iterator(obj, iteratee, memo, keys, index, length) {
			for (; index >= 0 && index < length; index += dir) {
				var currentKey = keys ? keys[index] : index;
				memo = iteratee(memo, obj[currentKey], currentKey, obj);
			}
			return memo;
		}

		return function (obj, iteratee, memo, context) {
			iteratee = optimizeCb(iteratee, context, 4);
			var keys = !isArrayLike(obj) && _.keys(obj),
				length = (keys || obj).length,
				index = dir > 0 ? 0 : length - 1;
			// Determine the initial value if none is provided.
			if (arguments.length < 3) {
				memo = obj[keys ? keys[index] : index];
				index += dir;
			}
			return iterator(obj, iteratee, memo, keys, index, length);
		};
	}

	// **Reduce** builds up a single result from a list of values, aka `inject`,
	// or `foldl`.
	_.reduce = _.foldl = _.inject = createReduce(1);

	// The right-associative version of reduce, also known as `foldr`.
	_.reduceRight = _.foldr = createReduce(-1);

	// Return the first value which passes a truth test. Aliased as `detect`.
	_.find = _.detect = function (obj, predicate, context) {
		var key;
		if (isArrayLike(obj)) {
			key = _.findIndex(obj, predicate, context);
		} else {
			key = _.findKey(obj, predicate, context);
		}
		if (key !== void 0 && key !== -1) return obj[key];
	};

	// Return all the elements that pass a truth test.
	// Aliased as `select`.
	_.filter = _.select = function (obj, predicate, context) {
		var results = [];
		predicate = cb(predicate, context);
		_.each(obj, function (value, index, list) {
			if (predicate(value, index, list)) results.push(value);
		});
		return results;
	};

	// Return all the elements for which a truth test fails.
	_.reject = function (obj, predicate, context) {
		return _.filter(obj, _.negate(cb(predicate)), context);
	};

	// Determine whether all of the elements match a truth test.
	// Aliased as `all`.
	_.every = _.all = function (obj, predicate, context) {
		predicate = cb(predicate, context);
		var keys = !isArrayLike(obj) && _.keys(obj),
			length = (keys || obj).length;
		for (var index = 0; index < length; index++) {
			var currentKey = keys ? keys[index] : index;
			if (!predicate(obj[currentKey], currentKey, obj)) return false;
		}
		return true;
	};

	// Determine if at least one element in the object matches a truth test.
	// Aliased as `any`.
	_.some = _.any = function (obj, predicate, context) {
		predicate = cb(predicate, context);
		var keys = !isArrayLike(obj) && _.keys(obj),
			length = (keys || obj).length;
		for (var index = 0; index < length; index++) {
			var currentKey = keys ? keys[index] : index;
			if (predicate(obj[currentKey], currentKey, obj)) return true;
		}
		return false;
	};

	// Determine if the array or object contains a given item (using `===`).
	// Aliased as `includes` and `include`.
	_.contains = _.includes = _.include = function (obj, item, fromIndex, guard) {
		if (!isArrayLike(obj)) obj = _.values(obj);
		if (typeof fromIndex != 'number' || guard) fromIndex = 0;
		return _.indexOf(obj, item, fromIndex) >= 0;
	};

	// Invoke a method (with arguments) on every item in a collection.
	_.invoke = function (obj, method) {
		var args = slice.call(arguments, 2);
		var isFunc = _.isFunction(method);
		return _.map(obj, function (value) {
			var func = isFunc ? method : value[method];
			return func == null ? func : func.apply(value, args);
		});
	};

	// Convenience version of a common use case of `map`: fetching a property.
	_.pluck = function (obj, key) {
		return _.map(obj, _.property(key));
	};

	// Convenience version of a common use case of `filter`: selecting only objects
	// containing specific `key:value` pairs.
	_.where = function (obj, attrs) {
		return _.filter(obj, _.matcher(attrs));
	};

	// Convenience version of a common use case of `find`: getting the first object
	// containing specific `key:value` pairs.
	_.findWhere = function (obj, attrs) {
		return _.find(obj, _.matcher(attrs));
	};

	// Return the maximum element (or element-based computation).
	_.max = function (obj, iteratee, context) {
		var result = -Infinity, lastComputed = -Infinity,
			value, computed;
		if (iteratee == null && obj != null) {
			obj = isArrayLike(obj) ? obj : _.values(obj);
			for (var i = 0, length = obj.length; i < length; i++) {
				value = obj[i];
				if (value > result) {
					result = value;
				}
			}
		} else {
			iteratee = cb(iteratee, context);
			_.each(obj, function (value, index, list) {
				computed = iteratee(value, index, list);
				if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
					result = value;
					lastComputed = computed;
				}
			});
		}
		return result;
	};

	// Return the minimum element (or element-based computation).
	_.min = function (obj, iteratee, context) {
		var result = Infinity, lastComputed = Infinity,
			value, computed;
		if (iteratee == null && obj != null) {
			obj = isArrayLike(obj) ? obj : _.values(obj);
			for (var i = 0, length = obj.length; i < length; i++) {
				value = obj[i];
				if (value < result) {
					result = value;
				}
			}
		} else {
			iteratee = cb(iteratee, context);
			_.each(obj, function (value, index, list) {
				computed = iteratee(value, index, list);
				if (computed < lastComputed || computed === Infinity && result === Infinity) {
					result = value;
					lastComputed = computed;
				}
			});
		}
		return result;
	};

	// Shuffle a collection, using the modern version of the
	// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher�Yates_shuffle).
	_.shuffle = function (obj) {
		var set = isArrayLike(obj) ? obj : _.values(obj);
		var length = set.length;
		var shuffled = Array(length);
		for (var index = 0, rand; index < length; index++) {
			rand = _.random(0, index);
			if (rand !== index) shuffled[index] = shuffled[rand];
			shuffled[rand] = set[index];
		}
		return shuffled;
	};

	// Sample **n** random values from a collection.
	// If **n** is not specified, returns a single random element.
	// The internal `guard` argument allows it to work with `map`.
	_.sample = function (obj, n, guard) {
		if (n == null || guard) {
			if (!isArrayLike(obj)) obj = _.values(obj);
			return obj[_.random(obj.length - 1)];
		}
		return _.shuffle(obj).slice(0, Math.max(0, n));
	};

	// Sort the object's values by a criterion produced by an iteratee.
	_.sortBy = function (obj, iteratee, context) {
		iteratee = cb(iteratee, context);
		return _.pluck(_.map(obj, function (value, index, list) {
			return {
				value: value,
				index: index,
				criteria: iteratee(value, index, list)
			};
		}).sort(function (left, right) {
			var a = left.criteria;
			var b = right.criteria;
			if (a !== b) {
				if (a > b || a === void 0) return 1;
				if (a < b || b === void 0) return -1;
			}
			return left.index - right.index;
		}), 'value');
	};

	// An internal function used for aggregate "group by" operations.
	var group = function (behavior) {
		return function (obj, iteratee, context) {
			var result = {};
			iteratee = cb(iteratee, context);
			_.each(obj, function (value, index) {
				var key = iteratee(value, index, obj);
				behavior(result, value, key);
			});
			return result;
		};
	};

	// Groups the object's values by a criterion. Pass either a string attribute
	// to group by, or a function that returns the criterion.
	_.groupBy = group(function (result, value, key) {
		if (_.has(result, key)) result[key].push(value); else result[key] = [value];
	});

	// Indexes the object's values by a criterion, similar to `groupBy`, but for
	// when you know that your index values will be unique.
	_.indexBy = group(function (result, value, key) {
		result[key] = value;
	});

	// Counts instances of an object that group by a certain criterion. Pass
	// either a string attribute to count by, or a function that returns the
	// criterion.
	_.countBy = group(function (result, value, key) {
		if (_.has(result, key)) result[key]++; else result[key] = 1;
	});

	// Safely create a real, live array from anything iterable.
	_.toArray = function (obj) {
		if (!obj) return [];
		if (_.isArray(obj)) return slice.call(obj);
		if (isArrayLike(obj)) return _.map(obj, _.identity);
		return _.values(obj);
	};

	// Return the number of elements in an object.
	_.size = function (obj) {
		if (obj == null) return 0;
		return isArrayLike(obj) ? obj.length : _.keys(obj).length;
	};

	// Split a collection into two arrays: one whose elements all satisfy the given
	// predicate, and one whose elements all do not satisfy the predicate.
	_.partition = function (obj, predicate, context) {
		predicate = cb(predicate, context);
		var pass = [], fail = [];
		_.each(obj, function (value, key, obj) {
			(predicate(value, key, obj) ? pass : fail).push(value);
		});
		return [pass, fail];
	};

	// Array Functions
	// ---------------

	// Get the first element of an array. Passing **n** will return the first N
	// values in the array. Aliased as `head` and `take`. The **guard** check
	// allows it to work with `_.map`.
	_.first = _.head = _.take = function (array, n, guard) {
		if (array == null) return void 0;
		if (n == null || guard) return array[0];
		return _.initial(array, array.length - n);
	};

	// Returns everything but the last entry of the array. Especially useful on
	// the arguments object. Passing **n** will return all the values in
	// the array, excluding the last N.
	_.initial = function (array, n, guard) {
		return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
	};

	// Get the last element of an array. Passing **n** will return the last N
	// values in the array.
	_.last = function (array, n, guard) {
		if (array == null) return void 0;
		if (n == null || guard) return array[array.length - 1];
		return _.rest(array, Math.max(0, array.length - n));
	};

	// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
	// Especially useful on the arguments object. Passing an **n** will return
	// the rest N values in the array.
	_.rest = _.tail = _.drop = function (array, n, guard) {
		return slice.call(array, n == null || guard ? 1 : n);
	};

	// Trim out all falsy values from an array.
	_.compact = function (array) {
		return _.filter(array, _.identity);
	};

	// Internal implementation of a recursive `flatten` function.
	var flatten = function (input, shallow, strict, startIndex) {
		var output = [], idx = 0;
		for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
			var value = input[i];
			if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
				//flatten current level of array or arguments object
				if (!shallow) value = flatten(value, shallow, strict);
				var j = 0, len = value.length;
				output.length += len;
				while (j < len) {
					output[idx++] = value[j++];
				}
			} else if (!strict) {
				output[idx++] = value;
			}
		}
		return output;
	};

	// Flatten out an array, either recursively (by default), or just one level.
	_.flatten = function (array, shallow) {
		return flatten(array, shallow, false);
	};

	// Return a version of the array that does not contain the specified value(s).
	_.without = function (array) {
		return _.difference(array, slice.call(arguments, 1));
	};

	// Produce a duplicate-free version of the array. If the array has already
	// been sorted, you have the option of using a faster algorithm.
	// Aliased as `unique`.
	_.uniq = _.unique = function (array, isSorted, iteratee, context) {
		if (!_.isBoolean(isSorted)) {
			context = iteratee;
			iteratee = isSorted;
			isSorted = false;
		}
		if (iteratee != null) iteratee = cb(iteratee, context);
		var result = [];
		var seen = [];
		for (var i = 0, length = getLength(array); i < length; i++) {
			var value = array[i],
				computed = iteratee ? iteratee(value, i, array) : value;
			if (isSorted) {
				if (!i || seen !== computed) result.push(value);
				seen = computed;
			} else if (iteratee) {
				if (!_.contains(seen, computed)) {
					seen.push(computed);
					result.push(value);
				}
			} else if (!_.contains(result, value)) {
				result.push(value);
			}
		}
		return result;
	};

	// Produce an array that contains the union: each distinct element from all of
	// the passed-in arrays.
	_.union = function () {
		return _.uniq(flatten(arguments, true, true));
	};

	// Produce an array that contains every item shared between all the
	// passed-in arrays.
	_.intersection = function (array) {
		var result = [];
		var argsLength = arguments.length;
		for (var i = 0, length = getLength(array); i < length; i++) {
			var item = array[i];
			if (_.contains(result, item)) continue;
			for (var j = 1; j < argsLength; j++) {
				if (!_.contains(arguments[j], item)) break;
			}
			if (j === argsLength) result.push(item);
		}
		return result;
	};

	// Take the difference between one array and a number of other arrays.
	// Only the elements present in just the first array will remain.
	_.difference = function (array) {
		var rest = flatten(arguments, true, true, 1);
		return _.filter(array, function (value) {
			return !_.contains(rest, value);
		});
	};

	// Zip together multiple lists into a single array -- elements that share
	// an index go together.
	_.zip = function () {
		return _.unzip(arguments);
	};

	// Complement of _.zip. Unzip accepts an array of arrays and groups
	// each array's elements on shared indices
	_.unzip = function (array) {
		var length = array && _.max(array, getLength).length || 0;
		var result = Array(length);

		for (var index = 0; index < length; index++) {
			result[index] = _.pluck(array, index);
		}
		return result;
	};

	// Converts lists into objects. Pass either a single array of `[key, value]`
	// pairs, or two parallel arrays of the same length -- one of keys, and one of
	// the corresponding values.
	_.object = function (list, values) {
		var result = {};
		for (var i = 0, length = getLength(list); i < length; i++) {
			if (values) {
				result[list[i]] = values[i];
			} else {
				result[list[i][0]] = list[i][1];
			}
		}
		return result;
	};

	// Generator function to create the findIndex and findLastIndex functions
	function createPredicateIndexFinder(dir) {
		return function (array, predicate, context) {
			predicate = cb(predicate, context);
			var length = getLength(array);
			var index = dir > 0 ? 0 : length - 1;
			for (; index >= 0 && index < length; index += dir) {
				if (predicate(array[index], index, array)) return index;
			}
			return -1;
		};
	}

	// Returns the first index on an array-like that passes a predicate test
	_.findIndex = createPredicateIndexFinder(1);
	_.findLastIndex = createPredicateIndexFinder(-1);

	// Use a comparator function to figure out the smallest index at which
	// an object should be inserted so as to maintain order. Uses binary search.
	_.sortedIndex = function (array, obj, iteratee, context) {
		iteratee = cb(iteratee, context, 1);
		var value = iteratee(obj);
		var low = 0, high = getLength(array);
		while (low < high) {
			var mid = Math.floor((low + high) / 2);
			if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
		}
		return low;
	};

	// Generator function to create the indexOf and lastIndexOf functions
	function createIndexFinder(dir, predicateFind, sortedIndex) {
		return function (array, item, idx) {
			var i = 0, length = getLength(array);
			if (typeof idx == 'number') {
				if (dir > 0) {
					i = idx >= 0 ? idx : Math.max(idx + length, i);
				} else {
					length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
				}
			} else if (sortedIndex && idx && length) {
				idx = sortedIndex(array, item);
				return array[idx] === item ? idx : -1;
			}
			if (item !== item) {
				idx = predicateFind(slice.call(array, i, length), _.isNaN);
				return idx >= 0 ? idx + i : -1;
			}
			for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
				if (array[idx] === item) return idx;
			}
			return -1;
		};
	}

	// Return the position of the first occurrence of an item in an array,
	// or -1 if the item is not included in the array.
	// If the array is large and already in sort order, pass `true`
	// for **isSorted** to use binary search.
	_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
	_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);

	// Generate an integer Array containing an arithmetic progression. A port of
	// the native Python `range()` function. See
	// [the Python documentation](http://docs.python.org/library/functions.html#range).
	_.range = function (start, stop, step) {
		if (stop == null) {
			stop = start || 0;
			start = 0;
		}
		step = step || 1;

		var length = Math.max(Math.ceil((stop - start) / step), 0);
		var range = Array(length);

		for (var idx = 0; idx < length; idx++ , start += step) {
			range[idx] = start;
		}

		return range;
	};

	// Function (ahem) Functions
	// ------------------

	// Determines whether to execute a function as a constructor
	// or a normal function with the provided arguments
	var executeBound = function (sourceFunc, boundFunc, context, callingContext, args) {
		if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
		var self = baseCreate(sourceFunc.prototype);
		var result = sourceFunc.apply(self, args);
		if (_.isObject(result)) return result;
		return self;
	};

	// Create a function bound to a given object (assigning `this`, and arguments,
	// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
	// available.
	_.bind = function (func, context) {
		if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
		if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
		var args = slice.call(arguments, 2);
		var bound = function () {
			return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
		};
		return bound;
	};

	// Partially apply a function by creating a version that has had some of its
	// arguments pre-filled, without changing its dynamic `this` context. _ acts
	// as a placeholder, allowing any combination of arguments to be pre-filled.
	_.partial = function (func) {
		var boundArgs = slice.call(arguments, 1);
		var bound = function () {
			var position = 0, length = boundArgs.length;
			var args = Array(length);
			for (var i = 0; i < length; i++) {
				args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
			}
			while (position < arguments.length) args.push(arguments[position++]);
			return executeBound(func, bound, this, this, args);
		};
		return bound;
	};

	// Bind a number of an object's methods to that object. Remaining arguments
	// are the method names to be bound. Useful for ensuring that all callbacks
	// defined on an object belong to it.
	_.bindAll = function (obj) {
		var i, length = arguments.length, key;
		if (length <= 1) throw new Error('bindAll must be passed function names');
		for (i = 1; i < length; i++) {
			key = arguments[i];
			obj[key] = _.bind(obj[key], obj);
		}
		return obj;
	};

	// Memoize an expensive function by storing its results.
	_.memoize = function (func, hasher) {
		var memoize = function (key) {
			var cache = memoize.cache;
			var address = '' + (hasher ? hasher.apply(this, arguments) : key);
			if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
			return cache[address];
		};
		memoize.cache = {};
		return memoize;
	};

	// Delays a function for the given number of milliseconds, and then calls
	// it with the arguments supplied.
	_.delay = function (func, wait) {
		var args = slice.call(arguments, 2);
		return setTimeout(function () {
			return func.apply(null, args);
		}, wait);
	};

	// Defers a function, scheduling it to run after the current call stack has
	// cleared.
	_.defer = _.partial(_.delay, _, 1);

	// Returns a function, that, when invoked, will only be triggered at most once
	// during a given window of time. Normally, the throttled function will run
	// as much as it can, without ever going more than once per `wait` duration;
	// but if you'd like to disable the execution on the leading edge, pass
	// `{leading: false}`. To disable execution on the trailing edge, ditto.
	_.throttle = function (func, wait, options) {
		var context, args, result;
		var timeout = null;
		var previous = 0;
		if (!options) options = {};
		var later = function () {
			previous = options.leading === false ? 0 : _.now();
			timeout = null;
			result = func.apply(context, args);
			if (!timeout) context = args = null;
		};
		return function () {
			var now = _.now();
			if (!previous && options.leading === false) previous = now;
			var remaining = wait - (now - previous);
			context = this;
			args = arguments;
			if (remaining <= 0 || remaining > wait) {
				if (timeout) {
					clearTimeout(timeout);
					timeout = null;
				}
				previous = now;
				result = func.apply(context, args);
				if (!timeout) context = args = null;
			} else if (!timeout && options.trailing !== false) {
				timeout = setTimeout(later, remaining);
			}
			return result;
		};
	};

	// Returns a function, that, as long as it continues to be invoked, will not
	// be triggered. The function will be called after it stops being called for
	// N milliseconds. If `immediate` is passed, trigger the function on the
	// leading edge, instead of the trailing.
	_.debounce = function (func, wait, immediate) {
		var timeout, args, context, timestamp, result;

		var later = function () {
			var last = _.now() - timestamp;

			if (last < wait && last >= 0) {
				timeout = setTimeout(later, wait - last);
			} else {
				timeout = null;
				if (!immediate) {
					result = func.apply(context, args);
					if (!timeout) context = args = null;
				}
			}
		};

		return function () {
			context = this;
			args = arguments;
			timestamp = _.now();
			var callNow = immediate && !timeout;
			if (!timeout) timeout = setTimeout(later, wait);
			if (callNow) {
				result = func.apply(context, args);
				context = args = null;
			}

			return result;
		};
	};

	// Returns the first function passed as an argument to the second,
	// allowing you to adjust arguments, run code before and after, and
	// conditionally execute the original function.
	_.wrap = function (func, wrapper) {
		return _.partial(wrapper, func);
	};

	// Returns a negated version of the passed-in predicate.
	_.negate = function (predicate) {
		return function () {
			return !predicate.apply(this, arguments);
		};
	};

	// Returns a function that is the composition of a list of functions, each
	// consuming the return value of the function that follows.
	_.compose = function () {
		var args = arguments;
		var start = args.length - 1;
		return function () {
			var i = start;
			var result = args[start].apply(this, arguments);
			while (i--) result = args[i].call(this, result);
			return result;
		};
	};

	// Returns a function that will only be executed on and after the Nth call.
	_.after = function (times, func) {
		return function () {
			if (--times < 1) {
				return func.apply(this, arguments);
			}
		};
	};

	// Returns a function that will only be executed up to (but not including) the Nth call.
	_.before = function (times, func) {
		var memo;
		return function () {
			if (--times > 0) {
				memo = func.apply(this, arguments);
			}
			if (times <= 1) func = null;
			return memo;
		};
	};

	// Returns a function that will be executed at most one time, no matter how
	// often you call it. Useful for lazy initialization.
	_.once = _.partial(_.before, 2);

	// Object Functions
	// ----------------

	// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
	var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
	var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
		'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

	function collectNonEnumProps(obj, keys) {
		var nonEnumIdx = nonEnumerableProps.length;
		var constructor = obj.constructor;
		var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;

		// Constructor is a special case.
		var prop = 'constructor';
		if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);

		while (nonEnumIdx--) {
			prop = nonEnumerableProps[nonEnumIdx];
			if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
				keys.push(prop);
			}
		}
	}

	// Retrieve the names of an object's own properties.
	// Delegates to **ECMAScript 5**'s native `Object.keys`
	_.keys = function (obj) {
		if (!_.isObject(obj)) return [];
		if (nativeKeys) return nativeKeys(obj);
		var keys = [];
		for (var key in obj) if (_.has(obj, key)) keys.push(key);
		// Ahem, IE < 9.
		if (hasEnumBug) collectNonEnumProps(obj, keys);
		return keys;
	};

	// Retrieve all the property names of an object.
	_.allKeys = function (obj) {
		if (!_.isObject(obj)) return [];
		var keys = [];
		for (var key in obj) keys.push(key);
		// Ahem, IE < 9.
		if (hasEnumBug) collectNonEnumProps(obj, keys);
		return keys;
	};

	// Retrieve the values of an object's properties.
	_.values = function (obj) {
		var keys = _.keys(obj);
		var length = keys.length;
		var values = Array(length);
		for (var i = 0; i < length; i++) {
			values[i] = obj[keys[i]];
		}
		return values;
	};

	// Returns the results of applying the iteratee to each element of the object
	// In contrast to _.map it returns an object
	_.mapObject = function (obj, iteratee, context) {
		iteratee = cb(iteratee, context);
		var keys = _.keys(obj),
			length = keys.length,
			results = {},
			currentKey;
		for (var index = 0; index < length; index++) {
			currentKey = keys[index];
			results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
		}
		return results;
	};

	// Convert an object into a list of `[key, value]` pairs.
	_.pairs = function (obj) {
		var keys = _.keys(obj);
		var length = keys.length;
		var pairs = Array(length);
		for (var i = 0; i < length; i++) {
			pairs[i] = [keys[i], obj[keys[i]]];
		}
		return pairs;
	};

	// Invert the keys and values of an object. The values must be serializable.
	_.invert = function (obj) {
		var result = {};
		var keys = _.keys(obj);
		for (var i = 0, length = keys.length; i < length; i++) {
			result[obj[keys[i]]] = keys[i];
		}
		return result;
	};

	// Return a sorted list of the function names available on the object.
	// Aliased as `methods`
	_.functions = _.methods = function (obj) {
		var names = [];
		for (var key in obj) {
			if (_.isFunction(obj[key])) names.push(key);
		}
		return names.sort();
	};

	// Extend a given object with all the properties in passed-in object(s).
	_.extend = createAssigner(_.allKeys);

	// Assigns a given object with all the own properties in the passed-in object(s)
	// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
	_.extendOwn = _.assign = createAssigner(_.keys);

	// Returns the first key on an object that passes a predicate test
	_.findKey = function (obj, predicate, context) {
		predicate = cb(predicate, context);
		var keys = _.keys(obj), key;
		for (var i = 0, length = keys.length; i < length; i++) {
			key = keys[i];
			if (predicate(obj[key], key, obj)) return key;
		}
	};

	// Return a copy of the object only containing the whitelisted properties.
	_.pick = function (object, oiteratee, context) {
		var result = {}, obj = object, iteratee, keys;
		if (obj == null) return result;
		if (_.isFunction(oiteratee)) {
			keys = _.allKeys(obj);
			iteratee = optimizeCb(oiteratee, context);
		} else {
			keys = flatten(arguments, false, false, 1);
			iteratee = function (value, key, obj) { return key in obj; };
			obj = Object(obj);
		}
		for (var i = 0, length = keys.length; i < length; i++) {
			var key = keys[i];
			var value = obj[key];
			if (iteratee(value, key, obj)) result[key] = value;
		}
		return result;
	};

	// Return a copy of the object without the blacklisted properties.
	_.omit = function (obj, iteratee, context) {
		if (_.isFunction(iteratee)) {
			iteratee = _.negate(iteratee);
		} else {
			var keys = _.map(flatten(arguments, false, false, 1), String);
			iteratee = function (value, key) {
				return !_.contains(keys, key);
			};
		}
		return _.pick(obj, iteratee, context);
	};

	// Fill in a given object with default properties.
	_.defaults = createAssigner(_.allKeys, true);

	// Creates an object that inherits from the given prototype object.
	// If additional properties are provided then they will be added to the
	// created object.
	_.create = function (prototype, props) {
		var result = baseCreate(prototype);
		if (props) _.extendOwn(result, props);
		return result;
	};

	// Create a (shallow-cloned) duplicate of an object.
	_.clone = function (obj) {
		if (!_.isObject(obj)) return obj;
		return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
	};

	// Invokes interceptor with the obj, and then returns obj.
	// The primary purpose of this method is to "tap into" a method chain, in
	// order to perform operations on intermediate results within the chain.
	_.tap = function (obj, interceptor) {
		interceptor(obj);
		return obj;
	};

	// Returns whether an object has a given set of `key:value` pairs.
	_.isMatch = function (object, attrs) {
		var keys = _.keys(attrs), length = keys.length;
		if (object == null) return !length;
		var obj = Object(object);
		for (var i = 0; i < length; i++) {
			var key = keys[i];
			if (attrs[key] !== obj[key] || !(key in obj)) return false;
		}
		return true;
	};


	// Internal recursive comparison function for `isEqual`.
	var eq = function (a, b, aStack, bStack) {
		// Identical objects are equal. `0 === -0`, but they aren't identical.
		// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
		if (a === b) return a !== 0 || 1 / a === 1 / b;
		// A strict comparison is necessary because `null == undefined`.
		if (a == null || b == null) return a === b;
		// Unwrap any wrapped objects.
		if (a instanceof _) a = a._wrapped;
		if (b instanceof _) b = b._wrapped;
		// Compare `[[Class]]` names.
		var className = toString.call(a);
		if (className !== toString.call(b)) return false;
		switch (className) {
			// Strings, numbers, regular expressions, dates, and booleans are compared by value.
			case '[object RegExp]':
			// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
			case '[object String]':
				// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
				// equivalent to `new String("5")`.
				return '' + a === '' + b;
			case '[object Number]':
				// `NaN`s are equivalent, but non-reflexive.
				// Object(NaN) is equivalent to NaN
				if (+a !== +a) return +b !== +b;
				// An `egal` comparison is performed for other numeric values.
				return +a === 0 ? 1 / +a === 1 / b : +a === +b;
			case '[object Date]':
			case '[object Boolean]':
				// Coerce dates and booleans to numeric primitive values. Dates are compared by their
				// millisecond representations. Note that invalid dates with millisecond representations
				// of `NaN` are not equivalent.
				return +a === +b;
		}

		var areArrays = className === '[object Array]';
		if (!areArrays) {
			if (typeof a != 'object' || typeof b != 'object') return false;

			// Objects with different constructors are not equivalent, but `Object`s or `Array`s
			// from different frames are.
			var aCtor = a.constructor, bCtor = b.constructor;
			if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
				_.isFunction(bCtor) && bCtor instanceof bCtor)
				&& ('constructor' in a && 'constructor' in b)) {
				return false;
			}
		}
		// Assume equality for cyclic structures. The algorithm for detecting cyclic
		// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

		// Initializing stack of traversed objects.
		// It's done here since we only need them for objects and arrays comparison.
		aStack = aStack || [];
		bStack = bStack || [];
		var length = aStack.length;
		while (length--) {
			// Linear search. Performance is inversely proportional to the number of
			// unique nested structures.
			if (aStack[length] === a) return bStack[length] === b;
		}

		// Add the first object to the stack of traversed objects.
		aStack.push(a);
		bStack.push(b);

		// Recursively compare objects and arrays.
		if (areArrays) {
			// Compare array lengths to determine if a deep comparison is necessary.
			length = a.length;
			if (length !== b.length) return false;
			// Deep compare the contents, ignoring non-numeric properties.
			while (length--) {
				if (!eq(a[length], b[length], aStack, bStack)) return false;
			}
		} else {
			// Deep compare objects.
			var keys = _.keys(a), key;
			length = keys.length;
			// Ensure that both objects contain the same number of properties before comparing deep equality.
			if (_.keys(b).length !== length) return false;
			while (length--) {
				// Deep compare each member
				key = keys[length];
				if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
			}
		}
		// Remove the first object from the stack of traversed objects.
		aStack.pop();
		bStack.pop();
		return true;
	};

	// Perform a deep comparison to check if two objects are equal.
	_.isEqual = function (a, b) {
		return eq(a, b);
	};

	// Is a given array, string, or object empty?
	// An "empty" object has no enumerable own-properties.
	_.isEmpty = function (obj) {
		if (obj == null) return true;
		if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
		return _.keys(obj).length === 0;
	};

	// Is a given value a DOM element?
	_.isElement = function (obj) {
		return !!(obj && obj.nodeType === 1);
	};

	// Is a given value an array?
	// Delegates to ECMA5's native Array.isArray
	_.isArray = nativeIsArray || function (obj) {
		return toString.call(obj) === '[object Array]';
	};

	// Is a given variable an object?
	_.isObject = function (obj) {
		var type = typeof obj;
		return type === 'function' || type === 'object' && !!obj;
	};

	// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
	_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function (name) {
		_['is' + name] = function (obj) {
			return toString.call(obj) === '[object ' + name + ']';
		};
	});

	// Define a fallback version of the method in browsers (ahem, IE < 9), where
	// there isn't any inspectable "Arguments" type.
	if (!_.isArguments(arguments)) {
		_.isArguments = function (obj) {
			return _.has(obj, 'callee');
		};
	}

	// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
	// IE 11 (#1621), and in Safari 8 (#1929).
	if (typeof /./ != 'function' && typeof Int8Array != 'object') {
		_.isFunction = function (obj) {
			return typeof obj == 'function' || false;
		};
	}

	// Is a given object a finite number?
	_.isFinite = function (obj) {
		return isFinite(obj) && !isNaN(parseFloat(obj));
	};

	// Is the given value `NaN`? (NaN is the only number which does not equal itself).
	_.isNaN = function (obj) {
		return _.isNumber(obj) && obj !== +obj;
	};

	// Is a given value a boolean?
	_.isBoolean = function (obj) {
		return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
	};

	// Is a given value equal to null?
	_.isNull = function (obj) {
		return obj === null;
	};

	// Is a given variable undefined?
	_.isUndefined = function (obj) {
		return obj === void 0;
	};

	// Shortcut function for checking if an object has a given property directly
	// on itself (in other words, not on a prototype).
	_.has = function (obj, key) {
		return obj != null && hasOwnProperty.call(obj, key);
	};

	// Utility Functions
	// -----------------

	// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
	// previous owner. Returns a reference to the Underscore object.
	_.noConflict = function () {
		root._ = previousUnderscore;
		return this;
	};

	// Keep the identity function around for default iteratees.
	_.identity = function (value) {
		return value;
	};

	// Predicate-generating functions. Often useful outside of Underscore.
	_.constant = function (value) {
		return function () {
			return value;
		};
	};

	_.noop = function () { };

	_.property = property;

	// Generates a function for a given object that returns a given property.
	_.propertyOf = function (obj) {
		return obj == null ? function () { } : function (key) {
			return obj[key];
		};
	};

	// Returns a predicate for checking whether an object has a given set of
	// `key:value` pairs.
	_.matcher = _.matches = function (attrs) {
		attrs = _.extendOwn({}, attrs);
		return function (obj) {
			return _.isMatch(obj, attrs);
		};
	};

	// Run a function **n** times.
	_.times = function (n, iteratee, context) {
		var accum = Array(Math.max(0, n));
		iteratee = optimizeCb(iteratee, context, 1);
		for (var i = 0; i < n; i++) accum[i] = iteratee(i);
		return accum;
	};

	// Return a random integer between min and max (inclusive).
	_.random = function (min, max) {
		if (max == null) {
			max = min;
			min = 0;
		}
		return min + Math.floor(Math.random() * (max - min + 1));
	};

	// A (possibly faster) way to get the current timestamp as an integer.
	_.now = Date.now || function () {
		return new Date().getTime();
	};

	// List of HTML entities for escaping.
	var escapeMap = {
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;',
		'"': '&quot;',
		"'": '&#x27;',
		'`': '&#x60;'
	};
	var unescapeMap = _.invert(escapeMap);

	// Functions for escaping and unescaping strings to/from HTML interpolation.
	var createEscaper = function (map) {
		var escaper = function (match) {
			return map[match];
		};
		// Regexes for identifying a key that needs to be escaped
		var source = '(?:' + _.keys(map).join('|') + ')';
		var testRegexp = RegExp(source);
		var replaceRegexp = RegExp(source, 'g');
		return function (string) {
			string = string == null ? '' : '' + string;
			return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
		};
	};
	_.escape = createEscaper(escapeMap);
	_.unescape = createEscaper(unescapeMap);

	// If the value of the named `property` is a function then invoke it with the
	// `object` as context; otherwise, return it.
	_.result = function (object, property, fallback) {
		var value = object == null ? void 0 : object[property];
		if (value === void 0) {
			value = fallback;
		}
		return _.isFunction(value) ? value.call(object) : value;
	};

	// Generate a unique integer id (unique within the entire client session).
	// Useful for temporary DOM ids.
	var idCounter = 0;
	_.uniqueId = function (prefix) {
		var id = ++idCounter + '';
		return prefix ? prefix + id : id;
	};

	// By default, Underscore uses ERB-style template delimiters, change the
	// following template settings to use alternative delimiters.
	_.templateSettings = {
		evaluate: /<%([\s\S]+?)%>/g,
		interpolate: /<%=([\s\S]+?)%>/g,
		escape: /<%-([\s\S]+?)%>/g
	};

	// When customizing `templateSettings`, if you don't want to define an
	// interpolation, evaluation or escaping regex, we need one that is
	// guaranteed not to match.
	var noMatch = /(.)^/;

	// Certain characters need to be escaped so that they can be put into a
	// string literal.
	var escapes = {
		"'": "'",
		'\\': '\\',
		'\r': 'r',
		'\n': 'n',
		'\u2028': 'u2028',
		'\u2029': 'u2029'
	};

	var escaper = /\\|'|\r|\n|\u2028|\u2029/g;

	var escapeChar = function (match) {
		return '\\' + escapes[match];
	};

	// JavaScript micro-templating, similar to John Resig's implementation.
	// Underscore templating handles arbitrary delimiters, preserves whitespace,
	// and correctly escapes quotes within interpolated code.
	// NB: `oldSettings` only exists for backwards compatibility.
	_.template = function (text, settings, oldSettings) {
		if (!settings && oldSettings) settings = oldSettings;
		settings = _.defaults({}, settings, _.templateSettings);

		// Combine delimiters into one regular expression via alternation.
		var matcher = RegExp([
			(settings.escape || noMatch).source,
			(settings.interpolate || noMatch).source,
			(settings.evaluate || noMatch).source
		].join('|') + '|$', 'g');

		// Compile the template source, escaping string literals appropriately.
		var index = 0;
		var source = "__p+='";
		text.replace(matcher, function (match, escape, interpolate, evaluate, offset) {
			source += text.slice(index, offset).replace(escaper, escapeChar);
			index = offset + match.length;

			if (escape) {
				source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
			} else if (interpolate) {
				source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
			} else if (evaluate) {
				source += "';\n" + evaluate + "\n__p+='";
			}

			// Adobe VMs need the match returned to produce the correct offest.
			return match;
		});
		source += "';\n";

		// If a variable is not specified, place data values in local scope.
		if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

		source = "var __t,__p='',__j=Array.prototype.join," +
			"print=function(){__p+=__j.call(arguments,'');};\n" +
			source + 'return __p;\n';

		try {
			var render = new Function(settings.variable || 'obj', '_', source);
		} catch (e) {
			e.source = source;
			throw e;
		}

		var template = function (data) {
			return render.call(this, data, _);
		};

		// Provide the compiled source as a convenience for precompilation.
		var argument = settings.variable || 'obj';
		template.source = 'function(' + argument + '){\n' + source + '}';

		return template;
	};

	// Add a "chain" function. Start chaining a wrapped Underscore object.
	_.chain = function (obj) {
		var instance = _(obj);
		instance._chain = true;
		return instance;
	};

	// OOP
	// ---------------
	// If Underscore is called as a function, it returns a wrapped object that
	// can be used OO-style. This wrapper holds altered versions of all the
	// underscore functions. Wrapped objects may be chained.

	// Helper function to continue chaining intermediate results.
	var result = function (instance, obj) {
		return instance._chain ? _(obj).chain() : obj;
	};

	// Add your own custom functions to the Underscore object.
	_.mixin = function (obj) {
		_.each(_.functions(obj), function (name) {
			var func = _[name] = obj[name];
			_.prototype[name] = function () {
				var args = [this._wrapped];
				push.apply(args, arguments);
				return result(this, func.apply(_, args));
			};
		});
	};

	// Add all of the Underscore functions to the wrapper object.
	_.mixin(_);

	// Add all mutator Array functions to the wrapper.
	_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function (name) {
		var method = ArrayProto[name];
		_.prototype[name] = function () {
			var obj = this._wrapped;
			method.apply(obj, arguments);
			if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
			return result(this, obj);
		};
	});

	// Add all accessor Array functions to the wrapper.
	_.each(['concat', 'join', 'slice'], function (name) {
		var method = ArrayProto[name];
		_.prototype[name] = function () {
			return result(this, method.apply(this._wrapped, arguments));
		};
	});

	// Extracts the result from a wrapped and chained object.
	_.prototype.value = function () {
		return this._wrapped;
	};

	// Provide unwrapping proxy for some methods used in engine operations
	// such as arithmetic and JSON stringification.
	_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

	_.prototype.toString = function () {
		return '' + this._wrapped;
	};

	// AMD registration happens at the end for compatibility with AMD loaders
	// that may not enforce next-turn semantics on modules. Even though general
	// practice for AMD registration is to be anonymous, underscore registers
	// as a named module because, like jQuery, it is a base library that is
	// popular enough to be bundled in a third party lib, but not be part of
	// an AMD load request. Those cases could generate an error when an
	// anonymous define() is called outside of a loader request.
	if (typeof define === 'function' && define.amd) {
		define('underscore', [], function () {
			return _;
		});
	}
}.call(this));
var Keaworks = {};
(function (self) {

	self.cancelEvent = function (event) {
		event.preventDefault && event.preventDefault();
		event.stopPropagation && event.stopPropagation();
	};

})(Keaworks);

(function () {
	//http://stackoverflow.com/a/4673436/10779
	String.prototype.format = function () {
		var args = arguments;
		return this.replace(/{(\d+)}/g, function (match, number) {
			return typeof args[number] != 'undefined'
      ? args[number]
      : match
			;
		});
	};

	//http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
	String.prototype.capitalize = function () {
		return this.charAt(0).toUpperCase() + this.slice(1);
	};

	String.prototype.isNullOrEmpty = function (value) {
		return !(typeof value === "string" && value.length > 0);
	}

	Number.prototype.clamp = function (min, max) {
		return Math.min(Math.max(this, min), max);
	};

	Number.prototype.min = function (min) {
		return Math.min(this, min);
	};

	Number.prototype.max = function (max) {
		return Math.max(this, max);
	};

	Array.prototype.remove = function (child, ignoreError) {
		var index = this.indexOf(child);
		if (index < 0) {
			if (ignoreError) {
				return;
			}
			throw "Can't find child in array!";
		}
		this.splice(index, 1);
	};
})();

if (Ractive && location.hostname != 'localhost') {
	Ractive.DEBUG = false;
}
;






